两个pandas列的字符串连接

nat*_*nat 66 python string numpy dataframe pandas

我有以下内容DataFrame:

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

它看起来像这样:

    bar foo
0    1   a
1    2   b
2    3   c
Run Code Online (Sandbox Code Playgroud)

现在我希望有类似的东西:

     bar
0    1 is a
1    2 is b
2    3 is c
Run Code Online (Sandbox Code Playgroud)

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

df['foo'] = '%s is %s' % (df['bar'], df['foo'])
Run Code Online (Sandbox Code Playgroud)

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

>>>print df.ix[0]

bar                                                    a
foo    0    a
1    b
2    c
Name: bar is 0    1
1    2
2
Name: 0
Run Code Online (Sandbox Code Playgroud)

抱歉有一个愚蠢的问题,但是这只熊猫:在DataFrame中合并两列对我没用.

Bre*_*arn 107

df['bar'] = df.bar.map(str) + " is " + df.foo.


Dan*_*kov 40

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

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

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


cs9*_*s95 38

这个问题已经得到了回答,但是我相信最好将一些以前没有讨论过的有用方法混入混合物中,并比较到目前为止提出的所有方法的性能。

以下是按性能递增顺序解决此问题的一些有用方法。


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
Run Code Online (Sandbox Code Playgroud)

您还可以在此处使用f字符串格式:

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
Run Code Online (Sandbox Code Playgroud)

char.array基于串联

将这些列转换为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
Run Code Online (Sandbox Code Playgroud)

列表理解zip

我不能高估熊猫的列表理解程度。

df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
Run Code Online (Sandbox Code Playgroud)

或者,使用str.joinconcat(也可以更好地扩展):

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

df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c
Run Code Online (Sandbox Code Playgroud)

列表理解在字符串操作方面表现出色,因为字符串操作本来就很难向量化,并且大多数熊猫“向量化”函数基本上都是循环的包装器。我在For循环与熊猫中写了很多有关该主题的文章-什么时候应该关心?。通常,如果您不必担心索引对齐,请在处理字符串和正则表达式操作时使用列表理解。

默认情况下,上面的列表组件不处理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'])]
Run Code Online (Sandbox Code Playgroud)

perfplot 绩效评估

在此处输入图片说明

使用perfplot生成的图。这是完整的代码清单

功能

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'])])
Run Code Online (Sandbox Code Playgroud)

  • 这就是我一直想了解的有关熊猫中字符串串联的全部信息,但又太害怕了! (3认同)
  • 您能否将绘图更新到下一个级别 10**4 (或什至更高),当前绘图限制为 10**3 (1000 对于今天的情况来说非常小)的快速直观答案是 cs3 是最好的,最终,当您看到 brenbarn 看起来比 cs3 指数更小时,因此对于大型数据集,brenbarn 很可能是最好(更快)的答案。 (2认同)

chr*_*lle 12

你也可以用

df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用,因为 df['bar'] 不是字符串列。正确的赋值是`df['bar'] = df['bar'].astype(str).str.cat(df['foo'], sep=' is ')`。 (2认同)

Mau*_*aça 7

10 年过去了,没有人提出最简单直观的方法,比这 10 年来提出的所有示例快 50%。

df.bar.astype(str) + ' is ' + df.foo
Run Code Online (Sandbox Code Playgroud)


Vla*_*hin 6

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
Run Code Online (Sandbox Code Playgroud)


joh*_*ger 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
Run Code Online (Sandbox Code Playgroud)

或者

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
Run Code Online (Sandbox Code Playgroud)

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