我最终希望将基于数据帧的“groupby”的表写入pdf文件
为了做到这一点,创建表的“绘图”似乎是实现它的一种方法
我使用下面的代码。使用print()
可以很好地显示该表,但在尝试绘制该表时会生成错误:
"TypeError: object of type 'numpy.float64' has no len()"
我根本不知道该如何避开它。代码在“完整”数据帧上运行良好
提前谢谢
我的代码:
df = pd.read_csv('Stock_holdings.csv', delimiter=";")
df1 = df.groupby(['Valuta','Risk type 1'])["Holding"].sum()
print(df1)
fig, ax =plt.subplots(figsize=(24,4))
ax.axis('tight')
ax.axis('off')
table = ax.table(cellText=df1.values,colLabels=df1.columns,loc='center')
table.set_fontsize(24)
使用print()进行分组的结果:
Valuta Risk type 1
DKK Consumer 2351.00
Financial 4668.00
Index 1666.00
Industrial 231.00
Medical 1631.00
Tankers 33.00
Utility 1900.00
EUR Consumer 468.00
Financial 2007.00
Industrial 849.00
Tankers 1100.00
NOK Tankers 1000.00
SEK Financial 450.00
USD Consumer 500.00
Financial 1607.00
Housing 3560.00
Index 649.00
Industrial 990.00
Medical 562.03
Tankers 1505.00
Name: Holding, dtype: float64
下面是初始数据帧(df)-前5行
Symbol Virksomhed Holding Count Valuta Pension Bank Instrument \
0 TNK Teekay Tankers 505.0 1 USD 0 Saxo Equity
1 SLRC Solar Capital 649.0 1 USD 0 Saxo Equity
2 FRO Frontline NYSE 1000.0 1 USD 0 Saxo Equity
3 SKT Tanger 500.0 1 USD 0 Saxo Equity
4 EURN.BR Euronav 1100.0 1 EUR 0 Saxo Equity
Risk type 1 Aktivklasse
0 Tankers Aktie
1 Index Aktie
2 Tankers Aktie
3 Consumer Aktie
4 Tankers Aktie
您可以使用^{} 。使用
.sum()
的groupby聚合返回一个系列,而plotting函数需要一个数据帧(或类似的2D字符串结构)。打印时,多索引数据框看起来类似于一个系列,因此很容易假设您为绘图生成了一个新的数据框。但是,您可能已经注意到,聚合系列的打印输出没有列名,而是在下面打印名称Holding
样本输出:
相关问题 更多 >
编程相关推荐