【发布时间】:2019-05-20 18:04:37
【问题描述】:
是否可以仅使用 pandas.Series.str 方法将一列中的字符串替换为 pandas 数据框中另一列中的相应字符串?“否”是可接受的答案,只要它伴随pandas 版本和文档的相关部分。
这是一个例子:
import pandas as pd
# version >= 0.19.2
df = pd.DataFrame(
{
'names': ['alice', 'bob', 'catherine', 'slagathor'],
'hobbies': [
'alice likes to knit',
'bob likes to bowl',
'plays with her cats',
'slagathor burniates peasants for fun'
]
}
)
def clean(df: pd.DataFrame) -> pd.Dataframe: ... # do the substitutions
assert all(
clean(df).hobbies == pd.Series([
'likes to knit',
'likes to bowl',
'plays with her cats',
'burniates peasants for fun'
])
)
在这种情况下,我想从hobbies 列中省略name 列中的字符串,使用类似
df.hobbies.str.replace('(' + df.names + r'\s*)?', '') # doesn't work
到目前为止,我不得不
import re
df['replaced'] = pd.Series(
re.sub(f'^{df.names[i]} ?', '', df.hobbies[i]) for i in df.index
)
如对Replace values from one column with another column Pandas DataFrame的回答
【问题讨论】:
-
值得注意,但不是这个问题的一部分:在连接字符串上调用
re.sub的解决方案需要清理这些字符串。我的实际数据集中包含'bob++'和'slag]athor'之类的字符串。如果你不逃避r'[\[\](){}+*\\?]',re.complie(rf'^{name}\s*')将会失败
标签: python python-3.x pandas