簡體   English   中英

如何在 python 中向 dataframe 中添加不同列長度的頁腳(行)?

[英]How to add a footer(row) to the dataframe with different column length in python?

cursor object 在Oracle處執行查詢並使用fetchAll方法獲取結果,並能夠將其轉換為csv file

但我想在文件末尾添加footer(<some static value>,<total number of records present in the dataframe>,<current date in DDMMYY format>)如下:

代碼:

statement= 'select firstname,lastname,age,gender,college,university from students;'
cursor.execute(statement)
result_list = cursor.fetchall();
df = pd.DataFrame(result_list)
print(df)

output:

   0       1     2   3    4            5
0  arun    sai   25  M  testcollege  testuniversity
1  varun   tej   28  F  testcollege  testuniversity
2  rachel  green 27  M  testcollege  testuniversity
3  le      blanc 25  M  testcollege  testuniversity

預期 Output:

   0       1     2   3    4            5
0  arun    sai   25  M  testcollege  testuniversity
1  varun   tej   28  F  testcollege  testuniversity
2  rachel  green 27  M  testcollege  testuniversity
3  le      blanc 25  M  testcollege  testuniversity
4  ABC     4     011221 

如何用 pandas dataframe 實現它?

我已經嘗試了很多方法使用dataframe appendDataframe.loc操作但無法實現。

當前 csv 文件:

arun,sai,25,M,testcollege,testuniversity
varun,tej,28,F,testcollege,testuniversity
rachel,green,27,M,testcollege,testuniversity
le,blanc,25,M,testcollege,testuniversity

預期的 csv 文件:

arun,sai,25,M,testcollege,testuniversity
varun,tej,28,F,testcollege,testuniversity
rachel,green,27,M,testcollege,testuniversity
le,blanc,25,M,testcollege,testuniversity
ABC,4,071221

使用:

Python3.5

Pandas1.3.4

這取決於您是否直接使用 DataFrame 將數據呈現給最終用戶——雖然它易於使用,但我認為 DataFrame 更多的是關於數據操作而不是關於數據呈現。

我們實現這一點的當前方法是使用 DataFrame 呈現表格,而是使用另一個 HTML 層向用戶呈現最終表格。

我們使用的框架稱為DataTables 但是,如果當前您只在 Jupyter Notebook 的世界中,那么這種方法將行不通......

經過所有分析,我相信在 Dataframe 進行操作對於這種情況是不正確的,甚至無法實現。

由於我從數據庫中獲取的結果記錄數量很大,因此繼續使用 pandas 僅將結果寫入 csv 文件,但是對於底部的頁腳處理,使用 csv 並在最后一行添加頁腳編寫器。 到目前為止,我可以看到這是唯一的解決方法,並期待社區提供更好的答案

# Pre-requisite - Import the writer class from the csv module
from csv import writer
  
# The data assigned to the list 
list_data=['03','Smith','Science']
  
# Pre-requisite - The CSV file should be manually closed before running this code.

# First, open the old CSV file in append mode, hence mentioned as 'a'
# Then, for the CSV file, create a file object
with open('CSVFILE.csv', 'a', newline='') as f_object:  
    # Pass the CSV  file object to the writer() function
    writer_object = writer(f_object)
    # Result - a writer object
    # Pass the data in the list as an argument into the writerow() function
    writer_object.writerow(list_data)  
    # Close the file object
    f_object.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM