从pandas数据帧中提取4位数的列名

时间:2015-09-24 01:07:21

标签: python pandas

我有一个包含以下列名的数据框:

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 个答案:

答案 0 :(得分: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才能在列名上应用 regex ,这是一种不将列名转换为{{的方法(不确定是否最有效) 1}}永久地仍然获得所需的数据是 -

str

演示 -

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