Top 3 items to be shown in wide format in pandas datafram 在pandas数据框中展示的前3个宽格式条目

2024-09-27 09:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧

code    attribute   rank_count
394 Feminine    9
394 Fresh   9
394 Heavy   8
418 Soft    13
418 Fresh   12
418 Clean   11
539 Fresh   14
539 Soft    14
539 Feminine    11
555 Feminine    9
555 Heavy   8
555 Soft    7

上面的dataframe有attributes字段和各种属性的代码字段,它们排在第三列,现在我需要它在下面的格式top1top2top3,应该是这样的

code    top1    top2    top3
394 Feminine (9)    Fresh (9)   Heavy (8)
418 Soft(13)    Fresh (12)  Clean (11)
539 Fresh(14)   soft(14)    Feminine(11)

我无法使用pivot表的属性,因为属性很多,我正在尝试以top3的方式重新排列数据


Tags: 数据代码cleandataframe属性countcodeattribute
2条回答

您可以使用:

df = (df.sort_values(['code','rank_count'], ascending=(True, False))
       .assign(attribute=df['attribute'] + ' (' + df['rank_count'].astype(str) + ')', 
               g=df.groupby('code').cumcount() + 1)
       .query('g < 4')
       .set_index(['code','g'])['attribute']
       .unstack()
       .add_prefix('top')
       .rename_axis(None, axis=1)
       .reset_index())
print (df)
   code          top1        top2           top3
0   394  Feminine (9)   Fresh (9)      Heavy (8)
1   418     Soft (13)  Fresh (12)     Clean (11)
2   539    Fresh (14)   Soft (14)  Feminine (11)
3   555  Feminine (9)   Heavy (8)       Soft (7)

解释:

  1. 每2列的第一个^{}
  2. 将列attributerank_count连接,通过^{}^{}添加新的计数列
  3. 如有必要,用^{}过滤顶部3
  4. 通过^{}^{}重塑形状
  5. ^{}^{}^{}用于更清洁的最终DataFrame

编辑:

不含assign的溶液:

df = df.sort_values(['code','rank_count'], ascending=(True, False))
df['attribute']=df['attribute'] + ' (' + df['rank_count'].astype(str) + ')'
df['g'] = df.groupby('code').cumcount() + 1

df = (df.query('g < 4')
       .set_index(['code','g'])['attribute']
       .unstack()
       .add_prefix('top')
       .rename_axis(None, axis=1)
       .reset_index())
print (df)
   code          top1        top2           top3
0   394  Feminine (9)   Fresh (9)      Heavy (8)
1   418     Soft (13)  Fresh (12)     Clean (11)
2   539    Fresh (14)   Soft (14)  Feminine (11)
3   555  Feminine (9)   Heavy (8)       Soft (7)

这是使用collections.defaultdict的一种方法。你知道吗

from collections import defaultdict
from operator import itemgetter

d = defaultdict(list)

for code, attr, rank in df.itertuples(index=False):
    d[code].append((attr, rank))

d = {k: sorted(v, key=itemgetter(1), reverse=True)[:3] for k, v in d.items()}

res = pd.DataFrame(d).T.reset_index()

print(res)

   index              0            1               2
0    394  (Feminine, 9)   (Fresh, 9)      (Heavy, 8)
1    418     (Soft, 13)  (Fresh, 12)     (Clean, 11)
2    539    (Fresh, 14)   (Soft, 14)  (Feminine, 11)
3    555  (Feminine, 9)   (Heavy, 8)       (Soft, 7)

您可以根据需要更改列名并提供其他格式。在我看来,存储元组比将数字数据转换成字符串更好。你知道吗

如果您真的需要字符串表示…

您可以使用pd.Series.apply

for col in [0, 1, 2]:
    res[col] = res[col].apply(lambda x: '{0} ({1})'.format(x[0], x[1]))

相关问题 更多 >

    热门问题