3

For example i have a dataframe like this :

import pandas as pd

df = pd.DataFrame([[1, 2.], [3, 4.]], columns=['a', 'b'])

print df

    a    b
0   1  2.0
1   3  4.0

I want to get a dataframe as follows :

    a     b
0  [1,3] [2,4]

1 Answer 1

2

One approach -

df_out = pd.DataFrame([df.values.T.astype(int).tolist()], columns=df.columns)

To retrieve back -

N = len(df_out.columns)
arr_back = np.concatenate(np.concatenate(df_out.values)).reshape(N,-1).T
df_back = pd.DataFrame(arr_back, columns=df_out.columns)

Sample run -

In [164]: df
Out[164]: 
   a    b
0  1  2.0
1  3  4.0
2  5  6.0

In [165]: df_out
Out[165]: 
           a          b
0  [1, 3, 5]  [2, 4, 6]

In [166]: df_back
Out[166]: 
   a  b
0  1  2
1  3  4
2  5  6
Sign up to request clarification or add additional context in comments.

1 Comment

if i want to back

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.