联盟2数据框按条件

时间:2019-05-26 07:38:55

标签: python-3.x pandas dataframe

我有2张桌子。 df中的第一名:

Date       X1   X2  X3
04.02.2019  2   2   12
05.02.2019  2   2   5
06.02.2019  1   2   1

第二个df1:

Date       X1   X2  X3
06.02.2019  1   1   2
07.02.2019  1   1   4
08.02.2019  2   2   2
09.02.2019  4   1   1

我需要用表2中的数据补充表1。数据应从Date,X1,X3列中获取,并且仅适用于条件为Date> 06.02.2019的行。结果为df:

Date       X1   X2  X3
04.02.2019  2   2   12
05.02.2019  2   2   5
06.02.2019  1   2   1
07.02.2019  1       4
08.02.2019  2       2
09.02.2019  4       1

1 个答案:

答案 0 :(得分:2)

使用:

#convert columns to datetimes
df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
df1['Date'] = pd.to_datetime(df1['Date'], format='%d.%m.%Y')

#filter expected columns by condition and by columns in list
df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]

#match by DatetimeIndex and add values from filtered DataFrame
df = df.set_index('Date').combine_first(df2.set_index('Date')).reset_index()
print (df)
        Date   X1   X2    X3
0 2019-02-04  2.0  2.0  12.0
1 2019-02-05  2.0  2.0   5.0
2 2019-02-06  1.0  2.0   1.0
3 2019-02-07  1.0  NaN   4.0
4 2019-02-08  2.0  NaN   2.0
5 2019-02-09  4.0  NaN   1.0

或者仅需将第二个DataFrame附加到第一个:

df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]
df = pd.concat([df, df2], ignore_index=True, sort=True)
print (df)
        Date  X1   X2  X3
0 2019-02-04   2  2.0  12
1 2019-02-05   2  2.0   5
2 2019-02-06   1  2.0   1
3 2019-02-07   1  NaN   4
4 2019-02-08   2  NaN   2
5 2019-02-09   4  NaN   1