gpt4 book ai didi

python - 通过另一个 DataFrame 的索引选择某些行

转载 作者:太空狗 更新时间:2023-10-29 21:19:14 24 4
gpt4 key购买 nike

我有一个 DataFrame,我会只选择包含索引值的行到 df1.index 中。

例如:

In [96]: df
Out[96]:
A B C D
1 1 4 9 1
2 4 5 0 2
3 5 5 1 0
22 1 3 9 6

和这些指标

In[96]:df1.index
Out[96]:
Int64Index([ 1, 3, 4, 5, 6, 7, 22, 28, 29, 32,], dtype='int64', length=253)

我想要这样的输出:

In [96]: df
Out[96]:
A B C D
1 1 4 9 1
3 5 5 1 0
22 1 3 9 6

最佳答案

使用isin :

df = df[df.index.isin(df1.index)]

或者获取所有相交的索引并通过loc进行选择:

df = df.loc[df.index & df1.index]
df = df.loc[np.intersect1d(df.index, df1.index)]
df = df.loc[df.index.intersection(df1.index)]

print (df)
A B C D
1 1 4 9 1
3 5 5 1 0
22 1 3 9 6

编辑:

I tried solution: df = df.loc[df1.index]. Do you think that this solution is correct?

解决方案不正确:

df = df.loc[df1.index]
print (df)

A B C D
1 1.0 4.0 9.0 1.0
3 5.0 5.0 1.0 0.0
4 NaN NaN NaN NaN
5 NaN NaN NaN NaN
6 NaN NaN NaN NaN
7 NaN NaN NaN NaN
22 1.0 3.0 9.0 6.0
28 NaN NaN NaN NaN
29 NaN NaN NaN NaN
32 NaN NaN NaN NaN
C:/Dropbox/work-joy/so/_t/t.py:23: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
print (df)

关于python - 通过另一个 DataFrame 的索引选择某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864923/

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