跳过 pandas 数据框行中的nan和shift元素 [英] Skip nan and shift elements in a pandas dataframe row
问题描述
我有一个这样的数据框[![数据框看起来像这样] [1]: https://i.stack.imgur.com/R7GmM.png 现在,我想跳过nan,以便数据向左移动,即[![格式化的数据帧应像这样] [1]: https://i.stack.imgur.com/yGYIy.png
I have a dataframe like this [![Dataframe looks like this][1]: https://i.stack.imgur.com/R7GmM.png Now I want to skip nan's and so that data shift towards left i.e. [![formatted dataframe should be like this] [1]: https://i.stack.imgur.com/yGYIy.png
我无法通过熊猫来做到这一点.如果我有一个可以说10万行的大型数据集,是否可以实现可扩展的解决方案?
I am not able to do it via pandas. Is a scalable solution possible for this if I have a large dataset of let say 100k rows?
:以下是数据和所需的输出:
: Here is the data and desired output:
#Original df
>>> df
A B C D
0 a NaN c NaN
1 b NaN b a
2 c NaN NaN d
3 d a b c
#Desired output:
A B C D
0 a c
1 b b a
2 c d
3 d a b c
推荐答案
这里是一种方法:
从名为 df
的数据框开始:
A B C D
0 a NaN c NaN
1 b NaN b a
2 c NaN NaN d
3 d a b c
应用以下行:
shifted_df = df.apply(lambda x: pd.Series(x.dropna().values), axis=1).fillna('')
shifted_df.columns = df.columns
然后您将得到结果 shifted_df
数据帧:
And you get your resulting shifted_df
dataframe:
>>> shifted_df
A B C D
0 a c
1 b b a
2 c d
3 d a b c
这篇关于跳过 pandas 数据框行中的nan和shift元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!