想要用Python替换某些值的列

时间:2018-03-02 06:41:04

标签: python python-3.x pandas dataframe replace

使用的代码:

def fn(x):
    for i in x:
        x=x.replace('Wood','Wooden')
        return x


test['Coming:'] = test['Column:'].apply(fn)

示例输出:

Column:       Coming:      Needed:
 Wood         Wooden       Wooden                                        
Wooden       Woodenen      Wooden

我希望Wooden和类似的类别保持完整,如Woodingswoods等。 还有栏:可以是字符串,例如“木头在地上”,需要的输出是“木有地面”

2 个答案:

答案 0 :(得分:1)

您可以使用pandas replace function。在字典中定义要替换的内容并替换新列中的单词:

import pandas as pd
#test data
df = pd.DataFrame(["Wood", "Wooden", "Woody Woodpecker", "wood", "wool", "wool suit"], columns = ["old"])
#dictionary for substitutions
subst_dict = {"Wood": "Wooden", "wool": "soft"}
df["new"] = df["old"].replace(subst_dict)
#output
                old               new
0              Wood            Wooden
1            Wooden            Wooden
2  Woody Woodpecker  Woody Woodpecker
3              wood              wood
4              wool              soft
5         wool suit         wool suit

虽然对于使用正则表达式的更复杂的替换,但编写函数并使用apply()方法可能是个好主意。

更改要求后更新:
如果您只想匹配短语中的整个单词,可以使用正则表达式:

import pandas as pd
#test data
df = pd.DataFrame(["Wood", "Wooden", "Woody Woodpecker", "wood", "wool", "wool suit", "Wood is delicious", "A beautiful wool suit"], columns = ["old"])
#dictionary for substitutions
subst_dict = {"Wood": "Wooden", "wool": "soft"}
#create dictionary of regex expressions
temp_dict = {r'(\b){}(\b)'.format(k) : v for k, v in subst_dict.items()}
#and substitute
df["new"] = df["old"].replace(temp_dict, regex = True)
#output
                     old                    new
0                   Wood                 Wooden
1                 Wooden                 Wooden
2       Woody Woodpecker       Woody Woodpecker
3                   wood                   wood
4                   wool                   soft
5              wool suit              soft suit
6      Wood is delicious    Wooden is delicious
7  A beautiful wool suit  A beautiful soft suit

答案 1 :(得分:1)

这是替换字典中所有子字符串的一种方法。请注意,如果字典中的任何值和键发生冲突,顺序可能会变得很重要:

import pandas as pd

s = pd.Series(['Wood', 'Wooden', 'Woody Woodpecker', 'wood', 'wood', 'wool suit'])

d = {'Wood': 'Wooden', 'wool': 'soft'}

for k, v in d.items():
    s = s.str.replace(k, v)

# 0                  Wooden
# 1                Woodenen
# 2    Woodeny Woodenpecker
# 3                    wood
# 4                    wood
# 5               soft suit
# dtype: object