为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

牧羊人nacy 2023-06-13 15:00:35
我在 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


查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信