python - 如何在 Pandas 中转换数据框

标签 python pandas

我在 Pandas 中有以下数据框

  key       no      lpm
  ab_12     1       12 
  ab_12     2       11
  ab_12     3       11
  ac_12     1       12 
  ac_12     2       11
  ac_12     4       11
  ad_12     1       12 
  ad_12     2       11
  ad_12     3       11

我想要的数据框如下

  key    no_1  no_2   no_3             no_4
  ab_12  12    11     11               does not exist
  ac_12  12    11     does not exist   11
  ad_12  12    11     11               does not exist 

我正在用 pandas 做以下操作,但它没有给我我需要的东西。

  df= df.melt('key').groupby(['key', 'value']).unstack(fill_value='Does not exist')

最佳答案

使用set_indexunstackadd_prefix :

df = df.set_index(['key', 'no'])['lpm'].unstack(fill_value='Does not exist').add_prefix('no_')
print (df)
no    no_1 no_2            no_3            no_4
key                                            
ab_12   12   11              11  Does not exist
ac_12   12   11  Does not exist              11
ad_12   12   11              11  Does not exist

如果解决方案不起作用,因为重复的 keyno 对是必需的聚合:

df = (df.groupby(['key', 'no'])['lpm']
        .mean()
        .unstack(fill_value='Does not exist')
        .add_prefix('no_'))

或者:

df = (df.pivot_table(index='key', 
                    columns='no', 
                    values='lpm', 
                    fill_value='Does not exist',
                    aggfunc='mean').add_prefix('no_'))

编辑:对于后缀添加 add_suffix :

df = (df.set_index(['key', 'no'])['lpm']
        .unstack(fill_value='Does not exist')
        .add_prefix('no_')
        .add_suffix('_lpm'))
print (df)
no    no_1_lpm no_2_lpm        no_3_lpm        no_4_lpm
key                                                    
ab_12       12       11              11  Does not exist
ac_12       12       11  Does not exist              11
ad_12       12       11              11  Does not exist

关于python - 如何在 Pandas 中转换数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873153/

相关文章:

python - 使用 pandas 和 numpy 获取差异并消除间隙时间序列数据

python - 从循环中的一周中减去日期时间

python - 如何通过迭代替换数据框列的某些值

python - 在 map 上绘制分布(直方图)

python - 使用变量进行 Django 对象过滤

python - 创建一个字典列表,其中每个字典都包含另一个字典作为值

python - 使用 concurrent.futures.ThreadPoolExecutor 时用户界面卡住

python - 页面未在django中保存表单数据

python - 遍历嵌套的字符串列表以获取第一项

python - TypeError : Level type mismatch: 0. 2.将数据拆分为训练集、验证集和测试集时