繁体   English   中英

在 pandas 中按数值范围对值进行排序

[英]Sort values by numerical range in pandas

我正在用 pandas 对一些指定具体节点的值进行排序,

node='tds210'

filtered_node=result[result.my_remote_host.str.contains(node,case=False,na=False)]

如何在单个 dataframe 中对 tds200 到 tds300 范围内的所有值进行排序?

我在测试字符串中添加了一个随机的 integer,以确保即使除了tdsXXX字符串之外还有任何其他字符(字母或数字),代码也能正常工作。 代码的str.extract部分使用正则表达式,在tdsXXX模式之间有单词边界。 为了验证数字实际上在 200 到 300 之间,使用了捕获组(2\d\d|300) 提取后,如果您只需要 200 到 300 之间的那些条目,请使用dropna()删除与所需范围不匹配的所有条目。 然后对剩余的值进行排序,并将该排序的结果index用于原始 dataframe ( result )。

结果dataframe 用作输入

              my_remote_host
0   this 26 is a tds136 test
1   this 68 is a tds132 test
2   this 16 is a tds215 test
3   this 31 is a tds382 test
4   this 18 is a tds259 test
5  this 100 is a tds247 test
6   this 13 is a tds137 test
7   this 40 is a tds343 test
8   this 63 is a tds170 test
9   this 50 is a tds205 test
import pandas as pd
import re

regex = r"\btds(2\d\d|300)\b"

# filter by TDS value
filtered_node = result.my_remote_host.str.extract \
        (pat = regex, flags = re.I).dropna()
# sort by TDS value
sorted_tds = filtered_node.sort_values([0])
# use sorted index over result dataFrame
sorted_res = result.iloc[sorted_tds.index]
print(sorted_res)

Output 来自sorted_res

              my_remote_host
9   this 50 is a tds205 test
2   this 16 is a tds215 test
5  this 100 is a tds247 test
4   this 18 is a tds259 test

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM