将方法应用于Pandas DataFrame中的列

时间:2017-05-18 21:52:24

标签: python pandas dataframe

我有一个通过Pandas导入的数据集,其中包含一个包含字符串的数组,即:

    'Entry'
0   ['test', 'test1', test2']
.
.
.
[n] ['test', 'test1n', 'test2n']

我想要做的是应用一个函数来确保数组中没有类似的元素。我的方法如下:

def remove_duplicates ( test_id_list ):
    new_test_ids = []
    for tags in test_id_list:
        if tags not in new_test_ids:
            new_test_ids.append(tags)
    return new_test_ids

我想通过apply()maps()将其应用于我的DataFrame中的“Entry”列,以清理每个列条目。我是通过

这样做的

training_data['Entry'].apply(remove_duplicates(training_data['Entry']))

但我收到错误:

Traceback (most recent call last):
  File "/home/main.py", line 32, in <module>
    training_data['Entry'].apply(remove_duplicates(training_data['Entry']))
  File "/home/~~~~/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2294, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/src/inference.pyx", line 1207, in pandas.lib.map_infer (pandas/lib.c:66124)
TypeError: 'list' object is not callable

如果有人可以帮我指出正确的方向,那将是美妙的!我现在有点迷失/使用Pandas进行数据操作。

2 个答案:

答案 0 :(得分:0)

如果你稍微分解你的表达,你可以看出错误。

training_data['Entry'].apply(remove_duplicates(training_data['Entry']))

在功能上等同于

x = remove_duplicates(training_data['Entry'])
training_data['Entry'].apply(x)

x是一个列表,因为这是remove_duplicates函数返回的内容。当Rauch指出时,apply方法需要函数,因此您希望x只是remove_duplicates

答案 1 :(得分:0)

<强>设置

df
Out[1190]: 
                    Entry
0     [test, test, test2]
1  [test, test1n, test2n]

要使代码正常工作,您可以这样做:

df.Entry.apply(func=remove_duplicates)
Out[1189]: 
0             [test, test2]
1    [test, test1n, test2n]
Name: Entry, dtype: object

如果没有自定义功能,您实际上可以执行此操作:

df.Entry.apply(lambda x: list(set(x)))
Out[1193]: 
0             [test, test2]
1    [test, test2n, test1n]
Name: Entry, dtype: object