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



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

我现在想转换数据帧,为每个值创建新的列,并且只显示值的频率。

我在下面写了一个例子。

示例数据帧:

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')

预期输出:

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')

根据对所需内容的描述,您需要对重塑的数据使用crosstab

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

然而,这与所提供的输出不匹配。

输出:

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