【问题标题】:Python Pivot loses last columnPython Pivot 丢失最后一列
【发布时间】:2018-07-12 23:53:18
【问题描述】:

我正在打开一个 .csv,并用 pandas 将其命名为 pull:

    Quarter                  Category       Value
7776   Q1-17  Autos and Transportation   6997035.2
7777   Q2-17  Autos and Transportation   7897574.5
7778   Q3-17  Autos and Transportation   6983654.1
7779   Q4-17  Autos and Transportation   7301336.9
7780   Q1-18  Autos and Transportation   7627895.3

有 6 个不同的类别,我想将其组织为:

Quarter                         Q2-17       Q3-17       Q4-17       Q1-18  
Category                                                                    
Autos and Transportation   12196407.0  13591411.0  14757349.0  15735009.0   
Building and Construction   7446408.5   7873713.2   9360943.1   9355093.8   
Business and Industry       9871899.8  10264492.0   9640937.3  10668084.0   
Food and Drugs              4287428.7   4363061.2   4528251.5   4605146.4   
Fuel and Service Stations   9551811.4   8637092.7   7649205.4   7542200.1   
General Consumer Goods     18120167.0  19035865.0  19692248.0  19775445.0   
Restaurants and Hotels      8138913.7   9021774.4   9712391.4  10649011.0   
Total                      76758539.0  81455234.0  84251489.0  87868048.0  

我试图通过写作来做到这一点:

reshape = pull.pivot(index='Category', columns='Quarter', values='Value')

除了我丢失了最后一列“Q1-18”之外它有效。知道如何保留所有列吗?

print(reshape.tail(4))

Quarter                         Q4-13       Q4-14       Q4-15       Q4-16  \
Category                                                                    
Fuel and Service Stations   9551811.4   8637092.7   7649205.4   7542200.1   
General Consumer Goods     18120167.0  19035865.0  19692248.0  19775445.0   
Restaurants and Hotels      8138913.7   9021774.4   9712391.4  10649011.0   
Total                      76758539.0  81455234.0  84251489.0  87868048.0   

Quarter                         Q4-17  
Category                               
Fuel and Service Stations   8395288.1  
General Consumer Goods     19794656.0  
Restaurants and Hotels     11036473.0  
Total                      93091370.0  

【问题讨论】:

  • 你能把输出打印出来吗?
  • 将它作为更新发布在您的问题中,否则需要一些沉重的心理体操:)
  • @GerardoFlores 哈哈,我的错,我是这个网站的新手。我刚刚将它添加到我的问题中
  • 别担心,兄弟,我们在这里为您提供帮助。所以看起来它只删除了你的最后一行,不是吗?
  • 列似乎排序为Q1-16Q1-17Q1-18Q2-16Q2-17Q2-18Q3-16Q3-17、@987654 ,Q4-17...。那么您是否检查了Q1-18 在您的输出中是否在Q1-17 之后?

标签: python pandas dataframe data-science


【解决方案1】:

我可以通过找到一个类似的帖子来解决这个问题。

只需要在枢轴之前添加order = pull['Quarter']。然后,您可以使用以下方法修复列顺序:reshape = reshape.reindex(columns=order)

【讨论】:

  • 明确地说,没有丢失任何列。只需对列重新排序。它应该是order=pull['Quarter'].unique()
猜你喜欢
  • 2021-12-13
  • 2011-01-21
  • 1970-01-01
  • 2022-01-25
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
相关资源
最近更新 更多