在 Pandas 中传递基本功能时遇到问题

Trouble passing basic function in Pandas

我有一个非常基本的函数,它获取字符串的前六个字母。我想将它应用到我的 DataFrame 中的列。

代码:

import re
import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,5,np.NaN], 
                    'B' : [1,0,3,5,0,0,np.NaN,9,0,0], 
                    'C' : ['AA1233445','A9875', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'], 
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Unassign','Assign','Ugly','Appreciate','Undo','Assign','Unicycle','Assign','Unicorn',]})
def six_dig(thing):
    return str(thing)[:6]

dfp6= dfp[dfp['C'].apply(six_dig, axis=1)]

但我得到:TypeError: six_dig() got an unexpected keyword argument 'axis' 我什至尝试使用 .map() 但得到了同样的错误。

如果我删除 axis=1 我得到:KeyError: ["STUFF"] not in index

我一定是遗漏了一些非常简单的东西,因为我之前在 DataFrame 列上使用过函数...

我想你可以:

dfp6 = dfp['C'].str[:6]

这个returns:

In [14]: dfp6
Out[14]: 
0    AA1233
1     A9875
2     rmacy
3    Idaho 
4    Ab1234
5    TV1928
6        RX
7    Ohio D
8    RX1234
9    USA Ph
Name: C, dtype: object

使用您的示例,以下工作正常:

print(dfp['C'].map(six_dig))
0    AA1233
1     A9875
2     rmacy
3    Idaho 
4    Ab1234
5    TV1928
6        RX
7    Ohio D
8    RX1234
9    USA Ph
Name: C, dtype: object

如果你想使用向量化函数——这里有一个例子:

In [35]: def my_slice(ser, start=0, end=10, step=1):
    ...:     return ser.str.slice(start, end, step)
    ...:

In [36]: my_slice(dfp.C, end=6)
Out[36]:
0    AA1233
1     A9875
2     rmacy
3    Idaho
4    Ab1234
5    TV1928
6        RX
7    Ohio D
8    RX1234
9    USA Ph
Name: C, dtype: object