python - 是否可以在python中将多索引更改为正常

标签 python python-3.x pandas group-by pivot-table

所以我有一个包含 4 个 ID 的数据集,每个 ID 有 70 个值,包括存在值和不存在值。我用以下代码计算了存在和不存在的值的数量

df=pd.pivot_table(df,index=["ID",'status'], values=["Sem1"], aggfunc=[len]).reset_index() 
df['ID'] = df['ID'].mask(df['ID'].duplicated(), '') 
df
  ID         Status      len
                         Sem1
 4234        Present     45
             Absent      25
 4235        Present     40
             Absent      30
 4236        Present     35
             Absent      35
 4237        Present     50
             Absent      20

 In: df.columns
 Out:ultiIndex(levels=[['len', 'status', 'ID'], ['sem1', '']],
       labels=[[2, 1, 0], [1, 1, 0]])

我需要将列分别添加到两个不同的数据框中 有什么办法可以将列分开吗? 另外,想知道是否可以改成下面的数据集?

  ID         Status      Sem1
 4234        Present     45
             Absent      25
 4235        Present     40
             Absent      30
 4236        Present     35
             Absent      35
 4237        Present     50
             Absent      20
In:df.columns
Out:Index(['ID', 'Status','Sem1'], dtype='object')

这可以从以前的数据集中完成吗

最佳答案

对我来说,你的解决方案运行良好。

df = pd.DataFrame({'Sem1':[1,3,5,7,1,0],
                   'Sem2':[5,3,6,9,2,4],
                   'ID':list('aaabbb')})

print (df)
   Sem1  Sem2 ID
0     1     5  a
1     3     3  a
2     5     6  a
3     7     9  b
4     1     2  b
5     0     4  b

df1 = df.groupby('ID').mean().reset_index()
print (df1)
  ID      Sem1      Sem2
0  a  3.000000  4.666667
1  b  2.666667  5.000000

编辑:

删除[]:

df = pd.pivot_table(df,index=["ID",'status'], values="Sem1", aggfunc='size').reset_index() 

关于python - 是否可以在python中将多索引更改为正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692842/

相关文章:

Python pandas 将带时区的 unix 时间戳转换为日期时间

python - 使用 2 种格式的 Python 更改类型列

python - 排序字符串列表时的问题

python-3.x - python3,出现错误 “Can' t分配给函数调用”

python - 在 python 中使用 `try` `except` 在不同目录上重复完全相同的代码

python - 用于重复连续元素 block 的 Numpy 向量化函数

python - Django 测试和中间件

python - 在 python 中使用来自 textinput 的值

Python从列表的索引中获取值

python - 获取所有自定义标记的列表