我有一个熊猫数据帧,格式如下:
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秒
将^{} 与} :在2.2秒内对68000行数据进行实验运行
groupby
一起使用,将值转换为list
,最后一个^{或者纯python解决方案—首先创建元组列表,然后创建字典,最后
json
:在0.06秒内实验性地运行68000行数据类似的解决方案:实验性地在0.06秒内运行68000行数据
@stevendesu的“新手”解决方案:实验性地在0.06秒内运行了68000行数据
相关问题 更多 >
编程相关推荐