【问题标题】:how to replace values with previous when conditions are met?满足条件时如何用以前的值替换值?
【发布时间】:2019-02-03 10:42:18
【问题描述】:

我正在尝试根据收到的报告制作非规范化数据框。我需要将记录分配给一个组,该组来自一行,其中包含随机文本和组名称之间的 nan。满足条件时如何重写这些行值?我写的循环似乎只在满足条件时才覆盖下一个值,并且在满足下一个条件之前不会这样做。请参阅下面我的数据和代码示例。本质上,我需要这些行是 Primary、Secondary 或我决定的任何其他组,但它必须运行到下一个指定的组被命中。

当前数据:

    Primary
    Week#
    1
    nan
    nan
    nan
    2
    nan
    nan
    nan
    Secondary
    Week#
    1
    nan
    nan
    nan
    2
    nan
    nan
    nan

代码:

for index, obj in enumerate(df['col0']):
    l = len(df['col0'])
    if obj == 'Primary':
        if index > 0:
            previous = df['col0'][index - 1]
        if index < (l - 1):
            next_ = df['col0'][index + 1]
            next_ = obj
            print (next_, obj)

    if obj == 'Secondary':
        if index > 0:
            previous = df['col0'][index - 1]
        if index < (l - 1):
            next_ = df['col0'][index + 1]
            next_ = obj
            print (next_, obj)  

预期输出:

Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary

【问题讨论】:

  • 我不确定我是否完全理解你想要实现的目标,但有两点很突出:1. 你在没有使用它的情况下为 previous 赋值,而你'连续两次重新分配给next_,所以next_ = df['col0'][index + 1]总是被next_ = obj覆盖
  • 我建议在您的问题中将示例数据与代码分开。我假设它们来自不同的文件,但现在示例数据部分看起来像格式错误的 Python 代码。也许你可以包括你得到的输出,以及你期望的输出?

标签: python-3.x loops iterator grouping conditional-statements


【解决方案1】:

做到这一点的更平易近人的方法是只保留您关心的值,并将它们转发到您不关心的地方。例如:

df["col0_cleaned"] = df["col0"].where(df["col0"].isin(["Primary", "Secondary"])).ffill()

如果我们分步进行,事情会变得更加清晰:

df["isin"] = df["col0"].isin(["Primary", "Secondary"])
df["where"] = df["col0"].where(df["col0"].isin(["Primary", "Secondary"]))
df["ffill"] = df["col0"].where(df["col0"].isin(["Primary", "Secondary"])).ffill()

这给了我:

In [350]: df
Out[350]: 
         col0   isin      where      ffill
0     Primary   True    Primary    Primary
1       Week#  False        NaN    Primary
2           1  False        NaN    Primary
3         nan  False        NaN    Primary
4         nan  False        NaN    Primary
5         nan  False        NaN    Primary
6           2  False        NaN    Primary
7         nan  False        NaN    Primary
8         nan  False        NaN    Primary
9         nan  False        NaN    Primary
10  Secondary   True  Secondary  Secondary
11      Week#  False        NaN  Secondary
12          1  False        NaN  Secondary
13        nan  False        NaN  Secondary
14        nan  False        NaN  Secondary
15        nan  False        NaN  Secondary
16          2  False        NaN  Secondary
17        nan  False        NaN  Secondary
18        nan  False        NaN  Secondary
19        nan  False        NaN  Secondary

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多