首页 > 解决方案 > 为什么我收到 TypeError:字符串索引必须是整数?

问题描述

我对编码很陌生,我正在尝试编写一段代码来在 csv 文件中的列中搜索关键字。当我尝试测试我拥有的代码时,我不明白为什么会收到“TypeError:字符串索引必须是整数”。

我真的不知道该尝试什么。我尝试更改变量的名称,但这似乎没有帮助。

标准库

导入 os 导入 pandas 作为 pd 导入 argparse 导入 numpy 作为 np

定义参数

parser = argparse.ArgumentParser(description="Takes a CSV file and searches a specified column a keyword")
parser.add_argument("--csv", dest="csv", action='store', required=True,help="Name of the CSV file [required]")
parser.add_argument("--kw", dest="keyword", action='store', required=True,help="Keyword being searched for")
parser.add_argument("--cl", dest="column_name", action='store', required=True, help= "Name of column that is being searched")
parser.add_argument("--ocl", dest='output_column_name', action='store', required=True, help="Name of column in ouput file")
parser.add_argument("--outdir", dest="odir" , action='store', required=True, help="Out directory path")
args=parser.parse_args()

在继续之前标准化了一些路径

file= args.csv
key = args.keyword
outColName= args.output_column_name
outdir= args.odir

print(key)

def gene_database_search(key, file):
    colName = 'flag_' + key
    file[colName] = np.where(file[args.column_name].str.contains(key), 1, 0)
    return file[[outColName,colName]]

keywordList = [key]

for key in keywordList:
    print(key)
    de = gene_database_search(key,file)
    de.to_csv(outdir/'flag_'+ key + '_list.csv')

我应该得到一个 csv 文件作为输出,但我在第 35 行和第 42 行得到了 TypeError。

标签: pythonstringtypeerrorargparse

解决方案


args.csv是一个字符串,这意味着file也是,但你正在做:

file[colName] = np.where(file[args.column_name].str.contains(key), 1, 0)

你想在这里做什么?


推荐阅读