熊猫用列表替换列值

use*_*047 3 python dataframe pandas

我有一个数据框df,其中某些列是字符串,而某些列是数字。我正在尝试将它们全部转换为数字。所以我想做的是这样的:

col = df.ix[:,i]
le = preprocessing.LabelEncoder()
le.fit(col)
newCol = le.transform(col)
df.ix[:,i] = newCol
Run Code Online (Sandbox Code Playgroud)

但这不起作用。基本上,我的问题是如何在不知道列名而仅知道列索引的情况下,如何从数据框中删除列,然后创建与删除的列同名的新列?

小智 6

newcol = [..,..,.....]

df['colname'] = newcol
Run Code Online (Sandbox Code Playgroud)

这将保持 colname 不变,同时用 newcol 替换其内容。


elP*_*tor 5

这应该为您做:

# 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
Run Code Online (Sandbox Code Playgroud)

... [1]索引在哪里都axis = 1应该更改。

这从字面上回答了您的问题,您要求在哪里放置一列然后再添加一列。但是现实是,只要将其替换为,就无需删除该列newCol