Skip to main content
 首页 » 编程设计

python之保留名称为整数且满足特定条件的数据框的列

2024年10月17日8birdshome

我有一个数据框 df,其中的列名称是单词或日期。我只想保留名称中包含单词或某些特定日期的列。特别是,数据框有“Price”、“Origin”、“Company”列,以及 1980 年到 2008 年的列,我只想保留 1996 年到 2008 年的列,以及以单词为列的列名字。

这是我编写的代码,但我很确定有一种更短、更优雅的方法可以做到这一点:

columns_to_keep = list()     
for c in df.columns.values: 
    if c.isdigit(): 
        if int(c) > 1995: 
            columns_to_keep.append(c) 
    else: 
        columns_to_keep.append(c) 
df_copy = df[columns_to_keep] 

有什么帮助吗?谢谢!

请您参考如下方法:

一种替代方法是使用列表理解并动态创建一个新列表:

df.columns 
Index(['Price', 'Origin', 'Company', '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'], 
      dtype='object') 
 
columns_to_keep = [col for col in df.columns if not (col.isdigit() and int(col) <= 1995)] 
 
['Price', 
 'Origin', 
 'Company', 
 '1996', 
 '1997', 
 '1998', 
 '1999', 
 '2000', 
 '2001', 
 '2002', 
 '2003', 
 '2004', 
 '2005', 
 '2006', 
 '2007', 
 '2008'] 

在 isdigit 之前将类型更改为字符串可以绕过任何“col is an integer”错误:

columns_to_keep = [col for col in df.columns if not (str(col).isdigit() and int(col) <= 1995)]