替换单元格内的特定值而不更改数据帧中的其他值 [英] Replace specific values inside a cell without chaging other values in a dataframe

查看:43
本文介绍了替换单元格内的特定值而不更改数据帧中的其他值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Pandas,并且有以下数据框 (df) 和一列 (mycol1).

I am using pandas and have the following dataframe (df) with a column (mycol1).

     mycol1
-----------------
|ABC            | 
|CDE            |
|EFG            |
|3              |
|2, GHI         |
|IJK            |
|2,4 KLM        |
|MNO            |
|5              |
|1, 2, 3, OPQ   |
|7 QRS          |
|STU            |
|UWX            |
|7              |
|XYZ            |
-----------------

我在 .replace 方法中使用了以下代码,但它替换了整个单元格字符串值,而不仅仅是数字.:

I have used the following code with .replace method but it replaces the whole cell string value and not only the numbers.:

df.mycol1.replace(to_replace=({'1':'anything','2':'Something',
'3':'Values here',
'4':'Homework','5':'my work',
'6':'Any values here',
'7':'More values'}))

我想用字符串值替换每个单元格中的数字代码,以便将字符串值与单元格中的现有字符串连接起来.例如,

I would like to replace the number codes in each cell with string values such that the string values will be concatenated with the existing string in the cells. For example,

     mycol1
-----------------
|ABC            
|CDE        
|EFG            
|Values here    
|Something, GHI 
|IJK            
|Something,Homework KLM
|MNO            
|my work              
|anything, Something, Values here, OPQ  
|More values QRS            
|STU            
|UWX            
|More values              
|XYZ            
-----------------

有人可以帮我解决这个问题吗?提前致谢!

Can anybody help me with this? Thanks in advance!

推荐答案

我认为你需要 replace 用数字作为带有代码的字符串的字典,替换子字符串添加 regex=True:

d = {'1':'a', '2':'b', '3':'c', '4':'d', '7':'e'}
df['mycol2'] = df['mycol1'].replace(d, regex=True)
print (df)
          mycol1        mycol2
0            ABC           ABC
1            CDE           CDE
2            EFG           EFG
3         2, GHI        b, GHI
4            IJK           IJK
5        2,4 KLM       b,d KLM
6            MNO           MNO
7   1, 2, 3, OPQ  a, b, c, OPQ
8          7 QRS         e QRS
9            STU           STU
10           UWX           UWX
11           XYZ           XYZ

这篇关于替换单元格内的特定值而不更改数据帧中的其他值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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