我想用逗号加入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
答案 0 :(得分:5)
您可以apply
fillna
将Popup
,map
列清空为<Border x:Name="PopupBorder"
BorderBrush="{ThemeResource SystemControlForegroundChromeHighBrush}"
BorderThickness="{ThemeResource ComboBoxDropdownBorderThickness}"
Background="{ThemeResource SystemControlBackgroundChromeMediumLowBrush}"
HorizontalAlignment="Stretch"
Margin="0,32,0,0">
和strip
:
string
或fillna
清空字符串,astype
改为string
和strip
:
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
编辑:如果您的列string
为df['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
,则可以省略dtype
或string
:
map
或者:
astype