![](/img/trans.png)
[英]How do I copy only the required rows from one csv file to other csv file using python?
[英]How do I take only specified required columns from CSV file and add into a table in postgresql?
考慮我有
*----*------*-----------*----------*----------*---------------*----------------*
| id | name | addressid | address1 | address2 | attendancekey | attendancedate |
*----*------*-----------*----------*----------*---------------*----------------*
CSV 文件中的列,我只想要
id, name要導入學生表和
addressid, address1, address2要導入地址表和
要導入到數據庫的考勤表中的考勤鍵和考勤日期。
使用什么查詢將所需的列導入表中?
數據庫 Postgresql 版本 - 12
Python 版本 - 3.4.4
Psycopg2 版本 - 2.7.5
您首先必須將數據COPY
到(可能是UNLOGGED
)臨時表並從那里填充表。
或者,您可以在 CSV 文件(必須位於數據庫服務器計算機上)上定義file_fdw外部表,並使用它來填充表。 這將使您暫時將文件加載到數據庫中。
你可以按順序嘗試這個......
1. 首先從主 csv 文件創建三個 csv 文件。
一種。 對於student
表,列將id
和name
;
灣對於address
表,列將addressid
和address1
;
C。 對於attendance
表,列將是attendancekey
和attendancedate
;
然后執行以下查詢
一種。 copy student(id,name) from 'filelocation studentfilename.csv' DELIMITERS ',' CSV;
灣copy address(addressid,address1) from 'filelocation addressfilename.csv' DELIMITERS ',' CSV;
C。 copy attendance(attendancekey ,attendancedate) from 'filelocation attendancefilename.csv' DELIMITERS ',' CSV;
您可以使用df.iterrows()
遍歷 csv,對於每一行,您可以僅將所需的鍵插入表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.