【问题标题】:Python DataFrame: rearrange the objects and empty values [duplicate]Python DataFrame:重新排列对象和空值
【发布时间】:2017-12-20 13:39:11
【问题描述】:

我有一个具有 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? 提前致谢

【问题讨论】:

    标签: python arrays pandas dataframe arrange-act-assert


    【解决方案1】:

    一种方式,虽然很慢,applydropnatolist

     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
    

    【讨论】:

    • set_axis() 获得了参数“轴”的多个值
    • @Kang 是的,你必须有 Pandas 0.21.0+ 升级 pandas。
    【解决方案2】:

    您可以编写一个自定义函数,对行进行排序,然后将索引(列)替换为原始顺序中的列。只需 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
    

    【讨论】:

    • 完美运行,但只有一个问题。我想保留订单,但删除 nan 值,但您的代码不保留原始订单。例如,在索引 3 中,它应该是 asd fsc ws zd ews df 顺序。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2022-12-01
    • 2020-03-22
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多