【问题标题】:Update row values using other row values while iterating over a Pandas dataframe在遍历 Pandas 数据框时使用其他行值更新行值
【发布时间】:2021-07-03 07:17:34
【问题描述】:

我有一个数据框 A,其中包含多个列,这是两个数据框合并的结果。合并后,我需要根据其他列的值更新A中答案列的值。

伪代码:

    for all agreements in A :
       if the length of the value in the year column in A is less than four:
          update string in answer column of A without the value from year column
       else: 
          update string in answer column of A with the value from year column

我正在尝试什么:

for row in A.itertuples() :
  if len(str(A.Year)) < 4 : 
    row.answer = 'Status on ' + row.Name + ' is ' + row.Status 

  else :
    row.answer = 'Status on ' + row.Name + ' ' + str(row.Year) + ' is ' + row.Status 

我收到一个错误 AttributeError: can't set attribute

有什么建议吗?

【问题讨论】:

    标签: python pandas dataframe loops attributeerror


    【解决方案1】:

    由于没有示例数据,我无法解释为什么代码会出现错误。不过你可以试试apply()

    def generate_answer(row):
      if len(str(row.Year)) < 4 :
        return ('Status on ' + row.Name + ' is ' + row.Status)
      else :
        return ('Status on ' + row.Name + ' ' + str(row.Year) + ' is ' + row.Status)
    
    A['answer'] = A.apply(generate_answer, axis=1)
    

    【讨论】:

    • @Andreas 如果您可以发布一些示例数据。我很乐意帮助您找出您的代码出了什么问题。
    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2017-10-23
    • 2021-02-01
    • 1970-01-01
    • 2014-11-21
    • 2022-01-20
    相关资源
    最近更新 更多