Sie können Parameter verwenden converters
in read_csv
und benutzerdefinierte Funktion für spliting definieren:
def f(x):
return [float(i) for i in x.split(',')]
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),
sep=";",
converters={'D_8_lamsoni_w_time':f, 'D_8_lamsoni_w_value':f})
print (df)
vin vorgangid eventkm D_8_lamsoni_w_time D_8_lamsoni_w_value
0 V345578 295234545 13 [-1000.0, -980.0] [7.9921875, 11.984375]
1 V346670 329781064 13 [-960.0, -940.0] [7.9921875, 11.984375]
Eine andere Lösung mit NaN
in 4.
und 5.
Spalten arbeiten:
Sie können read_csv
mit Separatoren ;
verwenden und dann str.split
auf 4.
undanwendenSpalte von iloc
ausgewählt und jeder Wert in list
konvertieren float
:
import pandas as pd
import numpy as np
import io
temp=u"""vin;vorgangid;eventkm;D_8_lamsoni_w_time;D_8_lamsoni_w_value
V345578;295234545;13;-1000.0,-980.0;7.9921875,11.984375
V346670;329781064;13;-960.0,-940.0;7.9921875,11.984375"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";")
print (df)
vin vorgangid eventkm D_8_lamsoni_w_time D_8_lamsoni_w_value
0 V345578 295234545 13 -1000.0,-980.0 7.9921875,11.984375
1 V346670 329781064 13 -960.0,-940.0 7.9921875,11.984375
#split 4.th and 5th column and convert to numpy array
df.iloc[:,3] = df.iloc[:,3].str.split(',').apply(lambda x: [float(i) for i in x])
df.iloc[:,4] = df.iloc[:,4].str.split(',').apply(lambda x: [float(i) for i in x])
print (df)
vin vorgangid eventkm D_8_lamsoni_w_time D_8_lamsoni_w_value
0 V345578 295234545 13 [-1000.0, -980.0] [7.9921875, 11.984375]
1 V346670 329781064 13 [-960.0, -940.0] [7.9921875, 11.984375]
Wenn Bedarf numpy arrays
statt lists
:
#split 4.th and 5th column and convert to numpy array
df.iloc[:,3] = df.iloc[:,3].str.split(',').apply(lambda x: np.array([float(i) for i in x]))
df.iloc[:,4] = df.iloc[:,4].str.split(',').apply(lambda x: np.array([float(i) for i in x]))
print (df)
vin vorgangid eventkm D_8_lamsoni_w_time D_8_lamsoni_w_value
0 V345578 295234545 13 [-1000.0, -980.0] [7.9921875, 11.984375]
1 V346670 329781064 13 [-960.0, -940.0] [7.9921875, 11.984375]
print (type(df.iloc[0,3]))
<class 'numpy.ndarray'>
Ich versuche Ihre solutiuon zu verbessern:
a=0;
csv_import=pd.read_csv(folder+FileName, ';')
for col in csv_import.columns:
a += 1
if type(csv_import.ix[0, col])== str and a>3:
# string to list of strings
csv_import[col]=csv_import[col].apply(lambda x: [float(y) for y in x.split(',')])
Interessanter Ansatz, wie funktioniert das in Python 3.5? importieren io pd.read_csv (io ('' .join (l.replace (';', ',')) für l in open ('stuff.csv')))) funktioniert nicht – valenzio
@valenzio Ich habe gerade dies auf 3.5.2 überprüft, und es ist genauso. –
Ich bekomme die Massage, kein Modul namens 'cStringIO' muss ich dieses Modul über Pip installieren, hatte ich das Gefühl, es kommt mit Python – valenzio