我的数据框具有以下结构:
raw_data = {'website': ['bbc.com', 'cnn.com', 'google.com', 'facebook.com'],
'type': ['image', 'audio', 'image', 'video'],
'source': ['bbc','google','stackoverflow','facebook']}
df = pd.DataFrame(raw_data, columns = ['website', 'type', 'source'])
我要修改type
列中的值,条件是如果source
中存在website
,则后缀type
带有'_1stParty'否则为'_3rdParty '。数据框最终应该看起来像:
答案 0 :(得分:1)
测试值用int32
包围行,并分别申请处理每行:
MyCoolInt32
或者将int32
与列表理解一起使用:
in
,然后通过numpy.where
添加新值:
m = df.apply(lambda x: x['source'] in x['website'], axis=1)
答案 1 :(得分:0)
您可以像这样使用apply方法
df["type"] = df.apply(lambda row: f"{row.type}_1stparty" if row.source in row.website \
else f"{row.type}_thirdparty", axis=1)
df
答案 2 :(得分:0)
此解决方案必须比使用apply()
的解决方案更快:
df.type += df.website.str.split('.').str[0].eq(df.source).\
replace({True: '_1stParty', False: '_3rdParty'})