如何使用PANDAS python按单个列对CSV行进行排序 [英] How to sort CSV rows by a single column using PANDAS python

查看:85
本文介绍了如何使用PANDAS python按单个列对CSV行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,在我的项目中,我试图按单个列对CVS工作表的行进行排序,我正在使用PANDAS,并且已经在互联网上看到了多个示例,但是当我自己实现此功能时,我无法

Currently on my project I am trying to sort the rows of a CVS sheet by a singular column, I am using PANDAS and I have seen several examples posted all around the internet, however when trying to implement this myself I have been unable to.

db = pd.read_csv(databasefile, skip_blank_lines=True, names=['ExampleOne','ExampleTwo','ExampleThree','ExampleFour'], header=1)
db.drop_duplicates(inplace=True)

db.sort_values(by=['ExampleOne'], ascending=[True])

db.to_csv(databasefile, index=False)

在我上面的代码中,我想将CSV转换为供PANDAS使用的数据帧,在该数据帧中,我删除所有重复的行,并按ExampleOne列进行排序.最后,我将该信息发送回CSV.但是,在代码运行无误后查看CSV时,数据不会以任何顺序排序.

In the code above my thought would be that I am turning a CSV into a dataframe for PANDAS to use, in that dataframe I am dropping any duplicated rows and am sorting by the ExampleOne Column. In the end I am sending that information back to the CSV. However, when viewing the CSV after the code runs with no errors the data is not sorted in any order.

数据库CSV链接

这里是txt格式的CSV,对前60行左右的行进行了排序,但是由于在此过程中更早,所以我将多个CSV合并为一个CSV.

Here is the CSV in a txt format, the first 60 or so rows are sorted but that is becuase earlier in this process I am combining multiple CSV's together into one CSV.

谢谢您的阅读!我将不胜感激,因为任何问题都会给我带来任何帮助或建议,任何人都可以尝试一下.再次感谢您的阅读!

Thankyou for reading! I would appreciate any help or suggestions anyone would have me try out as this problem has been frustrating for me. Thanks again for reading!

推荐答案

databasefile = r"path"
databasefile2 = r"path"
db = pd.read_csv(databasefile, skip_blank_lines=True, names=['ExampleOne','ExampleTwo','ExampleThree','ExampleFour'], header=1)
print(db['ExampleOne'])
db.drop_duplicates(inplace=True)
db.sort_values(by=['ExampleOne'], ascending=True).to_csv(databasefile, index=False)

这是解决您问题的方法.

Here is a solution to your problem.

这篇关于如何使用PANDAS python按单个列对CSV行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆