pandas:返回以特定数字开头的列值

2024-05-14 11:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下资料:

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')]类型的代码,但我不知道有什么“通配符”符号允许我输入截断的值。你知道吗

有什么想法吗?你知道吗


Tags: andcsvhttpsurldfdaterawcash
2条回答

您可以使用RegEx power:

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

将给出以531、92或5416-5419开头的所有值

对于以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)])]

相关问题 更多 >

    热门问题