熊猫:组合字符串和整数列。

时间:2022-11-16 04:25:51

I have a following DataFrame:

我有一个DataFrame:

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

It looks like this:

它看起来像这样:

    bar foo
0    1   a
1    2   b
2    3   c

Now I want to have something like:

现在我想要的是:

     bar
0    1 is a
1    2 is b
2    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                                                    a
foo    0    a
1    b
2    c
Name: bar is 0    1
1    2
2
Name: 0

Sorry for a dumb question, but this one pandas: combine two columns in a DataFrame wasn't helpful for me.

很抱歉问了一个愚蠢的问题,但是这个熊猫:将两个列合并到一个DataFrame中对我没有帮助。

4 个解决方案

#1


85  

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

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

#2


34  

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


9  

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 a
1    2 is b
2    3 is c
dtype: object

#1


85  

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

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

#2


34  

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


9  

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 a
1    2 is b
2    3 is c
dtype: object