在我的df文件中,下面的每个实体(Grubhub、Toasttab、Tenk)都有一列,并且每行的该列值中都显示“是”或“否”,我有以下代码,例如:df['Grubhub'] = df[['On GrubHub or Seamless?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['ToastTab'] = df[['On ToastTab?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['Tenk'] = df[['On Tenk?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['Udemy'] = df[['On Udmey?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['Postmates'] = df[['On Postmates?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['Doordash'] = df[['On DoorDash?']].apply(lambda x: any(x == 'Yes'), axis = 1)df['Google'] = df[['On Goole?']].apply(lambda x: any(x == 'Yes'), axis = 1)这为每个实体( Grubhub、Toasttab、Tenk )提供了一个新列,并且该列给出了 true 或 false 值,是否有一种更有效的方法可以在一行代码或函数中完成所有这些操作?感谢您提前的帮助
1 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
您可以创建一个列图并应用function内部loop:
columns_map = (
('Grubhub', 'On GrubHub or Seamless?'),
('ToastTab', 'On ToastTab?'),
('Tenk', 'On Tenk?'),
# etc ...
)
for new_col, alias in columns_map:
df[new_col] = df[alias].apply(lambda x: x == 'Yes')
# also you can easily remove aliases columns:
# df = df.drop(columns=[alias])
或者您可以将值设置到原始列中并根据需要重命名(不带drop()):
for new_col, alias in columns_map:
df[alias] = df[alias].apply(lambda x: x == 'Yes')
df.rename(
columns={alias: new_col for new_col, alias in columns_map},
inplace=True
)
添加回答
举报
0/150
提交
取消