如何用逗号连接Pandas数据框的2列?

时间:2016-02-01 07:30:23

标签: python pandas

我想用逗号加入Pandas数据框的2列,即:第1列中的“abc”与第2列中的“123”连接成为“abc,123”。

例如:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'IDx': ['a','b',np.nan,'C'], 'IDy':['1','','2','D']})
>>> df
   IDx  IDy
0    a    1
1    b     
2  NaN    2
3    C    D

以下不起作用:

>>> ', '.join([df['IDx'],df['IDy']])
>>> df.apply(lambda x: ', '.join([x['IDx'],x['IDy']]))

这是理想的结果:

>>> df = pd.DataFrame({'ID': ['a, 1', 'b', '2', 'C, D']})
>>> df
     ID
0  a, 1
1     b
2     2
3  C, D

1 个答案:

答案 0 :(得分:5)

您可以apply fillnaPopupmap列清空为<Border x:Name="PopupBorder" BorderBrush="{ThemeResource SystemControlForegroundChromeHighBrush}" BorderThickness="{ThemeResource ComboBoxDropdownBorderThickness}" Background="{ThemeResource SystemControlBackgroundChromeMediumLowBrush}" HorizontalAlignment="Stretch" Margin="0,32,0,0"> strip

string

fillna清空字符串,astype改为stringstrip

df['ID'] = df[['IDx', 'IDy']].apply(lambda x: ','.join(x.fillna('').map(str)), axis=1)
df['ID'] = df['ID'].str.strip(',')
print df
   IDx IDy   ID
0    a   1  a,1
1    b        b
2  NaN   2    2
3    C   D  C,D

编辑:如果您的列stringdf['ID'] = df['IDx'].fillna('').astype(str) + ',' + df['IDy'].fillna('').astype(str) df['ID'] = df['ID'].str.strip(',') print df IDx IDy ID 0 a 1 a,1 1 b b 2 NaN 2 2 3 C D C,D ,则可以省略dtypestring

map

或者:

astype