gpt4 book ai didi

python - 如何快速将 ID 重新映射到连续数字

转载 作者:太空狗 更新时间:2023-10-29 21:28:14 26 4
gpt4 key购买 nike

我有一个很大的 csv 文件,其中的行看起来像

stringa,stringb
stringb,stringc
stringd,stringa

我需要对其进行转换,以便 ID 从 0 开始连续编号。在这种情况下,以下内容将起作用

0,1
1,2
3,0

我当前的代码如下:

import csv
names = {}
counter = 0
with open('foo.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[0] in names:
id1 = row[0]
else:
names[row[0]] = counter
id1 = counter
counter += 1
if row[1] in names:
id2 = row[1]
else:
names[row[1]] = counter
id2 = counter
counter += 1
print id1, id2

Python 字典很遗憾地使用了大量内存,而且我的输入很大。

What can I do when the input is too large for the dict to fit in memory

如果有更好/更快的方法来解决这个问题,我也会很感兴趣。

最佳答案

df = pd.DataFrame([['a', 'b'], ['b', 'c'], ['d', 'a']])

v = df.stack().unique()
v.sort()
f = pd.factorize(v)
m = pd.Series(f[0], f[1])

df.stack().map(m).unstack()

enter image description here

关于python - 如何快速将 ID 重新映射到连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39356279/

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