David
David

Reputation: 51

How to flat a string to several columns in pandas?

fruit = pd.DataFrame({'type': ['apple: 1 orange: 2 pear: 3']})

I want to flat the dataframe and get the below format:

apple orange pear
1 2 3

Thanks

Upvotes: 0

Views: 46

Answers (1)

maow
maow

Reputation: 2887

You are making your live extremely difficult if you work with multiple values in a single field. You can basically use none of the pandas functions because they all assume they data in a field belong together and should stay together.

For instance with

In [10]: fruit = pd.Series({'apple': 1, 'orange': 2, 'pear': 3})

In [11]: fruit
Out[11]: 
apple     1
orange    2
pear      3
dtype: int64

you could easily transform your data as in

In [14]: fruit.to_frame()
Out[14]: 
        0
apple   1
orange  2
pear    3

In [15]: fruit.to_frame().T
Out[15]: 
   apple  orange  pear
0      1       2     3

Upvotes: 1

Related Questions