2017-10-18 6 views
0

Ich habe unter der Liste des Wörterbuchs.Fehler in der Liste von Wörterbuch zu Datenrahmen in Python

content = ['{"a": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E; 360SE)", "c": "US", "nk": 0, "tz": "America/Los_Angeles", "g": "1lj67KQ", "h": "1xupVE6", "mc": 807, "u": "https://cdn.adf.ly/js/display.js", "t": 1427288399, "cy": "Mountain View"}\n', 
'{"a": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E; 360SE)", "c": "US", "nk": 0, "tz": "America/New_York", "g": "1lj67KQ", "h": "1xupVE6", "mc": 514, "u": "https://cdn.adf.ly/js/display.js", "t": 1427288399, "cy": "Buffalo"}\n'] 

als ich versuchte Liste der Wörterbuch-Datenrahmen zu konvertieren oder Spalten mit Schlüsseln und Werten in den Zeilen erstellen, ich bin immer 'TypeError: string indices must be integers' Fehlermeldung.

Methode: 1

for x in content: 

    print (x["a"], x["nk"]) 

Methode: 2

result = [] 

sumlist = ["a", "nk"] 
for d in content: 

     result.append({"col1": d["a"], 
        "col2": d['nk']}) 

print (result) 

Antwort

3

Option 1
Es tatsächlich ist JSON, Sie können Verwendung json_normalize + json.loads.

df = pd.io.json.json_normalize([json.loads(x) for x in content]) 
print(df) 
                a c    cy \ 
0 Mozilla/5.0 (compatible; MSIE 9.0; Windows NT ... US Mountain View 
1 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT ... US  Buffalo 

     g  h mc nk   t     tz \ 
0 1lj67KQ 1xupVE6 807 0 1427288399 America/Los_Angeles 
1 1lj67KQ 1xupVE6 514 0 1427288399  America/New_York 

            u 
0 https://cdn.adf.ly/js/display.js 
1 https://cdn.adf.ly/js/display.js 

Wenn alles, was Sie wollen, sind a und nk verwenden:

df = pd.DataFrame.from_dict(content)[['a', 'nk']] 

Option 2
ast.literal_eval.

import ast 

content = [ast.literal_eval(x) for x in content] 
df = pd.DataFrame.from_dict(content) 

print(df)              
                a c    cy \ 
0 Mozilla/5.0 (compatible; MSIE 9.0; Windows NT ... US Mountain View 
1 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT ... US  Buffalo 

     g  h mc nk   t     tz \ 
0 1lj67KQ 1xupVE6 807 0 1427288399 America/Los_Angeles 
1 1lj67KQ 1xupVE6 514 0 1427288399  America/New_York 

            u 
0 https://cdn.adf.ly/js/display.js 
1 https://cdn.adf.ly/js/display.js 
+0

Schön, dass Sie, um zu sehen (-: – piRSquared

+0

@piRSquared Hallo Nizza zurück zu sein –

+0

@JayDhanki hinzugefügt eine andere Methode, könnte schneller sein, beide versuchen und sehen, was für Sie arbeitet Wenn die Antwort hilft,!... Bitte markieren Sie es akzeptiert! Danke. –

Verwandte Themen