【问题标题】:Add a new column with values based on groupby values two other columns添加一个新列,其值基于 groupby 值另外两列
【发布时间】:2020-01-21 09:38:42
【问题描述】:

我正在尝试根据原始数据框的 groupby 向数据框添加新列,并根据该 groupby 的结果分配三个值之一

即在下面的 df 中,我想添加第四列来显示我是否有太多的 'A'、太多的 'C' 或只是适量。

    col1 col2  col3
0   1111    A     1
1   1111    B     3
2   1111    B     3
3   1111    B     3
4   1111    C     1
5   2222    A     1
6   2222    B     1
7   2222    C     2
8   2222    C     2
9   3333    A     2
10  3333    A     2
11  3333    B     1
12  3333    C     1

变成……

    col1 col2  col3 col4
0   1111    A     1   OK
1   1111    B     3   OK
2   1111    B     3   OK
3   1111    B     3   OK
4   1111    C     1   OK
5   2222    A     1   >C
6   2222    B     1   >C
7   2222    C     2   >C
8   2222    C     2   >C
9   3333    A     2   >A
10  3333    A     2   >A
11  3333    B     1   >A
12  3333    C     1   >A

我正在考虑使用转换,但它返回系列,我认为在这种情况下我需要检查两个不同的列?

例子:

d1 = {'col1': ['1111', '1111', '1111', '1111', '1111', '2222', '2222', '2222', '2222', '3333', '3333', '3333', '3333'],
      'col2': ['A', 'B', 'B', 'B', 'C', 'A', 'B', 'C', 'C', 'A', 'A', 'B', 'C'],
      'col3': [1, 3, 3, 3, 1, 1, 1, 2, 2, 2, 2, 1, 1]}
df1 = pd.DataFrame(data=d1)
d2 = {'col1': ['1111', '1111', '1111', '1111', '1111', '2222', '2222', '2222', '2222', '3333', '3333', '3333', '3333'],
      'col2': ['A', 'B', 'B', 'B', 'C', 'A', 'B', 'C', 'C', 'A', 'A', 'B', 'C'],
      'col3': [1, 3, 3, 3, 1, 1, 1, 2, 2, 2, 2, 1, 1],
      'col4': ['OK', 'OK', 'OK', 'OK', 'OK', '>C', '>C', '>C', '>C', '>A', '>A', '>A', '>A']}
df2 = pd.DataFrame(data=d2)
print(df1)
print(df2)

【问题讨论】:

  • A 和 C 都多时会发生什么?
  • 为什么OK 值?因为3?还是因为3B
  • 您能说明一下您是如何填充第 4 列的吗?

标签: python pandas group-by


【解决方案1】:

据我了解,试试这个:

获取counts using crosstab of col2 wrt col1 值,然后使用.loc[] 过滤您要考虑的值,然后使用df.gt 比较计数是否大于1,并与列进行dot 乘法名字,最后map 回来series.fillna

解决方案:

values_to_filter = ['A','C'] #put B for testing and it will show >B for first group
m = pd.crosstab(df1['col1'],df1['col2']).loc[:,values_to_filter]
df1['col4'] = (df1['col1'].map(m.gt(1).dot(m.columns).replace('',np.nan)
                                             .radd('>')).fillna('OK'))

输出:

print(df1)

    col1 col2  col3 col4
0   1111    A     1   OK
1   1111    B     3   OK
2   1111    B     3   OK
3   1111    B     3   OK
4   1111    C     1   OK
5   2222    A     1   >C
6   2222    B     1   >C
7   2222    C     2   >C
8   2222    C     2   >C
9   3333    A     2   >A
10  3333    A     2   >A
11  3333    B     1   >A
12  3333    C     1   >A

其他详细信息:其中mcol2 值w.r.t col1 值的计数:

print(m)

col2  A  C
col1      
1111  1  1
2222  1  2
3333  2  1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 2022-12-01
    • 2019-08-06
    • 2013-09-05
    • 2021-01-18
    • 2020-09-16
    • 2022-11-21
    • 2021-12-02
    相关资源
    最近更新 更多