Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

python - Move non-empty cells to the left in pandas DataFrame

Suppose I have data of the form

Name    h1    h2    h3    h4
A       1     nan   2     3
B       nan   nan   1     3
C       1     3     2     nan

I want to move all non-nan cells to the left (or collect all non-nan data in new columns) while preserving the order from left to right, getting

Name    h1    h2    h3    h4
A       1     2     3     nan
B       1     3     nan   nan
C       1     3     2     nan

I can of course do so row by row. But I hope to know if there are other ways with better performance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, make function.

        def squeeze_nan(x):
            original_columns = x.index.tolist()

            squeezed = x.dropna()
            squeezed.index = [original_columns[n] for n in range(squeezed.count())]

            return squeezed.reindex(original_columns, fill_value=np.nan)

Second, apply the function.

df.apply(squeeze_nan, axis=1)

You can also try axis=0 and .[::-1] to squeeze nan to any direction.

[EDIT]

@Mxracer888 you want this?

def squeeze_nan(x, hold):
    if x.name not in hold:
        original_columns = x.index.tolist()

        squeezed = x.dropna()
        squeezed.index = [original_columns[n] for n in range(squeezed.count())]

        return squeezed.reindex(original_columns, fill_value=np.nan)
    else:
        return x

df.apply(lambda x: squeeze_nan(x, ['B']), axis=1)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...