我正在 Google Colab 上编写一个 python 方法,以便进入包含 84 个 .csv 的文件夹,将它们连接起来并输出一个新的 .csv
方法如下
def concatenate(indirectory = "/content/gdrive/My Drive/Folder/Folder", outfile = "/content/gdrive/My Drive/--.csv"):
os.chdir(indirectory)
fileList = glob.glob("*.csv")
dfList = []
colnames = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
for filename in fileList:
print(filename)
df = pd.read_csv(filename, header = None)
dfList.append(df)
concatDf = pd.concat(dfList, axis = 0)
concatDf.columns = colnames
concatDf.to_csv(outfile, index = None)
这在一定程度上连接文件是有效的,标题被复制到新行中,我手动删除了这些行,但很高兴知道如何在方法中删除它们。
但是,这获取了 A 列中保存的一些 ID,并将它们复制到 A 列为空的行中。直到我开始对涉及A列和
的数据进行一些分析时我才意识到aCount = df['A'].value_counts()
显示一些 ID 被多次复制到空行中。
最佳答案
您的列索引可能有问题。导致标题重复的原因是您告诉 pandas 您的 csv 没有标题,因此它正在读取 csv 的第一行作为数据,但听起来标题确实存在,因此它们作为数据包含在数据帧中。这也可能会扰乱您的索引,从而导致重复的数据。
for filename in fileList:
print(filename)
df = pd.read_csv(filename) # if the headers are the same, use them (i.e. don't use header=None if the headers are present)
# df.columns = colnames # if they are not the same, you should make them the same
dfList.append(df)
concatDf = pd.concat(dfList, axis=0) # you can also add arg ignore_index=True to concat on column order rather than column name
concatDf.to_csv(outfile, index=False)
关于python - 使用 Pandas 连接 CSV 文件会导致重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010168/