python - 如何用逗号连接 Pandas 数据框的两列?

标签 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

最佳答案

您可以使用 applyfillna清空 stringmap 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

fillna为空字符串和 astypestringstrip :

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

编辑:如果您的列的 dtypestring,您可以省略 mapastype:

df['ID'] = df[['IDx', 'IDy']].apply(lambda x: ','.join(x.fillna('')), axis=1)
df['ID'] = df['ID'].str.strip(',')

或者:

df['ID'] = df['IDx'].fillna('') + ',' + df['IDy'].fillna('')
df['ID'] = df['ID'].str.strip(',')
print df

关于python - 如何用逗号连接 Pandas 数据框的两列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125062/

相关文章:

python - 删除 x 刻度但保留网格线

python - Django:通过模型自动生成的 StackedInline 更友好的 header ?

python - 未解析的外部符号_stricoll

python - 使用列表推导式来产生副作用是 Pythonic 吗?

python - pandas 获取具有特定值的行的列平均值?

python - Python 数据框中的插值

python - pygame:当前时间毫秒和增量时间

python - 根据其他列中的 'NaN' 值在 Pandas Dataframe 中创建一个新列

python - 对数据进行分组以完成彼此之间的记录

python - Pandas 中有矢量化的 string.format 吗?