首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pandas未熔断数据集

Pandas未熔断数据集
EN

Stack Overflow用户
提问于 2017-02-05 07:01:40
回答 2查看 207关注 0票数 1

我有一个这样的数据集

代码语言:javascript
复制
    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中将它转换为这个

代码语言:javascript
复制
CookieID          Item1 Item2
ERG-278-RREDD     5651  2377
STQ-134-DDVH      1217  1798
XYZ-541-EFFG      1234  2378

我试着使用数据透视表,但是,它不起作用。下面是我的数据透视表命令

代码语言:javascript
复制
dfunmelt = pd.pivot_table(dfmelt, index=['CookieID'],columns='ItemID',aggfunc=len)

如何实现上述输出?

EN

回答 2

Stack Overflow用户

发布于 2017-02-05 07:41:58

  • set_index + ffill
  • groupby + cumcount
  • reassign index
  • unstack + rename

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2017-02-05 18:05:22

下面是一个使用pivot_table的单行代码

代码语言:javascript
复制
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

详细信息

assignNaN值创建一个新列。

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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()获取列名。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42046629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档