df = df.melt('Person', value_name='Item')
print (df)
Person variable Item
0 Adam Item1 Apple
1 Alex Item1 Chocolate
2 Gina Item1 Eggs
3 Adam Item2 Eggs
4 Alex Item2 Orange
5 Gina Item2 Apple
6 Adam Item3 Cookie
7 Alex Item3 Eggs
8 Gina Item3 Orange
9 Adam Item4 NaN
10 Alex Item4 Potato
11 Gina Item4 Milk
# get items
items = []
for c in df.columns[1:]:
items.extend(df[c].values)
items = list(set(items))
items.remove(None)
people = df.Person.values
counts = {}
for p in people:
counts[p] = [1 if item in df[df['Person'] == p].values else 0 for item in items]
new = pd.DataFrame(counts, index=items)
new['Count'] = new.sum(axis=1)
首先使用^{} 重塑形状:
然后用^{} 聚合} 创建新的
^{pr2}$list
s的自定义函数,然后通过构造函数和^{DataFrame
,以计数列:这不是你想要的,但是我不确定“换位”是否作为一个简单的函数存在。(顺便说一下,
transpose
,在线性代数之后,通常意味着将数据帧旋转90°)。在输出:
^{pr2}$编辑:和往常一样,jezrael给出了正确的答案,但是我修改了它以获得您想要的输出。对于初学者来说,这可能更容易理解。在
以“df”为例:
输出:
相关问题 更多 >
编程相关推荐