パラメータconverters
を使用しread_csv
て、分割用のカスタム関数を定義できます。
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]
および列NaN
で動作する別のソリューション:4.
5.
read_csv
セパレーターと一緒に使用し、選択した列;
に適用str.split
して4.
、各値を次のように変換できます。5.
iloc
list
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]
numpy arrays
代わりに必要な場合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'>
私はあなたの解決策を改善しようとします:
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(',')])