如何对数据进行排序,包括str和编号;“正常”;方式[Python]

如何对数据进行排序,包括str和编号;“正常”;方式[Python],python,Python,我有一个带有“str+number”列的数据框。比如说, Col.1 row.1. "txt 0.001 no" row.2. "txt 0.003no" row.3. "txt 5 yes" row.4. "txt 0.0001no" row.5. "txt 100yes" row.6. "txt 1 no" 但目前它有点像

我有一个带有“str+number”列的数据框。比如说,

            Col.1
row.1.  "txt 0.001 no"
row.2.  "txt 0.003no"
row.3.  "txt 5 yes"
row.4.  "txt 0.0001no"
row.5.  "txt 100yes"
row.6.  "txt 1 no"
但目前它有点像

        Col.1
row.3.  "txt 0.0001no"
row.1.  "txt 0.001 no"
row.2.  "txt 0.003no"
row.4.  "txt 100yes"
row.5.  "txt 1 no"
row.6.  "txt 5 yes"
我想把它分类为:

        Col.1
row.3.  "txt 0.0001no"
row.1.  "txt 0.001 no"
row.2.  "txt 0.003no"
row.5.  "txt 1 no"
row.6.  "txt 5 yes"
row.4.  "txt 100yes"

我知道这与python通常的排序方式有关,比如
100>5
,因为有一个,但是现在我在数字前面有了str,所以我不能使用
int()
。我该怎么办?

我也遇到过这种行为-请参阅以获取解释。解决方案是使用(像内置的
sorted(…)
函数一样使用):

导入natsort >>>natsort.natsorted([“0.001”、“0.01”、“0.1”、“1”、“5”、“100”]) ['0.001', '0.01', '0.1', '1', '5', '100']
请注意,
natsort
不包含在标准库中;这意味着yu必须使用操作系统的软件包管理器,
pip
或手动安装它。顺便说一句,它还提供了许多其他有用的函数。

我想您应该使用列1中的数字进行排序。您可以提取这些数字,然后尝试对它们进行排序-

df['Value'] = df['Col1'].str.extract(pat = r"(\d{1,}\.{0,}\d{0,})")
df['Value'] = pd.to_numeric(df['Value'])

如果您现在对“值”列进行排序,它将起作用。

请查看natsort模块(它不在标准中)library@Programmer问题解决了,请随意将此作为正式答案,但想知道为什么
natsorted(['txt 0.001'、'txt 0.1'、'txt 0.005'])
不工作?@MathAvengers idk,但使用
natsorted.realsorded
代替pf
natsort.natsorted
工作正常