我有一个大数据框,有很多NaN,我想把它存储到一个较小的数据框中,这个数据框存储所有索引和非NaN、非零值的值。在
dff = pd.DataFrame(np.random.randn(4,3), columns=list('ABC'))
dff.iloc[0:2,0] = np.nan
dff.iloc[2,2] = np.nan
dff.iloc[1:4,1] = 0
数据帧可能如下所示:
^{pr2}$我想要这样的数据帧:
0 B -2.268882
0 C 0.337074
1 C 1.340350
2 A -1.526945
3 A -1.223816
4 C -2.185926
我怎么能很快做到呢,因为我有一个相对大的数据框,成千上千。。。在
非常感谢!在
将
0
替换为np.nan
,并.stack()
结果{a1}。在如果有可能在},以减少要透视的行数。如果这适用于
.replace()
之后的rows
中有所有np.nan
值,那么可以在.stack()
之前做{columns
do`.dropna(how='all',axis=1)。在根据需要与
.reset_index()
组合。在要从带有
^{pr2}$MultiIndex
的Series
中选择,请使用.loc[(level_0, level_1)]
:在docs中有关切片等的详细信息。在
我想出了一个有点难看的方法来实现目标,但是嘿,这很管用。但是这个解决方案的索引是从0开始的,并且不会像您的问题一样保留“A”、“B”、“C”的原始顺序,如果这很重要的话。在
我期待更多的
pandas/python
类似的回答我自己!在相关问题 更多 >
编程相关推荐