Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据中的列名称和索引转换为列本身,并将相应的值作为第三列的有效方法?_Python_Pandas_Pivot_Itertools - Fatal编程技术网

Python 将数据中的列名称和索引转换为列本身,并将相应的值作为第三列的有效方法?

Python 将数据中的列名称和索引转换为列本身,并将相应的值作为第三列的有效方法?,python,pandas,pivot,itertools,Python,Pandas,Pivot,Itertools,我有一个非常大的python数据集,它来自一个NETCDF文件。列名是纬度,索引是经度。对于数据库中的每个索引/列,都有一个我感兴趣的z值。我想要一个新的数据框,其列['Latitude','Longitude','Z']。我能够使用itertools提出一个解决方案,但我的数据帧维度(720014400)给了我103680000个值来迭代。有没有更有效的方法来做到这一点。我在这里提供了一个示例输入和输出,以简化测试。熊猫中是否有枢轴功能或其他有效方法来解决此问题 #import librari

我有一个非常大的python数据集,它来自一个NETCDF文件。列名是纬度,索引是经度。对于数据库中的每个索引/列,都有一个我感兴趣的z值。我想要一个新的数据框,其列
['Latitude','Longitude','Z']
。我能够使用itertools提出一个解决方案,但我的数据帧维度(720014400)给了我103680000个值来迭代。有没有更有效的方法来做到这一点。我在这里提供了一个示例输入和输出,以简化测试。熊猫中是否有枢轴功能或其他有效方法来解决此问题

#import libraries
import numpy as np
import pandas as pd
import itertools

#Create Sample Data
columns=['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 df
df=pd.DataFrame(data,columns=columns,index=rows)

df


Out[]
     a    b    c
1  0.1  0.2  0.3
2  0.1  0.2  0.3
3  0.1  0.2  0.3
这是一个有效但缓慢的解决方案

#iterate all combinations of columns and rows
col_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.T
desired_output.columns=['Latitude','Longitude','Z']
desired_output

Out[]: 
       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
    

您可以使用
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