【问题标题】:How to determine the length of lists of list in a pandas dataframe column?如何确定熊猫数据框列中列表的长度?
【发布时间】:2021-04-05 03:30:10
【问题描述】:

我有一个数据框,其中有一列包含这样的列表。

index ('source', 'target') value of shortest path list of paths
0 ('a', 'b') 3 [['a', 'c', 'b'], ['a', 'c', 'd', 'b'], ['a', 'e', 'f', 'g', 'b']]
1 ('g', 'z') 1 [['g', 'z'], ['g', 'l', 'z']]

我想在第一列中创建 2 列我想为该列表中的每个列表创建一个路径长度列表,除非路径长度等于最短路径的长度(路径长度为等于每个列表的大小减 1)。在第二列中,我想对“路径长度”列中每一行的反转值求和。

lenght of paths total value
[3, 4] 0.583
[2] 0.5

我尝试使用的代码是:

path_lenght = []
for i, row in df.iterrows():
    for k in df['list of paths']:
        if (len(k)-1) > row['shorthest_path_value']:
            path_lenght.append(len(k)-1)
       
    df['lenght of paths'] = path_lenght

但是,这会返回以下错误:

ValueError: Length of lenght of paths (243007) does not match length of index (252454)

我该如何解决这个问题?

【问题讨论】:

  • 您能否澄清一下:“在第二列中,我想对“路径长度”列中每一行的反转值求和。”?
  • 另外我相信你的预期输出不正确

标签: python pandas dataframe


【解决方案1】:

您可以创建 2 个函数,每列一个,然后使用 apply() 方法应用它们。见下文:

def length_of_paths(l):
    k=[len(i) for i in l]
    minlen=min(k)
    return [i-1 for i in k if i!=minlen]

def total_value(l):
    return sum([1/i for i in l])

df['length of paths']=df['list of paths'].apply(lambda x: length_of_paths(x))

df['total value']=df['length of paths'].apply(lambda x: total_value(x))

输出:

>>> print(df)

                                list of paths length of paths  total value
0  [[a, c, b], [a, c, d, b], [a, e, f, g, b]]          [3, 4]     0.583333
1                         [[g, z], [g, l, z]]             [2]     0.500000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多