【问题标题】:Combining values from an arbitrary number of pandas columns into a new column — a 'join' in the not-SQL sense将任意数量的 pandas 列中的值组合成一个新列——非 SQL 意义上的“连接”
【发布时间】:2015-01-04 15:59:59
【问题描述】:

我正在尝试执行here 所描述的操作,但并非只有一个列被填充,我想要一个分隔符。

我想替换的代码(用任意数量的 k 替换)是:

    raw_df["all ks"] = raw_df["k1"].fillna("") + "/" + \
                       raw_df["k2"].fillna("") + "/" + \
                       raw_df["k3"].fillna("") + "/" + \
                       raw_df["k4"].fillna("")

我想知道this solution 是否会以某种方式做出响应,但我希望有更简单的东西。

感谢您提供任何有用的建议。搜索网络一直令人沮丧,因为我正在尝试进行连接(在 Python 意义上),并且大多数搜索结果都与数据库意义上的连接列相关(包括在 pandas 中改编的)。

【问题讨论】:

    标签: python-2.7 pandas dataframe concatenation


    【解决方案1】:

    您可以使用cat 字符串方法来连接字符串值。使用此方法,您可以指定分隔符以及应将 NaN 值替换为什么。

    例如,这是一个 DataFrame:

    >>> df = pd.DataFrame({'a': ['x', np.nan, 'x'], 
                           'b': ['y', 'y', np.nan], 
                           'c': ['z', 'z', np.nan]})
         a    b    c
    0    x    y    z
    1  NaN    y    z
    2    x  NaN  NaN
    

    然后从列 a 开始,并使用列表推导传递其余列:

    >>> df['a'].str.cat(others=[df[col] for col in df.columns[1:]], 
                        sep='/', na_rep='')
    0    x/y/z
    1     /y/z
    2      x//
    

    【讨论】:

    • @BobHaffner:谢谢!也很高兴看到使用apply 的解决方案;它可以很方便地实现更多奇特的连接功能。
    • 尽可能使用 str.cat 而非 apply。感觉快了无数倍。
    【解决方案2】:

    所以这就是我想出的。它使用 Apply() 和一个函数。不像我希望的那样简洁,但它适用于任意数量的 K。也许有人会想出更好的东西

    生成数据框

     d = {'k1' : [np.nan,'a','b'], 'k2' : ['c', np.nan, 'c'], 'k3' : ['r','t',np.nan], 'k4': [np.nan,'t','e']}
        raw_df = pd.DataFrame(d)
        raw_df
    
        k1   k2   k3   k4
    0   Nan  c    r    Nan
    1   a    Nan  t    t
    2   b    c    Nan  e
    

    定义一个函数

    def concatKs(s):
        allK = ''
        for k in s:
            if k is not np.nan:            
                allK += k + '/'
            else:
                allK += '' + '/'
        return allK    
    

    然后是 apply() 并传递我们的函数

    raw_df['all ks'] =  raw_df.apply(concatKs, axis=1)
    raw_df
    
        k1  k2  k3  k4  all ks
    0   NaN c   r   NaN /c/r//
    1   a   NaN t   t   a//t/t/
    2   b   c   NaN e   b/c//e/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多