【问题标题】:loop columns to create new columns循环列以创建新列
【发布时间】:2018-11-19 03:43:24
【问题描述】:

我的数据如下:

# data
A    B    C
5    10   20
30   90   270
6    36   54

我使用以下代码创建新列:

data['A/B'] = wine['A'] / wine['B']
data['A/C'] = wine['A'] / wine['C']
data['B/C'] = wine['B'] / wine['C']

# data
A    B    C     A/B     A/C     B/C
5    10   20    1/2     1/4     1/2
30   90   270   1/3     1/9     1/3
6    36   54    1/6     1/9     2/3

如果我有很多列,如何使用 for 循环创建新列?或者在不使用 for 循环的情况下还有其他好的解决方案。

【问题讨论】:

    标签: python for-loop data-manipulation


    【解决方案1】:

    我只能想到使用for循环和排列,下面是我的尝试。

    import pandas as pd
    import numpy as np
    from itertools import permutations
    
    df = pd.DataFrame(np.random.randint(0,5,size=(5, 3)), columns=list('ABC'))
    
    func = lambda d,x,y: d[x]/d[y]
    perms = [x for x in permutations('ABC', 2)]
    for p in perms:
        x,y = p
        s = r'/'.join([x,y])
        df[s]=func(df,x,y)
    print(df)
    
    
    A   B   C   A/B A/C B/A B/C C/A C/B
    0   0   4   1   0.000000    0.0 inf 4.00    inf 0.250000
    1   4   3   4   1.333333    1.0 0.750000    0.75    1.000000    1.333333
    2   3   0   2   inf 1.5 0.000000    0.00    0.666667    inf
    3   4   2   1   2.000000    4.0 0.500000    2.00    0.250000    0.500000
    4   3   0   1   inf 3.0 0.000000    0.00    0.333333    inf
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2019-08-12
      • 2018-12-03
      • 2013-03-04
      • 2013-04-29
      • 2021-03-31
      相关资源
      最近更新 更多