首页 > 解决方案 > 为什么我不能将 tempDF 附加到 df?

问题描述

我有那个代码:

def show_files(upload_files):

    tempDF = pd.DataFrame()
    tempDF2 = pd.DataFrame()

    for file in upload_files:
        file = file.name
        if file.startswith('L'):
            Table = Dbf5(file)
            DF1 = Table.to_dataframe()
            tempDF = tempDF.append(DF1, sort=False)

        elif file.startswith('M'):
            Table = Dbf5(file)
            DF2 = Table.to_dataframe()
            tempDF2 = tempDF2.append(DF2, sort=False)
            print(f"final 2 - {tempDF2}")

  return [tempDF, tempDF2]

Upload_files 它是一个带有文件名的列表。例子:

["M22.dbf", "M31.dfb", "L22.dfb"]

所有 dbf 都成功加载为 DF。我调试了它。所以DF1 = Table.to_dataframe()工作正常。但是函数仅从最后加载的文件中返回 DF ...

例如:

1. Load M22 (500rows)
2. Put in TEMP_DF2 (temp_df2 = 500rows)
3. Load M31 (266rows)
4. Put in TEMP_DF2 with append(temp_DF2 = 266 rows, excepted 766)

我不知道为什么?我无法注意到一个错误。

标签: pythonpandasstreamlit

解决方案


不确定您的DataFrame外观如何,但是,问题似乎不是附加(参见下面的示例)。会不会是通过列表的问题?重现您的错误的完整示例可能会有所帮助。

import pandas as pd

uploads = ['M1', 'M2', 'L1', 'L2', 'M3']

df_m = pd.DataFrame()
df_l = pd.DataFrame()

for upload in uploads:
    if upload.lower().startswith('l'):
        df_l = df_l.append(pd.DataFrame({'a' : [i for i in range(10)]}))
    else:
        df_m = df_m.append(pd.DataFrame({'a' : [i for i in range(10)]}))

print('M: ', df_m.shape) #(30,1)
print('L: ', df_l.shape) #(20,1)

推荐阅读