【问题标题】:pandas: return column values that begin with certain number(s)pandas:返回以特定数字开头的列值
【发布时间】:2016-04-25 16:41:48
【问题描述】:

我有以下df:

url = 'https://raw.githubusercontent.com/108michael/ms_thesis/master/sic_naics_catcode.csv'
df= pd.read_csv(url, index_col=0)
df.head(3)

    SICcode     Catcode     Category    SICname                      MultSIC    2012 NAICS Code     2002to2007 NAICS
0   111         A1500   Wheat, corn, soybeans and cash grain    Wheat   X           111140           111140
1   112         A1600   Other commodities (incl rice, peanuts, honey)   X           111160           111160
2   115         A1500   Wheat, corn, soybeans and cash grain    Corn    X           111150           111150

我想返回所有以 531 或 92 开头的行,或者在某些情况下,返回 2002to2007 NAICS 列中以 5416 到 5419 开头的值。

我认为这一定很容易。我熟悉(这只是一个模板)dz = df[(df['date'] > '01/03/2005') & (df['date'] < '01/03/2015')] 类型代码,但我不知道任何允许我输入截断值的“通配符”符号。

有什么想法吗?

【问题讨论】:

    标签: python pandas dataframe wildcard


    【解决方案1】:

    您可以为此使用 RegEx 功能:

    df.loc[df['2002to2007 NAICS'].astype(str).str.contains(r'^(?:531|92|541[6-9])')]
    

    将为您提供以 531 或 92 或 5416-5419 开头的所有值

    【讨论】:

    • 我想知道是否有更简洁的方法可以做到这一点。感谢您加入!
    【解决方案2】:

    对于以 531 或 92 开头的值:

    df.loc[(df["2002to2007 NAICS"].astype(str).str.startswith("531")) | (df["2002to2007 NAICS"].astype(str).str.startswith("92"))]
    

    对于以 5416:5419 开头的值:

    df.loc[df["2002to2007 NAICS"].astype(str).str.slice(0,4).isin([str(i) for i in range(5416, 5420)])]
    

    【讨论】:

    • 宾果游戏!感谢您的提示!
    猜你喜欢
    • 2023-01-19
    • 2020-05-07
    • 1970-01-01
    • 2020-05-11
    • 2017-07-03
    • 1970-01-01
    • 2019-10-06
    • 2017-11-02
    • 2022-11-11
    相关资源
    最近更新 更多