python - 如何从具有多个索引的数据系列中删除一个值?
问题描述
我有一个数据框,其中记录了每天/每月/每年的温度。然后我使用 groupby 和 min 函数找到每个月的最低温度,这给出了一个具有多个索引的数据系列。
如何删除特定年份和月份的值?例如。2005 年 12 月?
# Find the lowest value per each month
[In] low = df.groupby([df['Date'].dt.year,df['Date'].dt.month])['Data_Value'].min()
[In] low
[Out]
Date Date
2005 1 -60
2 -114
3 -153
4 -13
5 -14
6 26
7 83
8 65
9 21
10 36
11 -36
12 -86
2006 1 -75
2 -53
3 -83
4 -30
5 36
6 17
7 85
8 82
9 66
10 40
11 -2
12 -32
2007 1 -63
2 -42
3 -21
4 -11
5 28
6 74
7 73
8 61
9 46
10 -33
11 -37
12 -97
[In] low.index
[Out] MultiIndex(levels=[[2005, 2006, 2007], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]],
names=['Date', 'Date'])
解决方案
这行得通。
#dummy data
mux = pd.MultiIndex.from_arrays([
(2017,)*12 + (2018,)*12,
list(range(1, 13))*2
], names=['year', 'month'])
df = pd.DataFrame({'value': np.random.randint(1, 20, (len(mux)))}, mux)
然后只需使用drop。
df.drop((2017, 12), inplace=True)
>>> print(df)
value
year month
2017 1 18
2 13
3 14
4 1
5 8
6 19
7 19
8 8
9 11
10 5
11 7 <<<
2018 1 9
2 18
3 9
4 14
5 7
6 4
7 6
8 12
9 12
10 1
11 19
12 10
推荐阅读
- c# - Parallel.Foreach 覆盖 System.IO.File 操作并导致错误
- php - 在 URL 显示详细信息中加密 site_id
- c# - Docker 中的 C# 应用程序
- php - 未捕获的异常:DateTime::__construct():无法解析时间字符串
- mysql - 从多个 (4) 表中返回记录
- azure - 无法从应用服务访问在 Azure AKS Kubernates 上运行的应用程序
- java - 如何在java中将时间戳日期转换为java.util date(yyyy-mm-dd)
- java - 作为 Android 开发者,如何保持更新?
- c - 如何检查pid是线程还是进程
- java - 如何从父活动调用片段中的方法?