1

我需要以与 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

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

4

1 回答 1

2

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

对于具有以下内容的文件filee.csv :

Name,LastName
Andy,Blue
Joe,Smith 

在 else 之后,需要返回一个Last Name字符串而不是一个 row 对象,如下所示: 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['LastName']

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

产生以下输出:

   Name LastName
0  Andy     Blue
1   Joe    Black
于 2013-05-09T00:27:11.147 回答