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

2024-10-05 10:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想创建两个独立的数据帧并将它们连接在一起,但我不确定这是否是最有效的方法。你知道吗

提前谢谢你的建议。你知道吗


Tags: 数据importdfdateasnprangeval
2条回答

可以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

您可以在concat之后对dupli_df的右侧部分进行切片,并使用^{},例如:

dupli_df = pd.concat([df]*3, ignore_index=True)
# get all the column that are datetime and the length of the dataframe
l_col_datetime = dupli_df.select_dtypes('datetime').columns
len_df = len(df)
#add or remove a day depending on the slice 
dupli_df.loc[len_df:2*len_df-1, l_col_datetime ] +=  pd.DateOffset(days=1)
dupli_df.loc[2*len_df:, l_col_datetime ] -=  pd.DateOffset(days=1)

print(dupli_df)
      Arrive       Dept       Val
0 2015-02-24 2015-02-25  1.450079
1 2015-02-25 2015-02-26 -1.478552
2 2015-02-26 2015-02-27 -0.596992
3 2015-02-25 2015-02-26  1.450079
4 2015-02-26 2015-02-27 -1.478552
5 2015-02-27 2015-02-28 -0.596992
6 2015-02-23 2015-02-24  1.450079
7 2015-02-24 2015-02-25 -1.478552
8 2015-02-25 2015-02-26 -0.596992

相关问题 更多 >

    热门问题