Python 两列的字符串连接

Python 两列的字符串连接,python,string,pandas,numpy,dataframe,Python,String,Pandas,Numpy,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' % (d

我有以下
数据帧

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

很抱歉提出了一个愚蠢的问题,但这个问题对我没有帮助。

df['bar']=df.bar.map(str)+“is”+df.foo
代码中的问题是希望对每一行应用该操作。但是,您编写它的方式需要整个“bar”和“foo”列,将它们转换为字符串并返回一个大字符串。你可以这样写:

df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
它比另一个答案长,但更通用(可用于非字符串的值)。

您也可以使用

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

@丹尼尔韦尔科夫的回答是正确的,但是 使用字符串文字更快:

# 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)

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

以下是解决此问题的一些有用的解决方案,按性能的递增顺序排列


这是一种简单的方法

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字符串格式:

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

基于的连接 将列转换为串联为
chararray
,然后将它们添加到一起

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

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

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

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

列表理解在字符串操作中表现出色,因为字符串操作本质上很难矢量化,而且大多数“矢量化”函数基本上都是围绕循环的包装器。关于这个话题,我在年写了很多文章。一般来说,如果您不必担心索引对齐,那么在处理字符串和正则表达式操作时使用列表理解

默认情况下,上面的列表comp不处理NAN。但是,您可以编写一个函数包装一次尝试,除非您需要处理它

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
性能测量

使用生成的图形。这是我的建议

功能


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

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


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

我遇到了我这边的一个特殊情况,数据帧中有10^11行,在这种情况下,建议的解决方案都不合适。我已经使用了类别,当唯一字符串的数量不太大时,在所有情况下都可以使用。这在带有XxY和factors的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

这不起作用,因为df['bar']不是字符串列。正确的赋值是
df['bar']=df['bar'].astype(str).str.cat(df['foo'],sep='is')
。这就是我一直想知道的关于pandas中字符串连接的所有内容,但我太害怕了,不敢问!请您将绘图更新到下一个级别104(或更高),当前绘图限制为103(1000,对于今天的情况来说非常小)时,一个快速的视觉回答是cs3是最好的,最终当您看到brenbarn比cs3看起来指数更小时,因此对于大数据集,brenbarn很可能是最好的(更快)回答。@VelizarVESSELINOV已更新!让我惊讶的是,numpy连接比list comp和pandas连接都慢。您是否考虑过在
cs3()中使用
df['bar'].tolist()
df['foo'].tolist()
?我的猜测是,它会稍微增加“基本”时间,但它会扩展得更好。太棒了!我遇到了10^11行的问题。提议的解决办法不起作用。我提出了另一个,更接近R软件中的因子乘法,这里使用类别。在您的案例中也可以对其进行测试。Regard此答案也适用于未确定列数(>1)和未确定列名,因此比其他答案更有用。
df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c
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'])]
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'])])
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
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