gpt4 book ai didi

python - 尝试更新数据框时出现 Pandas Reduction 错误

转载 作者:行者123 更新时间:2023-12-01 05:44:45 26 4
gpt4 key购买 nike

我需要更新数据框中的一些数据,就像 SQL 中的更新查询一样。我当前的代码如下:

import pandas

df = pandas.read_csv('filee.csv') # load trades from csv file

def updateDataframe(row):
if row['Name'] == "Joe":
return "Black"
else:
return row

df['LastName'] = df.apply(updateDataframe,axis=1)

但是,它返回以下错误:

Traceback (most recent call last):
File "test.py", line 11, in <module>
df['LastName'] = df.apply(updateDataframe,axis=1)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.py", line 2038, in __setitem__
self._set_item(key, value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.py", line 2085, in _set_item
NDFrame._set_item(self, key, value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/generic.py", line 582, in _set_item
self._data.set(key, value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/internals.py", line 1459, in set
_set_item(self.items[loc], value)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/internals.py", line 1454, in _set_item
block.set(item, arr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/internals.py", line 176, in set
self.values[loc] = value
ValueError: output operand requires a reduction, but reduction is not enabled

我该如何解决这个问题。或者有更好的方法来完成我想做的事情吗?

最佳答案

@Jeff 在上面的注释中对您的问题有一个很好的简洁实现,但是如果您想修复代码中的错误,请尝试以下操作:

对于包含以下内容的文件filee.csv:

Name,LastName
Andy,Blue
Joe,Smith

在else之后,您需要返回Last Name字符串而不是行对象,如下所示: 导入 Pandas

df = pandas.read_csv('filee.csv') # load trades from csv file       

def updateDataframe(row):
if row['Name'] == "Joe":
return "Black"
else:
return row['LastName']

df['LastName'] = df.apply(updateDataframe,axis=1)
print df

产生以下输出:

   Name LastName
0 Andy Blue
1 Joe Black

关于python - 尝试更新数据框时出现 Pandas Reduction 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com