python - 根据另一列中的先前条件添加行

标签 python pandas

我是 pandas 模块的新手。并有一个关于数据操作的简单问题:

假设我有一个如下表:

Tool | WeekNumber | Status | Percentage
-----|------------|--------|------------
  M1 |     1      |   good |     85
  M1 |     4      |   bad  |     75
  M1 |     7      |   good |     90

根据状态中的条件,我想添加百分比。

例如:

  1. 如果状态为“良好”,则后续周数的以下行应全部为 100,即接下来的行应为第 2 周和第 3 周,且为 100%

  2. 如果状态为“不良”,则接下来的周数的百分比应为 0,即第 5 周和第 6 周为 0。

我对如何处理条件有一些想法,但不知道添加行:

import os, re
import pandas as pd
df = pd.read_excel("test.xlsx")

add_rows = []
for elem in df.Status:
    if elem == "good":
        add_rows.append(100)
    if elem == "bad":
        add_rows.append(0)

df.Percent = pd.Series(add_rows)

但是,这仅根据条件给了我三个值,并更改了特定周数的值。但我想要以下内容:

Tool | WeekNumber | Status | Percentage
-----|------------|--------|------------
  M1 |     1      |   good |     85
  M1 |     2      |   good |     100
  M1 |     3      |   good |     100
  M1 |     4      |   bad  |     75
  M1 |     5      |   bad  |      0
  M1 |     6      |   bad  |      0
  M1 |     7      |   good |     90

最佳答案

这是另一个

val = pd.DataFrame({'WeekNumber':np.arange(df['WeekNumber'].min(), df['WeekNumber'].max()+ 1, 1)})
new_df = df.merge(val, on='WeekNumber', how = 'outer').sort_values(by = 'WeekNumber').reset_index(drop = True)
new_df[['Tool', 'Status']] = new_df[['Tool', 'Status']].ffill()
new_df['Percentage'] = np.where((new_df['Status'] == 'good') & 
new_df['Percentage'].isnull(), 100, new_df['Percentage'])
new_df['Percentage'] = new_df['Percentage'].fillna(0)

你得到了

    Tool    WeekNumber  Status  Percentage
0   M1      1           good    85.0
1   M1      2           good    100.0
2   M1      3           good    100.0
3   M1      4           bad     75.0
4   M1      5           bad     0.0
5   M1      6           bad     0.0
6   M1      7           good    90.0

关于python - 根据另一列中的先前条件添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229738/

相关文章:

python - 为什么我在用 python 抓取时无法获取字符串?

python - 如何读取文本文件的特定部分 (Py 3x)

python - 如何使用 pandas 根据行和列名称创建数组

python - 使用 numpy 或 pandas 的时间序列

python - 如何根据python中的公共(public)ID值将2列的垂直pandas表转换为水平表

python - 如何有效地复制 pandas 行,仅更改一列?

python - 从 python 运行命令行来生成条形码

python - python中的数组语句

python - 从 pandas 时间戳中删除日期部分的最快方法

python - 将 csv 文件路径数组与指定项目名称数组进行比较的逻辑方法