python - 使用 pandas 操作 csv 数据

标签 python csv pandas

这是一个关于 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/

相关文章:

python - 如何访问列表字典中的每个元素?

python - 在 Twisted 中发起 HTTPS 请求

php - 包括一个 .py 文件,仍然不会破坏 cronjob(Python,初学者)?

python - 根据 pandas 数据框中的相邻列将 NaN 值替换为特定文本

php - 如何使用 PHP 获取 CSV 文件中的总行数?

C++ 从 CSV 文件中读取一列数据

python - pandas:计算出每天每只股票的平均值和总值(value)

python - 将一些行转到 DataFrame 中的新列

python - 网络摄像头:libv4l2 & VIDIOC_DQBUF:没有这样的设备

python - 操作 pandas 中的直方图