首页 > 解决方案 > 新列作为其他列的列表,但没有 nans

问题描述

基本上,我有这样的数据框:

  c1   c2    
0  a    x  
1  b  NaN  

我想要这样的专栏c

  c1   c2       c
0  a    x  [a, x]
1  b  NaN     [b]

这是我的解决方案:

import pandas as pd
import numpy as np

df = pd.DataFrame({'c1': ['a', 'b'], 'c2': ['x', np.nan]})

df['c'] = df[['c1', 'c2']].values.tolist()
df['c'] = df['c'].apply(lambda x: [i for i in x if i is not np.nan])

但我认为存在一些更短、更简单、更流行的东西。你能帮我解决这个问题吗?

标签: pythonpandaslistnumpy

解决方案


df["c"] = df.apply(lambda x: x[x.notna()].tolist(), axis=1)
print(df)

印刷:

  c1   c2       c
0  a    x  [a, x]
1  b  NaN     [b]

推荐阅读