pandas: return 以特定数字开头的列值
pandas: return column values that begin with certain number(s)
我有以下 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
我想 return 所有以 531 或 92 开头的行,或者在某些情况下,2002to2007 NAICS
列中以 5416 到 5419 开头的值。
我想这一定很容易。我熟悉(这只是一个模板)dz = df[(df['date'] > '01/03/2005') & (df['date'] < '01/03/2015')]
类型代码,但我不知道任何允许我输入截断值的 'wild-card' 符号。
有什么想法吗?
对于以 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)])]
您可以为此使用 RegEx 功能:
df.loc[df['2002to2007 NAICS'].astype(str).str.contains(r'^(?:531|92|541[6-9])')]
将为您提供所有以 531 或 92 或 5416-5419 开头的值
我有以下 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
我想 return 所有以 531 或 92 开头的行,或者在某些情况下,2002to2007 NAICS
列中以 5416 到 5419 开头的值。
我想这一定很容易。我熟悉(这只是一个模板)dz = df[(df['date'] > '01/03/2005') & (df['date'] < '01/03/2015')]
类型代码,但我不知道任何允许我输入截断值的 'wild-card' 符号。
有什么想法吗?
对于以 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)])]
您可以为此使用 RegEx 功能:
df.loc[df['2002to2007 NAICS'].astype(str).str.contains(r'^(?:531|92|541[6-9])')]
将为您提供所有以 531 或 92 或 5416-5419 开头的值