我想在pandas / matplotlib中将以下数据显示为单个饼图。有什么聪明的方法呢?我的方法似乎很草率。
import pandas as pd
from pandas import DataFrame, Series
matplotlib.style.use("ggplot")
df = DataFrame({"Support": {"Pet Camper": 10, "Non-Pet Camper": 20},
"Oppose": {"Pet Camper": 15, "Non-Pet Camper": 55},
})
d = {}
for r in df.index:
for c in df.columns:
d[r + ", " + c] = df[c][r]
jd = Series(d)
pie_d = Series(d).plot(kind="pie", autopct="%1.1f%%")
plt.legend()
plt.ylabel("")
plt.title("Dedicated Pet Section?")
plt.show()
数据帧:
Oppose Support
Non-Pet Camper 55 20
Pet Camper 15 10
系列:
Non-Pet Camper, Oppose 15
Non-Pet Camper, Support 55
Pet Camper, Oppose 10
Pet Camper, Support 20
答案 0 :(得分:1)
使用stack
,然后将MultiIndex
转换为index
:
s = df.stack()
s.index = s.index.map(','.join)
print (s)
Non-Pet Camper,Oppose 55
Non-Pet Camper,Support 20
Pet Camper,Oppose 15
Pet Camper,Support 10
dtype: int64
另一种解决方案:
s = df.stack()
s.index = [''.join(idx) for idx in s.index]
print (s)
Non-Pet CamperOppose 55
Non-Pet CamperSupport 20
Pet CamperOppose 15
Pet CamperSupport 10
dtype: int64