給出以下數據:data = pd.DataFrame( dict( source=["file1", "file1", "file2", "file2"], variable=["shipp", "carrr", "shipp", "bikee"], ))vals = pd.Series(["ship", "bike"])看起來像: source variable0 file1 shipp1 file1 carrr2 file2 shipp3 file2 bikee我想創建以下內容: ship bikefile1 True Falsefile2 True True不過,我不確定該怎么做,我嘗試了以下方法:data.groupby("source").apply( lambda grp: pd.Series([any(grp["variable"].str.contains(v)) for v in vals]))這花了我幾次,我現在想知道是否有更好的方法。(歡迎任何幫助編寫更好的標題)
1 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
我們這樣extract做pd.crosstab
data['new']=data.variable.str.extract('('+'|'.join(vals)+')')[0]
s=pd.crosstab(data.source,data.new).astype(bool)
new bike ship
source
file1 False True
file2 True True
添加回答
舉報
0/150
提交
取消