如何组合一列然后将两列分开?

时间:2018-02-16 17:01:39

标签: python pandas

我是pandas的新手,我想在我的pandas数据框中创建一个新列。我想分组一列,然后将另外两列分开。

这完美有效:

 df['new_col'] = (df.col2/df.col3)

然而,当我用另一列分组时,我所拥有的不起作用:

 df['new_col'] = df.groupby('col1')(df.col2/df.col3)

有谁知道如何重写上述代码?谢谢。

2 个答案:

答案 0 :(得分:1)

这可能是您正在寻找的:

import pandas as pd

df = pd.DataFrame([['A', 4, 3], ['B', 2, 4], ['C', 5, 1], ['A', 5, 1], ['B', 2, 7]],
                  columns=['Col1', 'Col2', 'Col3'])

#   Col1  Col2  Col3
# 0    A     4     3
# 1    B     2     4
# 2    C     5     1
# 3    A     5     1
# 4    B     2     7

df['Col4'] = df['Col2'] / df['Col3']
df = df.sort_values('Col1')

#   Col1  Col2  Col3      Col4
# 0    A     4     3  1.333333
# 3    A     5     1  5.000000
# 1    B     2     4  0.500000
# 4    B     2     7  0.285714
# 2    C     5     1  5.000000

或者如果您需要先执行groupby.sum

df = df.groupby('Col1', as_index=False).sum()
df['Col4'] = df['Col2'] / df['Col3']

#   Col1  Col2  Col3      Col4
# 0    A     9     4  2.250000
# 1    B     4    11  0.363636
# 2    C     5     1  5.000000

答案 1 :(得分:1)

设置

df = pd.DataFrame(dict(
    Col1=list('AAAABBBB'),
    Col2=range(1, 9, 1),
    Col3=range(9, 1, -1)
))

df

df.groupby('Col1').sum().eval('Col4 = Col2 / Col3')

  Col1  Col2  Col3
0    A     1     9
1    A     2     8
2    A     3     7
3    A     4     6
4    B     5     5
5    B     6     4
6    B     7     3
7    B     8     2

<强>解决方案
使用pd.DataFrame.eval
我们可以使用eval在管道中创建新列

df.groupby('Col1', as_index=False).sum().eval('Col4 = Col2 / Col3')

  Col1  Col2  Col3      Col4
0    A    10    30  0.333333
1    B    26    14  1.857143