python - 在 Pandas 数据框中创建日期时间索引

标签 python pandas

  1988   1   1  7.88 15.57 25.00  0.00  0.81  4.02
  1988   1   2  6.50 10.37 24.87  0.00  0.49  4.30
  1988   1   3  6.48 -8.79 21.28  0.00  0.62  3.91

我把上面的文件读成:

df = pd.read_fwf('27_35.txt', header=None, widths=[6,4,4,6,6,6,6,6,6])

第一列是年,第二列是月,第三列是日。如何从这 3 列 ('1988-1-1') 创建索引?

最佳答案

使用parse_dates param 并在列表中传递一个列表(因此它理解您希望将列列表视为单个实体进行解析):

In [83]:
t="""1988   1   1  7.88 15.57 25.00  0.00  0.81  4.02
  1988   1   2  6.50 10.37 24.87  0.00  0.49  4.30
  1988   1   3  6.48 -8.79 21.28  0.00  0.62  3.91"""
df = pd.read_fwf(io.StringIO(t), header=None, widths=[6,4,4,6,6,6,6,6,6], parse_dates=[[0,1,2]])
df

Out[83]:
       0_1_2       3       4      5  6     7     8
0 1988-01-01  7.88 1  5.57 2   5.00  0  0.81  4.02
1 1988-01-02    6.50   10.37  24.87  0  0.49  4.30
2 1988-01-03    6.48   -8.79  21.28  0  0.62  3.91

In [84]:
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 7 columns):
0_1_2    3 non-null datetime64[ns]
3        3 non-null object
4        3 non-null object
5        3 non-null float64
6        3 non-null float64
7        3 non-null float64
8        3 non-null float64
dtypes: datetime64[ns](1), float64(4), object(2)
memory usage: 192.0+ bytes

编辑

要保留原始日期列,请添加参数 keep_date_col=True

df = pd.read_fwf('27_35.txt', header=None, widths=[6,4,4,6,6,6,6,6,6], parse_dates=[[0,1,2]], keep_date_col=True)

关于python - 在 Pandas 数据框中创建日期时间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388741/

相关文章:

python - 如何用 python "join"两个文本文件?

python - 如何在给定的不规则日期对时间序列重新采样

python - 在 pandas 中查找组中的第一个非零元素

python - 在 python 中获取行百分比来绘制

python - 在多个 Seaborn Stripplot 中可视化样本大小

Python 多处理队列可扩展到大量工作线程

python - 如何逐行打印 telnet 响应?

python - 在 Pandas 中混合数据帧

python - 字典中的分组数据

python - 使用 Python 中的 matplotlib 从线性模型绘制 3d 曲面图