替换Python列表内的pandas数据框列中的字符串值

时间:2019-06-03 12:21:22

标签: python pandas

我的数据框中有这样的一列:

  ___________________________
 |  columnn                  |
 ____________________________
 | [happiness#sad]           |
 | [happy ness#moderate]     |
 | [happie ness#sad]         |
 ____________________________

我想用“幸福”代替“幸福”,“幸福”,“幸福”。我目前正在使用此方法,但没有任何改变。

  string exactly matching 
  happy ness===> happyness
  happiness  ===> happyness
  happie ness===>happyness

我尝试以下两种方法

第一种方法

   df['column']
   df.column=df.column.replace({"happiness":"happyness" ,"happy ness":"happyness" ,"happie ness":"happynesss" })

第二种方法

   df['column']=df['column'].str.replace("happiness","happyness").replace(“happy ness”.”happyness”).replace(“happie ness”,”happynesss”) 

所需的输出:

           ______________________
          |  columnn             |
           _______________________
          | [happyness,sad]      |
          | [happyness,moderate] |
          | [happyness,sad]      |
          _______________________

2 个答案:

答案 0 :(得分:1)

这是将replaceregex=True结合使用的一种方法。

例如:

import pandas as pd

df = pd.DataFrame({"columnn": [["happiness#sad"], ["happy ness#moderate"], ["happie ness$sad"]]})
data = {"happiness":"happyness" ,"happy ness":"happyness" ,"happie ness":"happynesss" }
df["columnn"] = df["columnn"].apply(lambda x: pd.Series(x).replace(data, regex=True).tolist())
print(df)

输出:

                columnn
0       [happyness#sad]
1  [happyness#moderate]
2      [happynesss$sad]

答案 1 :(得分:0)

尝试这种方法,我认为这将为您工作。

df['new_col']=df['column'].replace(to_replace = 
['happyness','happiness','happie ness'], value = 
['happyness','happyness','happyness'])