简体   繁体   English

根据值的条件对数据框中的列重新排序

[英]Re-order Columns In A Data Frame Depending On Conditions Of Values

a = [[0,0,0,0],[0,-1,1,0],[1,-1,1,0],[1,-1,1,0]]

df = pd.DataFrame(a, columns=['A','B','C','D'])
df

Output:

    A    B    C    D
0   0    0    0    0
1   0   -1    1    0
2   1   -1    1    0
3   1   -1    1    0

So reading down vertically per column, values in the columns all begin at 0 on the first row, once they change they can never change back and can either become a 1 or a -1.因此,每列垂直向下读取,列中的值都从第一行的 0 开始,一旦它们改变,它们就永远不会变回来,可以变成 1 或 -1。 I would like to re arrange the dataframe columns so that the columns in this order:我想重新排列 dataframe 列,以便按以下顺序排列:

  1. Order columns that hit 1 in the earliest row as possible尽可能对最早行中达到 1 的列进行排序
  2. Order columns that hit -1 in the earliest row as possible对最早行中命中 -1 的列进行排序
  3. Finally the remaining rows that never changed values and remained as zero (if there are even any left)最后,剩余的行从未改变过值并保持为零(如果还有的话)
Desired Output:
    C    A    B    D
0   0    0    0    0
1   1    0   -1    0
2   1    1   -1    0
3   1    1   -1    0


The my main data frame is 3000 rows and 61 columns long, is there any way of doing this quickly?我的主要数据框是 3000 行和 61 列长,有什么方法可以快速做到这一点?

We have to handle the positive and negative values seperately.我们必须分别处理正值和负值。 One way is take sum of the columns, then using sort_values , we can adjust the ordering:一种方法是对列sum ,然后使用sort_values ,我们可以调整排序:

a = df.sum().sort_values(ascending=False)
b = pd.concat((a[a.gt(0)],a[a.lt(0)].sort_values(),a[a.eq(0)]))
out = df.reindex(columns=b.index)

print(out)

   C  A  B  D
0  0  0  0  0
1  1  0 -1  0
2  1  1 -1  0
3  1  1 -1  0

Try with pd.Series.first_valid_index尝试使用pd.Series.first_valid_index

s = df.where(df.ne(0))
s1 = s.apply(pd.Series.first_valid_index)
s2 = s.bfill().iloc[0]
out = df.loc[:,pd.concat([s2,s1],axis=1,keys=[0,1]).sort_values([0,1],ascending=[False,True]).index]
out
Out[35]: 
   C  A  B  D
0  0  0  0  0
1  1  0 -1  0
2  1  1 -1  0
3  1  1 -1  0

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

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