我有dataframe,其中有两个字符串列,这两个列需要连接到单个列
在2列中有3个值。
1.列Comment_vol由Blank、Pass和VolA组成
2. 2.Column Comment_wt由wtA、Pass组成
现在我需要一个专栏,
输入:
Comment_vol Comment_wt
Pass wtA
Pass
VolA Pass
Pass Pass
wtA
VolA wtA
输出:
Comment_vol Comment_wt Comment_final
Pass wtA wtA
Pass Pass
VolA Pass VolA
Pass Pass Pass
wtA wtA
VolA wtA VolA, WtA
代码:
df['Comment'] = df['comment_vol'].str.cat(df['comment_wt'], sep =" ")
发布于 2019-05-23 07:12:14
def concatcolumns(x):
vol = str(x[0])
wt = str(x[1])
if vol in ['nan', 'Pass']:
return wt
elif wt == 'Pass':
return vol
else:
return ", ".join(x)
df['Comment'] = df[['Comment_vol', 'Comment_wt']].apply(lambda x: concatcolumns(x),axis=1)
发布于 2019-05-23 07:36:56
编辑:添加说明
df.Comment_vol.str.strip().isin(['Pass', ''])
去掉前面和后面的空格,并使用isin
检查列Comment_vol
中的值是“Pass”还是“”。我使用strip
来确保您的数据包含诸如“Pass”或“VolA”之类的单词(请注意前面和后面的空格),它仍然有效。这将返回一个布尔值系列,'Pass‘或'’时为True
,否则为False
。将此赋值给n
df.Comment_wt.str.strip().isin(['Pass', ''])
相同,但应用于列Comment_wt
并赋值给m
'~'
是否定运算符,~n
表示Comment_vol
中既不'Pass‘也不’的任何单词
np.select([n, ~n & m], [df.Comment_wt, df.Commnt_vol], df.Comment_vol.str.cat(df.Comment_wt, sep=', '))
等同于逻辑
if n:
df.Comment_wt
elif ~n & m: #`Comment_vol` is NOT 'Pass' or '' and df.Comment_wt is 'Pass' or ''
df.Commnt_vol
else:
df.Comment_vol.str.cat(df.Comment_wt, sep=', ') #concat both columns using `,'
此np.select
返回数组,如下所示:
np.select([n, ~n & m], [df.Comment_wt, df.Comment_vol], df.Comment_vol.str.cat(df.Comment_wt, sep=', '))
Out[350]: array(['wtA', 'Pass', 'VolA', 'Pass', 'wtA', 'VolA, wtA'], dtype=objec
t)
此数组用于创建df
的Comment_final
列
您可以阅读np.select
的文档以了解更多信息https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html
原创:
如果我正确理解了您的描述和输出,这是使用np.select
的典型案例
n = df.Comment_vol.str.strip().isin(['Pass', ''])
m = df.Comment_wt.str.strip().isin(['Pass', ''])
df['Comment_final'] = np.select([n, ~n & m], [df.Comment_wt, df.Comment_vol], df.Comment_vol.str.cat(df.Comment_wt, sep=', '))
Out[591]:
Comment_vol Comment_wt Comment_final
0 Pass wtA wtA
1 Pass Pass
2 VolA Pass VolA
3 Pass Pass Pass
4 wtA wtA
5 VolA wtA VolA, wtA
https://stackoverflow.com/questions/56264223
复制相似问题