gpt4 book ai didi

python - 从 Pandas 数据框中删除和索引相关数据

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:26 24 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:

df = pd.DataFrame({'a': {('0hr', '0.01um', 0): 12,
('0hr', '0.01um', 1): 10,
('0hr', '0.1um', 0): 8,
('0hr', '0.1um', 1): 6,
('0hr', 'Control', 0): 4,
('0hr', 'Control', 1): 2,
('24hr', '0.01um', 0): 18,
('24hr', '0.01um', 1): 15,
('24hr', '0.1um', 0): 12,
('24hr', '0.1um', 1): 9,
('24hr', 'Control', 0): 6,
('24hr', 'Control', 1): 3},
'b': {('0hr', '0.01um', 0): 42,
('0hr', '0.01um', 1): 35,
('0hr', '0.1um', 0): 28,
('0hr', '0.1um', 1): 21,
('0hr', 'Control', 0): 14,
('0hr', 'Control', 1): 7,
('24hr', '0.01um', 0): 30,
('24hr', '0.01um', 1): 25,
('24hr', '0.1um', 0): 20,
('24hr', '0.1um', 1): 15,
('24hr', 'Control', 0): 10,
('24hr', 'Control', 1): 5}})

我想创建一个具有相同索引和列但在索引轴上少一个级别的数据框。

我知道我可以做到:

df2 = pd.DataFrame(index=df.index columns=df.columns)

然后重置索引以降到第二级:

df2.reset_index(level=2,drop=True,inplace=True)

但这会产生:

                a    b
0hr 0.01um NaN NaN
0.01um NaN NaN
0.1um NaN NaN
0.1um NaN NaN
Control NaN NaN
Control NaN NaN
24hr 0.01um NaN NaN
0.01um NaN NaN
0.1um NaN NaN
0.1um NaN NaN
Control NaN NaN
Control NaN NaN

如何使我的重复数据框看起来像这样:

                a    b
0hr 0.01um NaN NaN
0.1um NaN NaN
Control NaN NaN
24hr 0.01um NaN NaN
0.1um NaN NaN
Control NaN NaN

最佳答案

您可以使用drop_duplicates 方法:

In [11]: df.index.droplevel(2)
Out[11]:
MultiIndex(levels=[[u'0hr', u'24hr'], [u'0.01um', u'0.1um', u'Control']],
labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2]])

In [12]: df.index.droplevel(2).drop_duplicates()
Out[12]:
MultiIndex(levels=[[u'0hr', u'24hr'], [u'0.01um', u'0.1um', u'Control']],
labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

您可以将其输入到您的 DataFrame 中:

In [13]: pd.DataFrame(index=df.index.droplevel(2).drop_duplicates(), columns=df.columns)
Out[13]:
a b
0hr 0.01um NaN NaN
0.1um NaN NaN
Control NaN NaN
24hr 0.01um NaN NaN
0.1um NaN NaN
Control NaN NaN

关于python - 从 Pandas 数据框中删除和索引相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com