我正在使用 python 3.x。我有一個 numpy 形狀陣列 (29982,29982) 和一個形狀串列 29982。示例陣列看起來像
array([[1,5,7,2,9...],
[2,6,4,1,5...],
[7,9,1,12,4...],
...
...
[6,8,13,2,4...]])
示例串列看起來像
['John','David','Josua',......,'Martin']
我想得到一個組合這個陣列和串列的熊貓資料框,這樣陣列值應該大于5。資料框應該看起來像
'John' 'David' 'Josua'
'John' 0 0 7
'David' 0 6 0
'Josua' 7 9 0
....
'Martin' 6 8 13
你能建議我該怎么做嗎?
uj5u.com熱心網友回復:
只需從陣列中創建資料框pd.DataFrame,并將您的串列傳遞為index和columns。然后使用df.where僅保留大于 5 的值:
arr = [...]
lst = ['John','David','Josua',...,'Martin']
df = pd.DataFrame(arr, index=lst, columns=lst)
df = df.where(df > 5, 0)
uj5u.com熱心網友回復:
您可以嘗試numpy.ma.masked_where在 numpy 陣列上進行處理
arr = np.array([[1,5,7,2,],
[2,6,4,1,],
[7,9,1,12],
[6,8,13,2]])
lst = ['John','David','Josua', 'Martin']
df = pd.DataFrame(np.ma.masked_where(arr<=5, arr).filled(0), index=lst, columns=lst)
print(df)
John David Josua Martin
John 0 0 7 0
David 0 6 0 0
Josua 7 9 0 12
Martin 6 8 13 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483007.html
標籤:Python 数组 python-3.x 熊猫 麻木的
