循环列以创建新列

时间:2018-11-19 03:43:24

标签: python for-loop data-manipulation

我的数据如下:

# 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循环。

1 个答案:

答案 0 :(得分:0)

我只能想到使用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
相关问题