[英]Efficient way to pivot columns names and index in pandas df to columns themselves, with corresponding values as third column?
我在 python 中有一个来自网络 CDF 文件的非常大的数据集。 列名是纬度,索引是经度。 对于数据库中的每个索引/列,我感兴趣的 az 值。我想要一个新的 dataframe 列['Latitude','Longitude','Z']
。 我能够使用 itertools 提出一种解决方案,但我的 dataframe 尺寸为 (7200,14400) 给我 103,680,000 个值进行迭代。 有没有更有效的方法来做到这一点。 我在这里提供了一个示例输入和 output 以简化测试。 pandas 中是否有 pivot function 或解决此问题的其他有效方法?
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.