基于多个条件,使用NP.SELECT更改数据框中的值
我想使用np.select更改数据框中的值 但是,我遇到了一个错误,Google没有找到针对类似问题的任何解决方案。 有人可以帮我吗?预先感谢您的时间和帮助。 这是我的数据框
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,0,-0.6,-1,0.7],
'B':[-1,1,-0.3,0.5,1]})
df
,这是我的代码,其中DF值被重新编码如下:
值小于或等于-0.5成为-1
值大于-0.5,小于或等于0.5变为0
值大于0.5变为1
new_df = pd.dataframe( np.Select([DF.LE(-0.5),df.gt( - 。5)& df.le(0.5),df.gt(0.5)], [-1,0,1]), index = df.index, 列= df.columns )
new_df
我的代码给我以下错误,我不确定怎么了,如何解决它 keyError:<函数dispatch_to_series..column_op at 0x7f64a469d158>
I would like to change values in a dataframe using np.select
However, I'm getting an error and google didn't find any solution for similar issues.
Could somebody help me out? Thank you in advance for your time and help.
Here is my dataframe
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,0,-0.6,-1,0.7],
'B':[-1,1,-0.3,0.5,1]})
df
Then, this my code where df values are recoded as follow:
values less than or equal to -0.5 become -1
values greater than -0.5 and less than or equal to 0.5 become 0
values greater than 0.5 become 1
new_df = pd.DataFrame(
np.select([df.le(-0.5), df.gt(-.5) & df.le(0.5), df.gt(0.5)],
[-1, 0, 1]),
index=df.index,
columns=df.columns
)new_df
My code gave me the following error and I'm not sure what's wrong and how to fix it
KeyError: <function dispatch_to_series..column_op at 0x7f64a469d158>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试尝试一下 - 我相信将小数舍入到零数字的情况下也遵守您的所有条件:
You could try this instead - I believe rounding the decimals to zero digits obeys all your conditions as well :