我有一個浮點陣列(大小 9300)和另一個整數陣列(大小 2600),其中包含第一個陣列的索引。我正在嘗試根據第二個陣列中的索引獲取第一個陣列中的值。例子:
index 1st_array
0 12.00
1 3.89
2 24.20
3 34.60
index 2nd_array
0 0
1 2
輸出:
index 3nd_array
0 12.00
1 24.20
編輯:這些實際上是 numpy 陣列:
a1 = np.array([12.00, 3.89, 24.20, 34.60])
a2 = np.array([0, 2])
uj5u.com熱心網友回復:
import numpy as np
arr1 = np.array([12.00, 3.89, 24.20, 34.60])
arr2 = np.array([0, 2])
print(arr1[arr2])
印刷
[12. 24.2]
uj5u.com熱心網友回復:
如果您有兩個 Seriess1和s2,請使用:
s1.loc[s2]
例子:
s1 = pd.Series(['a', 'b', 'c', 'd'])
s2 = pd.Series([0, 2])
s1.loc[s2]
0 a
2 c
dtype: object
對于 numpy 陣列
a1[a2]
例子:
a1 = np.array(['a', 'b', 'c', 'd'])
a2 = np.array([0, 2])
a1[a2]
array(['a', 'c'], dtype='<U1')
對于資料幀:
df1.set_index('index').loc[df2['2nd_array']].reset_index()
注意。僅當“索引”是列時才需要set_index/reset_index
例子:
df1 = pd.DataFrame({'index': [0, 1, 2, 3],
'1st_array': [12.0, 3.89, 24.2, 34.6]})
df2 = pd.DataFrame({'index': [0, 1],
'2nd_array': [0, 2]})
(df1
.set_index('index')
.loc[df2['2nd_array']]
.reset_index()
)
index 1st_array
0 0 12.0
1 2 24.2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/462197.html
