日期帧的摘录可能如下所示(它肯定要大得多):
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
有没有一种快速的方法来对齐行,以便日期(在 Date3
和 Log3
列中)与 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/