简体   繁体   English

如何连接两个csv文件然后按python排序

[英]how to concat two csv file and then sort by python

I have two .csv files named all_cv.csv and common_cv.csv files.我有两个名为 all_cv.csv 和 common_cv.csv 文件的 .csv 文件。 First I have concat this two csv files by pandas, and then save the data into a new file named join_cv_common.csv by pandas.首先我用pandas连接了这两个csv文件,然后将数据保存到pandas一个名为join_cv_common.csv的新文件中。 After that I sorted the join_cv_common.csv file by pandas as below, and stored data are stored into a new file named sorted_cv_common.csv.之后,我按如下所示通过 pandas 对 join_cv_common.csv 文件进行排序,并将存储的数据存储到名为 sorted_cv_common.csv 的新文件中。 I want to rewrite these two functions of pandas - concat and sort by pure python (2.6 and 3.4).我想重写pandas的这两个函数——concat和纯python排序(2.6和3.4)。 Can someone help me in this regards?有人可以在这方面帮助我吗? Thank you very much.非常感谢。

Pandas concat function熊猫连接功能

cv = pd.read_csv('all_cv.csv')

ac = pd.read_csv('common_cv.csv')

merged = pd.concat([cv, ac])

merged.to_csv('join_cv_common.csv')

Pandas sorting function熊猫排序功能

df = pd.read_csv('join_cv_common.csv')

df = df.sort(["adv_id", "conv_id"])

df.to_csv('sorted_cv_common.csv')

Using the file i/o and list sorting使用文件 i/o 和列表排序

By my knowledge it can be done by reading both the files using the file i/o after that just join and convert the string to a list after that sort the newly created list and put it in the final output csv by converting the list to a string.据我所知,可以通过使用文件 i/o 读取这两个文件来完成,然后加入并将字符串转换为列表,然后对新创建的列表进行排序,并通过将列表转换为 a 将其放入最终输出 csv细绳。 Following is the code implementation for that.以下是其代码实现。

123.csv 123.csv

1,a 1,a

2,b 2,b

4,d 4,d

456.csv 456.csv

3,c 3,c

5,d 5,d

Read csv file in d1 and d2 using file open function使用文件打开功能读取 d1 和 d2 中的 csv 文件

d = d1 + '\n' +  d2
lst = d.split('\n')
data = "\n".join(sorted(lst))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM