繁体   English   中英

从 DataFrame 中获取不是 nan 的行、列对

[英]Get row, column pairs that are not nan from a DataFrame

我有一个 DataFrame,它包含很多 NAN 值,它有大约 100 列和 100 行,这使得很难概览非 NAN 的行、列对。

获取非 NAN 的行、列对列表的最佳方法是什么?

为简单起见,我们假设以下 DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame(data=
[[np.nan, 300, np.nan,  200,],
[400, 300, 100,  200],
[np.nan, np.nan, 100,  np.nan],
[400, np.nan, 100,  200],
[400, 300, np.nan,  200]],
columns=["col1","col2","col3","col4"])

df

我想得到一个列表,其中包含所有不是 NAN 的行、列对。

您可以堆叠丢弃 NaN 的帧,然后您可以获取非 NaN 行列对的索引:

>>> df.stack().index.tolist()

[(0, "col2"),
 (0, "col4"),
 (1, "col1"),
 (1, "col2"),
 (1, "col3"),
 (1, "col4"),
 (2, "col3"),
 (3, "col1"),
 (3, "col3"),
 (3, "col4"),
 (4, "col1"),
 (4, "col2"),
 (4, "col4")]

暂无
暂无

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

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