如果特定列存在于列表中,是否有一种方法可以对它们求和?

Is there a way of summing specific columns if they exist in a list?

我正在尝试查找 df2 中的列,并且只对 df1 中存在于 df2 列中的列求和

df1 =
London, New York, Paris, LA, Chicago
1000, 2000, 5000, 10000, 3000

df2 =
US Cities
New York
Miami
LA
Chicago
Seattle 

结果:

df1 =
London, New York, Paris, LA, Chicago, Sum of US Cities
1000, 2000, 5000, 10000, 3000, 15000

给你:

df1['Sum of US Cities'] = df1.loc[:, df1.columns.isin(df2['US Cities'])].sum(axis=1)

输出

   London  New York  Paris     LA  Chicago  Sum of US Cities
0    1000      2000   5000  10000     3000             15000