Pandas 用列表替换列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44608524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas replace column values with a list
提问by user3494047
I have a dataframe df
where some of the columns are strings and some are numeric. I am trying to convert all of them to numeric. So what I would like to do is something like this:
我有一个数据框df
,其中一些列是字符串,一些列是数字。我正在尝试将它们全部转换为数字。所以我想做的是这样的:
col = df.ix[:,i]
le = preprocessing.LabelEncoder()
le.fit(col)
newCol = le.transform(col)
df.ix[:,i] = newCol
but this does not work. Basically my question is how do I delete a column from a data frame then create a new column with the same name as the column I deleted when I do not know the column name, only the column index?
但这不起作用。基本上我的问题是如何从数据框中删除一列然后创建一个与我删除的列同名的新列,当我不知道列名,只知道列索引时?
回答by elPastor
This should do it for you:
这应该为你做:
# 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
...where [1]
can be whatever the index is, axis = 1
should not change.
... where[1]
可以是任何索引,axis = 1
不应更改。
This answers your question very literally where you asked to drop a column and then add one back in. But the reality is that there is no need to drop the column if you just replace it with newCol
.
这从字面上回答了您要求删除列然后重新添加列的问题。但现实情况是,如果您只是将其替换为newCol
.
回答by Sree Charan
newcol = [..,..,.....]
df['colname'] = newcol
This will keep the colname intact while replacing its contents with newcol.
这将保持 colname 不变,同时用 newcol 替换其内容。