![](/img/trans.png)
[英]How to merge two CSV files by value in column using pandas PYTHON
[英]How to merge two CSV files into one using Python
我已經閱讀了有關堆棧溢出的一些信息,例如使用 Python 合並兩個 CSV 文件,但似乎該策略並不完全適合我。 我有兩個要合並的 csv 文件,第一個看起來像這樣:
這就是我的代碼的樣子:
# Find first school csv file in file explore
file1 = file1_path_in_folder
df1 = pd.read_csv(file1)
df1.head()
# Find second school csv file in file explore
file2 = file2_path_in_folder
df2 = pd.read_csv(file2)
df2.head()
merged = df1.merge(df2, on=' ') # The space in quotation marks is there because the first cell (A1) is blank
merged.to_csv("output.csv", index=False)
我最終得到一個看起來像這樣的錯誤:
Traceback (most recent call last):
File "c:\Users\anyuy\Documents\College_search\program\compare_read_csv.py", line 25, in <module>
merged = df1.merge(df2, on=' ')
File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\frame.py", line 9345, in merge
return merge(
File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\reshape\merge.py", line 107, in merge
op = _MergeOperation(
File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\reshape\merge.py", line 700, in __init__
) = self._get_merge_keys()
File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\reshape\merge.py", line 1097, in _get_merge_keys
right_keys.append(right._get_label_or_level_values(rk))
File "C:\Users\anyuy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\generic.py", line 1840, in _get_label_or_level_values
raise KeyError(key)
KeyError: ' '
我試着去掉引號中的空格,它仍然拋出同樣的錯誤。 我做錯了什么,我應該如何解決? 感謝您提供的所有幫助。
您可以使用 pandas DataFrame 合並兩個 csv 文件。
df3 = pd.concat([df1,df2], axis=1, join='inner')
試試這個可能有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.