Python 替换 Pandas DataFrame 中的列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23307301/
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
Replacing column values in a pandas DataFrame
提问by Black
I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.
我正在尝试替换数据帧的一列中的值。列 ('female') 仅包含值 'female' 和 'male'。
I have tried the following:
我尝试了以下方法:
w['female']['female']='1'
w['female']['male']='0'
But receive the exact same copy of the previous results.
但收到与先前结果完全相同的副本。
I would ideally like to get some output which resembles the following loop element-wise.
理想情况下,我希望获得一些类似于以下循环元素的输出。
if w['female'] =='female':
w['female'] = '1';
else:
w['female'] = '0';
I've looked through the gotchas documentation (http://pandas.pydata.org/pandas-docs/stable/gotchas.html) but cannot figure out why nothing happens.
我已经查看了 gotchas 文档(http://pandas.pydata.org/pandas-docs/stable/gotchas.html),但无法弄清楚为什么什么也没发生。
Any help will be appreciated.
任何帮助将不胜感激。
采纳答案by BrenBarn
If I understand right, you want something like this:
如果我理解正确,你想要这样的东西:
w['female'] = w['female'].map({'female': 1, 'male': 0})
(Here I convert the values to numbers instead of strings containing numbers. You can convert them to "1"
and "0"
, if you really want, but I'm not sure why you'd want that.)
(这里我将值转换为数字而不是包含数字的字符串。如果你真的想要,你可以将它们转换为"1"
and "0"
,但我不确定你为什么想要那样。)
The reason your code doesn't work is because using ['female']
on a column (the second 'female'
in your w['female']['female']
) doesn't mean "select rows where the value is 'female'". It means to select rows where the indexis 'female', of which there may not be any in your DataFrame.
您的代码不起作用的原因是因为['female']
在列('female'
您的第二个w['female']['female']
)上使用并不意味着“选择值为'女性'的行”。这意味着选择索引为“女性”的行,其中在您的 DataFrame 中可能没有任何行。
回答by Jimmy Petersson
You can edit a subset of a dataframe by using loc:
您可以使用 loc 编辑数据帧的子集:
df.loc[<row selection>, <column selection>]
In this case:
在这种情况下:
w.loc[w.female != 'female', 'female'] = 0
w.loc[w.female == 'female', 'female'] = 1
回答by jfs
w.female.replace(to_replace=dict(female=1, male=0), inplace=True)
回答by deckard
Slight variation:
轻微变化:
w.female.replace(['male', 'female'], [1, 0], inplace=True)
回答by Nick Crawford
This should also work:
这也应该有效:
w.female[w.female == 'female'] = 1
w.female[w.female == 'male'] = 0
回答by galliwuzz
Alternatively there is the built-in function pd.get_dummies for these kinds of assignments:
或者,对于这些类型的赋值,有内置函数 pd.get_dummies:
w['female'] = pd.get_dummies(w['female'],drop_first = True)
This gives you a data frame with two columns, one for each value that occurs in w['female'], of which you drop the first (because you can infer it from the one that is left). The new column is automatically named as the string that you replaced.
这为您提供了一个包含两列的数据框,一个用于 w['female'] 中出现的每个值,您删除其中的第一列(因为您可以从剩下的列中推断出它)。新列将自动命名为您替换的字符串。
This is especially useful if you have categorical variables with more than two possible values. This function creates as many dummy variables needed to distinguish between all cases. Be careful then that you don't assign the entire data frame to a single column, but instead, if w['female'] could be 'male', 'female' or 'neutral', do something like this:
如果您有具有两个以上可能值的分类变量,这将特别有用。该函数创建了区分所有情况所需的尽可能多的虚拟变量。请注意,不要将整个数据框分配给单个列,而是如果 w['female'] 可以是 'male'、'female' 或 'neutral',请执行以下操作:
w = pd.concat([w, pd.get_dummies(w['female'], drop_first = True)], axis = 1])
w.drop('female', axis = 1, inplace = True)
Then you are left with two new columns giving you the dummy coding of 'female' and you got rid of the column with the strings.
然后你会留下两个新的列,给你“女性”的虚拟编码,你摆脱了带有字符串的列。
回答by Roald
There is also a function in pandas
called factorize
which you can use to automatically do this type of work. It converts labels to numbers: ['male', 'female', 'male'] -> [0, 1, 0]
. See thisanswer for more information.
还有一个pandas
被调用的函数factorize
,您可以使用它来自动执行此类工作。它将标签转换为数字:['male', 'female', 'male'] -> [0, 1, 0]
。有关更多信息,请参阅此答案。
回答by student
You can also use apply
with .get
i.e.
您也可以apply
与.get
ie 一起使用
w['female'] = w['female'].apply({'male':0, 'female':1}.get)
:
w['female'] = w['female'].apply({'male':0, 'female':1}.get)
:
w = pd.DataFrame({'female':['female','male','female']})
print(w)
Dataframe w
:
数据框w
:
female
0 female
1 male
2 female
Using apply
to replace values from the dictionary:
使用apply
从字典替换值:
w['female'] = w['female'].apply({'male':0, 'female':1}.get)
print(w)
Result:
结果:
female
0 1
1 0
2 1
Note:apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
注意:apply
如果数据框中列的所有可能值都在字典中定义,则应使用字典,否则字典中未定义的值将为空。
回答by Azz
This is very compact:
这是非常紧凑的:
w['female'][w['female'] == 'female']=1
w['female'][w['female'] == 'male']=0
Another good one:
另一个不错的:
w['female'] = w['female'].replace(regex='female', value=1)
w['female'] = w['female'].replace(regex='male', value=0)
回答by Alex-droid AD
I think that in answer should be pointed which type of object do you get in all methods suggested above: is it Series or DataFrame.
我认为在回答中应该指出您在上面建议的所有方法中获得哪种类型的对象:它是 Series 还是 DataFrame。
When you get column by w.female.
or w[[2]]
(where, suppose, 2 is number of your column) you'll get back DataFrame.
So in this case you can use DataFrame methods like .replace
.
当您通过w.female.
or获取列时w[[2]]
(假设,2 是您的列数),您将返回 DataFrame。因此,在这种情况下,您可以使用 DataFrame 方法,例如.replace
.
When you use .loc
or iloc
you get back Series, and Series don't have .replace
method, so you should use methods like apply
, map
and so on.
当您使用.loc
或iloc
返回 Series 时,Series 没有.replace
方法,因此您应该使用诸如apply
, 之类的方法map
。