使用Pandas时,将数据帧的值四舍五入以与给定值进行比较。

huangapple go评论49阅读模式
英文:

Pandas rounding values of a dataframe when comparing to a given value

问题

我有一个奇怪的问题。
我有一个数据框df。我想通过拒绝所有具有'position'(列名)值介于2.750和3.250之间的行,创建另一个数据框df2。
我已经多次按照以下方式完成:

df_a = df[(df['position'] < 2.750)]
df_b = df[(df['position'] > 3.250)]
df2 = pd.concat([df_a, df_b])

问题是,当列的值类似于2.750003甚至2.75时,似乎pandas会将该值四舍五入,然后保留该行,尽管它应该被拒绝。

有人有建议吗?
谢谢

英文:

I have a strange problem.
I have a dataframe df. I want to create another dataframe df2 out of the first one by rejecting all the rows that have 'position' (name of the column) values between 2.750 and 3.250.
I have done that many times as followed:

df_a = df[(df[&#39;position&#39;] &lt; 2.750)]
df_b = df[((df[&#39;position&#39;] &gt; 3.250)]
df2 = pd.concat([df_a, df_b])

The problem is that, when the value of the column is like 2.750003 or even 2.75, it seems like pandas rounds the value and then the row is kept even though it should be rejected.

Does anyone have a suggestion?
Thanks

答案1

得分: 1

以下是翻译好的部分:

If you want to reject everything between 2.75 and 3.25, you can use:

out = df[(df['position'] < 2.750) | (df['position'] > 3.250)]

Or:

out = df[~df['position'].between(2.75, 3.250)]

Example output:

   position
0   1.00000
1   2.00000
2   2.74000
7   3.25001
8   4.00000

Used input:

df = pd.DataFrame({'position': [1,
                                2,
                                2.74,
                                2.75,         #
                                2.750000001,  # 应该被拒绝
                                3,            # 被拒绝
                                3.25,         #
                                3.25001,
                                4,
                               ]})
英文:

If you want to reject everything between 2.75 and 3.25, you can use:

out = df[(df[&#39;position&#39;] &lt; 2.750) | (df[&#39;position&#39;] &gt; 3.250)]

Or:

out = df[~df[&#39;position&#39;].between(2.75, 3.250)]

Example output:

   position
0   1.00000
1   2.00000
2   2.74000
7   3.25001
8   4.00000

Used input:

df = pd.DataFrame({&#39;position&#39;: [1,
                                2,
                                2.74,
                                2.75,         #
                                2.750000001,  # should be
                                3,            # rejected
                                3.25,         #
                                3.25001,
                                4,
                               ]})

huangapple
  • 本文由 发表于 2023年3月31日 21:01:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定