将两个pandas列进行字符串连接
将两个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 对我没有帮助。
问题:如何将两列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'])]
以上是几种解决这个问题的方法,可以根据性能要求选择合适的方法进行字符串连接。