使用drop时,Python Pandas Drop重新排序我的数据框

时间:2019-02-04 05:47:49

标签: python pandas

我正在使用一个数据框,其中我必须将两列(数量和销售额)相加,然后将其删除,然后大写列名的首字母。问题是当我使用drop时,它将其保存到另一个数据帧。在文档中,问题出在

  

inplace = false

import pandas as pd

pie_info_original = pd.DataFrame(
    [("classic", "apple"), ("tangy", "orange"), ("creamy", "banana"),
     ("sour", "raspberry")], 
    columns = ["flavor", "fruit"])
pie_info_original.loc[:,'quant'] = [5,1,8,3]
pie_info_original.loc[:,'sales'] = [2,1,2,3]
pie_info = pie_info_original.drop(['quant', 'sales'], axis=1)
pie_info.rename(index=str, columns={"fruit": "Fruit", "flavor" : "Flavor"})
print(pie_info)

我的数据来自此

|  |fruit|flavor |quant|sales|
*****************************
| 0|apple|classic|5    | 2   |
| 1|orange|tangy|1    | 1   |
| 2|banana|creamy|8    | 3   |
| 3|raspberry|sour|3    | 3   |

对此

|  flavor | fruit 
*****************
| 0|classic|apple|
| 1|tangy|orange |
| 2|creamy|banana|
| 3|sour|raspberry|

我如何能够重新排列我的列,以便它们以正确的顺序显示。我尝试将inplace设置为true,但这会阻止创建新的数据框。

**我希望水果先于风味

2 个答案:

答案 0 :(得分:1)

您可以使用str.title方法来代替重命名:

In [11]: pie_info.columns.str.title()
Out[11]: Index(['Fruit', 'Flavor'], dtype='object')

In [12]: pie_info.columns = df.columns.str.title()

这不会重新排列列。

答案 1 :(得分:0)

pie_info_original = pd.DataFrame(
    [("classic", "apple"), ("tangy", "orange"), ("creamy", "banana"),
     ("sour", "raspberry")], 
    columns = ["flavor", "fruit"])
pie_info_original.loc[:,'quant'] = [5,1,8,3]
pie_info_original.loc[:,'sales'] = [2,1,2,3]
pie_info = pie_info_original.drop(['quant', 'sales'], axis=1)
pie_info = pie_info.rename(index=str, columns={"fruit": "Fruit", "flavor" : "Flavor"})
pie_info = pie_info[["Fruit", "Flavor"]]
print(pie_info)

输出

       Fruit   Flavor
0      apple  classic
1     orange    tangy
2     banana   creamy
3  raspberry     sour