2017-01-30 2 views
3

Diese Pandas Aktualisierung ist meine CSV-Dateiwie Zeile in Datenrahmen hinzufügen iterativ es nach jedem for-Schleife in Python vorzugsweise

Choco_Type,ID,Cocoa,Milk,Sugar,ID,Cocoa,Milk,Sugar 
Dark,Batch_11,80,0,16,Batch_12,78,0,14 
Milk,Batch_72,35,25,25,Batch_73,32,27,22 
Swiss,Batch_52,30,30,20,Batch_53,28,33,18 

Das ist mein Code

for row in reader_in: 
    type_chocolate=row[0] 
    a= [(type_chocolate,row[1],row[2],row[3],row[4]),(type_chocolate,row[5],row[6],row[7],row[8])] 
    df=DataFrame.from_records(a) 

soll dies meine Ausgabe ist Datenrahmen

Choco_Type ID Cocoa Milk Sugar 
Dark Batch_11 80 0 16 
Dark Batch_12 78 0 14 
Milk Batch_72 35 25 25 
Milk Batch_73 32 27 22 
Swiss Batch_52 30 30 20 
Swiss Batch_53 28 33 18  

vermag ich nicht zu verstehen, wie die DataFrame'df für ‚Schleife‘ nach jedem‘aktualisieren mit neuen Zeilen welche aktualisiert von ‚from_records‘ Funktion, die eine Liste von dem Iterables reader_in nimmt, wie es Eingang der

+1

Frage, warum laden Sie eine einzelne Zeile auf einmal? Warum liest du nicht einfach die ganze Datei mit 'read_table' oder' read_csv'? – EdChum

+0

Ich lese die vollständige CSV-Datei, aber ich modifiziere jede Zeile und weiter wollte ich einen DataFrame daraus erstellen –

Antwort

2

Inbetriebnahme read_csv für DataFrame von csv erzeugen.

Dann replace.1 zu leeren String, was für NO-Duplikate in Spaltennamen hinzugefügt wurde.

set_index mit ersten Spalte und verwenden concat mit der Auswahl ersten und letzten 4 Spalten von iloc:

import pandas as pd 
from pandas.compat import StringIO 

temp=u"""Choco_Type,ID,Cocoa,Milk,Sugar,ID,Cocoa,Milk,Sugar 
Dark,Batch_11,80,0,16,Batch_12,78,0,14 
Milk,Batch_72,35,25,25,Batch_73,32,27,22 
Swiss,Batch_52,30,30,20,Batch_53,28,33,18""" 
#after testing replace 'StringIO(temp)' to 'filename.csv' 
df = pd.read_csv(StringIO(temp)) 
print (df) 

    Choco_Type  ID Cocoa Milk Sugar  ID.1 Cocoa.1 Milk.1 Sugar.1 
0  Dark Batch_11  80  0  16 Batch_12  78  0  14 
1  Milk Batch_72  35 25  25 Batch_73  32  27  22 
2  Swiss Batch_52  30 30  20 Batch_53  28  33  18 


df.columns = df.columns.str.replace('.1', '') 
df = df.set_index('Choco_Type') 
df = pd.concat([df.iloc[:, :4], df.iloc[:, 4:]]).reset_index() 

print (df) 
    Choco_Type  ID Cocoa Milk Sugar 
0  Dark Batch_11  80  0  16 
1  Milk Batch_72  35 25  25 
2  Swiss Batch_52  30 30  20 
3  Dark Batch_12  78  0  14 
4  Milk Batch_73  32 27  22 
5  Swiss Batch_53  28 33  18 

Wenn erforderlich ist, um gewünschte Ausgangs geändert:

df.columns = df.columns.str.replace('.1', '') 
df = df.set_index('Choco_Type') 
df = pd.concat([df.iloc[:, :4], df.iloc[:, 4:]], keys=(1,2), axis=1) 
     .stack(0) 
     .reset_index(level=1, drop=True) 
     .reset_index() 
print (df) 

    Choco_Type  ID Cocoa Milk Sugar 
0  Dark Batch_11  80  0  16 
1  Dark Batch_12  78  0  14 
2  Milk Batch_72  35 25  25 
3  Milk Batch_73  32 27  22 
4  Swiss Batch_52  30 30  20 
5  Swiss Batch_53  28 33  18 

Eine andere Lösung mit pd.lreshape durch dict was von dict comprehension mit Spaltennamen erstellt wird, die .1 nicht enthält, ist auch notwendig y entfernen Choco_Type:

cols = df.columns[~((df.columns.str.contains('.1')) | (df.columns == 'Choco_Type'))] 
print (cols) 
Index(['ID', 'Cocoa', 'Milk', 'Sugar'], dtype='object') 

d = {x: df.columns[df.columns.str.contains(x)].tolist() for x in cols} 
print (d) 
{'Milk': ['Milk', 'Milk.1'], 
'Sugar': ['Sugar', 'Sugar.1'], 
'ID': ['ID', 'ID.1'], 
'Cocoa': ['Cocoa', 'Cocoa.1']} 

df = pd.lreshape(df, d) 
print (df) 
    Choco_Type Milk Sugar  ID Cocoa 
0  Dark  0  16 Batch_11  80 
1  Milk 25  25 Batch_72  35 
2  Swiss 30  20 Batch_52  30 
3  Dark  0  14 Batch_12  78 
4  Milk 27  22 Batch_73  32 
5  Swiss 33  18 Batch_53  28 
+0

was bedeutet .1 bedeuten in str.replace –

+0

bedeutet es Spaltennamen sind 'ID.1' so müssen Sie entfernen'. 1' (dieses Problem ist in Pandas 0.19.2, in einigen älteren Versionen pandas doesnt '.1' wenn doppelte Spaltennamen) – jezrael

+0

Vielen Dank !!! aber könntest du mir etwas erklären, was ist reset_index und wie wird es hier verwendet? –

Verwandte Themen