[英]How to merge multiple CSV files with different languages into one CSV file?
[英]Merge multiple csv files into a new one csv file with the help of jupyter notebook
事實上,我在使用 python jupyter notebook 合並 csv 文件時遇到了問題。 我寫了下面的代碼,但是,我仍然有問題,因為列不在同一級別,第二列從第一列的末尾開始,依此類推。 不同csv文件中的列內容如下:時間戳,負載能量數據,照明數據,運行數據,請大家幫忙。
path = "C:/Users"
file_list = glob.glob(path + "/*.csv")
print('File names:', file_list)
csv_list = []
for file in file_list:
csv_list.append(pd.read_csv(file))
csv_merged = pd.DataFrame()
for csv_file in csv_list:
csv_merged = csv_merged.append(csv_file, ignore_index=True)
csv_merged.to_csv('C:/Users.csv',index=False)
我可以在此代碼中添加更多詳細信息,例如列名,以及排除某些列,如果可能,請告訴我該怎么做。
嘗試pandas.merge函數而不是使用 list 例如:
import pandas as pd
path = "C:/Users"
file_list = glob.glob(path + "/*.csv")
print('File names:', file_list)
# merge data
data_frame = pd.read_csv(path + file_list[0])
for file in file_list:
if file == file_list[0]:
continue
df_to_merge = pd.read_csv(path + file)
data_frame.merge(df_to_merge)
data_frame.to_csv('C:/merge.csv')
正如 Krishna 所提到的,目前尚不清楚您的代碼有什么問題。 示例文件將有助於更好地理解該問題。
但是,在數據幀的 for 循環中使用 append 效率很低。 最好如下使用 pd.concat 。
代碼
path = "C:/Users"
file_list = glob.glob(path + "/*.csv")
print('File names:', file_list)
pd.concat(map(pd.read_csv, file_list),
ignore_index=True).to_csv('C:/Users.csv',index=False)
解釋:
我們使用以下方法創建合並的數據框:
pd.concat(map(pd.read_csv, file_list),
ignore_index=True)
使用以下命令創建輸出 CSV 文件:
to_csv('C:/Users.csv',index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.