[英]Pandas replace all column values if index is in another dataframe without list the columns?
I have two dataframes ( df1, df3
) with 12 columns and values for the next 12 months.我有两个数据框(
df1, df3
),其中包含 12 列和接下来 12 个月的值。 I want to replace the values of df1
if index is in df2
with values of df3
.如果索引在
df2
,我想用df3
的值替换df1
值。 The two dataframes ( df1, df3
) comes automatically with 12-month rolling columns.两个数据框 (
df1, df3
) 自动带有 12 个月滚动列。
df1 = pd.DataFrame(np.array([[100, 200, 300, 100, 150, 200, 220, 230, 300, 340, 250, 300], [400, 500, 600, 200, 300, 100, 150, 200, 220, 230, 300, 340], [150, 200, 220, 230, 300, 340, 200, 150, 90, 200, 200, 150]]),
columns=['March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February'],
index= ['AB', 'CD', 'EF'])
df3 = pd.DataFrame(np.array([[200, 120, 150, 200, 300, 150, 150, 200, 320, 230, 250, 120], [450, 400, 500, 100, 300, 200, 150, 200, 320, 230, 250, 100], [300, 250, 190, 300, 200, 150, 200, 120, 150, 200, 300, 100]]),
columns=['March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February'],
index= ['AB', 'CD', 'EF'])
data = ['AB', 'RE', 'AF']
df2 = pd.DataFrame(data, columns = ['Lookup'])
Expected output would be for index 'AB' the values of df3
for the next 12 months and for 'CD' and 'EF' the values of df1
.预期输出将是索引 'AB' 未来 12 个月的
df3
值,以及 'CD' 和 'EF' df1
的值。
After trying and google I came across the following code which perfectly works.在尝试和谷歌之后,我遇到了以下完美工作的代码。
matches = df1.index.isin(df2.Lookup)
df1.loc[matches, :] = df3.loc[matches, :]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.