下面的问题已被简化。
该解决方案应该适用于更大的数据集和更大的字典。
给定一个pandas.DataFrame
import pandas as pd
pd.DataFrame(data = {'foo': [1223, 2931, 3781],
'bar': ["34 fake st, footown", "88 real crs, barrington", "28 imaginary st, bazington"]})
| | foo | bar |
|---:|------:|:---------------------------|
| 0 | 1223 | 34 fake st, footown |
| 1 | 2931 | 88 real crs, barrington |
| 2 | 3781 | 28 imaginary st, bazington |
和一个字典对象:
my_dictionary = {'st':'street', 'crs':'crescent'}
将 pandas.DataFrame
中的列中包含的子字符串替换为 my_dictionary
的最佳方法是什么?
我希望得到一个看起来像这样的pandas.DataFrame
:
| | foo | bar |
|---:|------:|:--------------------------------|
| 0 | 1223 | 34 fake street, footown |
| 1 | 2931 | 88 real crescent, barrington |
| 2 | 3781 | 28 imaginary street, bazington |
我尝试过以下方法:
for key, val in my_dictionary.items():
df.bar.loc[df.bar.str.contains(key)] = df.bar.loc[df.bar.str.contains(key)].apply(lambda x: x.replace(key,val))
df.bar
使用给定的输出。
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self._setitem_with_indexer(indexer, value)
0 34 fake street, footown
1 88 real crescent, barrington
2 28 imaginary street, bazington
Name: bar, dtype: object
如何在不收到上述警告消息的情况下执行重新分配;并且不使用 .copy()
?
最佳答案
您可以使用Series.replace
:
df["bar"] = df["bar"].replace(my_dictionary, regex=True)
print (df)
foo bar
0 1223 34 fake street, footown
1 2931 88 real crescent, barrington
2 3781 28 imaginary street, bazington
关于python-3.x - 使用 pandas 数据帧列中的字典对象重新分配子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60715645/