将两个pandas列进行字符串连接

20 浏览
0 Comments

将两个pandas列进行字符串连接

我有一个如下的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 对我没有帮助。

0
0 Comments

问题的原因是想要对每一行应用操作,但是代码中的写法将整个'bar'和'foo'列转换为字符串,然后返回一个大字符串。可以像下面这样写:

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

这种写法比其他答案更长,但更通用(可以用于非字符串值)。

0
0 Comments

问题的出现原因是想要将两个pandas列进行字符串拼接,但是直接使用"+"操作符在pandas中是不支持的。因此,需要寻找解决方法。

解决方法是使用map函数和字符串连接操作来实现字符串拼接。首先,通过map函数将列"bar"中的元素转换为字符串,然后使用"+"操作符将转换后的字符串与列"foo"进行连接,最终将结果赋值给新的列"bar"。

具体实现的代码如下:

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

使用上述代码可以实现两个pandas列的字符串拼接。

0
0 Comments

问题:如何将两列pandas数据框中的字符串进行连接?

原因:这个问题的出现可能是因为用户想要将两列数据框中的字符串进行连接,但是不知道如何实现。

解决方法:

1. 使用DataFrame.agg方法,基于str.format方法进行连接。

代码示例:

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

或者使用f-string格式化字符串:

   df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
   

2. 使用char.array方法进行连接。

将要连接的列转换为chararray,然后进行加法运算。

代码示例:

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

3. 使用列表推导式和zip函数进行连接。

代码示例:

   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'])]
   

以上是几种解决这个问题的方法,可以根据性能要求选择合适的方法进行字符串连接。

0