Pandas将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()进行转换。我还尝试用dt['Date'].apply(str)
来改变对象的数据类型,并且我还尝试使用一个特殊的数据类型对象:
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 个回答
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
如果你想用循环来处理这些日期,你可以先创建一个日期的列表或者用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]