2015-09-24 50 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