【问题标题】:Pandas "cut" based on other column熊猫根据其他专栏“切”
【发布时间】:2019-05-08 23:46:56
【问题描述】:

我想在我的 pandas 数据框的一些变量中使用 pd.cut(将连续变量转换为离散变量),但我希望该剪切依赖于其他列。想象一下,我想要 3 个垃圾箱。

例如:

+------+------+------+--------+
| col1 | col2 | col3 | sector |
+------+------+------+--------+
| 4.5  | 6    | 7    | a      |
+------+------+------+--------+
| 8    | 9    | 17   | a      |
+------+------+------+--------+
| 0    | 9    | 8    | b      |
+------+------+------+--------+
| 8    | 9    | 0    | b      |
+------+------+------+--------+
| 1    | 2    | 3.5  | b      |
+------+------+------+--------+

我只想根据sector 将col1 和col2 切割成3 个bin,以便为每个扇区执行切割。这对于比较不同来源的变量非常有用。

结果会是(它是虚构的,不要指望它是 100% 准确的):

+----------+----------+------+--------+
| col1_cut | col2_cut | col3 | sector |
+----------+----------+------+--------+
| 2        | 2        | 7    | a      |
+----------+----------+------+--------+
| 3        | 3        | 17   | a      |
+----------+----------+------+--------+
| 1        | 3        | 8    | b      |
+----------+----------+------+--------+
| 3        | 3        | 0    | b      |
+----------+----------+------+--------+
| 1        | 1        | 3.5  | b      |
+----------+----------+------+--------+

PS:我做这个问答是因为我遇到了这个问题并且找不到 自己解决。随意回答您自己的解决方案或改进 我的,感谢您的反馈。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为可以缩短为

    s=pd.concat([y[['col1','col2']].apply(pd.cut,bins=3,labels=False)for x, y in df.groupby('sector')])
    s
    Out[157]: 
       col1  col2
    0     0     0
    1     2     2
    2     0     2
    3     2     2
    4     0     0
    
    df.update(s)
    

    【讨论】:

    • 哇,谢谢。很好的解决方案,但是我如何保留其余的列,就像我的解决方案一样?
    【解决方案2】:

    要执行该操作,您只需要:

    col_add = []
    
    sectors = df['sector'].unique()
    
    for col in df.columns:
        if col in ['col1','col2']:
            col_add.append(col)
            df['{}_cut'.format(col)] = 0 # Initialized (not needed but I like to)
            for sector in sectors:
                df['{}_cut'.format(col)][df['sector'] == sector] = pd.cut(df[col][df['sector'] == sector], 3, labels=False)
    
    df.drop(col_add, axis = 1, inplace = True) # Remove old cols
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2021-10-18
      • 2018-04-26
      • 2019-12-09
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2020-10-21
      相关资源
      最近更新 更多