gpt4 book ai didi

python - 根据条件创建虚拟 DataFrame

转载 作者:行者123 更新时间:2023-12-05 09:02:02 25 4
gpt4 key购买 nike

我尝试根据具有多个条件的 DataFrame df 创建一个虚拟 DataFrame df_dummy

  • 如果值 > 0 --> 1
  • 如果值 < 0 --> 0
  • 否则 (0, NaN) --> 0
df:
ID1 ID2 ID3
Date
2022-01-01 -1.0 -0.1 0.0
2022-01-02 0.0 1.2 0.7
2022-01-03 NaN 2.0 1.0
2022-01-04 -0.8 0.0 0.0
2022-01-05 1.1 NaN -0.5

df_dummy:
ID1 ID2 ID3
Date
2022-01-01 0 0 NaN
2022-01-02 NaN 1 1
2022-01-03 NaN 1 1
2022-01-04 NAN NaN NaN
2022-01-05 1 NaN 0

我试过为假人定义一个信号:

def signal(x):
if(x>0):
return 1
elif(x<0):
return 0
else:
return np.nan
df_dummy = df[:].apply(lambda x: signal, axis=1)

data_signal = df[:].apply(lambda x: 1 if x>0 -1 if x<0 else np.nan, axis=1)

有没有一种直观的方法可以为 df_dummy 创建这样的条件?

非常感谢!

最佳答案

你可以使用np.select:

# np.select returns a numpy array
# so we copy data to reserve index/columns
df_dummy = df.copy()
df_dummy[:] = np.select((df > 0, df < 0), (1, 0), np.nan)

还有:

df_dummy = pd.DataFrame(np.select((df > 0, df < 0), (1, 0), np.nan),
index=df.index, columns=df.columns)

输出:

            ID1  ID2  ID3
Date
2022-01-01 0.0 0.0 NaN
2022-01-02 NaN 1.0 1.0
2022-01-03 NaN 1.0 1.0
2022-01-04 0.0 NaN NaN
2022-01-05 1.0 NaN 0.0

关于python - 根据条件创建虚拟 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72216306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com