【问题标题】:Pivot in pandas creates issues with indexingPandas 中的 Pivot 会产生索引问题
【发布时间】:2017-11-14 16:41:03
【问题描述】:

在 pandas 中旋转数据框会在列上创建一个烦人的索引。 reset_index() 似乎并没有解决这个问题。有人可以帮我继续。下面列出了代码库和我目前看到的内容

import pandas as pd

products = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'],
                    'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'],
                    'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55],
                    'testscore': [4, 3, 5, 7, 5, 8]})

pivot_products = products.pivot(index='category', columns='store', values='price') 

print(pivot_products)

运行此代码块提供的输出为

store            Dia   Fnac  Walmart
category                            
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55

当我在 pivot_products 上重置索引时,它提供了

store       category    Dia   Fnac  Walmart
 0           Cleaning  23.50    NaN    11.42
 1      Entertainment    NaN  15.95    19.99
 2               Tech  55.75    NaN   111.55

我真的不希望此处显示的 store 列 - 它不捕获任何相关数据并最终保存垃圾值。有什么想法吗?

【问题讨论】:

  • store 是你的列名...
  • 另外,请参阅stackoverflow.com/a/47152692/2336654,了解有关如何进行数据透视的更多信息。请特别注意列名如何作为 Index 对象的名称放置。

标签: python pandas pivot


【解决方案1】:

store 不是一列。这是columns 对象的名称。使用pd.DataFrame.rename_axis

pivot_products.rename_axis(None, 1)

                 Dia   Fnac  Walmart
category                            
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55

【讨论】:

  • 非常感谢。这让我在最后一天发疯了
  • 结合 reset_index() 可以防止我在最终输出中看到存储
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多