2015-09-24 51 views
1

我有以下的列名的数据帧:提取4种的列名来自熊猫数据框中

array([u'country_name', u'country_code', u'functional_crop_code', 
     u'functional_crop_type', 1961, 1962, 1963, 1964, 1965, 1966, 1967, 
     1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 
     1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 
     1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 
     2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 
     2012, 2013], dtype=object) 

我想仅提取4个数字,即列名1961年,1962年......我试过这一点,但它不工作:

df.filter(regex=r'\d{4}$').columns.values 

我得到错误:*** TypeError: expected string or buffer

回答

1

的问题是,你尝试应用这些正则表达式时,有一些列是INT,因此int类型它失败,错误 -

TypeError: expected string or buffer 

您可以将列转换为str,然后应用DataFrame.filter -

df.columns = df.columns.astype(str) 
df.filter(regex=r'\d{4}$').columns.values 

演示 -

In [8]: df.columns = df.columns.astype(str) 

In [11]: df.filter(regex=r'\d{4}$').columns.values 
Out[11]: 
array(['1961', '1962', '1963', '1964', '1965', '1966', '1967', '1968', 
     '1969', '1970', '1971', '1972', '1973', '1974', '1975', '1976', 
     '1977', '1978', '1979', '1980', '1981', '1982', '1983', '1984', 
     '1985', '1986', '1987', '1988', '1989', '1990', '1991', '1992', 
     '1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', 
     '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', 
     '2009', '2010', '2011', '2012', '2013'], dtype=object) 

您需要转换为str,然后才能申请正则表达式列名,一种方式(不知道最有效的),不列名永久转换为str,仍然可以得到所需的数据是 -

df.columns[df.columns.astype(str).str.contains(r'\d{4}$')] 

演示 -

In [19]: df.columns[df.columns.astype(str).str.contains(r'\d{4}$')] 
Out[19]: 
Index([1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 
     1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 
     1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 
     1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
     2009, 2010, 2011, 2012, 2013], 
     dtype='object') 
+0

谢谢@阿南德,有没有办法永久改变列的类型?将类型更改为字符串会稍后破坏我的代码 – user308827

+1

添加了一种使用'.str.contains' –

+0

的方法谢谢,优秀的soln! – user308827