gpt4 book ai didi

python - Pandas:使用 pd.Series 对带有索引的 pd.DataFrame 进行排序

转载 作者:太空狗 更新时间:2023-10-30 01:16:15 26 4
gpt4 key购买 nike

我正在尝试按另一个按特定顺序排序的系列对 DataFrame (axis = 0) 进行排序。

例子:DataFrame 包含 CountryCodes 的索引:'AUS'、'BWA' ....(按字母顺序排序)系列包含国家代码列表及其相关的 GDP(按 GDP 排序)

我可以毫无问题地使用 DataFrame.join(Series),然后对“GDP”列进行排序,然后对 del DF['GDP'] 进行排序,但是有没有一种方法可以在不连接结构的情况下直接执行此操作?

最佳答案

您可以 reindex按(排序的)系列的索引:

In [1]: df = pd.DataFrame([[1, 2], [3, 4]], index=list('ab'))

In [2]: s = pd.Series([2,1], index=list('ab'))

In [3]: s
Out[3]:
a 2
b 1

In [4]: s.sort()

In [5]: df.reindex(s.index)
Out[5]:
0 1
b 3 4
a 1 2

关于python - Pandas:使用 pd.Series 对带有索引的 pd.DataFrame 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com