Pandas将dtype对象转换为字符串

4

我有问题将一列的 dtype 进行转换。我正在从雅虎财经加载一个 csv 文件。

dt = pd.read_csv('data/Tesla.csv')

这个给我以下信息:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 923 entries, 0 to 922
Data columns (total 7 columns):
Date         923 non-null object
Open         923 non-null float64
High         923 non-null float64
Low          923 non-null float64
Close        923 non-null float64
Volume       923 non-null int64
Adj Close    923 non-null float64
dtypes: float64(5), int64(1), object(1)

我试图将日期转换为字符串,但无论我尝试什么方法都不起作用。我尝试遍历行并使用str()进行转换。我尝试改变对象的dtype,使用dt['Date'].apply(str),还尝试了特殊的dtype对象来进行转换:
types={'Date':'str','Open':'float','High':'float','Low':'float','Close':'float','Volume':'int','Adj Close':'float'}
 dt = pd.read_csv('data/Tesla.csv', dtype=types)

但是似乎什么都不起作用。

我使用的是 Pandas 版本 0.13.1。


1
“object” dtype 是如何表示可变长度字符串的。您实际上想要做什么? - Jeff
我想将数据框中的日期与输入字段给出的日期进行比较,该日期为字符串。我需要比较这两个日期以向用户提供正确的信息。 - nick appel
1个回答

3

将您的日期转换为DateTime将使您能够轻松比较用户输入日期与数据中的日期。

#Load in the data
dt = pd.read_csv('data/Tesla.csv')

#Change the 'Date' column into DateTime
dt['Date']=pd.to_datetime(dt['Date'])

#Find a Date using strings
np.where(dt['Date']=='2014-02-28')
#returns     (array([0]),)

np.where(dt['Date']=='2014-02-21')
#returns (array([5]),)

#To get the entire row's information
index = np.where(dt['Date']=='2014-02-21')[0][0]
dt.iloc[index]

#returns:
Date         2014-02-21 00:00:00
Open                      211.64
High                      213.98
Low                       209.19
Close                      209.6
Volume                   7818800
Adj Close                  209.6
Name: 5, dtype: object

所以如果您想要进行for循环,您可以创建一个日期列表或numpy数组,然后迭代遍历它们,并用您的值替换索引中的日期:

input = np.array(['2014-02-21','2014-02-28'])
for i in input:
    index = np.where(dt['Date']==i)[0][0]
    dt.iloc[index]

数据可以在这里找到 链接 - nick appel
数据可以在这里找到[链接](http://finance.yahoo.com/q/hp?s=TSLA+Historical+Prices),我使用pd.to_datetime()转换了日期列。为了循环遍历行,我使用以下代码: for i in range(len(tesla),5): print type((tesla.iloc[[i]]['Date']))这给了我一个类型变量:<class 'pandas.core.series.Series'>我还使用以下代码将字符串转换为日期时间: datetime.strptime('2013-08-20', '%Y-%M-%d') 这给了我<type datetime.datetime>现在我需要将转换后的字符串与for循环中的值进行比较。 - nick appel
我正在接近目标,我只是想获取特定行中的所有信息。这就是为什么在for循环中使用了tesla.iloc[[i]]['Date']。 - nick appel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接