我有一個旋轉的熊貓資料框,其中包含代表 RGB 值的元組:
import pandas as pd
import numpy as np
rgb = pd.DataFrame([np.random.randint(0,255,9),np.random.randint(0,255,9),np.random.randint(0,255,9)], index = ['r','g','b']).transpose()
rgbtuples = [tuple(i) for i in rgb.values]
df = pd.DataFrame([[1,2,3,1,2,3,1,2,3],[1,1,1,2,2,2,3,3,3], rgbtuples], index=['vertical', 'horizontal', 'rgb']).transpose()
df_pivot = df.pivot(index='vertical', columns = 'horizontal', values ='rgb')
結果,就我而言,在輸出中:
df_pivot
Out[0]:
horizontal 1 2 3
vertical
1 (128, 75, 59) (148, 77, 138) (206, 47, 212)
2 (24, 219, 53) (26, 58, 165) (127, 66, 234)
3 (39, 13, 96) (226, 251, 135) (24, 116, 245)
df_pivot.iloc[0,0]對應于哪里(r=128,g=75,b=59)。
我想使用這些值來創建熱圖,例如海運。
有任何想法嗎?
uj5u.com熱心網友回復:
Seaborn 的熱圖與顏色圖一起使用,而您有明確的 rgb 值。df_pivot()您可以從(元組需要顯式轉換為陣列)中的值創建一個 numpy 陣列并用于imshow()顯示熱圖。
這是一個示例(稍微擴展資料,并使用不同的水平和垂直尺寸進行測驗):
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
rgb = pd.DataFrame([np.random.randint(0, 255, 20), np.random.randint(0, 255, 20), np.random.randint(0, 255, 20)],
index=['r', 'g', 'b']).transpose()
rgbtuples = [tuple(i) for i in rgb.values]
df = pd.DataFrame([np.tile(np.arange(1, 5), 5), np.repeat(np.arange(1, 6), 4), rgbtuples],
index=['vertical', 'horizontal', 'rgb']).transpose()
df_pivot = df.pivot(index='vertical', columns='horizontal', values='rgb')
fig, ax = plt.subplots()
df_pivot_asarray = np.array([[list(tup) for tup in row] for row in df_pivot.to_numpy()])
xlen = len(df_pivot.columns)
ylen = len(df_pivot.index)
ax.imshow(df_pivot_asarray, extent=[- 0.5, xlen - 0.5, -0.5, ylen - 0.5], origin='lower')
ax.set_xticks(range(xlen))
ax.set_xticklabels(df_pivot.columns)
ax.set_yticks(range(ylen))
ax.set_yticklabels(df_pivot.index)
ax.invert_yaxis() # seaborn shows the first row at the top
plt.show()

uj5u.com熱心網友回復:
此代碼將為您提供一個數字網格:
def colorValue(value):
retVal=((value[0]&0x0ff)<<16)|((value[1]&0x0ff)<<8)|(value[2]&0x0ff)
return retVal
colors=[]
df=pd.DataFrame(columns=['cell1','cell2','cell3'])
for index,(cell1,cell2,cell3) in df_pivot.items():
print(index,cell1,cell2,cell3)
df=df.append({'cell1':colorValue(cell1),'cell2':colorValue(cell2), 'cell3':colorValue(cell3)},ignore_index=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414799.html
標籤:
