小编NRV*_*RVA的帖子

用 NaN 填充条件后的值

我有一个这样的 df:

df = pd.DataFrame(
    [
        ['A', 1],
        ['A', 1],
        ['A', 1],
        ['B', 2],
        ['B', 0],
        ['A', 0],
        ['A', 1],
        ['B', 1],
        ['B', 0]
    ], columns = ['key', 'val'])
df
Run Code Online (Sandbox Code Playgroud)

打印:

    key val
0   A   1
1   A   1
2   A   1
3   B   2
4   B   0
5   A   0
6   A   1
7   B   1
8   B   0
Run Code Online (Sandbox Code Playgroud)

我想填充 val 列中 2 之后的行(在示例中,val 列中从第 3 行到第 8 行的所有值都替换为 nan)。

我试过这个:

df['val'] = np.where(df['val'].shift(-1) == 2, np.nan, df['val'])
Run Code Online (Sandbox Code Playgroud)

并像这样迭代行: …

numpy python-3.x pandas

5
推荐指数
1
解决办法
59
查看次数

Plotly:如何使用 For 循环突出显示具有矩形形状的 Pandas 时间序列中的某些时期?

我试图在 Plotly 中突出显示时间段。我似乎最好的方法是使用 Shapes,就像这样,但在现实世界中,您不想像示例 url 中那样手动添加每个形状。我认为 for 循环是最好的解决方案,但欢迎其他(计算量较小的)建议。

我的脚本如下所示:

np.random.seed(12345)
rows = 20
x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum()
df = pd.DataFrame({"index": x})

# add column showing what to shade
df["signal"] = df['index'] < 5

# plot index and highlight periods with Rectangle Shapes in Plotly
fig = px.line(df, x=df.index, y="index")

for row in df.iterrows():
    if df['signal'] == False:
        ply_shapes['shape_' + str(i)]=go.layout.Shape(type="rect",
                                                            x0=df.dato[i-1],
                                                            y0=0,
                                                            x1=df.dato[i],
                                                            y1=2000,
                                                            opacity=0.5,
                                                            layer="below"
                                                        )

lst_shapes=list(ply_shapes.values())
fig.update_layout(shapes=lst_shapes)
fig.show()
Run Code Online (Sandbox Code Playgroud)

但这返回:

ValueError: The truth value of a Series …
Run Code Online (Sandbox Code Playgroud)

python pandas plotly plotly-python

5
推荐指数
1
解决办法
3273
查看次数

标签 统计

pandas ×2

numpy ×1

plotly ×1

plotly-python ×1

python ×1

python-3.x ×1