在 pandas 系列上使用 .apply() 时出现 Str 属性错误
Str attribute error when using .apply() on a pandas series
我有一个df如下:
data = {'Internal': ['unpaid second interator 4,000 USD and third', '35 $ unpaid', "all good"],
'Name': ['Charlie', 'Rodolf', 'samuel']}
df = pd.DataFrame(data)
print (df)
我想 运行 这个公式与 .apply():
def unspent(row):
if row['Internal'].str.contains('unspent',case=False)==True:
val="unspent in text"
else:
val="unspent is NOT in text"
return val
& 得到带有附加列的 table:
df['Unspent']=df.apply(unspent,axis=1)
但我得到了一个错误:
AttributeError: 'str' object has no attribute 'str'
我尝试在公式 def unspent
中省略 .str.
并得到另一个错误:
AttributeError: 'str' object has no attribute 'contains'
问题是,您正在尝试对字符串使用 str.contains
,这是一个 pandas 系列方法(因为 row['Internal']
是每个 row
的字符串)
你可以做的是替换
if row['Internal'].str.contains('unspent',case=False)==True:
和
if 'unspent' in row['Internal']:
在您的函数中或在 df['Internal']
列上使用 str.contains
创建一个布尔系列并使用 np.where
到 select 值:
df['Unspent'] = np.where(df['Internal'].str.contains('unspent', case=False), "unspent in text", "unspent is NOT in text")
输出:
Internal Name \
0 unpaid second interator 4,000 USD and third Charlie
1 35 $ unpaid Rodolf
2 all good samuel
Unspent
0 unspent is NOT in text
1 unspent is NOT in text
2 unspent is NOT in text
我有一个df如下:
data = {'Internal': ['unpaid second interator 4,000 USD and third', '35 $ unpaid', "all good"],
'Name': ['Charlie', 'Rodolf', 'samuel']}
df = pd.DataFrame(data)
print (df)
我想 运行 这个公式与 .apply():
def unspent(row):
if row['Internal'].str.contains('unspent',case=False)==True:
val="unspent in text"
else:
val="unspent is NOT in text"
return val
& 得到带有附加列的 table:
df['Unspent']=df.apply(unspent,axis=1)
但我得到了一个错误:
AttributeError: 'str' object has no attribute 'str'
我尝试在公式 def unspent
中省略 .str.
并得到另一个错误:
AttributeError: 'str' object has no attribute 'contains'
问题是,您正在尝试对字符串使用 str.contains
,这是一个 pandas 系列方法(因为 row['Internal']
是每个 row
的字符串)
你可以做的是替换
if row['Internal'].str.contains('unspent',case=False)==True:
和
if 'unspent' in row['Internal']:
在您的函数中或在 df['Internal']
列上使用 str.contains
创建一个布尔系列并使用 np.where
到 select 值:
df['Unspent'] = np.where(df['Internal'].str.contains('unspent', case=False), "unspent in text", "unspent is NOT in text")
输出:
Internal Name \
0 unpaid second interator 4,000 USD and third Charlie
1 35 $ unpaid Rodolf
2 all good samuel
Unspent
0 unspent is NOT in text
1 unspent is NOT in text
2 unspent is NOT in text