2017-05-29 22 views
1

Ich bin auf Python 3.4 arbeiten und ich habe eine Pandas Datenframe-Spalte enthält:Split Pandas Spalte Python

0 [0.3785766661167145, -0.449486643075943, -0.15...] 
1 [0.204025000333786, -0.3685399889945984, 0.231...] 
2 [0.684576690196991, -0.5823000073432922, 0.269...] 
3 [-0.02300500124692917, -0.22056499123573303, 0...] 
Name: comments, dtype: object 

und ich würde es teilen möchte und es in multople Spalten drehen:

column1    column2    ...columnx 
0 0.3785766661167145 -0.449486643075943  last element in the first list 
1 0.204025000333786  -0.3685399889945984 last element in the 2nd list 
2 0.684576690196991  -0.5823000073432922 last element in the 3rd list 
3 -0.02300500124692917 -0.22056499123573303 last element in the 4th list 

Könnten Sie mir bitte helfen? Vielen Dank im Voraus

Antwort

0

H Mit @ dDanny dem Beispiel Datenrahmen, aving ein Datenrahmen

df = pd.Series(
    {'comments': [list(np.random.randn(3).round()) for i in range(4)] 
    } 
) 

wo df=

comments 
0 [1.0, -2.0, 0.0] 
1 [1.0, -3.0, -0.0] 
2 [-0.0, -0.0, -1.0] 
3 [-2.0, -2.0, -2.0] 

df2 = DataFrame(list(df['comments'])) 

aufrufen Sie

 0 1 2 
0 1.0 -2.0 0.0 
1 1.0 -3.0 -0.0 
2 -0.0 -0.0 -1.0 
3 -2.0 -2.0 -2.0 
0

Testfall:

import pandas as pd 
df = pd.DataFrame({ 
       'var1':['20, -20, -50','30, 20, -50','40','30'], 
       'var2':['10','50','60','70'] 
       }) 
print(df) 

    var1   var2 
0 20, -20, -50 10 
1 30, 20, -50  50 
2 40    60 
3 30    70 

pd.concat([df[['var2']], df['var1'].str.split(',', expand=True)], axis=1) 

enter image description here

1

Wenn in Daten sind lists Notwendigkeit DataFrame Konstruktor mit Spalten Umwandlung comments zu numpy array von values + tolist:

print (type(df.loc[0, 'comments'])) 
<class 'list'> 

df1 = pd.DataFrame(df['comments'].values.tolist()) 
#rename columns if necessary 
df1 = df1.rename(columns = lambda x: 'column' + str(x + 1)) 
print (df1) 
    column1 column2 column3 
0 0.378577 -0.449487 -0.150 
1 0.204025 -0.368540 0.231 
2 0.684577 -0.582300 0.269 
3 -0.023005 -0.220565 0.000 
0

erhalten

df = pd.DataFrame(
    {'comments': [list(np.random.randn(3).round()) for i in range(4)] 
    }) 

Sie können Apply anwenden, um die Spalte, die Listen enthält, in einen Dataframe umzuwandeln.

df.comments.apply(pd.Series) 
Out[127]: 
    0 1 2 
0 -2.0 -3.0 -1.0 
1 1.0 0.0 1.0 
2 -1.0 -1.0 -0.0 
3 1.0 1.0 0.0 
Verwandte Themen