英文:
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['position'] < 2.750)]
df_b = df[((df['position'] > 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['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, # should be
3, # rejected
3.25, #
3.25001,
4,
]})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论