ValueError:将函数应用于数据帧时,值的长度与索引的长度不匹配

2024-04-19 04:57:46 发布

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

我有一个自定义函数,必须应用于数据帧。但当我应用这个函数时,它给出了上面的错误。数据帧如下所示:

enter image description here

功能是:

def f(x):
    G = nx.from_pandas_edgelist(x, 'restart_A', 'restart_B')
    l = x.apply(lambda n: ','.join(nx.node_connected_component(G, n['restart_A'])), axis=1)
    return l

df_2['subgroup_name'] = df_2.groupby('Group').apply(f).to_numpy()

我做错了什么?我还做了重置索引,这里不可见

df_2 = pd.DataFrame(
    {
        "Date": ['2020-07-01', '2020-07-01', '2020-07-01'],
        "restart_A": ['User-1013861701','User-1013861701','User-1013861701'],
        "restart_B": ['User-202955957','User-1744844911','User-5711961755'],
        "Group":['G0', 'G0','G0']
    }
)

Tags: 数据函数from功能pandasdfdef错误
1条回答
网友
1楼 · 发布于 2024-04-19 04:57:46

你能试一试吗

import pandas as pd
import networkx as nx

df_2 = pd.DataFrame(
    {
        "Date": ['2020-07-01', '2020-07-01', '2020-07-01'],
        "restart_A": ['User-1013861701','User-1013861701','User-1013861701'],
        "restart_B": ['User-202955957','User-1744844911','User-5711961755   '],
        "Group":['G0', 'G0','G0']
    }
)

def f(x):
    G = nx.from_pandas_edgelist(x, 'restart_A', 'restart_B')
    l = x.apply(lambda n: ','.join(nx.node_connected_component(G, n['restart_A'])), axis=1)
    x['subgroup_name'] = l.to_numpy()
    return x

df_2 = df_2.groupby('Group').apply(f)

print(df_2)

输出:

         Date        restart_A           restart_B Group                                      subgroup_name
0  2020-07-01  User-1013861701      User-202955957    G0  User-202955957,User-1013861701,User-5711961755...
1  2020-07-01  User-1013861701     User-1744844911    G0  User-202955957,User-1013861701,User-5711961755...
2  2020-07-01  User-1013861701  User-5711961755       G0  User-202955957,User-1013861701,User-5711961755...

相关问题 更多 >