簡體   English   中英

在 Pandas df 中創建新列,其中每一行的值取決於其正上方行中不同列的值

[英]Creating new column in a Pandas df, where each row's value depends on the value of a different column in the row immediately above it

假設以下 Pandas df:

# Import dependency.
import pandas as pd

# Create data for df.
data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],
        'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1]
       }

# Create DataFrame
df = pd.DataFrame(data)
display(df)

我想在 df 中添加一個名為“Placeholder”的新列。 Placeholder 的值將基於基於以下規則的“Dummy_Variable”列:

  • 如果所有先前行的“Dummy_Variable”值為 0,則該行的“占位符”值將等於該行的“值”。
  • 如果行的“Dummy_Variable”值等於 1,則該行的“占位符”值將等於該行的“值”。
  • 如果行的“Dummy_Variable”值等於 0,但其正上方行的“Placeholder”值大於 0,則該行的“Placeholder”值將等於正上方行的“Placeholder”值它。

所需的結果是一個帶有新“占位符”列的 df,它看起來像通過運行以下代碼生成的 df:

desired_data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],
        'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1],
        'Placeholder': [1000,1020,1011,1011,1011,1011,1001,1001,1121,1131]}

df1 = pd.DataFrame(desired_data)
display(df1)

我可以在 Excel 中輕松地做到這一點,但我無法弄清楚如何在 Pandas 中不使用循環來做到這一點。 任何幫助是極大的贊賞。 謝謝!

您可以為此使用np.where

import pandas as pd
import numpy as np

data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],
        'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1]
       }

df = pd.DataFrame(data)

df['Placeholder'] = np.where((df.Dummy_Variable.cumsum() == 0) | (df.Dummy_Variable == 1), df.Value, np.nan)

# now forward fill the remaining NaNs
df['Placeholder'].fillna(method='ffill', inplace=True)

df

   Value  Dummy_Variable  Placeholder
0   1000               0       1000.0
1   1020               0       1020.0
2   1011               1       1011.0
3   1010               0       1011.0
4   1030               0       1011.0
5    950               0       1011.0
6   1001               1       1001.0
7   1100               0       1001.0
8   1121               1       1121.0
9   1131               1       1131.0


# check output:
desired_data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],
        'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1],
        'Placeholder': [1000,1020,1011,1011,1011,1011,1001,1001,1121,1131]}

df1 = pd.DataFrame(desired_data)

check = df['Placeholder'] == df1['Placeholder']
check.sum()==len(df1)
# True

暫無
暫無

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

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