我在 python 中有一個非常大的數據集,它來自一個網絡 CDF 文件。列名是緯度,索引是經度。對于數據庫中的每個索引/列,都有我感興趣的 az 值。我想要一個包含 columns 的新數據框['Latitude','Longitude','Z']。我能夠使用 itertools 提出一個解決方案,但我的數據框尺寸是 (7200,14400) 給了我 103,680,000 個值來迭代。有沒有更有效的方法來做到這一點。我在這里提供了一個示例輸入和輸出,以便于測試。pandas 中是否有一個 pivot 函數或其他有效的方法來解決這個問題?#import librariesimport numpy as npimport pandas as pdimport itertools#Create Sample Datacolumns=['a','b','c']rows=['1','2','3']d_base=np.array([0.1,0.2,0.3])data=np.tile(d_base,(3,1))#create dfdf=pd.DataFrame(data,columns=columns,index=rows)dfOut[] a b c1 0.1 0.2 0.32 0.1 0.2 0.33 0.1 0.2 0.3這是可行但速度慢的解決方案。#iterate all combinations of columns and rowscol_index_pairs=list(itertools.product(columns, rows))desired_output=pd.DataFrame()#lookup the value of each possible pair in the original dataframe and put it into a new one.for item in col_index_pairs: desired_output[item]=[item[0],item[1],df.loc[item[1],item[0]]] desired_output=desired_output.Tdesired_output.columns=['Latitude','Longitude','Z']desired_outputOut[]: Latitude Longitude Z a 1 0.1 a 2 0.1 a 3 0.1 b 1 0.2 b 2 0.2 b 3 0.2 c 1 0.3 c 2 0.3 c 3 0.3
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
你可以檢查melt
s = df.reset_index().melt('index')
Out[18]:
index variable value
0 1 a 0.1
1 2 a 0.1
2 3 a 0.1
3 1 b 0.2
4 2 b 0.2
5 3 b 0.2
6 1 c 0.3
7 2 c 0.3
8 3 c 0.3
添加回答
舉報
0/150
提交
取消