python - 为什么我收到 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。
解决方案
args.csv
是一个字符串,这意味着file
也是,但你正在做:
file[colName] = np.where(file[args.column_name].str.contains(key), 1, 0)
你想在这里做什么?
推荐阅读
- python - TypeError:pushDefaultLayers() 采用 1 个位置参数,但给出了 2 个
- python - 如何创建无限组的维恩图?
- python-3.x - 如何从不同的路径在 Jupyter 笔记本中打开 .csv 文件
- php - 如何使用 symfony5 通过 url 发送上传的文档
- haskell - 为什么字节串的 Data.Binary 实例将字节串的长度添加为前缀
- android - 如何在谷歌播放控制台中恢复到旧版本
- android - TYPO3 - 添加到主屏幕图标
- javascript - 您如何将 mongodb 的 ObjectID 转换为对象以便存储在数组中?
- linux - 将环境变量从 shell 脚本传递到 .dat 文件
- c++ - C ++如何使用argv [1]读取第一个用户参数并将其存储在字符串中以读取/写入文本文件