小编ksg*_*gj1的帖子

如何使用字典替换Pandas系列中的多个子串?

我有一个熊猫系列的字符串.我想对每行的多个子串进行多次替换,请参阅:

testdf = pd.Series([
    'Mary went to school today',
    'John went to hospital today'
])
to_sub = {
    'Mary': 'Alice',
    'school': 'hospital',
    'today': 'yesterday',
    'tal': 'zzz',
}
testdf = testdf.replace(to_sub, regex=True)  # does not work (only replaces one instance per row)
print(testdf)
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,所需的输出是:

Alice went to hospital yesterday.
John went to hospizzz yesterday.
Run Code Online (Sandbox Code Playgroud)

注意第一行有三个字典替换.

除了逐行(在for循环中)之外,我怎样才能有效地执行此操作?

df.replace(...)在其他问题中尝试了许多其他答案,但只替换了一个子字符串,结果如下:Alice went to school today,在哪里schooltoday没有被替换..

另外要注意的是,替代应该发生一次全部用于任何单行.(参见hospital第一行中是未被取代的一第二时间hospizzz这将是错误的 …

python pandas

5
推荐指数
1
解决办法
483
查看次数

列表理解版"延伸"

以下是否存在1行等效(使用列表理解):

a = []
for i in range(6):
    a.extend(((-i,i,0,2),(-i-1,i,0,6)))
a = tuple(a)
Run Code Online (Sandbox Code Playgroud)

我在想类似的东西

tuple(((-i,i,0,2),(-i-1,i,0,6)) for i in range(6))
Run Code Online (Sandbox Code Playgroud)

但这给了:

(((0, 0, 0, 2), (-1, 0, 0, 6)),
 ((-1, 1, 0, 2), (-2, 1, 0, 6)),
 ((-2, 2, 0, 2), (-3, 2, 0, 6)),
 ((-3, 3, 0, 2), (-4, 3, 0, 6)),
 ((-4, 4, 0, 2), (-5, 4, 0, 6)),
 ((-5, 5, 0, 2), (-6, 5, 0, 6)))
Run Code Online (Sandbox Code Playgroud)

这不是我想要的.

期望的输出

((0, 0, 0, 2),
 (-1, 0, 0, 6),
 (-1, 1, 0, …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

3
推荐指数
1
解决办法
271
查看次数

标签 统计

python ×2

list-comprehension ×1

pandas ×1