gpt4 book ai didi

python - 将特定索引转换为自己的行

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:59 24 4
gpt4 key购买 nike

Trying to convert the indices of one column, into their own columns.

From:

[country, series, year, value]

[USA, A, 1994, 700000]
[USA, B, 1994, 701231]
[UK, A, 1994, 600000]
[UK, B, 1994, 601231]
[China, A, 1994, 6512312]
[China, B, 1994, 6432112]
To:

[country, A, B, year]

[USA, 700000, 701231, 1994]
[UK, 600000, 601231, 1994]
[China, 6512312, 6432112, 1994]

Have tried stacking/unstacking, pivoting, melting, groupby, etc..

I am fairly certain that one of these methods is the key to reorganizing this, I just cant seem to get it right.

End goal is to make a 3d scatterplot wherein one axis is year, another is A and another is B; while country will be indicated by color

更新:使用 Pivot,我能够以正确的方式获取数据看起来,但当我尝试绘制数据时,会出现同样的问题。

Because 'Year' and 'Country' are indexed, they cannot be identified as elements eligible for axes.

Expected 'A' or 'B' but got 'year'/'country'

最佳答案

Pivot the data, then reset the index and drop the resulting additional column being used as the new index column.

df.pivot_table(index=['country', 'year'], columns='series', values='value')
df.reset_index()

(optional) df.drop(column = 'series')

按照 @ALollz 的描述进行旋转可以使数据框看起来正确。

由于“年份”和“国家/地区”被编入索引,在尝试绘制图表时遇到了上述错误。

运行数据透视后简单地重置索引,解决了索引问题并将“国家/地区”和“年份”返回到正常列,同时将 A 和 B 保留为新列。 “Series”将是新的索引列,可以删除。

关于python - 将特定索引转换为自己的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57964967/

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