gpt4 book ai didi

python - 如何提取具有非零列值的行?

转载 作者:行者123 更新时间:2023-11-28 21:32:28 25 4
gpt4 key购买 nike

给定一个像这样的 tsv 文件:

doc_id/query_id 1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99  100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
1000001 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1000002 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

第一行是标题角色,以 doc_id/query_id 作为第一列标题,并使用来自 [1,150] 的 150 个整数。

值行由第一列中的 ID 和其他列中的零或一个组成。

目标是提取 ID 和非零列名称对,例如给定上面的两行数据,所需的输出是:

1000001 4
1000001 9
1000002 7
1000002 8

数据中有 800,000 行,因此我将避免使用 pandas 并使用 sframe,我已经尝试过:

import turicreate as tc
from tqdm import tqdm

df = tc.SFrame('data.tsv')

with open('ground_truth.non-zeros.tsv', 'w') as fout:
for i in tqdm(range(len(df))):
for j in range(1,151):
if df[i][str(j)]:
print(df[i]['doc_id/query_id', j)

是否有更简单的方法来提取非零值和行 ID?

Pandas 解决方案或其他数据框解决方案也受到赞赏!请说明限制(如果已知)和(如果有)=)

最佳答案

这是使用 stackquery 的 pandaic 方法:

(df.set_index('doc_id/query_id')
.stack()
.to_frame('tmp')
.query('tmp == 1')
.index
.values)

array([(1000001, '4'), (1000001, '9'), (1000002, '7'), (1000002, '8')],
dtype=object)

这是一种先优雅、后性能的方法。


您也可以从 numpy 开始,这是为了获得最佳性能。

arr = np.loadtxt(filename, skiprows=1, usecols=np.r_[1:151], dtype=int)
index = np.loadtxt(filename, skiprows=1, usecols=[0], dtype=int)

r, c = np.where(arr)
np.column_stack([index[r], c+1])

array([[1000001, 4],
[1000001, 9],
[1000002, 7],
[1000002, 8]])

关于python - 如何提取具有非零列值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com