繁体   English   中英

连接数据框后对特定列进行排序

[英]Sorting specific columns after concatenating data frames

我将 3 个数据帧连接成一个 dataframe。 现在我想对一些特定的列进行排序,所以我使用了这段代码:

final_df.sort_values(['Tab1_1', 'Tab2_2'], ascending=False)

但是,output 显示col1中的值是有序的,但col5中的值不是。 有人能告诉我我错过了什么吗?

下面是一个数据示例:

concat_table = {'ID': ['Sun_1'], 
                'Tab1': ['Al', 'Alu', 'Alt'],
                'Tab1_1': [6, 3, 4], 
                '%_Tab_1': [90, 50, 40], 
                'Tab2': ['Type1', 'Type2', 'Type3'], 
                'Tab2_2': [4, 5, 2],
                '%_Tab1_2': [60, 90, 40]}

这是应该如何订购的:

concat_table_ordered = {'ID': ['Sun_1'], 
                        'Tab1': ['Al', 'Alt', 'Alu'],
                        'Tab1_1': [6, 4, 3], 
                        '%_Tab_1': [90, 40, 50], 
                        'Tab2': ['Type2', 'Type1', 'Type3'], 
                        'Tab2_2': [5, 4, 2],
                        '%_Tab1_2': [90, 60, 40]}

如果在 pandas 中按多列排序,它按sequentially排序,这意味着首先按列表中的第一列,她的Tab1_1 ,然后按下一个值,但前提是前列中的值重复,这里Tab1_1

concat_table={'ID':'Sun_1', 
              'Tab1': ['Al','Alu','Alt', 'aaa'],
              'Tab1_1':[6,3,4,4], 
              '%_Tab_1':[90,50,40,100],
              'Tab2':['Type1','Type2','Type3','Type4'],
              'Tab2_2':[4,5,2,1],
              '%_Tab1_2':[60,90,40,20]}
df = pd.DataFrame (concat_table)
print (df)
      ID Tab1  Tab1_1  %_Tab_1   Tab2  Tab2_2  %_Tab1_2
0  Sun_1   Al       6       90  Type1       4        60
1  Sun_1  Alu       3       50  Type2       5        90 <-4 are duplicated
2  Sun_1  Alt       4       40  Type3       2        40 <-4 are duplicated
3  Sun_1  aaa       4      100  Type4       1        20

df1 = df.sort_values(['Tab1_1','Tab2_2'], ascending=False)
print (df1)
      ID Tab1  Tab1_1  %_Tab_1   Tab2  Tab2_2  %_Tab1_2
0  Sun_1   Al       6       90  Type1       4        60
2  Sun_1  Alt       4       40  Type3       2        40 <-sorted 2,1 
3  Sun_1  aaa       4      100  Type4       1        20 <-sorted 2,1 
1  Sun_1  Alu       3       50  Type2       5        90

如果需要单独排序,则必须先拆分列,排序然后分配回,但需要通过reset_index(drop=True)设置默认索引值:

df1 = df.iloc[:, :4].sort_values(['Tab1_1'], ascending=False)
df2 = df.iloc[:, 4:].sort_values(['Tab2_2'], ascending=False)

final_df = pd.concat([df1.reset_index(drop=True), 
                      df2.reset_index(drop=True)], axis=1)
print (final_df)
      ID Tab1  Tab1_1  %_Tab_1   Tab2  Tab2_2  %_Tab1_2
0  Sun_1   Al       6       90  Type2       5        90
1  Sun_1  Alt       4       40  Type1       4        60
2  Sun_1  Alu       3       50  Type3       2        40

您是否将此 output 分配给另一个 df? 否则使用inplace=True

final_df.sort_values(['col1','col5'], ascending=False, inplace=True)

暂无
暂无

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

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