有条件的join或在pythonpandas中连接

我有6列excel,我想join其中5个; 然而,在所有列的单元格中,我没有任何string中的一些具有“0”。 我需要的是:join5列,当单元格不是“0”时使用“>”分隔符,当它为零时,只保留它为空白。 你能帮我怎么在Python或Excel中做到这一点? 下面的例子:

The original file is:(C1:C6 are columns' name) C1 C2 C3 C4 C5 C6 H1 C0 0 LL 0 H2 R0LL AB 0 0 0 I need the results like:(C1 and RESULTS are columns'name) C1 RESULTS H1 C0>L>L H2 R0LL>AB 

谢谢

  • 使用mask'0'零串转换为np.nan
  • 当我们用np.nan或者np.nan叠加时,它们被丢弃
  • 现在,我已经删除了空值,我可以pd.MultiIndex我创build的pd.MultiIndex的第一层进行pd.MultiIndex
  • apply '>'.joinfunction
  • rename该系列并joindf的第一列

 df = df.astype(str) s = df.mask(df == '0').loc[:, 'C2':'C6'].stack() s = s.groupby(level=0).apply('>'.join).rename('RESULTS') c = df[['C1']] df[['C1']].join(s) C1 RESULTS 0 H1 C0>L>L 1 H2 R0LL>AB 
 #use apply to join the non 0 columns by '>' df['RESULTS'] = df.apply(lambda x: '>'.join([e for e in x[1:].astype(str) if e!='0']),axis=1) df Out[90]: C1 C2 C3 C4 C5 C6 RESULTS 0 H1 C0 0 LL 0 C0>L>L 1 H2 R0LL AB 0 0 0 R0LL>AB