【问题标题】:Merging list with another list python without loops将列表与另一个没有循环的列表python合并
【发布时间】:2019-04-30 15:58:24
【问题描述】:

我有 2 个看起来像这样的熊猫系列:

import pandas as pd
listA = [5,4,3]
listB = ["a","b","c"]
s = pd.Series(listA)
print(s)
p = pd.Series(listB)
print(p)

我想获得一个混合在一起的 2 个列表的列表,如下所示:

listTogether = ["a5","a4","a3","b5","b4","b3","c5","c4","c3"]
t = pd.Series(listTogether)
print(t)

你有什么提示吗?是否可以通过避免循环来做到这一点?

非常感谢您的帮助

【问题讨论】:

  • 你试过什么?这可以通过zip 和理解/map 来实现。

标签: string python-3.x pandas join merge


【解决方案1】:

不管你喜不喜欢,你都在循环播放。

[f'{b}{a}' for b in listB for a in listA]

['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']

【讨论】:

    【解决方案2】:

    您可以使用 itertools 产品

    from itertools import product
    
    pd.DataFrame(list(product(p.tolist(),s.astype(str).tolist()))).apply(''.join, axis = 1).tolist()
    
    839 µs ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    ['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']
    

    如果你想要一个非常高效的解决方案,请使用纯 python 方式

    [''.join(i) for i in list(product(p.tolist(),s.astype(str).tolist()))]
    79 µs ± 924 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    【讨论】:

      【解决方案3】:

      zip 的使用可能会对您有所帮助。

      你可以为你的列表做类似的事情,但是它涉及一个 for 循环:

      listTogether = ['{}{}'.format(a,b) for (a,b) in zip(listA,listB)]
      

      【讨论】:

        【解决方案4】:

        MultiIndex的一个技巧

        listTogether = pd.MultiIndex.from_product([p,s.astype(str)]).map(''.join).tolist()
        listTogether 
        Out[242]: ['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']
        

        【讨论】:

        • 谢谢,这正是我想要的。我一直在纠结如何使用 MultiIndex。谢谢!
        猜你喜欢
        • 2015-05-07
        • 1970-01-01
        • 2020-09-27
        • 2021-02-23
        • 2014-07-11
        • 2014-05-16
        • 2011-03-09
        • 2021-07-29
        • 1970-01-01
        相关资源
        最近更新 更多