python - Pandas 分层数据框

标签 python dataframe pandas

我有一个数据框:

Form nr Element Type    Text    Options
   1    Name1   select  text1   op1
   1    Name1   select  text    op2
   1    Name1   select  text    op3
   1    Name2   input   text2   NaN
   2    Name1   input   text2   NaN

有没有办法像这样创建一个“嵌套”的分层索引:

Form nr Element Type    Text    Options
   1    Name1   select  text1   op1
                                op2
                                op3
        Name2   input   text2   NaN
   2    Name1   input   text2   NaN

最佳答案

假设 Text 列中有错字,text <-> text1? 我将从您的第一个 DataFrame 开始。

In [11]: df
Out[11]: 
   Form nr Element    Type   Test Options
0     1      Name1  select  text1     op1
1     1      Name1  select   text     op2
2     1      Name1  select   text     op3
3     1      Name2   input  text2     NaN
4     2      Name1   input  text2     NaN

In [12]: df.set_index(['Form', 'nr Element', 'Type', 'Test'])
Out[12]: 
                             Options
Form nr Element Type   Test         
1    Name1      select text1     op1
                       text      op2
                       text      op3
     Name2      input  text2     NaN
2    Name1      input  text2     NaN

关于python - Pandas 分层数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597926/

相关文章:

python - 我如何获得 Redis 中的所有键?总共 1+ 十亿个 key

python - Pandas pd.Grouper 和每组的顺序日期差异

python - 如何编写对数据帧进行多重过滤的函数?

python - 在 Matplotlib 绘图中将轴的范围更改为非连续数字

pandas - 如何配置 Pandas 读取 .dat 文件

Python 随机音频

python - Jinja2 模板 : how I check in an if statement whether the boolean is False or None

python - 将字典转换为数据帧,其中键和值都有自己的列

r - 计算R中数据帧的相关性

pandas - AWS Redshift Spectrum 十进制类型读取 Parquet 双类型