簡體   English   中英

如何根據隨后的行單元格值更改數據幀單元格的值?

[英]How to change values of dataframe cells based on following row cell value?

我正在使用Pandas DataFrames在Python中工作。

我的數據框看起來像這樣的一個問題:

Index    A       B    Copy_of_B
1        a       0       0
2        a       1       1
3        a       5       5
4        b       0       0
5        b       4       4
6        c       6       6

我的預期輸出是:

Index    A       B    Copy_of_B
1        a       0       1
2        a       1       1
3        a       5       5
4        b       0       4
5        b       4       4
6        c       6       6

我想用下一行中的值替換Copy_of_B列中的0值,但是我不想使用for循環進行迭代。 有一個簡單的解決方案嗎?

謝謝,

巴納

您可以使用maskbfill

df['Copy_of_B'] = df['B'].mask(df['B'].eq(0)).bfill()

輸出:

   Index  A  B  Copy_of_B
0      1  a  0        1.0
1      2  a  1        1.0
2      3  a  5        5.0
3      4  b  0        4.0
4      5  b  4        4.0
5      6  c  6        6.0

我利用您的DataFrame具有由連續數字組成的索引這一事實。

從創建2個索引開始:

ind = df[df.Copy_of_B == 0].index
ind2 = ind + 1

第一個包含其中Copy_of_B == 0的行的索引值。 第二個包含后續行的索引。

然后,要將數據從后續行“復制”到包含零的行,請運行:

df.loc[ind, 'Copy_of_B'] = df.loc[ind2, 'Copy_of_B'].tolist()

如您所見,整個DataFrame上沒有任何循環運行。

暫無
暫無

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

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