Pandas用列表替换列值

时间:2017-06-17 19:19:42

标签: python pandas dataframe

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

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

但这不起作用。基本上我的问题是如何从数据框中删除一列然后创建一个新列,其名称与我不知道列名时删除的列相同,只列列索引?

2 个答案:

答案 0 :(得分:2)

这应该适合你:

# 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替换它,则无需删除列。

答案 1 :(得分:1)

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

df['colname'] = newcol

这将在使用newcol替换其内容时保持名称不变。

相关问题