【问题标题】:Python Pandas CSV filter a column with its values N first charPython Pandas CSV 过滤一列,其值为 N first char
【发布时间】:2020-03-20 18:20:24
【问题描述】:

我正在使用 pandas csv 来处理一个巨大的 csv 文件,基本上我有一个 python 脚本,其中包含一些作为过滤条件的 args,其中一个是代表一系列数字的字符串(例如:83351828),然后将结果导出到新的 csv 文件。 我想要做的是能够通过它的 4 个第一个字符来过滤这个列。

这是我的代码:

  elif devicePool == '' and css == '' and dirNumber != '' and routePartition == '':
        df = pd.concat(( [chunk[chunk['Directory Number 1'][0:4] == dirNumber] for chunk in pd.read_csv(sourceFile, iterator=True, chunksize=10**4)]))

如您所见,我使用了“[0:4]”,但它不起作用。

def main(argv):
    inputfile = ''
    outputfile = ''
    devicePool = ''
    css = ''
    dirNumber = ''
    routePartition = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:p:c:n:r:",["ifile=","ofile=", "dpool=", "css=", "dnumber=", "route="])
    except getopt.GetoptError:
        print('test.py -i <inputfile> -o <outputfile> -p <devicepool> -c <CSS> -n <directorynumber> -r <routepartition>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -i <inputfile> -o <outputfile> -p <devicepool> -c <CSS> -n <directorynumber> -r <routepartition>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-p", "--dpool"):
            devicePool = arg
        elif opt in ("-c", "--css"):
            css = arg
        elif opt in ("-n", "--dnumber"):
            dirNumber = arg
        elif opt in ("-r", "--route"):
            routePartition = arg

    read_CSV(inputfile, outputfile, devicePool, css, dirNumber, routePartition)

这是错误信息:

pandas.core.indexing.IndexingError:作为索引器提供的不可对齐的布尔系列(布尔系列的索引和索引对象的索引不匹配)。

【问题讨论】:

  • 您的输入及其类型到底是什么?我的意思是devicePoolcssdirNumberroutePartition
  • 字符串,但在这种情况下,我只使用 dirNumber,它是一个 4 位数字的字符串,我希望这 4 位数字与“目录号 1”列的前 4 位数字匹配跨度>
  • 好的。这些字符串必须在矩阵中。什么类型的矩阵?大批?数据框?我想你有一个DataFrame,你有一个标题,我的意思是列号吗?他们是谁?显示之前的代码,您可以在其中获取变量。
  • 我真的不知道,我是pandas新手,当我做chunk['Directory Number 1'] == "random string"时,效果很好,意思是chunk['Directory Number 1'] 也是一个字符串,对吗?那么为什么我不能用 [0:4] 访问它的前 4 个字符
  • 我编辑了我的帖子,我只是用 cmd args 获取这些变量

标签: python pandas csv


【解决方案1】:

我认为您需要使用 str 进行索引以获取前 4 个字母,还应省略 0

chunk['Directory Number 1'].str[:4]

如果值不是字符串,则添加 Series.astype:

chunk['Directory Number 1'].astype(str).str[:4]

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2019-07-26
    • 2014-04-19
    • 2018-11-05
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多