简体   繁体   English

连接 dataframe 中除 NaN 之外的所有列

[英]Concatenate all columns in dataframe except for NaN

Another simple one.另一个简单的。 I have a DataFrame (1056 x 39) that contains reference variables from a pivot table.我有一个 DataFrame (1056 x 39),其中包含来自 pivot 表的参考变量。 I now need to generate a column of concatenated values of all columns, which exclude NaNs.我现在需要生成一列所有列的串联值,不包括 NaN。 The trouble is that I have quite a few NaNs which are interfering with the output.问题是我有很多干扰 output 的 NaN。

Based on another post that I have found Concatenating all columns in pandas dataframe , I can use this approach.根据我发现Concatenating all columns in pandas dataframe 的另一篇文章,我可以使用这种方法。

df['Merge'] = df.astype(str).agg(' or '.join,axis=1)

The trouble is that NaNs remain.问题是 NaN 仍然存在。 How can I modify this line to exclude NaN values (skip them essentially) such that the output will only contain concatenated values.如何修改此行以排除 NaN 值(基本上跳过它们),以便 output 将仅包含连接值。

The intended output should appear as (first row):预期的 output 应显示为(第一行):

df['Merge'][0] = 'Var1 or Var2 or Var 20 or Var28' (all NaN values were excluded) df['Merge'][0] = 'Var1 or Var2 or Var 20 or Var28'(排除所有 NaN 值)

Thanks:)谢谢:)

You can stack to remove the NaN then cast to string and groupby + str.join您可以stack以删除NaN ,然后强制转换为字符串和groupby + str.join

import pandas as pd
df = pd.DataFrame([[1.0, np.NaN, 2, 3, 'foo'], [np.NaN, None, 5, 'bar', 'bazz']])

df['merged'] = df.stack().astype(str).groupby(level=0).agg(' or '.join)
#     0   1  2    3     4                merged
#0  1.0 NaN  2    3   foo  1.0 or 2 or 3 or foo
#1  NaN NaN  5  bar  bazz      5 or bar or bazz

Or you can apply along the rows, dropping nulls, casting to string then joining all the non-nulls.或者您可以沿行应用,删除空值,转换为字符串,然后加入所有非空值。

df = pd.DataFrame([[1.0, np.NaN, 2, 3, 'foo'], [np.NaN, None, 5, 'bar', 'bazz']])

df['merged'] = df.apply(lambda row: ' or '.join(row.dropna().astype(str)), axis=1)
#     0   1  2    3     4                merged
#0  1.0 NaN  2    3   foo  1.0 or 2 or 3 or foo
#1  NaN NaN  5  bar  bazz      5 or bar or bazz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM