【问题标题】:Creating several new concatenated string columns--how to make pythonic?创建几个新的连接字符串列——如何制作 pythonic?
【发布时间】:2020-05-21 20:49:12
【问题描述】:

当我第一次开始使用 Python 时,我可以接受以下代码,因为它完成了工作。但是目前正在重新编写和清理这段代码以备将来使用——有没有更好的方法通过循环或函数使它更 Pythonic?

movements['Agency.1_2'] = movements['Agency.1'] + ' to ' + movements['Agency.2']
movements['Agency.2_3'] = movements['Agency.2'] + ' to ' + movements['Agency.3']
movements['Agency.3_4'] = movements['Agency.3'] + ' to ' + movements['Agency.4']
movements['Agency.4_5'] = movements['Agency.4'] + ' to ' + movements['Agency.5']
movements['Agency.5_6'] = movements['Agency.5'] + ' to ' + movements['Agency.6']
movements['Agency.6_7'] = movements['Agency.6'] + ' to ' + movements['Agency.7']
movements['Agency.7_8'] = movements['Agency.7'] + ' to ' + movements['Agency.8']
movements['Agency.8_9'] = movements['Agency.8'] + ' to ' + movements['Agency.9']
movements['Agency.9_10'] = movements['Agency.9'] + ' to ' + movements['Agency.10']

最终,这段代码会吐出一堆新列,其中包含连接字符串,中间有一个 ' to ',例如:

+-------+------------+------------+
|  id   | Agency.1_2 | Agency.2_3 | 
+-------+------------+------------+
|   1   |   a to b   |   b to c   | 
|   2   |   b to d   |   f to g   | 
|   3   |   z to y   |            | 
+-------+------------+------------+

当前代码有效,如果没有更好的方法,请注意。但很想学习如何做到这一点,这样我就可以推动自己。谢谢!

【问题讨论】:

    标签: python string concatenation


    【解决方案1】:
    for i in range(10):
        movements[f"Agency.{i}_{i+1}"] = f"{movements[f'Agency.{i}']} to {movements[f'Agency.{i+1}']}"
    

    【讨论】:

    • 谢谢!这让我在一个有效的代码范围内! for i in range(10): a[f"Agency.{i+1}_{i+2}"] = a[f"Agency.{i+1}"] + ' to ' + a[f"Agency.{i+2}"]
    • @ColinSorensen 我很高兴!你能告诉我为什么我使用的东西不起作用,以便我可以尝试改进它吗?
    • 它在没有任何“to”的单元格中创建了一些奇怪的字符串值......例如这是复制/粘贴的:''0 foo\n1 bar\n2 baz\n3."
    • 啊!我错过了最后的花括号!你可以使用任何你喜欢的,但我的现在应该可以工作了。
    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 2017-01-27
    • 2013-09-02
    • 1970-01-01
    • 2011-08-15
    • 2012-01-11
    • 2015-11-05
    相关资源
    最近更新 更多