Python 数据帧中元素和子集的总长度

Python 数据帧中元素和子集的总长度,python,pandas,dataframe,variable-length,Python,Pandas,Dataframe,Variable Length,如何计算数据帧中的所有元素(包括子集),并将结果放入新列中 import pandas as pd x = pd.Series([[1, (2,5,6)], [2, (3,4)], [3, 4], [(5,6), (7,8,9)]], \ index=range(1, len(x)+1)) df = pd.DataFrame({'A': x}) 我尝试使用以下代码,但每行给出2: df['Length'] = df['A'].apply(len) print(df

如何计算数据帧中的所有元素(包括子集),并将结果放入新列中

import pandas as pd
x = pd.Series([[1, (2,5,6)], [2, (3,4)], [3, 4], [(5,6), (7,8,9)]], \
              index=range(1, len(x)+1))
df = pd.DataFrame({'A': x})
我尝试使用以下代码,但每行给出2:

df['Length'] = df['A'].apply(len)

print(df)

                         A  Length
    1       [1, (2, 5, 6)]       2
    2          [2, (3, 4)]       2
    3               [3, 4]       2
    4  [(5, 6), (7, 8, 9)]       2
不过,我想得到的是:

                         A  Length
    1       [1, (2, 5, 6)]       4
    2          [2, (3, 4)]       3
    3               [3, 4]       2
    4  [(5, 6), (7, 8, 9)]       5

谢谢

使用
itertools

df['Length'] = df['A'].apply(lambda x: len(list(itertools.chain(*x))))

您可以尝试使用此函数,它是递归的,但可以工作:

def recursive_len(item):
    try:
       iter(item)
       return sum(recursive_len(subitem) for subitem in item)
    except TypeError:
       return 1
然后按以下方式调用apply函数:

df['Length'] = df['A'].apply(recursive_len)
鉴于:

您可以编写一个递归生成器,为每个不可编辑的嵌套元素生成
1
。大致如下:

import collections 

def glen(LoS):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in LoS:
        if iselement(el):
            yield 1
        else:
            for sub in glen(el): yield sub    

df['Length'] = df['A'].apply(lambda e: sum(glen(e)))
屈服:

>>> df
                     A  Length
0       [1, (2, 5, 6)]       4
1          [2, (3, 4)]       3
2               [3, 4]       2
3  [(5, 6), (7, 8, 9)]       5
这将在Python2或Python3中工作。对于Python 3.3或更高版本,您可以使用
yield from
替换循环:

def glen(LoS):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in LoS:
        if iselement(el):
            yield 1
        else:
            yield from glen(el) 

很好的一般回答。我喜欢对你所做的修改。此外,我的链接的导入采用Python3@piRSquared:谢谢。原始代码来自一个。Python3.3+也有一个改进,它使用了所示的
yield。
def glen(LoS):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in LoS:
        if iselement(el):
            yield 1
        else:
            yield from glen(el)