簡體   English   中英

如何基於字典在多列上過濾熊貓數據框?

[英]How to filter pandas dataframe on multiple columns based on a dictionary?

我有3本字典:A,B,C

以及帶有以下列的熊貓數據框:

['id',
 't1',
 't2',
 't3',
 't4']

現在,我只想保留那些在字典A中出現t1,在字典B中出現t2和在字典C中出現t3的行。

我在A中嘗試了dataframe ['t1'],這給出了一個錯誤:Series對象是可變的,無法進行哈希處理...

您可以嘗試這樣。

df.loc[(df['t1'].isin(A.keys()) & df['t2'].isin(B.keys()) & df['t3'].isin(C.keys()))]

我希望這就是你想要的。

In [51]: df
Out[51]: 
   t1  t2  t3  t4  max_value
0   1   4   5   2          5
1  34  70   1   5         70
2  43  89   4  11         89
3  22  76   4   3         76

In [52]: A = {34: 4}

In [53]: B = {70: 5, 89: 3}

In [54]: C = {1: 3, 5:1}

In [55]: df.loc[(df['t1'].isin(A.keys()) & df['t2'].isin(B.keys()) & df['t3'].isin(C.keys()))]
Out[55]: 
   t1  t2  t3  t4  max_value
1  34  70   1   5         70

為了回答@EdChum,我假設OP想要檢查字典鍵中值的存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM