python - pandas 数据框中按日期对齐行

标签 python pandas dataframe

日期帧的摘录可能如下所示(它肯定要大得多):

            Date1        Log1     Date2     Log2    Date3       Log3   
 Index
   0       01.01.2000    1000   02.01.2000  2000   01.01.2000   3000
   1       02.01.2000    1050   03.01.2000  1950   02.01.2000   3020
   2       03.01.2000    1100   04.01.2000  2000   03.01.2000   3000

有没有一种快速的方法来对齐行,以便日期(在 Date3Log3 列中)与 Date1 列中的日期匹配>?

            Date1        Log1     Date2     Log2    Date3       Log3   
 Index
   0       01.01.2000    1000   NaN                01.01.2000   3000
   1       02.01.2000    1050   02.01.2000  2000   02.01.2000   3020
   2       03.01.2000    1100   03.01.2000  1950   03.01.2000   3000

提前非常感谢

最佳答案

我假设您只想在日期与 Date1 中的日期匹配时保留 ['Date2', 'Log2'] 和 ['Date3', 'Log3'] 中的值。

您可以将不同的列读入单独的数据帧并使用合并。然后过滤以仅保留 Date1 列不为空的行。

df
>>>
        Date1  Log1       Date2  Log2       Date3  Log3
0  01.01.2000  1000  02.01.2000  2000  01.01.2000  3000
1  02.01.2000  1050  03.01.2000  1950  02.01.2000  3020
2  03.01.2000  1100  04.01.2000  2000  03.01.2000  3000

df1 = df[['Date1', 'Log1']]
df2 = df[['Date2', 'Log2']]
df3 = df[['Date3', 'Log3']]

df_out = df1.merge(df2, how='outer', left_on='Date1', right_on='Date2')
df_out = df_out.merge(df3, how='outer', left_on='Date1', right_on='Date3')
df_out = df_out[df_out['Date1'].notnull()]

df_out
>>>
        Date1    Log1       Date2    Log2       Date3    Log3
0  01.01.2000  1000.0         NaN     NaN  01.01.2000  3000.0
1  02.01.2000  1050.0  02.01.2000  2000.0  02.01.2000  3020.0
2  03.01.2000  1100.0  03.01.2000  1950.0  03.01.2000  3000.0

关于python - pandas 数据框中按日期对齐行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39966021/

相关文章:

python - Pandas:根据复杂逻辑删除具有特定字符串的行和列

python - Pyinstaller导入报错没有模块命名路径

python - 为什么 PostgreSQL 适配器 psycopg2 在 Google App Engine dev_appserver.py 中失败?

python - 将一个数据框中的值与另一个数据框中的列中的值进行比较,并从第三列获取数据

python - Pandas 按总和分组仅保留索引之一作为列

python - 创建没有 NaN 的 pandas MultiIndex Dataframe

R循环长数据返回最小值和累计值

python - 我如何使用 pd.concat' 一次连接所有列而不是多次调用 `frame.insert` ?

python - 用 Pytorch 随机选择?

python - 读取 python 文件时出错