从 natsort 创建一个新的 pandas 索引列
Create a new pandas column of indexes from natsort
鉴于此输入
df = pd.DataFrame(
[["1 (2)", "4"], ["5 (3)", "2"], ["4 (2)", "4"], ["1 (1)", "4"], ["1 (2)", "3"]],
columns=["a", "b"],
)
a b
0 1 (2) 4
1 5 (3) 2
2 4 (2) 4
3 1 (1) 4
4 1 (2) 3
达到这个输出
expected = pd.DataFrame(
[["1 (2)", "4", 2], ["5 (3)", "2", 0], ["4 (2)", "4", 1], ["1 (1)", "4", 4], ["1 (2)", "3", 3]],
columns=["a", "b", "c"],
)
a b c
0 1 (2) 4 2
1 5 (3) 2 0
2 4 (2) 4 1
3 1 (1) 4 4
4 1 (2) 3 3
其中 c 列包含已自然排序的 a 列中项目的顺序。我需要这样做:
indexes_human_sorted = natsort.index_humansorted(df["a"], reverse=True) # [1, 2, 0, 4, 3] gets the values in order x[1], x[2], x[0] etc.
for i, x in enumerate(indexes_human_sorted):
df.loc[x, "c"] = i
a b c
0 1 (2) 4 2.0
1 5 (3) 2 0.0
2 4 (2) 4 1.0
3 1 (1) 4 4.0
4 1 (2) 3 3.0
我认为索引上的循环(很慢)应该是不必要的,我想我错过了 natsort 的一些技巧。
你可以使用 np.argsort
我相信:
df['c'] = np.argsort(natsort.index_humansorted(df['a'],reverse=True))
print(df)
a b c
0 1 (2) 4 2
1 5 (3) 2 0
2 4 (2) 4 1
3 1 (1) 4 4
4 1 (2) 3 3
鉴于此输入
df = pd.DataFrame(
[["1 (2)", "4"], ["5 (3)", "2"], ["4 (2)", "4"], ["1 (1)", "4"], ["1 (2)", "3"]],
columns=["a", "b"],
)
a b
0 1 (2) 4
1 5 (3) 2
2 4 (2) 4
3 1 (1) 4
4 1 (2) 3
达到这个输出
expected = pd.DataFrame(
[["1 (2)", "4", 2], ["5 (3)", "2", 0], ["4 (2)", "4", 1], ["1 (1)", "4", 4], ["1 (2)", "3", 3]],
columns=["a", "b", "c"],
)
a b c
0 1 (2) 4 2
1 5 (3) 2 0
2 4 (2) 4 1
3 1 (1) 4 4
4 1 (2) 3 3
其中 c 列包含已自然排序的 a 列中项目的顺序。我需要这样做:
indexes_human_sorted = natsort.index_humansorted(df["a"], reverse=True) # [1, 2, 0, 4, 3] gets the values in order x[1], x[2], x[0] etc.
for i, x in enumerate(indexes_human_sorted):
df.loc[x, "c"] = i
a b c
0 1 (2) 4 2.0
1 5 (3) 2 0.0
2 4 (2) 4 1.0
3 1 (1) 4 4.0
4 1 (2) 3 3.0
我认为索引上的循环(很慢)应该是不必要的,我想我错过了 natsort 的一些技巧。
你可以使用 np.argsort
我相信:
df['c'] = np.argsort(natsort.index_humansorted(df['a'],reverse=True))
print(df)
a b c
0 1 (2) 4 2
1 5 (3) 2 0
2 4 (2) 4 1
3 1 (1) 4 4
4 1 (2) 3 3