python - 在 Pandas df 中创建新列,其中每行的值取决于紧邻其上方的行中不同列的值

标签 python pandas dataframe

假设以下 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,则该行的“Placeholder”值将等于该行的“Value”。
  • 如果某行的“Dummy_Variable”值等于 1,则该行的“Placeholder”值将等于该行的“Value”。
  • 如果某行的“Dummy_Variable”值等于 0,但其上一行的“Placeholder”值 >0,则该行的“Placeholder”值将等于该行的“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

关于python - 在 Pandas df 中创建新列,其中每行的值取决于紧邻其上方的行中不同列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72904702/

相关文章:

python - pandas:如何查询多级列数据框?

python - 是有多个脚本文件还是每个函数只有一个大脚本文件更好?

python - Keras LSTM 神经网络 : TypeError: LSTM() missing 1 required positional argument: 'Y'

python - SQLAlchemy:如何将通用映射逻辑添加到我的自定义基类(使用声明式映射)?

python - 连接两个没有值的系列(pandas DataFrame)?

python - FutureWarning in using iteritems() in use .iloc() pandas

python - 用另一个数据框列值中的值填充数据框列

python - 如何加速 Pandas 数据帧上的迭代函数?

python - 从数据帧构造多索引数据帧

python - 如何使用 python-xmpp 设置 Jabber 状态?