繁体   English   中英

如何根据两列中的值删除 pandas dataframe 中的行?

[英]How to remove rows in a pandas dataframe based on values in two columns?

我有 excel 数据这里

已转换为 pandas dataframe:

         Year  Month   Day  Rain       Date
1.0      1988      1   1.0   0.0 1988-01-01
2.0      1988      1   2.0   0.0 1988-01-02
3.0      1988      1   3.0   0.0 1988-01-03
4.0      1988      1   4.0   0.0 1988-01-04
      ...    ...   ...   ...        ...
11156.0  2017     12  27.0   0.0 2018-06-08
11157.0  2017     12  28.0   0.0 2018-06-09
11158.0  2017     12  29.0   0.0 2018-06-10
11159.0  2017     12  30.0   0.0 2018-06-11
11160.0  2017     12  31.0   0.0 2018-06-12

问题在于,月份和日期列分别延伸到每年的“12”和“31”,这导致月份和日期列中的“2”和“31”等值的不可能组合,分别针对降雨列还包含一个值。 如何删除包含这种不可能的值集的行?

PS:如果日期列因此而混乱也没关系,因为我可以在 excel 中再次生成日期。

目前尚不清楚您在做什么,或者为什么您在 Excel 中生成数据但仍在使用 Pandas。 即便如此,Excel 具有用于生成日期范围的内置功能 除非您使用 Excel 有其他原因,否则我认为没有任何意义。 相反,如果您计划使用 Pandas 中的数据,您不妨使用 Pandas 来生成日期范围:

import pandas as pd

dates = pd.date_range("1988-01-01", "2017-12-31")
df = pd.DataFrame({"Date": dates, "Year": dates.year, "Month": dates.month, "Day": dates.day})

Output:

In [3]: df
Out[3]:
            Date  Year  Month  Day
0     1988-01-01  1988      1    1
1     1988-01-02  1988      1    2
2     1988-01-03  1988      1    3
3     1988-01-04  1988      1    4
4     1988-01-05  1988      1    5
...          ...   ...    ...  ...
10953 2017-12-27  2017     12   27
10954 2017-12-28  2017     12   28
10955 2017-12-29  2017     12   29
10956 2017-12-30  2017     12   30
10957 2017-12-31  2017     12   31

[10958 rows x 4 columns]

In [4]: df[(df.Month==2) & (df.Day==31)]
Out[4]:
Empty DataFrame
Columns: [Date, Year, Month, Day]
Index: []

In [5]: df[(df.Month==2) & (df.Day==29)]
Out[5]:
            Date  Year  Month  Day
59    1988-02-29  1988      2   29
1520  1992-02-29  1992      2   29
2981  1996-02-29  1996      2   29
4442  2000-02-29  2000      2   29
5903  2004-02-29  2004      2   29
7364  2008-02-29  2008      2   29
8825  2012-02-29  2012      2   29
10286 2016-02-29  2016      2   29

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM