【问题标题】:Filter Pandas DataFrame depending on whether the filter value is specified [duplicate]根据是否指定过滤器值过滤 Pandas DataFrame [重复]
【发布时间】:2016-03-11 10:36:45
【问题描述】:

我正在尝试编写一个函数,该函数将返回一系列满足某些条件的 DataFrame 行。

说白了就是这样:

def get_measurement(measurements_base, data_selection, condition_id="", subject_id="", scan_type_id=""):
        measurement_path = data_selection[(data_selection["condition"] == condition_id)&(data_selection["subject"] == subject_id)&(data_selection["scan_type"] == scan_type_id)]["measurement"]

然而,我希望每个条件(由& 分隔的语句)仅在实际指定要检查的变量时应用。比如:

logical_set=[]
if condition_id:
    logical_set.extend((data_selection["condition"] == condition_id))

我知道它不会像这样工作 - 但是解决这个问题的有效且(如果可能)优雅的方法是什么?

【问题讨论】:

    标签: python pandas dataframe filtering


    【解决方案1】:

    你可以先初始化一个全真布尔选择掩码,然后用每个指定的条件更新掩码:

    # Assuming df is the input DataFrame
    mask = pd.Series(True, index=df.index)
    if condition_id:
        mask &= df['condition_id'] == condition_id
    if subject_id:
        mask &= ...
    

    如果您有很多列,最好使用字典来表示条件。那么,一个更通用的选择函数可以实现如下:

    def get_measurement(df, conditions):
        mask = pd.Series(True, index=df.index)
        for k, v in conditions.iteritems():
            mask &= (df[k] == v)
        return df[mask]
    
    df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'measurement': [100,200,300]})
    print df
    print get_measurement(df, {'a': 1, 'b': 4})
    

    输出:

    # Input
       a  b  measurement
    0  1  4          100
    1  2  5          200
    2  3  6          300
    
    # Selected using {'a': 1, 'b': 4}
       a  b  measurement
    0  1  4          100
    

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 2022-12-04
      • 2018-01-02
      • 1970-01-01
      • 2019-04-29
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多