如何检查和添加丢失的头到csv文件

igetnqfo  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(158)

我有一个CSV文件,比方说它总共有6个列标题,其中第一个是A1(位置)总是固定的。但是,由于动态数据,我有时只得到3列标题出其他5个标题在CSV文件中,这些可以是任何列出这5列从B1到F1。第一个屏幕截图显示了所有的列,我想有,第二个截图显示我得到了什么。

现在我想做的是,不知何故,应该能够检查文件中的标题第一,如果它已经可用,然后忽略它,如果它没有然后添加失踪的标题到下一列的CSV文件使用python。
注:只有标题对我来说就足够了,我会用0或空白填充下面的空行以匹配表格。
帮帮我吧!

v7pvogib

v7pvogib1#

import pandas as pd

file_path='Yourfile.csv' #file name
df = pd.read_csv(file_path) #reading csv file 
df = df.fillna(0) #replace NaN to 0
u0njafvf

u0njafvf2#

不幸的是,我不知道有什么干净直接的方法可以声明比csv文件中存在的列更多的列。
但是一旦你有了一个Pandas DataFrame,就很容易添加缺少的列:

# read a CSV file having missing columns:
tmp = pd.read_csv('file.csv')

#create an empty dataframe with all the expected columns
df = pd.DataFrame(columns=['Location', 'Total', 'Open', 'Checkin', 'Closed', 'Cancelled'])

# just copy the data:
df[tmp.columns] = tmp

仅此而已。缺失的列将用NaN值填充。

0g0grzrc

0g0grzrc3#

import pandas as pd

#Read the first excel file content
df1 = pd.read_excel(r'/content/MainFile.xlsx')

#Read the second excel file content where headers are missing
df2 = pd.read_excel(r'/content/ClientFile.xlsx')

现在查找两个文件之间的不同列,并将它们提取到新的数据框中:

extracted_col= df1[df1.columns.difference(df2.columns)]

然后将提取的列加入到缺少的头文件中。

df2=df2.join(extracted_col)

相关问题