2017-05-12 3 views
1

Je suis en train d'obtenir une liste de listes qui ressemble à ceci (appelons ce « tous »):Prenez une liste de listes, diviser une liste, puis convertir en dataframe

[['Albany County, Wyoming', '56', '001'], 
['Big Horn County, Wyoming', '56', '003'], 
['Campbell County, Wyoming', '56', '005'],... 

et le convertir dans un dataframe qui ressemblera à ceci:

COUNTY   STATE  FIPS1 FIPS2 
'Albany County' 'Wyoming' '56' '001' 
'Big Horn County' 'Wyoming' '56' '003' 
'Campbell County' 'Wyoming' '56' '005' 

C'est ce que j'ai jusqu'ici pour la liste des listes:

for index, line in enumerate(All): 
    All[index] = line[0].split(','), line[1:] 

pd.DataFrame(All) 

Mais ce retour est ing:

      0   1 
0  [Albany County, Wyoming] [56, 001] 
1  [Big Horn County, Wyoming] [56, 003] 
2  [Campbell County, Wyoming] [56, 005] 

Merci d'avance pour votre aide!

Répondre

2
All = [ 
    ['Albany County, Wyoming', '56', '001'], 
    ['Big Horn County, Wyoming', '56', '003'], 
    ['Campbell County, Wyoming', '56', '005'] 
] 

pd.DataFrame(
    [line[0].split(', ') + line[1:] for line in All], 
    columns=['COUNTY', 'STATE', 'FIPS1', 'FIPS2'] 
) 

      COUNTY STATE FIPS1 FIPS2 
0 Albany County Wyoming 56 001 
1 Big Horn County Wyoming 56 003 
2 Campbell County Wyoming 56 005 

Ou

df = pd.DataFrame(All, columns=['COUNTY, STATE', 'FIPS1', 'FIPS2']) 

col = 'COUNTY, STATE' 
df[col].str.extract(
    '(?P<COUNTY>.*), (?P<STATE>.*)', expand=True 
).join(df.drop(col, 1)) 

      COUNTY STATE FIPS1 FIPS2 
0 Albany County Wyoming 56 001 
1 Big Horn County Wyoming 56 003 
2 Campbell County Wyoming 56 005 
+0

Désolé, je quittais la dernière ligne de code. Je viens de l'éditer (pd.DataFrame (All)). – jtam

+0

@ user2970409 change 'ligne [0] .split (','), ligne [1:]' à 'ligne [0] .split (',') + ligne [1:]' – piRSquared

+0

Ce premier fonctionne! J'apprécie vraiment l'aide. – jtam

0

Vous pouvez aussi essayer ceci:

lst = [['Albany County, Wyoming', '56', '001'], 
['Big Horn County, Wyoming', '56', '003'], 
['Campbell County, Wyoming', '56', '005']] 

df = pd.DataFrame(lst) 
df.columns = ['COUNTY_STATE', 'FIPS1', 'FIPS2'] 
print(df) 
       COUNTY_STATE FIPS1 FIPS2 
0 Albany County, Wyoming 56 001 
1 Big Horn County, Wyoming 56 003 
2 Campbell County, Wyoming 56 005 

ALL = pd.DataFrame(df['COUNTY_STATE'].str.split(',').tolist(), columns = ['COUNTY','STATE']) 
ALL[['FIPS1', 'FIPS2']] = df[['FIPS1', 'FIPS2']] 
print(ALL) 
      COUNTY  STATE FIPS1 FIPS2 
0 Albany County Wyoming 56 001 
1 Big Horn County Wyoming 56 003 
2 Campbell County Wyoming 56 005 
+0

Merci! C'est toujours agréable de voir une autre solution. – jtam