我有这样的数据集
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)
如何实现上述输出?
答案 0 :(得分:2)
set_index
+ ffill
groupby
+ cumcount
index
unstack
+ rename
s = 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
答案 1 :(得分:2)
这是使用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()
获取列名称。