您可以使用read_csv
和参数sep=';'
和header=None
(如果csv
中没有标题)。然后,你需要apply
功能str.split
,因为string
功能与Series
(的df
列)只工作:
import pandas as pd
import io
temp=u"""1,1,1;2,2,2;3,3,3
1,1,1;2,2,2;3,3,3
1,1,1;2,2,2;3,3,3"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";", header=None)
print (df)
0 1 2
0 1,1,1 2,2,2 3,3,3
1 1,1,1 2,2,2 3,3,3
2 1,1,1 2,2,2 3,3,3
print (df.apply(lambda x: x.str.split(',')))
0 1 2
0 [1, 1, 1] [2, 2, 2] [3, 3, 3]
1 [1, 1, 1] [2, 2, 2] [3, 3, 3]
2 [1, 1, 1] [2, 2, 2] [3, 3, 3]
print (df.apply(lambda x: x.str.split(',')).values.tolist())
[[['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']],
[['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']],
[['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']]]
但如果int
需求清单:
import pandas as pd
import io
temp=u"""1,1,1;2,2,2;3,3,3
1,1,1;2,2,2;3,3,3
1,1,1;2,2,2;3,3,3"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";", header=None)
print (df)
0 1 2
0 1,1,1 2,2,2 3,3,3
1 1,1,1 2,2,2 3,3,3
2 1,1,1 2,2,2 3,3,3
for col in df.columns:
df[col] = df[col].str.split(',')
#if need convert string numbers to int
df[col] = [[int(y) for y in x] for x in df[col]]
print (df.values.tolist())
[[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]