python - 如何在 pandas 数据框中复制和修改日期行 Python

标签 python pandas dataframe duplicates

我正在处理一个包含多个日期列的巨大数据框。这是一个示例:

import pandas as pd
import numpy as np
rng = pd.date_range('2015-02-24', periods=3)
rng2 = pd.date_range('2015-02-25', periods=3)
df = pd.DataFrame({ 'Arrive': rng, 'Dept': rng2, 'Val' : np.random.randn(len(rng))})

print(df)
 Arrive       Dept       Val
0 2015-02-24 2015-02-25 -1.576528
1 2015-02-25 2015-02-26  0.803651
2 2015-02-26 2015-02-27  0.166160

现在我使用以下方法将行复制两次:

dupli_df = pd.concat([df]*3, ignore_index=True)
print(dupli_df)
    Arrive       Dept       Val
0 2015-02-24 2015-02-25 -1.576528
1 2015-02-25 2015-02-26  0.803651
2 2015-02-26 2015-02-27  0.166160
3 2015-02-24 2015-02-25 -1.576528
4 2015-02-25 2015-02-26  0.803651
5 2015-02-26 2015-02-27  0.166160
6 2015-02-24 2015-02-25 -1.576528
7 2015-02-25 2015-02-26  0.803651
8 2015-02-26 2015-02-27  0.166160

我想做的是为重复行之一的 df['Arrive']df['Dept'] 添加一天,并且从另一重复行的两列中减去一天。所以基本上,我试图获取这样的数据框:


    Arrive       Dept       Val
0 2015-02-24 2015-02-25 -1.576528
1 2015-02-25 2015-02-26  0.803651
2 2015-02-26 2015-02-27  0.166160
3 2015-02-25 2015-02-26 -1.576528
4 2015-02-26 2015-02-27  0.803651
5 2015-02-27 2015-02-28  0.166160
6 2015-02-23 2015-02-24 -1.576528
7 2015-02-24 2015-02-25  0.803651
8 2015-02-25 2015-02-26  0.166160

我正在考虑创建两个单独的数据帧并将它们连接在一起,但我不确定这是否是最有效的方法。

预先感谢您的任何建议。

最佳答案

可以使用以天为单位的偏移量的键concat。然后我们添加。

import pandas as pd

res = pd.concat([df]*3, keys=[0, 1, -1])

cols = ['Arrive', 'Dept']
res[cols] = res[cols].add(pd.to_timedelta(res.index.get_level_values(0), unit='d'), axis=0)
#res = res.reset_index(drop=True)  # If you want a RangeIndex

         Arrive       Dept       Val
 0 0 2015-02-24 2015-02-25 -0.038529
   1 2015-02-25 2015-02-26 -0.025718
   2 2015-02-26 2015-02-27  1.037771
 1 0 2015-02-25 2015-02-26 -0.038529
   1 2015-02-26 2015-02-27 -0.025718
   2 2015-02-27 2015-02-28  1.037771
-1 0 2015-02-23 2015-02-24 -0.038529
   1 2015-02-24 2015-02-25 -0.025718
   2 2015-02-25 2015-02-26  1.037771

关于python - 如何在 pandas 数据框中复制和修改日期行 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57630881/

相关文章:

python - 图中的节点未显示正确的标签

python - 属性错误 : Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects

Python dateutil 不解析月份

python - os.fork() sem_wait : Permission denied

python - 多处理和垃圾收集

python - nunique 排除 pandas 中的某些值

python - 根据字典引用的不同列的值对 pandas 列执行算术

r - 根据另一行中的条件聚合 data.table

python - 在 Pandas 中解析 JSON

python请求响应位置