python - 如何用pivot reshape pandas数据框?

标签 python pandas dataframe

我有一个数据框,

    Year  Start  End   Name       Price
0   nan   0101   0331  Squirtle    876
1  2021   0101   1231  Squirtle    200
2   nan   0101   0331  Wartortle   1000
3  2021   0101   1231  Wartortle   1200
4   nan   0101   0331  Blastoise   3100
5  2021   0101   1231  Blastoise   4200
6  2022   0101   1231  Blastoise   10000

我想把它 reshape 成这样,

                   Name    Squirtle      Wartortle       Blastoise
Year  Start End
nan   0101  0331              876           1000            3100
2021  0101  1231              200           1200            4200
2022  0101  1231                                            10000

我试过了, df.pivot(index=['年份', '开始', '结束'], columns='名称', value='价格')。但没有得到任何运气。 任何帮助将不胜感激!

最佳答案

你们已经很接近了。使用pivot_table而不是pivot来获得您想要的分组。唯一需要注意的是,您需要替换 NA 值(如果它们实际上是 NA 而不是字符串 'nan')。

df.fillna('NA').pivot_table(index=['Year', 'Start', 'End'], columns='Name', values='Price')
# returns:
Name               Blastoise  Squirtle  Wartortle
Year   Start End
2021.0 101   1231     4200.0     200.0     1200.0
2022.0 101   1231    10000.0       NaN        NaN
NA     101   331      3100.0     876.0     1000.0

关于python - 如何用pivot reshape pandas数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59886994/

相关文章:

python - 如何将输出保存到txt文件?

python - 如何优雅地深入堆叠字典

python - 在 Pandas 系列中找到第一个非零值

python - python 中的 UTC 偏移量变得疯狂(to_datetime panda 函数和 datetime 对象)

python - Pandas (如何修复): List is actually string and the value of length is misleading

python - 在 Dask 中高效删除行

python - 如何从两个具有相同键值的字典创建一个 pandas 数据框?

python - selenium.common.exceptions.WebDriverException : Message: invalid session id using Selenium with ChromeDriver and Chrome through Python

python - urllib - 从 Python2 更新到 Python3

python - 创建太长整数的数据帧