![](/img/trans.png)
[英]Python : Add a column into a dataframe with different length repeating the added column till fill the dataframe length
[英]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 append
和Dataframe.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.