Pandas将dtype对象转换为字符串

时间:2014-03-02 13:04:17

标签: python pandas

我无法转换列的dtype。我正在从yahoo finance加载一个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)

我尝试将Date转换为字符串,但无论我尝试它都无法正常工作。我试图遍历行并用str()转换它。我试图用dt['Date'].apply(str)更改对象的dtype,我尝试了一个特殊的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 个答案:

答案 0 :(得分:3)

将日期转换为日期时间可以让您轻松地将用户输入的日期与数据中的日期进行比较。

#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]
相关问题