gpt4 book ai didi

python - 将多行合并到数据框列的一行

转载 作者:行者123 更新时间:2023-12-01 01:05:40 24 4
gpt4 key购买 nike

我当前的数据框如下所示,

              0           1         2
0 HA-567034786 AB-1018724 None
1 AB-6348403 HA-7298656 None

使用 apply() 后,我只是将其设置为,

def make_dict(row):
s = set(x for x in row if x)
return {x: list(s - {x}) for x in s}

result = df.apply(make_dict, axis=1).to_frame(name = 'duplicates')

duplicates
1 {'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786']}
2 {'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']}

现在我坚持将其变成如下所示的单维字典,

{
'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786'],
'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']
}

最佳答案

相反,apply使用带有扁平化的字典理解:

print (df)
0 1
0 HA-567034786 AB-1018724
1 AB-6348403 HA-7298656

def make_dict(row):
s = set(x for x in row if x)
return {x: list(s - {x}) for x in s}

result = {k:v for x in df.values for k, v in make_dict(x).items()}

print (result)
{'HA-567034786': ['AB-1018724'],
'AB-1018724': ['HA-567034786'],
'HA-7298656': ['AB-6348403'],
'AB-6348403': ['HA-7298656']}

另一个使用apply的解决方案:

result = {k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()}

关于python - 将多行合并到数据框列的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392261/

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