Python 3.x 在单个级别上添加新列时,如何使用pandas group by?
原始数据如下所示:Python 3.x 在单个级别上添加新列时,如何使用pandas group by?,python-3.x,pandas,dataframe,group-by,grouping,Python 3.x,Pandas,Dataframe,Group By,Grouping,原始数据如下所示: Date E 0 2017-09-01 - 1 2017-09-01 + 2 2017-09-01 + 3 2017-09-01 + ... ... 应用groupby后: df.groupby(['Date', 'E'])['Date'].count().to_frame(name = 'Count').reset_index() 我得到的数据帧如下所示: Date E
Date E
0 2017-09-01 -
1 2017-09-01 +
2 2017-09-01 +
3 2017-09-01 +
...
...
应用groupby后:
df.groupby(['Date', 'E'])['Date'].count().to_frame(name = 'Count').reset_index()
我得到的数据帧如下所示:
Date E Count
0 2017-09-01 + 11
1 2017-09-01 - 1
2 2017-09-04 + 1
3 2017-09-04 - 7
4 2017-09-05 + 1
5 2017-09-05 - 23
Date + -
0 2017-09-01 11 1
2 2017-09-04 1 7
4 2017-09-05 1 23
我如何将其转换为如下所示的数据帧:
Date E Count
0 2017-09-01 + 11
1 2017-09-01 - 1
2 2017-09-04 + 1
3 2017-09-04 - 7
4 2017-09-05 + 1
5 2017-09-05 - 23
Date + -
0 2017-09-01 11 1
2 2017-09-04 1 7
4 2017-09-05 1 23
我认为使用更好,因为用于计算非NaN
值
然后通过以下方式重塑:
较少的键入解决方案,但在较大的df中,slowier是:
或者,使用
pd.crosstab
In [1736]: pd.crosstab(df.Date, df.E)
Out[1736]:
E + -
Date
2017-09-01 3 1
2017-09-02 1 0
或者,pivot\u表
In [1737]: pd.pivot_table(df, index=['Date'], columns=['E'], aggfunc=len, fill_value=0)
Out[1737]:
E + -
Date
2017-09-01 3 1
2017-09-02 1 0