gpt4 book ai didi

python - 根据数据框中的列对数据进行切片

转载 作者:行者123 更新时间:2023-12-01 04:34:30 25 4
gpt4 key购买 nike

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

Month   Day Year    TmaxF
4 1 1912 56.00
4 2 1912 56.00
4 3 1912 74.00
1 1 1913 38
1 2 1913 28
1 3 1913 21
1 1 1914 30.00
1 2 1914 31.00
1 3 1914 20.00

我只想选择 1913 年和 1914 年的数据。.isin 不是我想要的,因为这是一个简化的数据集。

我更寻找类似的东西:

df.loc['1913':'1914'] 

但是当我将 Year 设置为索引并运行此代码时,它会返回错误:

TypeError: cannot do slice indexing on <class 'pandas.core.index.Int64Index'> with these indexers [1913] of <type 'str'>

df.info() 返回:

Month     36397 non-null int64
Day 36397 non-null int64
Year 36397 non-null int64
TmaxF 35600 non-null float64

最佳答案

首先,请注意您的数据是数字(int64)而不是字符串。从您尝试查询数据的方式来看,我相信您遵循了以日期作为索引的指南(在这种情况下,您可以按日期或部分日期进行切片)

抛开这一点,重要的是要记住 df.loc 用于根据索引进行切片(该索引不会出现在您发送的表中)。

虽然您可以将年份设置为索引,但根据需要对数据进行切片的更优雅的方法是使用 "boolean indexing" :

df[(df.Year >= 1913) && (df.Year <= 1914)]

如果你仍然坚持以年份作为索引,可以这样做:

df.index = df.Year
df.loc[1913:1914]

关于python - 根据数据框中的列对数据进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954941/

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