gpt4 book ai didi

python - 根据 pandas 列中的有序值从 DataFrame 中选择行

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:15 25 4
gpt4 key购买 nike

根据列值选择 pandas 数据框行的问题已在以下位置解决:

Select rows from a DataFrame based on values in a column in pandas

不考虑基于列值顺序的行排序。

举个例子,考虑:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df.loc[df['D'].isin([0,2])])

产量:

     A    B  C  D
0 foo one 0 0
1 bar one 1 2

同样:

print(df.loc[df['D'].isin([2,0])])

其中列值的顺序已颠倒。

我想知道如何修改此表达式以尊重所需列值的顺序,以便输出为:

     A    B  C  D
1 bar one 1 2
0 foo one 0 0

最佳答案

您可以将值放入数据框中,然后进行内部联接(默认情况下合并),这应该 preserve the order左侧数据框:

D = pd.DataFrame({"D": [2, 0]})
D.merge(df)

# D A B C
#0 2 bar one 1
#1 0 foo one 0

或者更确定的方法来做到这一点:

D.reset_index().merge(df).sort_values("index").drop("index", 1)
# D A B C
#0 2 bar one 1
#1 0 foo one 0

关于python - 根据 pandas 列中的有序值从 DataFrame 中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213744/

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