简体   繁体   English

根据其他列使用python重新排序(排序)CSV中的行

[英]Reorder(Sort) rows in CSV using python based on other columns

I am trying to reorder rows in csv where I want to have "All" as the last row, in csv. 我想在csv中重新排列行,以便在其中将“所有”作为最后一行。 I have tried using sort_index and sort_Values but I have not been able to achieve what I want. 我曾尝试使用sort_index和sort_Values,但无法实现所需的功能。 Here is my code: 这是我的代码:

import pandas as pd
import csv

df1=pd.read_csv("C:\\testfolder\\testdemofinal1.csv",sep=',',na_filter=False)

df=pd.DataFrame(df1)

a=df.pivot_table(index=['Parameter1_Calculation','Parameter2_Calculation'],columns='Measure Names', values='Measure Values',aggfunc='first',dropna=True,margins_name='All')

#a=a.sort_values(by='Total Earn',ascending=0)

This does sort the rows but does not give me the right result. 这确实对行进行了排序,但没有给我正确的结果。


#a=a.sort_index(by=['Parameter1_Calculation','Parameter2_Calculation'],ascending=[True,False])

This gives me error. 这给我错误。

b=a.to_csv("C:\\newfile1.csv",sep=',')

I have attached the sample csv below: 我在下面附上了示例csv:

在此处输入图片说明 Thanks in advance 提前致谢

I have a sample of textual data below: 我在下面有一个文本数据示例:

Parameter1   Parameter2 CPS  CallE  Calls ClickEarn      Clicks  
ABC - Health 8/23/2017  0.78    0    0    31.5          15  
Ad Network   8/23/2017  0.01    0    0     1.3           1  
All             All     0.27    0    0    17,502,274    3,493,532
Quotes       8/23/2017  0       0    0      0            0  

The fast but stupid way is to drop that row and append that later. 快速但愚蠢的方法是删除该行并在以后追加。

data = df
c = df[df['Parameter1_Calculation']=='ALL']
data.drop(c.index).append(c)

but this may create unexpected result when you have more than one row 但是当您有多于一行时,这可能会产生意外的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM