Python Pandas如何过滤CSV文件中某列的前N个字符?

3

我正在使用 Pandas CSV 处理一个非常大的 CSV 文件。基本上,我有一个 Python 脚本,其中包含一些筛选条件的参数。其中之一是表示数字序列的字符串(例如:83351828),然后将结果导出到新的 CSV 文件中。

我想做的是能够通过前四个字符过滤此列。

这是我的代码:

  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 - Catalina Chircu
字符串,但在这种情况下,我只使用dirNumber,它是一个由4个数字组成的字符串,我希望这4个数字与“Directory Number 1”列的前4个数字匹配。 - ryuzak1
好的。这些字符串必须在矩阵中。是什么类型的矩阵?数组?数据帧?我想你有一个数据帧,你有一个标题吗,我的意思是列数?它们是什么?在获取变量之前,请先展示代码。 - Catalina Chircu
我其实不太清楚,我是pandas的新手,当我执行chunk['Directory Number 1'] == "random string"时,它能正常工作,这意味着chunk['Directory Number 1']也是一个字符串,对吧?那么为什么我不能用[0:4]访问它的前四个字符呢? - ryuzak1
我编辑了我的帖子,我只是用cmd args获取那些变量。 - ryuzak1
1个回答

3
我认为你需要用str进行索引以获取前4个字母,同时应省略0:
chunk['Directory Number 1'].str[:4]

如果值不是字符串,请添加Series.astype
chunk['Directory Number 1'].astype(str).str[:4]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接