Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas columns values to row

Tags:

python

pandas

I am trying to convert a dataframe to long form.

The dataframe I am starting with:

df = pd.DataFrame([['a', 'b'],
                   ['d', 'e'], 
                   ['f', 'g', 'h'],
                   ['q', 'r', 'e', 't']])
df = df.rename(columns={0: "Key"})

    Key 1   2   3
0   a   b   None    None
1   d   e   None    None
2   f   g   h       None
3   q   r   e       t

The number of columns is not specified, there may be more than 4. There should be a new row for each value after the key

This gets what I need, however, it seems there should be a way to do this without having to drop null values:

new_df = pd.melt(df, id_vars=['Key'])[['Key', 'value']]
new_df = new_df.dropna()


    Key value
0   a   b
1   d   e
2   f   g
3   q   r
6   f   h
7   q   e
11  q   t​
like image 402
johnchase Avatar asked Mar 23 '18 01:03

johnchase


2 Answers

Option 1
You should be able to do this with set_index + stack:

df.set_index('Key').stack().reset_index(level=0, name='value').reset_index(drop=True)

  Key value
0   a     b
1   d     e
2   f     g
3   f     h
4   q     r
5   q     s
6   q     t

If you don't want to keep resetting the index, then use an intermediate variable and create a new DataFrame:

v = df.set_index('Key').stack()
pd.DataFrame({'Key' : v.index.get_level_values(0), 'value' : v.values})

  Key value
0   a     b
1   d     e
2   f     g
3   f     h
4   q     r
5   q     s
6   q     t

The essence here is that stack automatically gets rid of NaNs by default (you can disable that by setting dropna=False).


Option 2
More performance with np.repeat and numpy's version of pd.DataFrame.stack:

i = df.pop('Key').values
j = df.values.ravel()

pd.DataFrame({'Key' : v.repeat(df.count(axis=1)), 'value' : j[pd.notnull(j)]
})

  Key value
0   a     b
1   d     e
2   f     g
3   f     h
4   q     r
5   q     s
6   q     t
like image 168
cs95 Avatar answered Oct 10 '22 12:10

cs95


By using melt(I do not think dropna create more 'trouble' here)

df.melt('Key').dropna().drop('variable',1)
Out[809]: 
   Key value
0    a     b
1    d     e
2    f     g
3    q     r
6    f     h
7    q     s
11   q     t

And if without dropna

s=df.fillna('').set_index('Key').sum(1).apply(list)
pd.DataFrame({'Key': s.reindex(s.index.repeat(s.str.len())).index,'value':s.sum()})


Out[862]: 
  Key value
0   a     b
1   d     e
2   f     g
3   f     h
4   q     r
5   q     s
6   q     t
like image 35
BENY Avatar answered Oct 10 '22 14:10

BENY