【问题标题】:Selecting part of a dataframe based on whether element is in an external array根据元素是否在外部数组中选择数据框的一部分
【发布时间】:2017-03-20 03:45:09
【问题描述】:

我正在尝试选择满足某个条件的 pandas 数据框的一个子部分——在这种情况下,某个列的每个元素都是外部列表的一部分。我惊讶地发现这不起作用,因为其他带有 .loc 的条件语句非常简单。我怎样才能做到这一点?

MWE:

import pandas as pd
import numpy as np

test_dict = {'first': [0,1,0,0,1,0], 'second': [1,2,3,4,5,6]}

test_df =  pd.DataFrame(test_dict)

arr1 = [-1,-4,2,-9,8,7,-5,5,-8,0]
arr2 = [2,5]


new_df1 = test_df.loc[test_df.second in arr1]
new_df2 = test_df.loc[test_df.second in arr2]

print new_df1
print new_df2

【问题讨论】:

    标签: python pandas dataframe selection


    【解决方案1】:

    Series.isin() 是您要找的吗?

    In [55]: new_df1 = test_df.loc[test_df.second.isin(arr1)]
    
    In [56]: new_df2 = test_df.loc[test_df.second.isin(arr2)]
    
    In [57]: new_df1
    Out[57]:
       first  second
    1      1       2
    4      1       5
    
    In [58]: new_df2
    Out[58]:
       first  second
    1      1       2
    4      1       5
    

    您也可以使用类似 SQL 的样式 - DataFrame.query():

    In [60]: test_df.query("second in @arr1")
    Out[60]:
       first  second
    1      1       2
    4      1       5
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2022-10-05
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2018-10-24
      • 2011-04-25
      • 2014-10-20
      • 1970-01-01
      相关资源
      最近更新 更多