在Python中使用多个np.where连接字符串

问题描述 投票:0回答:1

我正在尝试创建供 python/pandas 中的不同程序使用的数据键,并且在连接字符串时遇到真正的问题。

为了构建密钥,我需要调整数据框(或列表)中现有列的值,所以我开始如下:

df_mpf['DATAKEY'] = np.where(df_mpf['SEX']==1,'M','F').astype(str)

这个效果很好。

然后我检查了使用 + 是否可以通过将代码加倍来将它们连接在一起:

df_mpf['DATAKEY'] = np.where(df['SEX']==1,'M','F').astype(str) + np.where(df['SEX']==1, 'M','F').astype(str)

这失败了,给我以下错误:

UFuncTypeError:ufunc 'add' 不包含签名匹配类型的循环 (dtype(' dtype('

我可以使用 + 添加不是 np.where 的内容,无论它是来自列表还是列,都没有问题:

df_mpf['DATAKEY'] = np.where(df_mpf['SEX']==1,'M','F').astype(str) + TERM_Y.astype(str) + df_mpf['AGE']. astype(str)

python pandas concatenation
1个回答
0
投票

这是因为你有两个 numpy 数组,它们比 Series 更难连接起来。

使用系列:

s = pd Series(np.where(df_mpf['SEX']==1,'M','F').astype(str), index=df.index)
df_mpf['DATAKEY'] = s + s

或者,没有 numpy:

s = df_mpf['SEX'].eq(1).map({True: 'M', False: 'F'})

或者,“SEX”对于 F/M 来说只包含 0/1

s = df_mpf['SEX'].map({0: 'F', 1: 'M'})

注意。数组+系列之所以有效,是因为系列。

© www.soinside.com 2019 - 2024. All rights reserved.