Python 替换整个 DataFrame 中的字符串/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17142304/
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
Replace string/value in entire DataFrame
提问by jonas
I have a very large dataset were I want to replace strings with numbers. I would like to operate on the dataset without typing a mapping function for each key (column) in the dataset. (similar to the fillna method, but replace specific string with assosiated value). Is there anyway to do this?
我有一个非常大的数据集,我想用数字替换字符串。我想在不为数据集中的每个键(列)键入映射函数的情况下对数据集进行操作。(类似于 fillna 方法,但用关联值替换特定字符串)。有没有办法做到这一点?
Here is an example of my dataset
这是我的数据集的示例
data
resp A B C
0 1 poor poor good
1 2 good poor good
2 3 very good very good very good
3 4 bad poor bad
4 5 very bad very bad very bad
5 6 poor good very bad
6 7 good good good
7 8 very good very good very good
8 9 bad bad very bad
9 10 very bad very bad very bad
The desired result:
想要的结果:
data
resp A B C
0 1 3 3 4
1 2 4 3 4
2 3 5 5 5
3 4 2 3 2
4 5 1 1 1
5 6 3 4 1
6 7 4 4 4
7 8 5 5 5
8 9 2 2 1
9 10 1 1 1
very bad=1, bad=2, poor=3, good=4, very good=5
非常差=1、差=2、差=3、好=4、非常好=5
//Jonas
//乔纳斯
采纳答案by waitingkuo
回答by Jash Shah
Considering datais your pandas DataFrameyou can also use:
考虑到data您pandas DataFrame还可以使用:
data.replace({'very bad': 1, 'bad': 2, 'poor': 3, 'good': 4, 'very good': 5}, inplace=True)
回答by Nikola S
data = data.replace(['very bad', 'bad', 'poor', 'good', 'very good'],
[1, 2, 3, 4, 5])
data = data.replace(['very bad', 'bad', 'poor', 'good', 'very good'],
[1, 2, 3, 4, 5])
You must state where the result should be saved. If you say only data.replace(...)it is only shown as a change in preview, not in the envirable itself.
您必须说明结果应保存在何处。如果你只说data.replace(...)它只显示为预览中的更改,而不是在 envirable 本身中。

