0

我有一个具有 20000+ 值的 Python DataFrame,如下所示。而且我想用 NaN 有效地重新排列 df 跟随值的字符串。

    IT1     IT2     IT3     IT4     IT5     IT6
0   qwe     NaN     NaN     rew     NaN     NaN
1   NaN     NaN     sdc     NaN     NaN     wer
2   NaN     NaN     NaN     NaN     NaN     NaN
3   asd     fsc     ws      zd      ews     df 
.....

    IT1     IT2     IT3     IT4     IT5     IT6
0   qwe     rew     NaN     NaN     NaN     NaN
1   sdc     wer     NaN     NaN     NaN     NaN     
2   NaN     NaN     NaN     NaN     NaN     NaN
3   asd     fsc     ws      zd      ews     df 
.....

所以每一行都不能有像 index = 2 这样的值,或者像 index = 3 这样的所有值。有没有办法有效地重新排列我的数据框 df?提前致谢

4

2 回答 2

1

一种方式,虽然很慢,apply, dropna, 和tolist:

 df.apply(lambda x: pd.Series(x.dropna().tolist()),1)\
   .set_axis(df.columns, axis=1, inplace=False)

输出:

   IT1  IT2  IT3  IT4  IT5  IT6
0  qwe  rew  NaN  NaN  NaN  NaN
1  sdc  wer  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN  NaN  NaN
3  asd  fsc   ws   zd  ews   df
于 2017-12-20T03:51:19.320 回答
1

您可以编写一个自定义函数,对行进行排序,然后将索引(列)替换为原始顺序中的列。简单apply地按行传递给数据框

def row_sort(s):
    s2 = s.sort_values()
    s2.index = s.index
    return s2

df.apply(row_sort, axis=1)
# returns:
   IT1  IT2  IT3  IT4  IT5  IT6
0  qwe  rew  NaN  NaN  NaN  NaN
1  sdc  wer  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN  NaN  NaN
3  asd   df  ews  fsc   ws   zd
于 2017-12-20T04:00:07.657 回答