Pandas 在DataFrame中,仅当两个值都存在时,如何使用分隔符连接两个列?
例如,假设我有以下数据帧Pandas 在DataFrame中,仅当两个值都存在时,如何使用分隔符连接两个列?,pandas,dataframe,Pandas,Dataframe,例如,假设我有以下数据帧 col1 col2 a b NaN b a NaN 如果我这么做的话 df['col1'].fillna('')+'-'+df['col2'].fillna('') 我去拿 a-b -b a- 我想要的是 a-b b a 我只想在两边都有值时包含分隔符 与agg叠加 如果我的一个col2值以“-”结尾会怎么样?这种方法可能会去掉这个角色谢谢!成功了。现在我需要研究它到底在做什么。英雄联盟 (df['col1'].fillna('')+'-'+df[
col1 col2
a b
NaN b
a NaN
如果我这么做的话
df['col1'].fillna('')+'-'+df['col2'].fillna('')
我去拿
a-b
-b
a-
我想要的是
a-b
b
a
我只想在两边都有值时包含分隔符
与agg叠加
如果我的一个col2值以“-”结尾会怎么样?这种方法可能会去掉这个角色谢谢!成功了。现在我需要研究它到底在做什么。英雄联盟
(df['col1'].fillna('')+'-'+df['col2'].fillna('')).str.strip('-')
Out[367]:
0 a-b
1 b
2 a
dtype: object
df.stack().groupby(level=0).agg('-'.join)
Out[371]:
0 a-b
1 b
2 a
dtype: object