【发布时间】:2023-03-07 01:46:01
【问题描述】:
我有一个带有性别列的数据框。它包括对性别的预测。现在,性别列具有诸如 most_male、most_female 之类的值。我主要想删除。于是我试了df['gender'] = df['gender'].map(lambda x: x.lstrip('mostly_'))
但我有一个值为 'male' 的列对应于 'ale'
【问题讨论】:
标签: python python-3.x pandas nlp
我有一个带有性别列的数据框。它包括对性别的预测。现在,性别列具有诸如 most_male、most_female 之类的值。我主要想删除。于是我试了df['gender'] = df['gender'].map(lambda x: x.lstrip('mostly_'))
但我有一个值为 'male' 的列对应于 'ale'
【问题讨论】:
标签: python python-3.x pandas nlp
pandas.DataFrame.replace您可以将字典传递给此方法以指定要使用的列
df.replace({'gender': {'mostly_': ''}}, regex=True)
pandas.Series.str.replace优点是不需要指定regex=True
df.gender.str.replace('mostly_', '')
pandas.Series.str投票“最可能”打破。但是,如果您知道所有条目都以 "mostly_" 开头,那为什么不呢
df.gender.str[7:]
pandas.Series.map我不喜欢其他选项,因为它们都涉及字符串操作。您可以更明确地使用字典映射并保持恒定时间查找
df.gender.map({'mostly_male': 'male', 'mostly_female': 'female'})
df = pd.DataFrame(dict(gender=[f"mostly_{g}" for g in ['male', 'female'] * 10000]))
%timeit df.replace({'gender': {'mostly_': ''}}, regex=True)
%timeit df.gender.str.replace('mostly_', '')
%timeit df.gender.str[7:]
%timeit df.gender.map({'mostly_male': 'male', 'mostly_female': 'female'})
100 loops, best of 3: 12.8 ms per loop
100 loops, best of 3: 16.1 ms per loop
100 loops, best of 3: 5.42 ms per loop
1000 loops, best of 3: 1.8 ms per loop
【讨论】:
你应该使用替换:
df['gender'] = df['gender'].str.replace('mostly_', '')
这会将“mostly_”的任何完全匹配项替换为空白“”。如果在您传递的字符串中找到任何前导字符,您的示例将从行中删除前导字符。所以“m”被lstrip找到了,“mostly_”被去掉了,但是由于“male”中有一个“m”,它也会被去掉。
【讨论】:
male 中的m 也被删除也可能会有所帮助。 lstrip() 将要删除的字符集作为输入,并且看到 m 是这些字符之一,它还将删除 male 中的 m:python-reference.readthedocs.io/en/latest/docs/str/lstrip.html
您可以使用replace 删除不需要的字符串。 lstrip 将删除所有符合条件的字符。详情lstrip docs
也可以使用正则表达式库替换子字符串
import re
df['gender'].map(lambda x: re.sub('^mostly_','',x))
【讨论】: