映射两个数据框并使用字典执行求和运算

constiii

我有一个数据框df

df

   Object        Action  Cost1  Cost2
0     123      renovate  10000   2000
1     456  do something      0     10
2     789        review   1000     50

字典(称为字典)

dictionary

{'Object_new': ['Object'],
 'Action_new': ['Action'],
 'Total_Cost': ['Cost1', 'Cost2']}

此外,我有一个(开头为空)数据帧df_new,其中应包含与df几乎相同的信息,除了列名需要不同(根据字典命名)并且应该合并df中的某些列(例如基于字典的和运算)。

结果应如下所示:

df_new

   Object_new    Action_new  Total_Cost
0         123      renovate       12000
1         456  do something          10
2         789        review        1050

如何仅使用字典来达到此结果?我尝试使用.map()函数,但无法弄清楚如何使用它执行求和运算。

附有用于重现数据帧和字典的代码:

# import libraries
import pandas as pd


### create df
data_df = {'Object':  [123, 456, 789],
        'Action': ['renovate', 'do something', 'review'],
        'Cost1': [10000, 0, 1000],
        'Cost2': [2000, 10, 50],
        }

df = pd.DataFrame(data_df)


### create dictionary
dictionary = {'Object_new':['Object'], 
              'Action_new':['Action'], 
              'Total_Cost' : ['Cost1', 'Cost2']}


### create df_new
# data_df_new = pd.DataFrame(columns=['Object_new', 'Action_new', 'Total_Cost' ])
data_df_new = {'Object_new':  [123, 456, 789],
        'Action_new': ['renovate', 'do something', 'review'],
        'Total_Cost': [12000, 10, 1050],
        }
df_new = pd.DataFrame(data_df_new)
广晃

玩法groupby

inv_dict = {x:k for k,v in dictionary.items() for x in v}
df_new =  df.groupby(df.columns.map(inv_dict),
                     axis=1).sum()

输出:

     Action_new  Object_new  Total_Cost
0      renovate         123       12000
1  do something         456          10
2        review         789        1050

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章