我想你需要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