python - 值错误: arrays must all be same length in python

标签 python dataframe

我尝试了不同的可能性来找出错误的原因。但没有找到错误原因。请帮我看看我的代码出了什么问题。

def businesslogic(dirs, userpath):
    data = {}
    for fold in dirs:
        files = os.listdir(fold)
        if 'Test.txt' in files:
            with open(os.path.join(fold,'Test.txt'),'r') as te:
                lines = [line.rstrip('\n') for line in te.readlines()]
        else:
            print('Test.txt does not exist')

        rows = [value.split(';')[0] for value in lines]
        data[fold] = [value.split(';')[1] for value in lines]

    df = pd.DataFrame.from_dict(data)---->>>ValueError: arrays must all be same length

    df.index = rows
    cols = list(df.columns.values)

    req = df.loc[['TubeType', 'Digits']]
    req = req[cols].astype(int)

最佳答案

由于您的文件夹不一定具有相同数量的文件,因此您会收到此错误。根据您的格式,每个文件夹都表示为一列。所有文件夹的第一个文件将位于第一行,第二个文件将位于第二行,依此类推...当两个不同的文件夹中有不同数量的文件时,就会出现问题。特定文件夹需要 10 行(因为它包含 10 个文件),而另一个文件夹只需要 8 行。Pandas 认为这是输入错误。

如果您想将所有信息放在同一行中,您可以这样做:

# Example a data dict where folders contain different number of files
data= {'folder1' : ['file1', 'file2'], 'folder2' : ['file3'] }

pd.DataFrame({x : [[y for y in data[x]]] for x in data})
<小时/>

输出:

          folder1  folder2
0  [file1, file2]  [file3]

关于python - 值错误: arrays must all be same length in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57145902/

相关文章:

python - 在 Sphinx 中,我可以注册一堆应该始终翻译成链接的关键字吗?

Python(scipy)从文本文件导入时间

使用 cut() 添加十分位数列时接收 NA

python - 使用字典将重复行映射到原始行 - Python 3.6

python - 在 Redshift 中创建 Python UDF 以替换字符串中的字符

python - Python 中的小数模数和复数

python - 从字典生成 pandas 数据框,其值是不同数量的字典列表

python - 在 Python 中按唯一值对列进行分组

python - 无法在数据框中基于其他列创建列。尝试了几种选择 - 没有一个有效。 (Python、 Pandas )

python - 值错误 : circular reference detected with replit database