【问题标题】:Replace letter in string pandas替换字符串熊猫中的字母
【发布时间】:2019-02-06 09:57:58
【问题描述】:

我有这个数据框:

import pandas as pd

columns = ['ID','Data']
data = [['26A20',123],
        ['12A20',123],
        ['23A20',123]]
df = pd.DataFrame.from_records(data=data, columns=columns)

>>df
      ID  Data
0  26A20   123
1  12A20   123
2  23A20   123

还有一个简单的任务,当 ID 以 26 或 23 开头时,从 ID 中删除 A:s:

df.loc[df['ID'].str.startswith(('23','26'))]['ID'] = df['ID'].str.replace('A','')

SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片。尝试使用 .loc[row_indexer,col_indexer] = 取而代之的价值

没有任何变化:

>>df
      ID  Data
0  26A20   123
1  12A20   123
2  23A20   123

我在使用 loc,我做错了什么?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    还有np.where() 方法:

    df['ID'] = np.where(df['ID'].str.startswith(('23','26')), df['ID'].str.replace('A', ''), df['ID'])
    

    【讨论】:

      【解决方案2】:

      删除双重][以避免chained assignments:

      df.loc[df['ID'].str.startswith(('23','26')), 'ID'] = df['ID'].str.replace('A','')
      print (df)
            ID  Data
      0   2620   123
      1  12A20   123
      2   2320   123
      

      也可以在两侧过滤以减少函数replace的执行:

      mask = df['ID'].str.startswith(('23','26'))
      df.loc[mask, 'ID'] = df.loc[mask, 'ID'].str.replace('A','')
      print (df)
            ID  Data
      0   2620   123
      1  12A20   123
      2   2320   123
      

      【讨论】:

        猜你喜欢
        • 2019-06-03
        • 2017-03-12
        • 2019-11-23
        • 1970-01-01
        • 2021-09-07
        • 2019-09-21
        • 2018-08-01
        • 2023-03-19
        相关资源
        最近更新 更多