【问题标题】:Split column of list of names into all combinations of initials将名称列表的列拆分为所有首字母组合
【发布时间】:2020-06-29 13:41:58
【问题描述】:

我有一个带有“名字”列的数据框,例如约翰·理查德。 我想查找名称 + 首字母的所有 4 种组合并将其存储在单独的列中。所以在这种情况下,我想返回 [(J R, John R, J Richard, John Richard)]。我知道我可以编写一个 for 循环并在列表的每个元素上循环,但是有更快/更有效的方法吗?

谢谢!

【问题讨论】:

    标签: pandas dataframe split names


    【解决方案1】:

    是的,python 有高效的itertools 实现:

    import pandas as pd
    from itertools import product
    
    df = pd.DataFrame([['John Richard'],['John Fitz Kennedy']],columns=['name'])
    
    def cart_prod(lst):
        for i in range(len(lst)): lst[i] = [lst[i],lst[i][0]]
        return [" ".join(i) for i in product(*lst)]
    
    df['new_names'] = df.name.str.split().apply(cart_prod)
    df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多