gpt4 book ai didi

Python Pandas - 数据透视表输出意外 float

转载 作者:行者123 更新时间:2023-11-28 20:33:39 25 4
gpt4 key购买 nike

我有一个包含整数的数据框,但是当我旋转它时,它会创建 float ,我无法弄清楚原因:

我的数据框 (dfDis) 如下所示:

    Year    Type                                                Total
0 2006 A talk or presentation 34
1 2006 A magazine, newsletter or online publication 33
2 2006 A formal working group, expert panel or dialogue 2
3 2006 Scientific meeting (conference/symposium etc.) 10
4 2006 A press release, press conference or response ... 6
....

我的枢轴代码是:

dfDisB = pd.pivot_table(dfDis, index=['Year'], columns = ['Type'],fill_value=0)

出于某种原因,dfDisB 最终变成了这样(很抱歉格式化,我希望你明白要点):

    Total
Type A broadcast e.g. TV/radio/film/podcast (other than news/press) A formal working group, expert panel or dialogue A magazine, newsletter or online publication A press release, press conference or response to a media enquiry/interview A talk or presentation Engagement focused website, blog or social media channel Participation in an activity, workshop or similar Participation in an open day or visit at my research institution Scientific meeting (conference/symposium etc.)
Year
2006 1.000000 1.571429 6.125000 2.000000 3.235294 1.000000 4.222222 1.000000 5.500000
2007 0.000000 3.666667 24.500000 11.500000 32.250000 1.000000 5.250000 2.500000 28.000000
2008 0.000000 2.500000 21.333333 13.000000 38.230769 1.000000 7.909091 1.000000 37.000000

我很困惑,因为我在我的报告中旋转了一些其他数据,但我没有遇到问题。

有什么建议吗?我已将 dfDis 导出到 csv 以检查那里没有 float ,也没有,它只是整数。

谢谢

最佳答案

要了解此行为,请注意:

  1. pd.pivot_table 的默认聚合方法是“均值”。
  2. 3个整数的平均值往往不是整数。
  3. 如果数据透视表中的任何值是float [包括NaN],所有值系列都将转换为 float

下面是最小的例子。

转换为 float 触发

df = pd.DataFrame({'A': [1, 2, 1, 2, 1, 1, 2, 1],
'B': ['a', 'b', 'a', 'c', 'b', 'c', 'a', 'a'],
'C': [1, 2, 3, 4, 5, 6, 7, 4]})

df = pd.pivot_table(df, index='A', columns=['B'], values='C', aggfunc='mean')

print(df)

B a b c
A
1 2.666667 5.0 6.0
2 7.000000 2.0 4.0

转换为 float 未触发

df = pd.DataFrame({'A': [1, 2, 1, 2, 1, 1, 2, 1],
'B': ['a', 'b', 'a', 'c', 'b', 'c', 'a', 'a'],
'C': [1, 2, 3, 4, 5, 6, 7, 5]})

df = pd.pivot_table(df, index='A', columns=['B'], values='C', aggfunc='mean')

print(df)

B a b c
A
1 3 5 6
2 7 2 4

关于Python Pandas - 数据透视表输出意外 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com