【发布时间】:2019-06-19 12:43:20
【问题描述】:
cat1 cat2 col_a col_b
0 (34.0, 38.0] (15.9, 47.0] 29 10
1 (34.0, 38.0] (15.9, 47.0] 37 22
2 (28.0, 34.0] (47.0, 56.0] 3 13
3 (34.0, 38.0] (47.0, 56.0] 15 7
4 (28.0, 34.0] (56.0, 67.0] 42 20
5 (28.0, 34.0] (47.0, 56.0] 31 23
6 (28.0, 34.0] (56.0, 67.0] 26 17
7 (28.0, 34.0] (56.0, 67.0] 7 1
8 (28.0, 34.0] (56.0, 67.0] 36 19
9 (19.0, 28.0] (56.0, 67.0] 5 7
10 (19.0, 28.0] (56.0, 67.0] 21 5
11 (28.0, 34.0] (67.0, 84.0] 37 13
在上面的数据框中,我想用 pandas 做这个数据透视表操作
pd.pivot_table(df, index='cat1', columns='cat2', values='col_a')
但我得到了错误:
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'
col_a 和 col_b 都是 int32 类型,cat1 和 cat2 都是分类类型。我该如何摆脱这个错误?
【问题讨论】:
-
不确定我在看什么。您的列
cat1和cat2是字符串类型吗?因为它们是由(和]分隔的,所以它们不是元组或列表。 -
如果可以,您可以将所有内容转换为
string,然后在pivot_table之后重新转换为int。可能不是最好的解决方案,但无法重现您的错误 -
您能提供 DataFrame 或 csv 的定义吗?
-
您预期的旋转输出会是什么样子?因为 'cat1' 和 'cat2' 不是唯一的 - 并且您没有指定要在 'col_a' 上执行的任何聚合函数
-
鉴于您没有指定 aggfunc,默认假定为“mean”。
标签: python pandas dataframe pivot-table