[英]Replace string/value in entire DataFrame
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).
(类似于 fillna 方法,但用关联值替换特定字符串)。 Is there anyway to do this?
有没有办法做到这一点?
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 //乔纳斯
考虑到data
是您的pandas DataFrame
data
pandas DataFrame
您还可以使用:
data.replace({'very bad': 1, 'bad': 2, 'poor': 3, 'good': 4, 'very good': 5}, inplace=True)
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 本身中显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.