根据另一个csv文件过滤csv文件中的行,并将过滤后的数据保存到新的fi中

2024-04-25 22:12:03 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好

所以我试图根据file1过滤file2,其中file1是file2的子集。但是file2有description列,我需要能够分析file1中的数据。我要做的是过滤file2,只得到file1中的标题及其描述。我试过了,但我不确定它是否完全正确,而且它正在工作,但我的计算机中没有保存任何文件

import re
import mmap
from pandas import DataFrame
output = []
with open('file2.csv', 'r') as f2:
    mm = mmap.mmap(f2.fileno(), 0, access=mmap.ACCESS_READ)
    for line in open('file1.csv', 'r'):
        Title = bytes("")
        nameMatch = re.search(Title, mm)
        if nameMatch:
            # output.append(str(""))
            fulltypes = [ 'O*NET-SOC Code', 'Title' , 'Discription' ]
            final = DataFrame(columns=fulltypes)
            final.to_csv(output.append(str("")))
    mm.close()

有什么想法吗?在


Tags: csvimportredataframeoutputtitleopenfile1
1条回答
网友
1楼 · 发布于 2024-04-25 22:12:03

假设您的csv文件不是太大,您可以通过读入pandas并使用join方法来实现这一点。以下面的例子为例:

import pandas as pd

file1 = pd.DataFrame({'Title': ['file1.csv', 'file2.csv', 'file3.csv']})
file2 = pd.DataFrame({'Title': ['file1.csv', 'file2.csv', 'file4.csv'],
                      'Description': ['List of files', 'List of descriptions', 'Something unrelated']})

joined = pd.merge(file1, file2, left_on='Title', right_on='Title')

print joined

打印:

^{pr2}$

也就是说,只有存在于两者中的文件。在

由于pandas可以本机将csv读入数据帧,因此您可以:

import pandas as pd

file1 = pd.DataFrame.from_csv('file1.csv')
file2 = pd.DataFrame.from_csv('file2.csv')

joined = pd.merge(file1, file2, left_on='Title', right_on='Title')

joined.to_csv('Output.csv', index=False)

相关问题 更多 >