【问题标题】:Re-index with Python使用 Python 重新索引
【发布时间】:2018-12-13 22:14:53
【问题描述】:

您好,我有一个学生数据集,其中包含他们的姓名、科目和分数。

每个学生有 5 个科目要写。然而,下表缺少一些学生在科目和分数方面的数据。请查看下表:

Name    Subject Score
Harry   Math    4
Harry   Science 5
Harry   Social  3
Harry   French  5
Harry   Spanish 4
Steve   Math    5
Steve   Science 3
Steve   Social  5
Steve   French  4
Tom     Math    5
Tom     Science 4
Tom     Social  5

我想查找分数少于 5 个科目的姓名并附加额外的行,以便所有学生都有他们所有 5 个科目的个人分数。预期输出如下:

Name    Subject     Score
Harry   Math         4
Harry   Science      5
Harry   Social       3
Harry   French       5
Harry   Spanish      4
Steve   Math         5
Steve   Science      3
Steve   Social       5
Steve   French       4
Steve   Spanish      4

您可以在此处看到 Steve、Harry 和 Tom 在所有 5 个科目上都有分数。

【问题讨论】:

  • 如何为添加的行得出分数?
  • 我有用于填充数据的原始数据

标签: python pandas sorting pandas-groupby


【解决方案1】:

这似乎是reindex的完美应用

给定设置:

z=io.StringIO("""Name    Subject Score
Harry   Math    4
Harry   Science 5
Harry   Social  3
Harry   French  5
Harry   Spanish 4
Steve   Math    5
Steve   Science 3
Steve   Social  5
Steve   French  4
Tom     Math    5
Tom     Science 4
Tom     Social  5""")

df=pd.read_table(z,delim_whitespace=True)

然后

new_index = pd.MultiIndex.from_product([df['Name'].unique(), df['Subject'].unique()], names=['Name', 'Subject'])
df.set_index(['Name', 'Subject']).reindex(new_index)

                        Score
Name    Subject 
Harry   Math            4.0
        Science         5.0
        Social          3.0
        French          5.0
        Spanish         4.0
Steve   Math            5.0
        Science         3.0
        Social          5.0
        French          4.0
        Spanish         NaN
Tom     Math            5.0
        Science         4.0
        Social          5.0
        French          NaN
        Spanish         NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多