首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫:如何将特定列作为索引并将索引更改为不同的列

熊猫:如何将特定列作为索引并将索引更改为不同的列
EN

Data Science用户
提问于 2018-10-25 13:06:46
回答 2查看 1.3K关注 0票数 1

嗨,我是数据科学的新手。从课程时代开始学习数据科学。我有熊猫数据框架如下,

代码语言:javascript
复制
   time   value

A   9      5
A   8      4
A   7      3
B   9      3
B   8      2
B   7      1
C   9      3
C   8      2
C   7      1

我想把这个转化成,

代码语言:javascript
复制
       A   B  C

9      5   3  3 
8      4   2  2
7      3   1  1

当我开始为此编写查询时,它变得越来越复杂。有什么简单的方法吗?谢谢你的帮助。

EN

回答 2

Data Science用户

回答已采纳

发布于 2018-10-25 13:27:11

对我来说,在重塑数据数据(交换列/索引/行等)时,使用枢轴_表格函数是相当直观的。

代码语言:javascript
复制
my_df.pivot_table(index='time', columns=my_df.index, values='value')
票数 1
EN

Data Science用户

发布于 2018-10-25 15:12:45

重现你的问题:

代码语言:javascript
复制
import pandas as pd
d={'time':[9, 8, 7, 9, 8, 7, 9, 8, 7],'value':[5, 4, 3, 3, 2, 1, 3, 2, 1]}
df = pd.DataFrame(data=d,index=['A', 'A', 'A', 'B','B','B','C','C','C'])

使用带for循环的函数。

代码语言:javascript
复制
def change_my_df(give_df,column_to_index,value_in_cell):
"""Specify the dataframe, the column that will become the new inex, the column that will populate the cell of the new df"""
    new_index=give_df[column_to_index].unique().tolist()
    new_columns=list(set(give_df.index.values))
    new_df=pd.DataFrame(index=new_index,columns=new_columns)
    for l,r in give_df.iterrows():
        new_df[l][r[str(column_to_index)]]=r[str(value_in_cell)]
    return new_df
new_df=change_my_df(df,'time','value')
票数 0
EN
页面原文内容由Data Science提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://datascience.stackexchange.com/questions/40219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档