gpt4 book ai didi

python - 在多索引数据框中删除行?

转载 作者:行者123 更新时间:2023-12-01 03:32:33 24 4
gpt4 key购买 nike

我有这个 df:

temp = pd.DataFrame({'tic': ['IBM', 'AAPL', 'AAPL', 'IBM', 'AAPL'],
'industry': ['A', 'B', 'B', 'A', 'B'],
'price': [np.nan, 5, 6, 11, np.nan],
'shares':[100, 60, np.nan, 100, np.nan],
'dates': pd.to_datetime(['1990-01-01', '1990-01-01', '1990-04-01',
'1990-04-01', '1990-08-01'])
})

temp.set_index(['tic', 'dates'], inplace=True)
temp.sort_index(inplace=True)

其产量:

                industry  price  shares
tic dates
AAPL 1990-01-01 B 5.0 60.0
1990-04-01 B 6.0 NaN
1990-08-01 B NaN NaN
IBM 1990-01-01 A NaN 100.0
1990-04-01 A 11.0 100.0

如何在数据框中创建一个新列来显示每个抽动的观测值数量。因此,新专栏将如下所示:

        New column
AAPL ... 3
... 3
... 3
IBM ... 2
... 2

最佳答案

您可以使用.groupby(level=0).filter()方法:

In [79]: temp.groupby(level=0).filter(lambda x: len(x) >= 3)
Out[79]:
industry price shares
tic dates
AAPL 1990-01-01 B 5.0 60.0
1990-04-01 B 6.0 NaN
1990-08-01 B NaN NaN

回答你的第二个问题:

In [83]: temp['new'] = temp.groupby(level=0)['industry'].transform('size')

In [84]: temp
Out[84]:
industry price shares new
tic dates
AAPL 1990-01-01 B 5.0 60.0 3
1990-04-01 B 6.0 NaN 3
1990-08-01 B NaN NaN 3
IBM 1990-01-01 A NaN 100.0 2
1990-04-01 A 11.0 100.0 2

关于python - 在多索引数据框中删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709068/

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