假设我有一个巨大的DataFrame,它只包含少数几个与我执行的过滤匹配的单元格。如何才能在一个新的dataframe中只获得与其匹配的值(以及它们的索引和列),而不使用整个其他的DataFrame,而后者变成了Nan。使用dropna删除Nans只会删除整个列或行,而filter用Nans替换非匹配项。
这是我的密码:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((1000, 1000)))
# this one is almost filled with Nans
df[df<0.01]发布于 2020-12-18 11:39:23
如果需要其他格式的不缺失值,可以使用DataFrame.stack
np.random.seed(2020)
df = pd.DataFrame(np.random.randint(10, size=(5, 3)))
# this one is almost filled with Nans
df1 = df[df<7]
print (df1)
0 1 2
0 0.0 NaN 3.0
1 6.0 3.0 3.0
2 NaN NaN 0.0
3 0.0 NaN NaN
4 3.0 NaN 2.0
df2 = df1.stack().rename_axis(('a','b')).reset_index(name='c')
print (df2)
a b c
0 0 0 0.0
1 0 2 3.0
2 1 0 6.0
3 1 1 3.0
4 1 2 3.0
5 2 2 0.0
6 3 0 0.0
7 4 0 3.0
8 4 2 2.0https://stackoverflow.com/questions/65356280
复制相似问题