【问题标题】:Write common elements of 2 csv files(having different no of columns) in a single file在单个文件中写入 2 个 csv 文件的公共元素(具有不同的列数)
【发布时间】:2018-09-27 09:10:42
【问题描述】:

我有 2 个以下格式的 csv 文件-

文件1

David
Lennon

文件2

David  0.3
Lennon 1.3
Wright 2.5

期望的输出-

David 0.3
Lennon 1.3

我正在读取两个 csv 文件,然后检查文件 2 中是否存在相同的第一列,如果存在,我想保留它,然后删除其余的,但我不知道如何去第一个元素。

with open ('file1.csv') as h:
   an = h.readlines()
with open ('file2.csv') as n:
   non = n.readlines()

anno=[]
for i in an:
   anno.append(i.decode('utf-8').strip())

diff={}
for i in non:
   if i.decode('utf-8')[0].strip() in anno:
     diff[i[0]] = i[1]

我认为最后一行出现错误,这不是访问 csv 文件第一列和第二列的正确方法。 怎么做?

【问题讨论】:

    标签: python-3.x pandas csv


    【解决方案1】:

    好的,首先,如果您使用 csv 格式,请确保使用逗号分隔值(csv = 逗号分隔值)。所以把file1和file2改成这样:

    David
    Lennon
    

    David,0.3
    Lennon,1.3
    Wright,2.5
    

    好的,如果我是正确的,那么您只想从 file2 中获取 file1 中存在的数据名称。我将变量的名称更改为不那么神秘的名称,因为我不明白您的意思,但为了清楚起见,我将最后一个 Dictionary 保留为 diff(所需的输出)。

    现在从 file1 中读取名称并将它们放入带有 readlines 的列表中,但是“\n”中仍然有一些不需要的东西。我在 for 循环中用任何内容替换换行符,然后从中创建一个列表,只留下名称。

    with open ("file1.csv") as file1:
       data_file1 = [name.replace("\n", "") for name in file1.readlines()]
    

    对于 file2 做同样的事情并创建一个用逗号分隔的列表,所以“David, 0.3”变成了 [“David”, “0.3”]。请注意,值的类型仍然是字符串。

    with open ("file2.csv") as file1:
       data_file2 = [name.replace("\n", "").split(",") for name in file1.readlines()]
    

    现在比较 file1 和 file2 的数据:

    diff = {}
    for line in data_file2:
        if line[0] in data_file1:
            diff[line[0]] = line[1]
    

    这里 line[0] 是名称,line[1] 是该名称的对应值。

    现在 diff 应该返回

    >>> diff
    {'David': '0.3', 'Lennon': '1.3'}
    

    干杯, 耶勒

    【讨论】:

    • 你太棒了
    猜你喜欢
    • 2022-11-22
    • 2012-08-21
    • 2010-10-24
    • 2018-08-07
    • 2017-09-11
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多