[英]how do you filter a Pandas dataframe by a multi-column set?
有沒有辦法通過將多個列與一組元組進行比較來過濾大型 dataframe ,其中元組中的每個元素對應於不同的列值? 例如,是否有.isin()
方法將 DataFrame 的多列與一組元組進行比較?
例子:
df = pd.DataFrame({
'a': [1, 1, 1],
'b': [2, 2, 0],
'c': [3, 3, 3],
'd': ['not', 'relevant', 'column'],
})
# Filter the DataFrame by checking if the values in columns [a, b, c] match any tuple in value_set
value_set = set([(1,2,3), (1, 1, 1)])
new_df = ?? # should contain just the first two rows of df
您可以使用Series.isin
,但首先必須通過前 3 列創建元組:
print (df[df[['a','b','c']].apply(tuple, axis=1).isin(value_set)])
或將列轉換為索引並使用Index.isin
:
print (df[df.set_index(['a','b','c']).index.isin(value_set)])
a b c d
0 1 2 3 not
1 1 2 3 relevant
另一個想法是使用DataFrame.merge
的內部連接,由助手DataFrame
使用相同的 3 個列名,然后應該省略on
參數,因為通過兩個 df 的列名的交集進行連接:
print (df.merge(pd.DataFrame(value_set, columns=['a','b','c'])))
a b c d
0 1 2 3 not
1 1 2 3 relevant
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.