我有一个这样的数据集
CookieID ItemID
0 ERG-278-REDD 5651
1 NaN 2377
2 STQ-134-DDVH 1217
3 NaN 1798
4 XYZ-541-EFFG 1234
5 NaN 2378我想在Pandas中将它转换为这个
CookieID Item1 Item2
ERG-278-RREDD 5651 2377
STQ-134-DDVH 1217 1798
XYZ-541-EFFG 1234 2378我试着使用数据透视表,但是,它不起作用。下面是我的数据透视表命令
dfunmelt = pd.pivot_table(dfmelt, index=['CookieID'],columns='ItemID',aggfunc=len)如何实现上述输出?
发布于 2017-02-05 07:41:58
set_index + ffillgroupby + cumcountindexunstack + renames = df.set_index(df.CookieID.ffill()).ItemID
c = s.groupby(level=0).cumcount() + 1
s.index = [s.index, c]
s.unstack().rename(columns='Item_{}'.format)
Item_1 Item_2
CookieID
ERG-278-REDD 5651 2377
STQ-134-DDVH 1217 1798
XYZ-541-EFFG 1234 2378发布于 2017-02-05 18:05:22
下面是一个使用pivot_table的单行代码
In [371]: (df.assign(no = df['CookieID']isnull().astype(int))
.ffill()
.pivot_table(index='CookieID', values='ItemID', columns='no', aggfunc='sum')
.rename(columns='Item_{}'.format))
Out[371]:
no Item_0 Item_1
CookieID
ERG-278-REDD 5651 2377
STQ-134-DDVH 1217 1798
XYZ-541-EFFG 1234 2378详细信息
assign为NaN值创建一个新列。
In [372]: df.assign(no = df.CookieID.isnull().astype(int))
Out[372]:
CookieID ItemID no
0 ERG-278-REDD 5651 0
1 NaN 2377 1
2 STQ-134-DDVH 1217 0
3 NaN 1798 1
4 XYZ-541-EFFG 1234 0
5 NaN 2378 1然后使用ffill填充NaN值
In [373]: df.assign(no = df.CookieID.isnull().astype(int)).ffill()
Out[373]:
CookieID ItemID no
0 ERG-278-REDD 5651 0
1 ERG-278-REDD 2377 1
2 STQ-134-DDVH 1217 0
3 STQ-134-DDVH 1798 1
4 XYZ-541-EFFG 1234 0
5 XYZ-541-EFFG 2378 1然后,您可以按原样使用pivot_table
In [374]: df.assign(no = df.CookieID.isnull().astype(int)).ffill().pivot_table(ind
...: ex='CookieID', values='ItemID', columns='no', aggfunc='sum')
Out[374]:
no 0 1
CookieID
ERG-278-REDD 5651 2377
STQ-134-DDVH 1217 1798
XYZ-541-EFFG 1234 2378使用rename()获取列名。
https://stackoverflow.com/questions/42046629
复制相似问题