【问题标题】:String concatenation of two pandas columns两个熊猫列的字符串连接
【发布时间】:2012-08-05 04:56:55
【问题描述】:

我有一个关注者DataFrame

from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

看起来像这样:

    bar foo
0    1   a
1    2   b
2    3   c

现在我想要类似的东西:

     bar
0    1 is a
1    2 is b
2    3 is c

我怎样才能做到这一点? 我尝试了以下方法:

df['foo'] = '%s is %s' % (df['bar'], df['foo'])

但它给了我一个错误的结果:

>>>print df.ix[0]

bar                                                    a
foo    0    a
1    b
2    c
Name: bar is 0    1
1    2
2
Name: 0

很抱歉提出了一个愚蠢的问题,但这个pandas: combine two columns in a DataFrame 对我没有帮助。

【问题讨论】:

    标签: python string pandas numpy dataframe


    【解决方案1】:
    df['bar'] = df.bar.map(str) + " is " + df.foo
    

    【讨论】:

      【解决方案2】:

      这个问题已经得到解答,但我相信最好将一些以前没有讨论过的有用方法混在一起,并在性能方面比较迄今为止提出的所有方法。

      这里有一些有用的解决方案,按性能升序排列。


      DataFrame.agg

      这是一个简单的基于str.format 的方法。

      df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
      df
        foo  bar     baz
      0   a    1  1 is a
      1   b    2  2 is b
      2   c    3  3 is c
      

      你也可以在这里使用 f-string 格式:

      df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
      df
        foo  bar     baz
      0   a    1  1 is a
      1   b    2  2 is b
      2   c    3  3 is c
      

      char.array-based 串联

      将列转换为chararrays,然后将它们相加。

      a = np.char.array(df['bar'].values)
      b = np.char.array(df['foo'].values)
      
      df['baz'] = (a + b' is ' + b).astype(str)
      df
        foo  bar     baz
      0   a    1  1 is a
      1   b    2  2 is b
      2   c    3  3 is c
      

      List Comprehensionzip

      我不能夸大熊猫中的列表理解被低估的程度。

      df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
      

      或者,使用str.join 进行连接(也可以更好地扩展):

      df['baz'] = [
          ' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
      

      df
        foo  bar     baz
      0   a    1  1 is a
      1   b    2  2 is b
      2   c    3  3 is c
      

      列表推导在字符串操作方面表现出色,因为字符串操作本质上很难矢量化,而且大多数 pandas “矢量化”函数基本上都是循环的包装器。我在For loops with pandas - When should I care? 中写了很多关于这个主题的文章。一般来说,如果您不必担心索引对齐,则在处理字符串和正则表达式操作时使用列表推导。

      默认情况下,上面的列表组合不处理 NaN。但是,如果您需要处理它,您总是可以编写一个包装 try-except 的函数。

      def try_concat(x, y):
          try:
              return str(x) + ' is ' + y
          except (ValueError, TypeError):
              return np.nan
      
      
      df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]
      

      perfplot 性能测量

      使用perfplot 生成的图表。这是complete code listing

      函数

      def brenbarn(df):
          return df.assign(baz=df.bar.map(str) + " is " + df.foo)
      
      def danielvelkov(df):
          return df.assign(baz=df.apply(
              lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1))
      
      def chrimuelle(df):
          return df.assign(
              baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is '))
      
      def vladimiryashin(df):
          return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1))
      
      def erickfis(df):
          return df.assign(
              baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1))
      
      def cs1_format(df):
          return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1))
      
      def cs1_fstrings(df):
          return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1))
      
      def cs2(df):
          a = np.char.array(df['bar'].values)
          b = np.char.array(df['foo'].values)
      
          return df.assign(baz=(a + b' is ' + b).astype(str))
      
      def cs3(df):
          return df.assign(
              baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])
      

      【讨论】:

      • 这就是我一直想知道的关于 pandas 中字符串连接的全部内容,但是太害怕了!
      • 您能否将情节更新到下一个级别 104(甚至更高),这是当前情节限制为 103(1000 非常小)的快速视觉答案对于今天的情况)是 cs3 是最好的,最终当你看到 brenbarn 看起来没有 cs3 指数级时,所以很可能对于大型数据集 brenbarn 是最好(更快)的答案。
      • @VelizarVESSELINOV 已更新!让我吃惊的是,numpy 连接比 list comp 和 pandas 连接都慢。
      • 您是否考虑过在cs3() 中使用df['bar'].tolist()df['foo'].tolist()?我的猜测是它会稍微增加“基础”时间,但会更好地扩展。
      • 太棒了!在我的情况下,我遇到了 10^11 行的问题。建议的解决方案不起作用。我提出了另一个,更接近 R 软件中的因子乘法,这里使用类别。在您的情况下也可以测试它。问候
      【解决方案3】:

      您的代码中的问题是您希望对每一行都应用该操作。您编写它的方式虽然采用了整个 'bar' 和 'foo' 列,将它们转换为字符串并返回一个大字符串。你可以这样写:

      df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
      

      它比其他答案更长,但更通用(可用于非字符串的值)。

      【讨论】:

        【解决方案4】:

        你也可以使用

        df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
        

        【讨论】:

        • 这不起作用,因为 df['bar'] 不是字符串列。正确的分配是df['bar'] = df['bar'].astype(str).str.cat(df['foo'], sep=' is ')
        【解决方案5】:
        df.astype(str).apply(lambda x: ' is '.join(x), axis=1)
        
        0    1 is a
        1    2 is b
        2    3 is c
        dtype: object
        

        【讨论】:

        • 这个答案也适用于未确定的列数 (> 1) 和未确定的列名,使其比其他答案更有用。
        【解决方案6】:

        series.str.cat 是解决这个问题的最灵活的方法:

        对于df = pd.DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

        df.foo.str.cat(df.bar.astype(str), sep=' is ')
        
        >>>  0    a is 1
             1    b is 2
             2    c is 3
             Name: foo, dtype: object
        

        df.bar.astype(str).str.cat(df.foo, sep=' is ')
        
        >>>  0    1 is a
             1    2 is b
             2    3 is c
             Name: bar, dtype: object
        

        .join()(用于加入单个系列中包含的列表)不同,此方法用于将两个系列连接在一起。它还允许您根据需要忽略或替换 NaN 值。

        【讨论】:

        • 你能证明用str.cat 忽略/替换NaN 值吗?
        【解决方案7】:

        @DanielVelkov 的答案是正确的,但是 使用字符串文字更快:

        # Daniel's
        %timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
        ## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
        
        # String literals - python 3
        %timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
        ## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
        

        【讨论】:

          【解决方案8】:

          我遇到了一个特定情况,我的数据框中有 10^11 行,在这种情况下,建议的解决方案都不合适。我使用了类别,当唯一字符串的数量不太大时,这在所有情况下都可以正常工作。这很容易在带有 XxY 和因素的 R 软件中完成,但我在 python 中找不到任何其他方法(我是 python 新手)。如果有人知道实施此功能的地方,我会很高兴知道。

          def Create_Interaction_var(df,Varnames):
              '''
              :df data frame
              :list of 2 column names, say "X" and "Y". 
              The two columns should be strings or categories
              convert strings columns to categories
              Add a column with the "interaction of X and Y" : X x Y, with name 
              "Interaction-X_Y"
              '''
              df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
              df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
              CatVar = "Interaction-" + "-".join(Varnames)
              Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
              Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
              NbLevels=len(Var0Levels)
          
              names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
                                                          dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
                                   columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
              names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
              names["code01"]=names["code0"] + NbLevels*names["code1"]
              df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
              df.loc[:, CatVar]=  df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
              df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
              return df
          

          【讨论】:

            【解决方案9】:

            我认为对于任意数量的列最简洁的解决方案是this answer 的简短版本:

            df.astype(str).apply(' is '.join, axis=1)

            您可以使用df.agg() 再刮掉两个字符,但速度较慢:

            df.astype(str).agg(' is '.join, axis=1)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-08-08
              • 2019-04-12
              相关资源
              最近更新 更多