在整个数据帧中替换字符串/值 [英] replace string/value in entire dataframe

查看:116
本文介绍了在整个数据帧中替换字符串/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的数据集,我想用数字替换字符串。我想在数据集上操作,而不在数据集中为每个键(列)键入映射函数。 (类似于fillna方法,但是用特定的字符串替换具体的字符串)。
有没有这样做?



这是我的数据集的一个例子

 数据
resp ABC
0 1可怜的穷人
1 2好可怜
2 3非常好非常好
3 4坏的坏坏
4 5非常糟糕非常糟糕非常糟糕
5 6差不好很糟糕
6 7好好好
7 8非常好非常好非常好
8 9坏坏坏
9 10非常糟糕非常糟糕非常糟糕

所需结果:

 数据
resp ABC
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

非常糟糕= 1,ba d = 2,差= 3,好= 4,非常好= 5



// Jonas

解决方案

使用替换

 在[126]中:df.replace(['very bad','bad','poor','好,'很好'],
[1,2,3,4,5])
输出[126]:
resp ABC
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


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?

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

//Jonas

解决方案

Use replace

In [126]: df.replace(['very bad', 'bad', 'poor', 'good', 'very good'], 
                     [1, 2, 3, 4, 5]) 
Out[126]: 
      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

这篇关于在整个数据帧中替换字符串/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆