【问题标题】:Concatenate string columns and index连接字符串列和索引
【发布时间】:2018-08-23 13:26:41
【问题描述】:

我有一个这样的DataFrame

A    B
----------
c    d
e    f

我想介绍第三列,由AB 和索引的串联组成,因此DataFrame 变为:

A    B    C
---------------
c    d    cd0
e    f    ef1

我想这样做:

df['C'] = df['A'] + df['B'] + # and here I don't know how to reference the row index. 

我该怎么做?

【问题讨论】:

    标签: python string pandas dataframe concatenation


    【解决方案1】:
    df['C'] = df['A'].astype(str) + df['B'].astype(str) + np.array(map(str, df.index.values))
    

    基本上,您使用 df.index 访问 df 索引,并将其转换为 numpy 数组,您添加 .values,并将其转换为字符串(以便轻松添加到前面的列,即字符串),您可以使用地图功能。

    编辑:将 .astype(str) 添加到列 A 和 B,以将它们转换为字符串。如果它们已经是字符串,则不需要。

    【讨论】:

    • 对我不起作用,不幸的是:我收到了 TypeError: must be str, not map
    • 在 numpy/pandas 中执行类型转换时总是首选astype。此外,您的代码仅适用于 python2,除非您将 map 的输出收集到列表中。
    • @Zubo 你的列 A 和 B 必须不是字符串类型。我用 .astype(str) 命令编辑了我的帖子,将它们转换为字符串。对困惑感到抱歉。感谢 COLDSPEED 的提示。
    【解决方案2】:

    选项 1
    为了获得更好的可扩展性,请使用assign + agg

    df['C'] = df.assign(index=df.index.astype(str)).agg(''.join, 1)
    df
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    或者,以类似的方式使用np.add.reduce

    df['C'] = np.add.reduce(df.assign(index=df.index.astype(str)), axis=1)
    df
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    选项 2
    使用矢量化字符串连接的可扩展性较低的选项:

    df['C'] = df['A'] + df['B'] + df.index.astype(str)
    df
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    【讨论】:

    • 美丽。非常感谢!
    【解决方案3】:

    pd.DataFrame.itertuples
    Python 3.6

    df.assign(C=[f'{a}{b}{i}' for i, a, b in df.itertuples()])
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    pd.Series.str.cat

    df.assign(C=df.A.str.cat(df.B).str.cat(df.index.astype(str)))
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    Mish/Mash

    from operator import add
    from functools import reduce
    from itertools import chain
    
    df.assign(C=reduce(add, chain((df[c] for c in df), [df.index.astype(str)])))
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    求和

    df.assign(C=df.sum(1) + df.index.astype(str))
    
       A  B    C
    0  c  d  cd0
    1  e  f  ef1
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2022-01-18
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多