I have a following DataFrame
:
我有一个以下DataFrame:
from pandas import *df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
It looks like this:
它看起来像这样:
bar foo0 1 a1 2 b2 3 c
Now I want to have something like:
现在我希望有类似的东西:
bar0 1 is a1 2 is b2 3 is c
How can I achieve this?I tried the following:
我怎样才能做到这一点?我尝试了以下方法:
df['foo'] = '%s is %s' % (df['bar'], df['foo'])
but it gives me a wrong result:
但它给了我一个错误的结果:
>>>print df.ix[0]bar afoo 0 a1 b2 cName: bar is 0 11 22Name: 0
Sorry for a dumb question, but this one pandas: combine two columns in a DataFrame wasn't helpful for me.
抱歉有一个愚蠢的问题,但是这个熊猫:在DataFrame中组合两列对我没有帮助。
5 个解决方案
#1
87
df['bar'] = df.bar.map(str) + " is " + df.foo
.
df ['bar'] = df.bar.map(str)+“is”+ df.foo。
#2
35
The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
代码中的问题是您希望在每一行上应用操作。你编写它的方式需要整个'bar'和'foo'列,将它们转换为字符串并返回一个大字符串。你可以这样写:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
It's longer than the other answer but is more generic (can be used with values that are not strings).
它比其他答案更长,但更通用(可以使用非字符串的值)。
#3
11
You could also use
你也可以使用
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
#4
3
df.astype(str).apply(lambda x: ' is '.join(x), axis=1)0 1 is a1 2 is b2 3 is cdtype: object
#5
0
@DanielVelkov answer is the proper one BUTusing string literals is 10 times faster
@DanielVelkov答案是正确的,但是使用字符串文字的速度要快10倍
# Daniel's%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)# String literals - python 3%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
#1
87
df['bar'] = df.bar.map(str) + " is " + df.foo
.
df ['bar'] = df.bar.map(str)+“is”+ df.foo。
#2
35
The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
代码中的问题是您希望在每一行上应用操作。你编写它的方式需要整个'bar'和'foo'列,将它们转换为字符串并返回一个大字符串。你可以这样写:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
It's longer than the other answer but is more generic (can be used with values that are not strings).
它比其他答案更长,但更通用(可以使用非字符串的值)。
#3
11
You could also use
你也可以使用
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
#4
3
df.astype(str).apply(lambda x: ' is '.join(x), axis=1)0 1 is a1 2 is b2 3 is cdtype: object
#5
0
@DanielVelkov answer is the proper one BUTusing string literals is 10 times faster
@DanielVelkov答案是正确的,但是使用字符串文字的速度要快10倍
# Daniel's%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)# String literals - python 3%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)