我是 python 新手,正在尝试导入一个大型 csv 文件,具体取决于用户 GUI 输入中的复选框被选中为“True”的位置,并将这些 csv 文件合并到单个数据帧中。所有数据框都具有相同的数据列。
这是我到目前为止所拥有的。
import pandas as pd
file1_checkbox = True
file2_checkbox = False
file3_checkbox = True
file1 = pd.read_csv("/file1.csv")
file2 = pd.read_csv("/file2.csv")
file3 = pd.read_csv("/file3.csv")
df = pd.DataFrame().reindex_like(file1)
if file1_checkbox == True:
df.append(file1)
if file2_checkbox == True:
df.append(file2)
if file3_checkbox == True:
df.append(file3)
我意识到我可以/应该为此编写一个函数。 :)
我尝试过附加、连接和连接,但没有成功。我做错了什么?
您的方向是正确的,但您的代码存在一些问题。当使用 Pandas 连接或附加 DataFrame 时,您需要将结果分配回 DataFrame,因为 Pandas 操作会返回一个新的 DataFrame。此外,您应该使用
pd.concat
函数来连接 DataFrame。这是代码的修改版本,应该可以工作:
import pandas as pd
file1_checkbox = True
file2_checkbox = False
file3_checkbox = True
# Read the CSV files into DataFrames
file1 = pd.read_csv("/file1.csv")
file2 = pd.read_csv("/file2.csv")
file3 = pd.read_csv("/file3.csv")
# Create an empty DataFrame with the same columns as file1
df = pd.DataFrame(columns=file1.columns)
# Check the checkboxes and concatenate the DataFrames
if file1_checkbox:
df = pd.concat([df, file1], ignore_index=True)
if file2_checkbox:
df = pd.concat([df, file2], ignore_index=True)
if file3_checkbox:
df = pd.concat([df, file3], ignore_index=True)
# Now 'df' contains the combined data from selected CSV files
在此代码中:
df
,其列与 file1
相同。pd.concat
时,我们使用 True
连接 DataFrame。 ignore_index=True
用于重置生成的 DataFrame 中的索引,因此它是连续的。这样,您将拥有一个 DataFrame
df
,其中包含所选 CSV 文件中的组合数据。