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
Frage, warum laden Sie eine einzelne Zeile auf einmal? Warum liest du nicht einfach die ganze Datei mit 'read_table' oder' read_csv'? – EdChum
Ich lese die vollständige CSV-Datei, aber ich modifiziere jede Zeile und weiter wollte ich einen DataFrame daraus erstellen –