【问题标题】:Pandas - Add Column Name to Results of groupby [duplicate]Pandas - 将列名添加到 groupby 的结果 [重复]
【发布时间】:2018-12-12 07:44:40
【问题描述】:

我想将列名添加到 Python 3.6 中 DataFrame 上的 groupby 的结果中。

我试过这段代码:

import pandas as pd
d = {'timeIndex': [1, 1, 1, 1, 2, 2, 2], 'isZero': [0,0,0,1,0,0,0]}
df = pd.DataFrame(data=d)
df2 = df.groupby(['timeIndex'])['isZero'].sum()
print(df2)

结果

timeIndex
1    1
2    0
Name: isZero, dtype: int64

看起来timeIndex 是一个列标题,但尝试按名称寻址列会产生异常。

df2['timeIndex']
# KeyError: 'timeIndex'

df2['isZero']
# KeyError: 'isZero'

我正在寻找这个结果。

df2 

     timeIndex    isZero
0    1    1
1    2    0

df2['isZero']

0    1
1    0

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    方法一:

    groupby 中使用参数as_index = False

    df2 = df.groupby(['timeIndex'], as_index=False)['isZero'].sum()
    
    >>> df2
       timeIndex  isZero
    0          1       1
    1          2       0
    
    >>> df2['isZero']
    0    1
    1    0
    Name: isZero, dtype: int64
    

    方法二:

    您可以使用 to_frame 和所需的列名,然后使用 reset_index

    df2 = df.groupby(['timeIndex'])['isZero'].sum().to_frame('isZero').reset_index()
    
    >>> df2
       timeIndex  isZero
    0          1       1
    1          2       0
    
    >>> df2['isZero']
    0    1
    1    0
    Name: isZero, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-23
      • 2020-06-22
      • 2017-04-18
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多