这是一个有关熊猫数据的问题。我正在寻找的是从csv文件中获取两列,并在最终保存它们之前操纵这些数据。
csv文件如下所示:
year month
2007 1
2007 2
2007 3
2007 4
2008 1
2008 3
这是我当前的代码:
records = pd.read_csv(path)
frame = pd.DataFrame(records)
combined = datetime(frame['year'].astype(int), frame['month'].astype(int), 1)
错误是:
TypeError: cannot convert the series to "<type 'int'>"
有什么想法吗?
最佳答案
datetime不适用于pandas系列(数据框的列)。您可以使用to_datetime
,也可以在datetime
中使用apply
。类似于以下内容的东西应该起作用:
In [9]: df
Out[9]:
year month
0 2007 1
1 2007 2
2 2007 3
3 2007 4
4 2008 1
5 2008 3
In [10]: pd.to_datetime(df['year'].astype(str) + '-'
+ df['month'].astype(str)
+ '-1')
Out[10]:
0 2007-01-01
1 2007-02-01
2 2007-03-01
3 2007-04-01
4 2008-01-01
5 2008-03-01
dtype: datetime64[ns]
或使用申请:
In [11]: df.apply(lambda x: datetime(x['year'],x['month'],1),axis=1)
Out[11]:
0 2007-01-01
1 2007-02-01
2 2007-03-01
3 2007-04-01
4 2008-01-01
5 2008-03-01
dtype: datetime64[ns]
另一个编辑:您也可以使用
read_csv
进行大多数日期解析,但是您需要在读入日期后进行调整(注意,我的数据在名为“ data”的字符串中):In [12]: df = pd.read_csv(StringIO(data),header=True,
parse_dates={'date':['year','month']})
In [13]: df['date'] = df['date'].values.astype('datetime64[M]')
In [14]: df
Out[14]:
date
0 2007-01-01
1 2007-02-01
2 2007-03-01
3 2007-04-01
4 2008-01-01
5 2008-03-01
关于python - 使用Pandas处理来自CSV的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23212180/