python一列拆分成多列_使用python pandas将一列拆分为多列

也许另一种方法是将元组列转换为DataFrame,如下所示:In [10]: DataFrame(df['Turnstile'].tolist())

Out[10]:

0 1 2 3

0 A006 R079 00-00-04 5 AVE-59 ST

1 A006 R079 00-00-04 5 AVE-59 ST

2 A006 R079 00-00-04 5 AVE-59 ST

3 A006 R079 00-00-04 5 AVE-59 ST

4 A006 R079 00-00-04 5 AVE-59 ST

5 A006 R079 00-00-04 5 AVE-59 ST

6 A006 R079 00-00-04 5 AVE-59 ST

7 A006 R079 00-00-04 5 AVE-59 ST

8 A006 R079 00-00-04 5 AVE-59 ST

9 A006 R079 00-00-04 5 AVE-59 ST

如果是这样的话,下面是一个将元组列转换为DataFrame并将其添加回原始数据帧的示例:import numpy as np

import pandas as pd

from pandas import Series, DataFrame

# create a fake dataframe, repeating the tuple given in the example

In [2]: df = DataFrame(data={'Observations': np.random.randn(10) * np.arange(10),

...: 'Turnstile': (('A006', 'R079', '00-00-04', '5 AVE-59 ST'),)*10})

In [3]: df.head()

Out[3]:

Observations Turnstile

0 -0.000000 (A006, R079, 00-00-04, 5 AVE-59 ST)

1 -0.022668 (A006, R079, 00-00-04, 5 AVE-59 ST)

2 -2.380515 (A006, R079, 00-00-04, 5 AVE-59 ST)

3 -4.209983 (A006, R079, 00-00-04, 5 AVE-59 ST)

4 3.932902 (A006, R079, 00-00-04, 5 AVE-59 ST)

# all at once turn the column of tuples into a dataframe and concat that with the original df

In [4]: df = pd.concat([df,DataFrame(df['Turnstile'].tolist())], axis=1, join='outer')

In [5]: df.head()

Out[5]:

Observations Turnstile 0 1 2 \

0 -0.000000 (A006, R079, 00-00-04, 5 AVE-59 ST) A006 R079 00-00-04

1 -0.022668 (A006, R079, 00-00-04, 5 AVE-59 ST) A006 R079 00-00-04

2 -2.380515 (A006, R079, 00-00-04, 5 AVE-59 ST) A006 R079 00-00-04

3 -4.209983 (A006, R079, 00-00-04, 5 AVE-59 ST) A006 R079 00-00-04

4 3.932902 (A006, R079, 00-00-04, 5 AVE-59 ST) A006 R079 00-00-04

3

0 5 AVE-59 ST

1 5 AVE-59 ST

2 5 AVE-59 ST

3 5 AVE-59 ST

4 5 AVE-59 ST

# i assume you don't need this column anymore

In [6]: del df['Turnstile']

如果可以,当然可以根据需要命名新列。

你可能感兴趣的:(python一列拆分成多列)