用数据帧中的索引替换每个非零值

时间:2021-07-06 07:12:06

标签: python pandas

我有一个很大的 pandas.DataFrame (r:15000 c:50),我想用它们的索引值(在我的情况下是自定义的)替换每个非零值由浮点数组成)。

我可以用一些 for 循环来完成,但它很花时间,所以我想知道是否有一个命令可以让它运行得更快?

2 个答案:

答案 0 :(得分:2)

使用 DataFrame.where 设置不匹配的 0 来索引值:

np.random.seed(123)
df = pd.DataFrame(np.random.choice([0,1,3], size=(5,5)))
#sample FloatIndex
df.index /= 523
print (df)
          0  1  2  3  4
0.000000  3  1  3  3  0
0.001912  3  3  1  3  1
0.003824  3  1  0  1  3
0.005736  1  0  3  0  1
0.007648  3  1  0  0  0

df = df.where(df.eq(0), df.index)
print (df)
                 0         1         2         3         4
0.000000  0.000000  0.000000  0.000000  0.000000  0.000000
0.001912  0.001912  0.001912  0.001912  0.001912  0.001912
0.003824  0.003824  0.003824  0.000000  0.003824  0.003824
0.005736  0.005736  0.000000  0.005736  0.000000  0.005736
0.007648  0.007648  0.007648  0.000000  0.000000  0.000000

答案 1 :(得分:0)

您可以通过 Pandas 操作到达那里,这会更有效率。

给定一个看起来有点像的数据集

>>> df
      0    1    2    3    4
50  1.0  0.0  1.0  1.0  0.0
51  1.0  1.0  1.0  0.0  1.0
52  1.0  0.0  0.0  1.0  0.0
53  0.0  0.0  0.0  1.0  0.0
54  1.0  0.0  1.0  0.0  0.0

您可以使用 .apply 对每一列执行操作,其中使用 .where 屏蔽非零值,然后执行 .fillna 以使用索引值填充它们.

>>> df.apply(lambda col: col.where(col != 0).fillna(col.index.to_series()))
       0     1     2     3     4
50   1.0  50.0   1.0   1.0  50.0
51   1.0   1.0   1.0  51.0   1.0
52   1.0  52.0  52.0   1.0  52.0
53  53.0  53.0  53.0   1.0  53.0
54   1.0  54.0   1.0  54.0  54.0