我在 Pandas Dataframe 中有以下数据集:
Id | Year | Month | Total |
---|---|---|---|
0 | 2020 | 9 | 11788.33 |
1 | 2020 | 10 | 18373.99 |
2 | 2020 | 11 | 31018.59 |
3 | 2020 | 12 | 29279.30 |
4 | 2021 | 1 | 1875.10 |
5 | 2021 | 2 | 9550.06 |
6 | 2021 | 3 | 33844.39 |
7 | 2021 | 4 | 33126.53 |
8 | 2021 | 5 | 12910.05 |
9 | 2021 | 6 | 44628.63 |
10 | 2021 | 7 | 25830.03 |
11 | 2021 | 8 | 54463.08 |
12 | 2021 | 9 | 49723.93 |
13 | 2021 | 10 | 23753.81 |
14 | 2021 | 11 | 52532.49 |
15 | 2021 | 12 | 7467.32 |
16 | 2022 | 1 | 24333.54 |
17 | 2022 | 2 | 12394.11 |
18 | 2022 | 3 | 76575.46 |
19 | 2022 | 4 | 95119.82 |
20 | 2022 | 5 | 63048.05 |
我正在尝试根据去年(2021 年)的第一个月(第 1 个月)从总计列中动态返回 value。解决方案是 1875.10。
我在 PyCharm 中使用 Python 来完成这个。
注意:“Id”列是使用 pandas Dataframe 时自动生成的列。我相信它被称为 Pandas 中的索引。
任何帮助将不胜感激。谢谢你。
回答1
您可以使用 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html:
df.loc[(df['Year'] == 2021) & (df['Month'] == 1), 'Total']
这会给你:
0 1875.1
Name: Total, dtype: float64
要获得实际数字,您可以在末尾添加 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html:
df.loc[(df['Year'] == 2021) & (df['Month'] == 1), 'Total'].iloc[0]
输出:
1875.1
回答2
另一种方法是这样做。
df[df['Year']==2021].iloc[0]['Total']
这部分 df[df['Year']==2021]
创建了一个新的 dataframe,其中我们只有 2021 年的 values,并且 .iloc 在 'Total' 列的位置 0 处获取 value
回答3
简单的过滤器就足够了吗?
df[(df.Year == 2021) & (df.Month == 1)].Total