【问题标题】:replace string if it satisfies the condition pandas dataframe [duplicate]如果满足条件熊猫数据框,则替换字符串[重复]
【发布时间】:2020-11-09 13:02:23
【问题描述】:

我有以下代码,如果字符串或数字中有括号,我想替换国家名称,我们必须删除它 例如 'Bolivia (Plurinational State of)' 应该是 'Bolivia', 'Switzerland17' 应该是 'Switzerland'。

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
pd.set_option('display.max_columns',None)
pd.set_option('display.max_rows',None)

df=pd.read_excel('Energy Indicators.xls',skiprows=17, skipfooter=265-(227))
df.drop(df.columns[[0,1]], axis=1, inplace=True)
df.columns=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']

【问题讨论】:

    标签: pandas string dataframe rename


    【解决方案1】:

    试试pd.DataFrame.str.replace

    df=pd.DataFrame({'Country':['Bolivia (Plurinational State of)','Switzerland17'],'value':[1,2]})
    df
    #   Country                           value
    #0  Bolivia (Plurinational State of)    1
    #1  Switzerland17                       2
    
    df.Country=df.Country.str.replace('\(.*\)|(\d+)','')
    df
    #   Country                           value
    #0  Bolivia                             1
    #1  Switzerland                         2
    

    【讨论】:

    • 其实我想替换所有包含括号和数字的字符串
    • 答案有什么问题?当它不起作用时? @vedantaher
    • 您的答案仅指定了玻利维亚(多民族国家......而瑞士17 否?我正在寻找适用于所有包含括号和数字的 str 的通用代码
    • 当然,因为它们是 Country 列中的唯一元素。您是否使用原始数据框尝试过?另外,你没有回答我的问题......它什么时候失败了?......@vedantaher 如果你能发布一个你的数据框的示例数据以供使用以及预期的输出,那就太好了。
    • df.Country=df.Country.str.replace('(.*)|(\d+)','') 这段代码工作很抱歉 inconvininace 你能解释一下吗我熊猫学习新手
    猜你喜欢
    • 2020-06-08
    • 2019-09-06
    • 1970-01-01
    • 2023-03-08
    • 2018-02-11
    • 2021-11-20
    • 2019-08-01
    • 2020-11-26
    • 1970-01-01
    相关资源
    最近更新 更多