首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将列值转换为显示频率的新列

如何将列值转换为显示频率的新列
EN

Stack Overflow用户
提问于 2022-09-13 03:42:53
回答 1查看 33关注 0票数 0

我通过拆分一个列并展开它来创建一个新的dataframe。

现在,我希望转换dataframe来为每个值创建新列,并且只显示值的频率。

我在下面写了一个例子。

示例dataframe:

代码语言:javascript
复制
import pandas as pd
import numpy as np

df= pd.DataFrame({0:['cake','fries', 'ketchup', 'potato', 'snack'],
                1:['fries', 'cake', 'potato', np.nan, 'snack'],
                2:['ketchup', 'cake', 'potatos', 'snack', np.nan],
                3:['potato', np.nan,'cake', 'ketchup',np.nan],
                'index':['james','samantha','ashley','tim', 'mo']})

df.set_index('index')

预期产出:

代码语言:javascript
复制
output = pd.DataFrame({'cake': [1, 2, 1, 0, 0],
                       'fries': [1, 1, 0, 0, 0],
                       'ketchup': [1, 0, 1, 1, 0],
                       'potatoes': [1, 0, 2, 1, 0],
                       'snack': [0, 0, 0, 1, 2],
                       'index': ['james', 'samantha', 'asheley', 'tim', 'mo']})

output.set_index('index')
EN

回答 1

Stack Overflow用户

发布于 2022-09-13 04:25:31

根据对所需内容的描述,需要对重塑的数据进行crosstab

代码语言:javascript
复制
df2 = df.reset_index().melt('index')

out = pd.crosstab(df2['index'], df2['value'].str.lower())

但是,这与提供的输出不匹配。

输出:

代码语言:javascript
复制
value     apple  berries  cake  chocolate  drink  fries  fruits  ketchup  potato  potatoes  snack
index                                                                                            
Ashley        0        0     0          0      0      0       0        1       1         0      1
James         0        1     1          0      0      1       1        0       0         0      0
Mo            0        0     0          1      0      0       1        1       0         1      0
samantha      1        0     0          1      0      1       0        0       0         0      0
tim           0        0     0          0      1      0       0        0       0         0      1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73697322

复制
相关文章

相似问题

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