选择具有条件的组中的行

时间:2018-03-23 17:36:33

标签: python pandas

             A    D          E
0   2002-01-13  3.3    Tuesday
1   2002-01-13  3.9  Wednesday
2   2002-01-13  1.9   Thursday
3   2002-01-13  9.0   Saturday
4   2002-01-14  0.9    Tuesday
5   2002-01-14  0.2  Wednesday
6   2002-01-14  5.1   Thursday
7   2002-01-14  7.0     Friday
8   2002-01-14  1.9   Saturday
9   2002-01-15  4.2    Tuesday
10  2002-01-15  6.7  Wednesday
11  2002-01-15  1.2     Friday
12  2002-01-15  0.6   Saturday

我有一个上面按日期排序的数据框(A列)。 E列包含星期几的参考文献。我需要一个新的df,按以下条件过滤行。

  • 如果日期同时包含“星期四”和“星期五”引用(与“2002-01-14”相同),我只想保留引用“星期三”到“星期六”的行。
  • 否则(“2002-01-13”和“2002-01-15” A group 的情况),保持引用“星期二”到“星期六”的行(上面的所有行)例子)。

输出应为:

             A    D          E
0   2002-01-13  3.3    Tuesday
1   2002-01-13  3.9  Wednesday
2   2002-01-13  1.9   Thursday
3   2002-01-13  9.0   Saturday
5   2002-01-14  0.2  Wednesday
6   2002-01-14  5.1   Thursday
7   2002-01-14  7.0     Friday
8   2002-01-14  1.9   Saturday
9   2002-01-15  4.2    Tuesday
10  2002-01-15  6.7  Wednesday
11  2002-01-15  1.2     Friday
12  2002-01-15  0.6   Saturday

我试过了:

m1 = (group["E"] == "Wednesday")
m2 = (group["E"] == "Thursday")

grouped = df.groupby("A")

for idx, group in grouped:

    if (m1|m2).any():
        df[idx] = group[m1|m2]
    else:
        df[idx] = group[m2]

2 个答案:

答案 0 :(得分:1)

groupby上使用简单的自定义函数可以得到答案:

# helper function
def get_grp(grp):

    # values to consider
    a = ['Thursday', 'Friday']

    # set up condition
    cond = all(True if i in grp['E'].tolist() else False for i in a)

    # check conditions
    if cond:
        return grp[grp['E'].isin(['Wednesday','Thursday','Friday','Saturday'])]
    else:
        return grp[grp['E'].isin(['Tuesday','Wednesday','Thursday','Friday','Saturday'])]

## apply function on groupby object

df = df.groupby('A',as_index=False).apply(get_grp).reset_index(drop=True)

## output
df.head(7)

    A   D   E
0   2002-01-13  3.3     Tuesday
1   2002-01-13  3.9     Wednesday
2   2002-01-13  1.9     Thursday
3   2002-01-13  9.0     Saturday
4   2002-01-14  0.2     Wednesday
5   2002-01-14  5.1     Thursday
6   2002-01-14  7.0     Friday
7   2002-01-14  1.9     Saturday

答案 1 :(得分:1)

您可以使用np.whereisin

尝试此操作
df[df.groupby('A')['E']
     .transform(lambda x: np.where(x.eq('Thursday').any() & x.eq('Friday').any(),
                               x.isin(['Wednesday','Thursday','Friday','Saturday']),
                               x.isin(['Tuesday','Wednesday','Thursday','Friday','Saturday'])))]

输出:

             A    D          E
0   2002-01-13  3.3    Tuesday
1   2002-01-13  3.9  Wednesday
2   2002-01-13  1.9   Thursday
3   2002-01-13  9.0   Saturday
5   2002-01-14  0.2  Wednesday
6   2002-01-14  5.1   Thursday
7   2002-01-14  7.0     Friday
8   2002-01-14  1.9   Saturday
9   2002-01-15  4.2    Tuesday
10  2002-01-15  6.7  Wednesday
11  2002-01-15  1.2     Friday
12  2002-01-15  0.6   Saturday