简体   繁体   English

将列值的字符替换为Pandas中另一列的字符串

[英]Replace character of column value with string from another column in Pandas

name value_1
dd3   what, _ is
dd4   what, _ is

How to replace '_' from value_1 column with whole string from name column? 如何用名称列中的整个字符串替换value_1列中的'_'?

Desired output for value_1 column value_1列的所需输出

value_1
what, dd3 is
what, dd4 is

I have tried with this: 我已经尝试过:

df['value_1'] = df['value_1'].apply(lambda x:x.replace("_", df['name']))

And I got this error :expected a string or other character buffer object 我得到了这个error :expected a string or other character buffer object

Use apply with axis=1 for process by rows: apply with axis=1用于按行处理:

df['value_1'] = df.apply(lambda x:x['value_1'].replace("_", x['name']), axis=1)
print (df)
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is

UPDATE: similar to @jezrael's solution, but it should be bit faster for larger data sets (vectorized approach): 更新:类似于@jezrael的解决方案,但对于较大的数据集(矢量化方法)应该更快一些:

In [221]: df['value_1'] = (df.groupby('name')['value_1']
                             .transform(lambda x: x.str.replace('_', x.name)))

In [222]: df
Out[222]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is

Old answer: 旧答案:

you can create a helper DF: 您可以创建一个帮助DF:

In [181]: x = df.value_1.str.split('_', expand=True)

In [192]: x
Out[192]:
        0    1
0  what,    is
1  what,    is

then insert a new column into it: 然后在其中插入新列:

In [182]: x.insert(1, 'name', df['name'])

which yields: 产生:

In [194]: x
Out[194]:
        0 name    1
0  what,   dd3   is
1  what,   dd4   is

and replace the original column: 并替换原始列:

In [183]: df['value_1'] = x.sum(1)

In [184]: df
Out[184]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM