根据是否指定筛选值筛选数据帧

2024-04-19 11:52:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,它将返回一系列满足某些条件的数据帧行。你知道吗

说白了,它看起来像这样:

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))

我知道它不会像这样工作-但什么是一个功能和(如果可能的话)优雅的方式来解决这个问题?你知道吗


Tags: 数据函数iddatagetscandeftype
1条回答
网友
1楼 · 发布于 2024-04-19 11:52:44

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

# 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

相关问题 更多 >