【问题标题】:How to create a pandas dataframe vector that has values based on a groupby如何创建具有基于 groupby 值的 pandas 数据框向量
【发布时间】:2020-03-17 11:55:24
【问题描述】:

给定以下数据:

x1 = 'one'
x2 = 'two'
x3 = 'three'
y1 = 'yes'
y2 = 'no'
n = 3


df = pd.DataFrame(dict(
    a = [x1]*n + [x2]*n + [x3]*n,
    b = [
        y1,
        y1,
        y2,
        y2,
        y2,
        y2,
        y2,
        y2,
        y1,
    ]
))

看起来像:

Out[5]:
       a    b
0    one  yes
1    one  yes
2    one   no
3    two   no
4    two   no
5    two   no
6  three   no
7  three   no
8  three  yes

我想知道是否可以按如下方式创建列c

Out[5]:
       a    b   c
0    one  yes   1
1    one  yes   1
2    one   no   1
3    two   no   0
4    two   no   0
5    two   no   0
6  three   no   1
7  three   no   1
8  three  yes   1

如果a 中的组b 包含yes,则c 被定义为1

我尝试了以下方法:

group_results = df.groupby('a').apply(lambda x:  'yes' in x.b.to_list() )
group_results = group_results.reset_index()
group_results = group_results.rename(columns = {0 : 'c'})
df = pd.merge(df, group_results, left_on = 'a', 
                  right_on = 'a', 
                  how = 'left').copy()

但我觉得好像有更好的方法。

【问题讨论】:

    标签: python pandas conditional-statements grouping


    【解决方案1】:

    a 列中至少有一个yes 的测试组使用Series.isin,最后使用Series.view 将掩码转换为整数:

    df['c'] = df['a'].isin(df.loc[df['b'].eq('yes'), 'a']).view('i1')
    print(df)
           a    b  c
    0    one  yes  1
    1    one  yes  1
    2    one   no  1
    3    two   no  0
    4    two   no  0
    5    two   no  0
    6  three   no  1
    7  three   no  1
    8  three  yes  1
    

    详情

    print(df.loc[df['b'].eq('yes'), 'a'])
    0      one
    1      one
    8    three
    Name: a, dtype: obje
    

    【讨论】:

      【解决方案2】:

      IIUC,您可以使用Groupby+transformany 在条件系列上分组后检查df['b'] equals 'yes' 并链接astype(int)view 以获得整数repr。

      df['c'] = df['b'].eq('yes').groupby(df['a']).transform('any').view('i1')
      print(df)
      

             a    b  c
      0    one  yes  1
      1    one  yes  1
      2    one   no  1
      3    two   no  0
      4    two   no  0
      5    two   no  0
      6  three   no  1
      7  three   no  1
      8  three  yes  1
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2021-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2021-07-26
        • 2020-07-30
        相关资源
        最近更新 更多