2016-04-25 83 views
1

我有以下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')]类型代码,但我不知道任何允许输入截断值的'通配符'符号。

任何想法?

回答

3

你可以使用正则表达式功率为:

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

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

+0

我想知道是否有一个更简洁的方法来做到这一点。感谢您的加入! –

3

对于开始与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)])] 
+0

宾果!谢谢你的提示! –

+0

不客气。 – ayhan