【问题标题】:change multiple dataframe columns based on list of users根据用户列表更改多个数据框列
【发布时间】:2022-01-10 18:53:30
【问题描述】:

假设我在 pandas 中有这个数据框:

data = {'user':['Apple', 'One', 'Tom'], 
        'col_1':[1, 2, 3],
        'col_2':[4, 5, 6],
        'col_3':[7, 8, 9]
}

df = pd.DataFrame(data)

哪些输出:

user col_1 col_2 col_3
Apple 1 2 3
One 4 5 6
Tom 7 8 9

现在,这是一笔交易:如果用户在特定的用户列表中,我想修改列 col_1col_2col_3 的值。否则,我必须保留列的当前值。

我的建议:

首先,我创建了一个字典,其中的键显示需要修改的用户。此外,我为每个用户创建了一个新值列表(分别为col_1col_2col_3)这样:

my_dict = {
    'one'  : ['col_1_value_one', 'col_2_value_one', 'col_3_value_one'],
    'two'  : ['col_1_value_two', 'col_2_value_two', 'col_3_value_two'],
    'apple': ['col_1_value_apple', 'col_2_value_apple', 'col_3_value_apple']
}

然后,我根据字典键创建了一个列表:

list_users = list(my_dict.keys())

最后,我能够通过使用np.wherecontains 和一些正则表达式来验证用户是否确实在密钥列表中(这就是为什么我用“|”加入列表的原因 并使用lower())。如果用户不在列表中,则在保留“旧”值时它可以正常工作。

df['col_1'] = np.where(df['user'].str.lower().str.contains('|'.join(list_users), na=False, regex=True), 
                                        "<I need to replace this!>", 
                                        df['col_1'])
df['col_2'] = np.where(df['user'].str.lower().str.contains('|'.join(list_users), na=False, regex=True), 
                                        "<I need to replace this!>", 
                                        df['col_2'])
df['col_3'] = np.where(df['user'].str.lower().str.contains('|'.join(list_users), na=False, regex=True), 
                                        "<I need to replace this!>", 
                                        df['col_3'])    

但是,如您所见,如果用户实际上在列表中,我无法找到替换字典值中存在的值的方法。例如,如果用户是“Apple”,那么col_1col_2col_3 的新值是:

  • col_1_value_apple
  • col_2_value_apple
  • col_3_value_apple

基于示例的预期输出:

user col_1 col_2 col_3
Apple col_1_value_apple col_2_value_apple col_3_value_apple
One col_1_value_one col_2_value_one col_3_value_one
Tom 7 8 9

这里,"Apple""One" 用户都被修改了,而 "Tom" 不在列表中,因此保留它们的原始值。

我确信这不是解决此问题的最佳方法,但我们将不胜感激任何帮助!谢谢!

【问题讨论】:

    标签: python pandas dataframe numpy


    【解决方案1】:

    这行得通:

    for name, cols in my_dict.items():
        df.loc[df['user'].str.lower() == name, ['col_1', 'col_2', 'col_3']] = cols
    

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 2018-12-24
      • 2020-04-15
      • 1970-01-01
      • 2018-09-06
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      相关资源
      最近更新 更多