我有以下df,我想按“名称”分组,所以有一个“ A”和“ B”计数列以及一个“总销售额”总和列:
例如将其旋转:
data = {'A or B' : ['A','A','B','B','A','B'],
'Name' : ['Ben','Ben','Ben','Sam','Sam','Sam'],
'Sales ($)' : [10,5,2,5,6,7]
}
df=pd.DataFrame(data, columns = ['A or B','Name','Sales ($)'])
所以看起来像这样:
grouped_data = {'A' : [2,1],
'B' : [1,2],
'Name' : ['Ben','Sam'],
'Total Sales ($)' : [17,18]
}
df=pd.DataFrame(grouped_data, columns = ['A','B','Name','Total Sales ($)'])
答案 0 :(得分:3)
您可以尝试使用pd.get_dummies
,join
和groupby
+ sum
:
pd.get_dummies(df['A or B'])\
.join(df.drop('A or B',1))\
.groupby('Name',as_index=False).sum()
输出:
Name A B Sales ($)
0 Ben 2 1 17
1 Sam 1 2 18
详细信息:
首先,使用get_dummies
将分类变量转换为虚拟变量/指标变量:
pd.get_dummies(df['A or B'])
# A B
#0 1 0
#1 1 0
#2 0 1
#3 0 1
#4 1 0
#5 0 1
然后使用join,在'A or B'
列被删除的情况下,使用原始df来连接假人:
pd.get_dummies(df['A or B']).join(df.drop('A or B',1))
# A B Name Sales ($)
#0 1 0 Ben 10
#1 1 0 Ben 5
#2 0 1 Ben 2
#3 0 1 Sam 5
#4 1 0 Sam 6
#5 0 1 Sam 7
最后,根据名称执行groupby
+ sum
:
pd.get_dummies(df['A or B']).join(df.drop('A or B',1)).groupby('Name',as_index=False).sum()
# Name A B Sales ($)
#0 Ben 2 1 17
#1 Sam 1 2 18
答案 1 :(得分:1)
您可以在import pandas as pd
import matplotlib.pyplot as plt
data = [[1, 10, 'red'], [2, 15, 'green'], [3, 14, 'blue']]
df = pd.DataFrame(data, columns = ['x', 'y', 'color'])
fig, ax = plt.subplots()
for i in df.index:
'''
Get two rows each time, every row has a point (x, y)
Two points can draw a line, use the color defined by first row
'''
partial = df.iloc[i:i+2, :]
ax.plot(partial['x'], partial['y'], color=partial['color'].iloc[0], zorder = 0)
plt.show()
内使用聚合
groupby
答案 2 :(得分:0)
分步解决方案:
import pandas as pd
data = {'A or B' : ['A','A','B','B','A','B'],
'Name' : ['Ben','Ben','Ben','Sam','Sam','Sam'],
'Sales ($)' : [10,5,2,5,6,7]
}
df=pd.DataFrame(data, columns = ['A or B','Name','Sales ($)'])
#first create dummy for 'A or B' column
y = pd.get_dummies(df['A or B'])
#concatenate with original data frame
df=pd.concat([y,df], axis=1)
#delete the column
del df['A or B']
#now do the group by
df=df.groupby('Name').agg({'A':'sum',
'B':'sum',
'Sales ($)': 'sum'})
#reset the index
df.reset_index(level=0, inplace=True)
print(df)
输出:
Name A B Sales ($)
0 Ben 2 1 17
1 Sam 1 2 18