2012-08-08 14 views
47

私は、次のDataFrameを持っている:パンダ:文字列を結合し、int型の列

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

それは次のようになります。

 bar 
0 1 is a 
1 2 is b 
2 3 is c 

bar foo 
0 1 a 
1 2 b 
2 3 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 

申し訳ありませんが、しかし、この1 pandas: combine two columns in a DataFrameが私のために有用ではなかったです。

答えて

81

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

32

コードの問題は、すべての行で操作を適用することです。あなたがそれを書いたやり方は、全体の 'bar'と 'foo'の列を取り、それらを文字列に変換し、大きな文字列を返します。

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

これはもう一方の答えよりも長いですが、より一般的です(文字列以外の値でも使用できます)。

9

また、使用することができ

df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ') 
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