【问题标题】:Pandas - String Concatenation with Array columnPandas - 与数组列的字符串连接
【发布时间】:2020-06-02 02:06:56
【问题描述】:

我正在尝试从我的数据框中的两列中创建一个新字符串。我的一列包含 1 个值。另一列包含一个数组。最终结果应该类似于下面的第三列。

  Alpha  Val                Result
0   A    ['1, 2, 3']    ['A1', 'A2', 'A3']

我尝试过列表理解,但它只返回一个错误“只能将 str(不是“list”)连接到 str”

[alpha + val for alpha in df['Alpha'].str.split(",") for val in df['Val'].str.split(",")]

这有点像 1X1 矩阵乘 1X3 矩阵(但连接字符串),但我不知道如何使用 pandas 来实现这一点。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    import pandas as pd
    
    df = pd.DataFrame({'Alpha':['A', 'B'],
                      'Val':[['1, 2, 3'], ['4, 5, 6, 7']]})
    
    def newlist(A,B):
        return [A + i.strip() for i in B[0].split(',')]
    
    df['Result'] = df.apply(lambda x: newlist(x.Alpha, x.Val), axis=1)
    
    

    【讨论】:

    • 如果我想跳过 Val 列的 NaN 值,我将如何添加条件?我尝试添加一个 if 语句,但不断收到“无效语法”
    • 你能给我看一个数据的例子吗?在不查看数据的情况下,这是我的建议,先删除 nans,然后应用上述函数。
    【解决方案2】:

    使用@challasandeep420 提供的数据,我们也可以这样做:

    df['Result'] = (df['Val'].str[0].str.split(',').explode().str.strip()
                             .radd(df['Alpha']).groupby(level=0).agg(list))
    print(df)
    
      Alpha           Val            Result
    0     A     [1, 2, 3]      [A1, A2, A3]
    1     B  [4, 5, 6, 7]  [B4, B5, B6, B7]
    

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 2020-05-26
      • 2012-05-18
      • 2015-11-14
      • 2017-02-04
      • 2022-08-04
      • 2023-01-03
      相关资源
      最近更新 更多