"'Series' object has no attribute 'gender'", u'occurred at index id')
这一类的报错都是因为没有axis=1
import pandas as pd
df = pd.DataFrame([
['JOHN SMITH', 'Male'],
['Jane Doe', 'Female'],
['joe schmo', 'Female']
],
columns=['last_name', 'gender'])
df['salutation']=df.apply(lambda row:'Dear Mr. %s'%row.last_name if row.gender=='Male' else'Dear Ms. %s'%row.last_name,axis=1)
print(df)
输出:
last_name gender salutation
0 JOHN SMITH Male Dear Mr. JOHN SMITH
1 Jane Doe Female Dear Ms. Jane Doe
2 joe schmo Female Dear Ms. joe schmo
you also can use:
orders['salutation']=orders.apply(lambda row:'Dear %s %s'%('Mr.' if row.gender=='Male' else 'Ms.',row.last_name),axis=1)
or:
mylambda = lambda row: \
'Dear Mr. {}'.format(row.last_name) \
if row.gender == 'male' \
else 'Dear Ms. {}'.format(row.last_name)