【问题标题】:Using replace and str.startswith() in a pandas dataframe to rename values在 pandas 数据框中使用 replace 和 str.startswith() 重命名值
【发布时间】:2019-04-29 04:49:07
【问题描述】:

我有一个名为 source 的列,其中包含几百行文本。 问题是其中一些可以组合在一起,我正在努力在 Pandas 数据框中做到这一点。这是我的代码:

df.source.replace({
                   df.source.str.startswith('share', na=False): 'sharePet',
                   df.source.str.startswith('2012-01-08', na=False): 'shareDate'

                 })

此外,这是否适用于以日期开头的第二行?如果不是,我可以将其保留在第一行和其他文本分组中。

希望得到一些建议。

【问题讨论】:

    标签: python string pandas series


    【解决方案1】:

    您可以使用字典并进行迭代:

    d = {'share': 'sharePet', '2012-01-08': 'shareDate'}
    
    for k, v in d.items():
        df.loc[df['source'].str.startswith(k, na=False), 'source'] = v
    

    Pandas str.startswith 仅适用于字符串。您可以通过set(map(type, df['source']))轻松查看您的系列中存在哪些类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-03
      • 2018-04-02
      • 2013-09-04
      • 2021-09-03
      • 2018-09-23
      • 2022-06-14
      • 2020-02-02
      • 2014-10-26
      相关资源
      最近更新 更多