【问题标题】:How to subtract from column in Dataframe based on conditions from other columns in row如何根据行中其他列的条件从数据框中的列中减去
【发布时间】:2020-06-25 20:40:28
【问题描述】:

我有一个字典,如下例所示,如果行中的键与字典中的值匹配并且该行中的字符串列是 yes,我试图从 DataFrame 中的列中减去值。

dic = {1:2300,
       2:3000,
       56:572
       37:2930}
df = key   string   value
     1     yes      5000
     4     yes      2000
     56    no       1000
     56    yes      6000
     14    yes      3000

仅当键存在于字典中并且字符串==yes 时,我希望该函数从值列中减去字典值。生成的 Dataframe 如下所示:

after = key   string   value
        1     yes      2700
        4     yes      2000
        56    no       1000
        56    yes      5428
        14    yes      3000

我尝试编写一个循环遍历 Dataframe 的每一行,如果键和字符串值匹配,则用 dic[row] 减去 df['value'],但在尝试调整多个内容后它不起作用。

for row in df:
    if dic.get(row['key'],0)!=0 and row['string']=='yes':
        row['value']=row['value']-dic[row['key']]

此代码不起作用,只是返回“TypeError:字符串索引必须是整数”。我应该改变什么来纠正它?

【问题讨论】:

  • 请提供完整的错误信息。以更方便的格式保存您的数据也将是一件好事。你有没有做过任何研究,阅读过 Pandas 文档?顺便说一句,为什么要使用 "yes"/"no" 而不是正确的布尔值?

标签: python pandas dataframe


【解决方案1】:

为此有 pandas 方法,尽量避免使用不必要的循环,这会减慢和弄脏代码。我们可以使用Series.map 和DataFrame.loc:

df.loc[df['string'].eq('yes'),'value']=(df['value'].sub(df['key'].map(dic))
                                                   .fillna(df['value']))

   key string   value
0    1    yes  2700.0
1    4    yes  2000.0
2   56     no  1000.0
3   56    yes  5428.0
4   14    yes  3000.0

【讨论】:

    【解决方案2】:
    #sample dataframe
    d = {'key': [1,4,56,56,14], 'string': ['yes','yes','no','yes','yes'], 'value': [5000, 2000, 1000, 6000,3000]}
    df = pd.DataFrame(data=d)
    #dictionary
    dic = {1:2300,
           2:3000,
           56:572,
           37:2930}
    
    #iterating through dataframe
    for i, row in df.iterrows():
      #assigning values
      key = df.loc[i,'key']
      string = df.loc[i,'string']
      value = df.loc[i,'value']
      #if key in dictionary and string == yes, get value from dictionary by key and calculate the result
      if key in dic.keys() and string == 'yes':
        dicValue = dic[key]
        result = value - dicValue
        print(result)
    
    

    【讨论】:

    • 请参阅pd.read_clipboard 以复制和使用数据框。另一方面,这里使用循环是低效的
    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多