这是一个关于 pandas 数据的问题。我正在寻找的是从 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'>"
有什么想法吗?
最佳答案
日期时间不会在 pandas 系列(数据帧的列)上运行。您可以使用 to_datetime
,也可以在 apply
中使用 datetime
。像下面这样的东西应该有效:
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/