data = pd.DataFrame({
'框': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a'],
'水果': ['香蕉', '苹果', '香蕉', '苹果', '香蕉', '苹果', '香蕉', '苹果', '橘子', '菠萝', '菠萝', '山竹', '西瓜', '草莓', '草莓'],
'值': [3, 5, 6, 7, 4, 3, 3, 3, 2, 1, 4, 5, 5, 5, 3]})
dd = data.groupby(['水果', '框']).count()
print(dd)
有这样一组数据,groupby后的结果如下。
值
水果 框
山竹 b 1
橘子 a 1
苹果 b 4
草莓 a 1
b 1
菠萝 a 1
b 1
西瓜 a 1
香蕉 a 4
我想把统计的a和b放到同一行上,没有的就赋值0或者nan都行,如下图,该怎么做呢
水果 a b
山竹 0 1
橘子 1 0
草莓 1 1
dd = data.groupby(['水果', '框'], as_index=False).count()
上次有个类似的题目。
这种做法有点复杂,适合各种复杂情况。
import pandas as pd
data = pd.DataFrame({
'框': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a'],
'水果': ['香蕉', '苹果', '香蕉', '苹果', '香蕉', '苹果', '香蕉', '苹果', '橘子', '菠萝', '菠萝', '山竹', '西瓜', '草莓', '草莓'],
'值': [3, 5, 6, 7, 4, 3, 3, 3, 2, 1, 4, 5, 5, 5, 3]})
dd = data.groupby(['水果', '框']).count()
# 处理过程
lst_dict = {}
for d in dd.iterrows():
temp = list(d[0])
temp_key = str(temp[:1])
print(temp_key,temp,d[1][0])
if temp_key in lst_dict:
temp_item = lst_dict[temp_key]
temp_item[temp[1]] = d[1][0]
else:
lst_dict[temp_key] = {temp[1]:d[1][0]}
print(lst_dict)
lst_2 = []
for d in lst_dict:
items = eval(d)
data = lst_dict[d]
items.append(data['a'] if 'a' in data else 0 )
items.append(data['b'] if 'b' in data else 0)
lst_2.append(items)
print(lst_2)
df3 = pd.DataFrame(lst_2)
df3.columns = ['水果','a框','b框']
print(df3)