python - 新列作为其他列的列表,但没有 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])
但我认为存在一些更短、更简单、更流行的东西。你能帮我解决这个问题吗?
解决方案
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]
推荐阅读
- spring - 在测试类之外使用 Spring Boot/JUnit 5 连接到测试生命周期事件
- php - 用两个表编码json数据
- eslint - 如何使用上次修改日期从 ESLint 中排除文件?
- java - 使用 log4j2 处理异常
- javascript - 函数执行后需要渲染 React js
- java - AWS lambda 使用 RestEasy 执行 http 请求:找不到内容类型应用程序/json 类型的编写器
- node.js - 节点使用 AJV 验证请求参数
- android - Volley - API 调用数据未显示在回收站视图中
- javascript - 查找具有连续差 = k 的数组中的子序列总数
- python - 如果数据框中的列名相同,则连接列