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

标签 python string pandas dataframe

我正在读取目录中的 .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])

当我这样做时,我会得到

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

AttributeError: 'str' object has no attribute 'str'

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

select columns based on columns names containing a specific string in pandas

drop column based on a string condition

AttributeError: 'str' object has no attribute 'str'

Drop multiple columns that end with certain string in Pandas

最佳答案

无需单独读取 header ,您就可以将可调用对象传递给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
<小时/>

示例数据:test.csv

TRIVIAL,HARD,EASYfoo,MEDIUM
1,2,3,4
5,6,7,8
1,1,1,1

关于python - 读取数据时删除列包含某些字符串: python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116315/

相关文章:

python - 在 Python/Pandas 中,如何将世纪月转换为 DateTimeIndex?

python - 展平 pandas DataFrame

python - SQLAlchemy:为什么我提出HTTPFound会导致没有数据插入数据库?

python - 如何在 Python 中使用 re.sub?

python - 将数据追加到 Python 数组会出现错误

javascript - Nodejs/expressjs 中请求参数的字符串不可变性问题

python - Pandas:如何从每行的一个单词重建字符串

PHP:使用正则表达式从字符串中删除多余的空格

python - 获取与Dataframe中每一行中的最大值相对应的所有列的列表

python - 处理Python中日期解析的异常和错误