开发者社区 问答 正文

使用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'}

my_dictionary替换pandas.DataFrame的一列中包含的子字符串的最佳方法是什么?

我期望有一个结果如下的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()吗?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 14:24:08 597 分享 版权
1 条回答
写回答
取消 提交回答
  • 您可以使用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
    

    回答来源:stackoverflow

    2020-03-24 14:24:15
    赞同 展开评论