[英]using df.apply to call function associate with different colum
給定一個pd.DataFrame
像:
to_remove pred_0 .... pred_10
0 ['apple'] ['apple','abc'] .... ['apple','orange']
1 ['cd','sister'] ['uncle','cd'] .... ['apple']
在每一行上,如果此元素顯示在同一行的to_remove
中,我想刪除pred_0
... pred_10
元素。
在此示例中,答案應為:
to_remove pred_0 .... pred_10
0 ['apple'] ['abc'].... ['orange'] # remove 'apple' this row
1 ['cd','sister'] ['uncle']....['apple'] # remove 'cd' and 'sister' this row
我想知道如何關聯代碼。
生成示例df:
from collections import OrderedDict
D=pd.DataFrame(OrderedDict({'to_remove':[['apple'],['cd','sister']],'pred_0':[['apple','abc'],['uncle','cd']],'pred_1':[['apple','orange'],['apple']]}))
您可以嘗試逐行進行迭代,並過濾該列中未指定的元素
考慮的數據幀
pred_0 pred_10 to_remove
0 [apple, abc] [apple, orage] [apple]
1 [uncle, cd] [apple] [cd, sister]
df.apply(lambda x: x[x.index.difference(['to_remove'])].apply(lambda y: [i for i in y if i not in x['to_remove']]),1)
日期:
pred_0 pred_10
0 [abc] [orage]
1 [uncle] [apple]
您可以使用幾個列表推導:
s = df['to_remove'].map(set)
for col in ['pred_0', 'pred_1']:
df[col] = [[i for i in L if i not in S] for L, S in zip(df[col], s)]
print(df)
to_remove pred_0 pred_1
0 [apple] [abc] [orange]
1 [cd, sister] [uncle] [apple]
列表pd.DataFrame.apply
可能比pd.DataFrame.apply
更有效,因為pd.DataFrame.apply
為每行構造一個序列並將其傳遞給一個函數非常昂貴。 如您所見,Pandas / NumPy並沒有真正滿足您的需求。
因此,除非您有能力將列表擴展為一系列字符串,否則dict
+ list
可能是更合適的數據結構選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.