[英]Update row values using other row values while iterating over a Pandas dataframe
我有一个 dataframe 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
有什么建议么?
由于没有示例数据,我不知道为什么代码会给你错误。 但是您可以尝试使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.