我想你需要str.split
:
data = pd.read_csv('data/training.csv')
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False)
然后选择第一个或一些带有str[1]
或str[n]
另一个数组中的元素:
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[0]
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[n]
样品:
import pandas as pd
data = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':['aa aa','ss uu','ee tt']})
print (data)
A B C D E F
0 1 4 7 1 5 aa aa
1 2 5 8 3 3 ss uu
2 3 6 9 5 6 ee tt
print (data.iloc[:,-1].str.split(expand=False))
0 [aa, aa]
1 [ss, uu]
2 [ee, tt]
Name: F, dtype: object
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[0]
print (data)
A B C D E F
0 1 4 7 1 5 aa
1 2 5 8 3 3 ss
2 3 6 9 5 6 ee
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[1]
print (data)
A B C D E F
0 1 4 7 1 5 aa
1 2 5 8 3 3 uu
2 3 6 9 5 6 tt
Can anyone explain why I am getting the above error and how can I get around it?
问题是imageString.split(" ")
返回list
并且如果分配给data[idx,-1]
,字符串的元素的长度短,因为所有的数据帧的长度。
Is this the proper way to apply a split to every value in the last column of my data frame?
更好的是使用字符串方法,请参阅pandas documentation。
数据[data.columns [-1] = data.iloc [: - 1] .MAP(拉姆达X:x.split ('')) – frist