簡體   English   中英

替換 Pandas Dataframe 中的值

[英]Replacing values in a Pandas Dataframe

我有一個 dataframe(名為 df)如下:

    s01  s03  s06  s07  s08
0   1    1    1    1    1
1   1    1    1    1    1
2   0    1    1    0    1
3   0    0    1    1    0
4   0    0    0    1    1

我想用它的索引值替換所有的。

最終結果應如下所示:

    s01  s03  s06  s07  s08
0   0    0    0    0    0
1   1    1    1    1    1
2   0    2    2    0    2
3   0    0    3    3    0
4   0    0    0    4    4

這只是一個示例。 真正的dataframe有數千行數千列。 首要任務是擁有一個能夠盡快修改數據的高效代碼。

我想到了 3 種可能的方法來解決這個問題:

  • 使用 2 個“for”循環和一個“if”語句並直接循環 panda object 或將數據轉換為 2D numpy 數組並循環該數組。

  • 在 pandas Z6A8064B5DF4794555570553 上使用某種 pandas 內置過濾 function。

  • Converting the dataframe into a 2D Numpy array and using some kind of numpy build-in function to modify the data.

哪種方式最省時?

有沒有其他更有效的方法,我還沒有想到呢?

謝謝

你可以用mask做:

df.mask(df.eq(1), df.index)

Output:

   s01  s03  s06  s07  s08
0    0    0    0    0    0
1    1    1    1    1    1
2    0    2    2    0    2
3    0    0    3    3    0
4    0    0    0    4    4

如果您的索引是本示例中的數字,您還可以執行以下操作:

df.mul(df.index, axis=0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM