python-3.x - 使用 pandas 数据帧列中的字典对象重新分配子字符串

标签 python-3.x pandas dataframe

下面的问题已被简化。

该解决方案应该适用于更大的数据集和更大的字典。

给定一个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/

相关文章:

python - 替代 Pandas DataFrame 中的嵌套 np.where

python - MacOS 上的 Tkinter Python 3 缩放问题

python - 如何使用Python将字典列表写入Excel文件?

python - 将新列添加到 pandas DataFrame 时的 NaN 值

r - 如何通过对数据框中的列进行排序来快速形成组(四分位数、十分位数等)

r - 保存和加载 data.frames

html - 如何将 svg 文件上传到 django 应用程序?

python-3.x - 定义以数字开头的函数名(在 Python 3 中)?

python-3.x - 如何使用 pandas get_dummies 函数消除键错误

python - pandas.DataFrame.round() 不会在所需位数后截断小数值