user1854186 user1854186 - 4 months ago 16
Python Question

append all column in list - pandas

I want to be able from a pandas Dataframe like this:

s = pd.Series([0,1,2,4])
pd.get_dummies(s)
Out[1]:
0 1 2 4
0 1.0 0.0 0.0 0.0
1 0.0 1.0 0.0 0.0
2 0.0 0.0 1.0 0.0
3 0.0 0.0 0.0 1.0


to get one like this

0 1 2 3
0 [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1]


I thought about something like this but it does not work

df.apply(lambda y: list(y))


Any idea?

Thank you.

EDIT:
Vinay87 answer work but it was not really my problem.

I was biased by my lack of knowledge and though good to simplify the problem.
What I wanted to do was to aggregate each group when applying groupby on a dataframe.
I knew only approach like the following

df.groupby("device_id").apply(function to turn dataframe in a dataframe with list)


I have been able to find a solution thanks to this problem and the answer of user2623954

Answer

How about this?

c = pd.Dataframe(columns = s.columns)
for column in s.columns: 
    c.set_value(0, column, list(s[column]))
Comments