读取数据时删除包含某些字符串的列:python

Ale*_*der 4 python string dataframe pandas

我正在读取目录中的 .txt 文件,并希望删除包含某些特定字符串的列。

for file in glob.iglob(files + '.txt', recursive=True):
    
    cols = list(pd.read_csv(file, nrows =1))
    
    df=pd.read_csv(file,header=0, skiprows=0, skipfooter=0, usecols =[i for i in cols if i.str.contains['TRIVIAL|EASY']==False])
Run Code Online (Sandbox Code Playgroud)

当我这样做时我得到

df=pd.read_csv(文件,header=0,skiprows=0,skipfooter=0,usecols =[i for i >in cols if i.str.contains['PASS']==True])

属性错误:“str”对象没有属性“str”

我无法弄清楚我需要修复哪一部分?

根据 pandas 中包含特定字符串的列名称选择列

根据字符串条件删除列

属性错误:“str”对象没有属性“str”

删除 Pandas 中以特定字符串结尾的多列

ALo*_*llz 5

如果不单独读取标头,您将传递一个可调用对象到usecols. 检查是否'EASY''TRIVIAL'列名中。

exclu = ['EASY', 'TRIVIAL']  # Any substring in this list excludes a column 
usecols = lambda x: not any(substr in x for substr in exclu)

df = pd.read_csv('test.csv', usecols=usecols)

print(df)
   HARD  MEDIUM
0     2       4
1     6       8
2     1       1
Run Code Online (Sandbox Code Playgroud)

样本数据:test.csv

TRIVIAL,HARD,EASYfoo,MEDIUM
1,2,3,4
5,6,7,8
1,1,1,1
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

896 次

最近记录:

5 年,9 月 前