0

I set a dataframe using the following code:

df = pd.DataFrame({'A':['a','a','b','c'],'B':[123,456,555,888]})

I then execute the following code:

pd.pivot(df.A, df.index, df.B)

The dataframe changes to this:

pic1

Now I want to know how to move non-NAN values to the front columns like this:

pic2

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
ltdong7788
  • 11
  • 3

3 Answers3

1

Instead of pivoting (and then repairing the result), you could use groupby:

In [321]: df = pd.DataFrame({'A':['a','a','b','c'],'B':[123,456,555,888]})

In [322]: df.groupby('A')['B'].apply(lambda x: pd.Series(x.values)).unstack()
Out[322]: 
       0      1
A              
a  123.0  456.0
b  555.0    NaN
c  888.0    NaN

Or, alternatively, use groupby/cumcount to assign the correct column numbers per group, and then pivot:

In [325]: df.assign(C=df.groupby('A').cumcount()).pivot(index='A', columns='C', values='B')
Out[325]: 
C      0      1
A              
a  123.0  456.0
b  555.0    NaN
c  888.0    NaN
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0
df.apply(lambda x : x[x.notnull()].values.tolist(),1).apply(pd.Series)
Out[262]: 
       0      1
A              
a  123.0  456.0
b  555.0    NaN
c  888.0    NaN
BENY
  • 317,841
  • 20
  • 164
  • 234
0

If you want to retain same amount of columns with NaNs

In [585]: dff = pd.pivot(df.A, df.index, df.B)

In [586]: (dff.apply(lambda x: pd.Series(x.dropna().values), axis=1)
              .reindex_axis(dff.columns, 1))
Out[586]:
       0      1   2   3
A
a  123.0  456.0 NaN NaN
b  555.0    NaN NaN NaN
c  888.0    NaN NaN NaN

If you don't need to

In [587]: dff.apply(lambda x: pd.Series(x.dropna().values), axis=1)
Out[587]:
       0      1
A
a  123.0  456.0
b  555.0    NaN
c  888.0    NaN
Zero
  • 74,117
  • 18
  • 147
  • 154