gpt4 book ai didi

python - 如何使用 .loc 对 DF 进行切片,列表中可能包含在索引/列中找不到的元素

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:08 27 4
gpt4 key购买 nike

我有几个列表,其中可能包含在 DataFrame 的索引/列中找不到的元素。我想使用这些索引获取特定的行/列,这样如果在索引/列中找不到列表中的元素,那么它就会被忽略。

df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5], 
"y":[3, 4, 5, 6, 7]},
index=['a', 'b', 'c', 'd', 'e'])

df1.loc[['c', 'd', 'e', 'f'], ['x', 'z']]

我想得到:

     x 
c 3.0
d 4.0
e 5.0

代替:

     x   z
c 3.0 NaN
d 4.0 NaN
e 5.0 NaN
f NaN NaN

最佳答案

我想你需要Index.intersection :

a = ['c', 'd', 'e', 'f']
b = ['x', 'z']

print (df1.index.intersection(a))
Index(['c', 'd', 'e'], dtype='object')

print (df1.columns.intersection(b))
Index(['x'], dtype='object')

df2 = df1.loc[df1.index.intersection(a),df1.columns.intersection(b)]
print (df2)
x
c 3
d 4
e 5

关于python - 如何使用 .loc 对 DF 进行切片,列表中可能包含在索引/列中找不到的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533496/

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