2017-06-17 128 views
2

我有一個數據框df其中一些列是字符串,一些是數字。我試圖將它們全部轉換爲數字。所以我想要做的是這樣的:熊貓用列表替換列值

col = df.ix[:,i] 
le = preprocessing.LabelEncoder() 
le.fit(col) 
newCol = le.transform(col) 
df.ix[:,i] = newCol 

但這不起作用。基本上我的問題是,如何從數據框中刪除一列,然後創建一個與列名相同的新列,當我不知道列名時只列名索引?

回答

1

這應該爲你做它:

# Find the name of the column by index 
n = df.columns[1] 

# Drop that column 
df.drop(n, axis = 1, inplace = True) 

# Put whatever series you want in its place 
df[n] = newCol 

...其中[1]可無論指數,axis = 1不應改變。

這個問題很直接地回答你的問題,你要求刪除一列然後再添加一列。但事實是,如果你用newCol替換它,沒有必要放棄列。