【问题标题】:Unique list of nodes in an edge-list边列表中节点的唯一列表
【发布时间】:2018-11-13 19:29:30
【问题描述】:

我有一个大边缘列表(约 2600 万),前两列作为节点,可选列的数量可变:

Node1    Node2    OptionalCol1    OptionalCol2   ...

Gene A    Gene D   --             --
Gene C    Gene F   --             --
Gene D    Gene C   --             --
Gene F    Gene A   --             --

我想要一个包含非冗余节点列表的文本文件,该列表结合了两个列。 输出:

Gene A
Gene D
Gene C
Gene F

我的python代码:

file1 = open("input.txt", "r")
node_id = file1.readlines()
node_list=[]

for i in node_id:
    node_info=i.split()
    node_info[0]=node_info[0].strip()
    node_info[1]=node_info[1].strip()
    if node_info[0] not in node_list:
        node_list.append(node_info[0])
    if node_info[1] not in node_list:
        node_list.append(node_info[1])

print node_list

可以用 awk 做到这一点吗?谢谢

【问题讨论】:

  • 您要从Node1Node2 生成唯一节点列表吗?
  • 是的,结合两列的唯一列表

标签: python awk


【解决方案1】:

假设分隔符是一个制表符 (\t)。如果是一堆空间(一堆不止一个)而不是-F"\t",请使用:-F" +"

$ awk -F"\t" 'NR>2{a[$1];a[$2]}END{for(i in a)print i}' file
Gene A
Gene C
Gene D
Gene F

输出没有任何特定的顺序,但可以。解释:

$ awk -F"\t" '
NR>2 {           # starting on the third record
    a[$1]        # hash first...
    a[$2]        # and second columns
}
END {            # after all that hashing
    for(i in a)  # iterate whole hash
        print i  # and output
}' file

【讨论】:

【解决方案2】:

您可以将 awk 与 sort unique 结合使用:

$ awk '/Gene/ {print $1, $2; print $3, $4}' file | sort -u
Gene A
Gene C
Gene D
Gene F

或者,如果您的列是制表符分隔的:

$ awk -F'\t' '/Gene/ {print $1; print $2}' file | sort -u
Gene A
Gene C
Gene D
Gene F

【讨论】:

    【解决方案3】:

    如果您的文件由制表符分隔,您可以使用它,但您可以将sep 参数更改为您的分隔符。

    import pandas as pd
    import numpy as np
    
    df = pd.read_csv('input.txt', sep='\t', usecols=['Node1', 'Node2'])
    node_list = np.concatenate((df['Node1'].unique(), df['Node2'].unique()))
    

    在处理关系数据时,例如您的文件外观,pandas 是一个非常有用且快速的工具,您可以使用。

    【讨论】:

      【解决方案4】:

      像这样在python 中使用set()

      file1=open("input.txt",'r')
      
      lines = file1.read().split('\n')
      
      all_nodes_as_string=' '.join(lines) #you can use '\t' here if that's what sepparates the nodes on each line
      
      all_nodes_with_dupes = all_nodes_as_string.split(' ')
      
      all_unique_nodes = set(all_nodes_with_dupes)
      

      【讨论】:

        猜你喜欢
        • 2015-11-10
        • 2022-07-05
        • 2022-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-22
        • 2017-11-02
        • 2017-04-12
        相关资源
        最近更新 更多