2016-03-23 5 views
1

Ich versuche Col3 zu concern, wenn Col1 gleich dem gleichen Wert in der Zeile davor ist und schreibe dann die Ausgabe in eine neue Datei. Ich habe eine CSV-Datei, die wie folgt aussieht:So gruppieren Sie die nachfolgenden Zeilen mit identischen Schlüsseln in einer CSV-Datei

col1,col2,col3 
a,12,"hello " 
a,13,"good day" 
a,14,"nice weather" 
b,1,"cat" 
b,2,"dog and cat" 
c,2,"animals are cute" 

Ausgang Ich möchte:

Dies ist, was ich versucht habe:

import csv 

with open('myfile.csv', 'rb') as inputfile, open('outputfile.csv','wb') as outputfile: 
    reader=csv.reader(inputfile) 
    writer=csv.writer(outputfile) 
    next(reader) 
    for row in reader: 
     while row[0]==row[0]: 
      concat_text=" ".join(row[2]) 
     print concat_text 
     writer.writerow((row[0],concat_text)) 

Es läuft, aber ich habe keine Ausgabe. Hilfe geschätzt.

+3

'während row [0] == row [0] nach der Ausführung: ...' wird nie Fortschritt, es ist eine Endlosschleife. –

Antwort

3

Wenn Sie sich mit dem pandas interessiert sind, können Sie Ihre Gruppe DataFrame gibt dann die eindeutigen Werte:

import pandas as pd 

df = pd.read_csv('test.txt') 
print(df) 

Ihren ursprünglichen Datenrahmen

col1 col2    col3 
0 a 12   hello 
1 a 13   good day 
2 a 14  nice weather 
3 b  1    cat 
4 b  2  dog and cat 
5 c  2 animals are cute 

Den zweiten Datenrahmen

df2 = df.groupby(df['col1']) 
df2 = df2['col3'].unique() 
df2 = df2.reset_index() 

print(df2) 

bewirkt:

df2['col3'] = df2['col3'].apply(lambda x: ' '.join(s.strip() for s in x)) 

    col1       col3 
0 a hello good day nice weather 
1 b    cat dog and cat 
2 c    animals are cute 

komplette Code:

import pandas as pd 

df = pd.read_csv('test.txt') 
df2 = df.groupby(df['col1']) 

df2 = df2['col3'].unique() 
df2 = df2.reset_index() 

df2['col3'] = df2['col3'].apply(lambda x: ' '.join(s.strip() for s in x)) 

df2.to_csv('output.csv') 

col1        col3 
0 a [hello , good day, nice weather] 
1 b    [cat, dog and cat] 
2 c    [animals are cute] 

die dritte Spalte verketten, werden Sie apply als solche verwenden, müssen

+0

Es gibt zwei Leerzeichen nach "Hallo", aber gut genug, würde ich sagen –

+0

Das ist, weil hallo in den Originaldaten ein Leerzeichen hinterher hatte. – Leb

+0

@Leb denken Sie daran, 'df2.to_csv ('somefile.csv')' –

1
import csv 

with open('myfile.csv', 'rb') as inputfile, open('outputfile.csv', 'wb') as outputfile: 
    reader=csv.reader(inputfile) 
    writer=csv.writer(outputfile) 
    prior_val = None 
    text = [] 
    for line in reader: 
     if line[0] == prior_val: 
      text.append(line[2]) 
     else: 
      if text: 
       writer.writerow([prior_val, " ".join(text)]) 
      prior_val = line[0] 
      text = [line[2]] 
    if text: 
     writer.writerow([prior_val, " ".join(text)]) 

>>> !cat outputfile.csv 
col1,col3 
a,hello good day nice weather 
b,cat dog and cat 
c,animals are cute 

>>> pd.read_csv('outputfile.csv', index_col=0) 
          col3 
col1        
a  hello good day nice weather 
b     cat dog and cat 
c     animals are cute 
0

Das Problem war, dass Sie die gleiche Zeile mit sich selbst verglichen haben. Diese Version vergleicht die letzte Zeile mit der aktuellen Zeile. Die Ausgabe ist nicht durch Anführungszeichen getrennt, aber sie ist korrekt. Inhalt script.py

#!/usr/bin/env python 

import csv 

with open('myfile.csv', 'rb') as inputfile, open('outputfile.csv','wb') as outputfile: 
    reader=csv.reader(inputfile) 
    writer=csv.writer(outputfile) 
    next(reader) 
    lastRow = None 
    # assumes data is in order on first column 
    for row in reader: 
     if not lastRow: 
      # start processing line with the first column and third column 
      concat_text = row[2].strip() 
      lastRow = row 
      print concat_text 
     else: 
      if lastRow[0]==row[0]: 
       # add to line 
       concat_text = concat_text + ' ' + row[2].strip() 
       print concat_text 
      else: 
       # end processing 
       print concat_text 
       writer.writerow((lastRow[0],concat_text)) 
       # start processing 
       concat_text = row[2] 
       print concat_text 
      lastRow = row 
    # write out last element 
    print concat_text 
    writer.writerow((lastRow[0],concat_text)) 

./script.py die Inhalte outputfile.csv

a,hello good day nice weather 
b,cat dog and cat 
c,animals are cute 
Verwandte Themen