熊猫:更高效的索引垃圾桶?

2024-05-16 05:37:25 发布

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

我有一个熊猫数据帧,格式如下:

              rtt rexb
asn   country
12345 US      300 0.5
54321 US      150 0.2
12345 MX      160 0.15

我希望转储两个JSON文件:一个包含给定ASN的所有国家的列表,另一个包含给定国家的所有ASN:

country-by-asn.json:
{
    "12345": ["US", "MX"],
    "54321": ["US"]
}

asn-by-country.json:
{
    "US": ["12345", "54321"],
    "MX": ["54321"]
}

我目前正在做以下工作:

asns = df.index.levels[0]
countries = df.index.levels[1]

country_by_asn = {}
asn_by_country = {}

for asn in asns:
    by_asn = df.loc[[d == asn for d in df.index.get_level_values("asn")]]
    country_by_asn[asn] = list(by_asn.index.get_level_values("country"))

for country in countries:
    by_country = df.loc[[d == country for d in df.index.get_level_values("country")]]
    asn_by_country[country] = list(by_country.index.get_level_values("asn"))

这很管用,但感觉有点笨重。有没有一种更有效的方法(就处理能力而言,不一定就代码复杂性而言)来获得相同的输出?你知道吗

实验证实是“笨重的”。在68000行数据上运行需要435秒


Tags: 数据indfforgetindexby国家
1条回答
网友
1楼 · 发布于 2024-05-16 05:37:25

^{}groupby一起使用,将值转换为list,最后一个^{}在2.2秒内对68000行数据进行实验运行

df1 = df.reset_index()

a = df1.groupby('asn')['country'].apply(list).to_json()
b = df1.groupby('country')['asn'].apply(list).to_json()

或者纯python解决方案—首先创建元组列表,然后创建字典,最后json在0.06秒内实验性地运行68000行数据

import json

l = df.index.tolist()

a, b = {}, {}
for x, y in l:
    a.setdefault(x, []).append(y)
    b.setdefault(y, []).append(y)

a = json.dumps(a)
b = json.dumps(b)

类似的解决方案:实验性地在0.06秒内运行68000行数据

l = df.index.tolist()

from collections import defaultdict

a, b = defaultdict( list ), defaultdict( list )

for n,v in l:
    a[n].append(v)
    b[v].append(n)

a = json.dumps(a)
b = json.dumps(b)

@stevendesu的“新手”解决方案:实验性地在0.06秒内运行了68000行数据

l = df.index.tolist()

a, b = {}, {}

for n, v in l:
    if n not in a:
        a[n] = []
    if v not in b:
        b[v] = []
    a[n].append(v)
    b[v].append(n)

a = json.dumps(a)
b = json.dumps(b)

print (a)
{"12345": ["US", "MX"], "54321": ["US"]}

print (b)
{"MX": [12345], "US": [12345, 54321]}

相关问题 更多 >