简体   繁体   English

如何根据特定条件删除 Pandas DataFrame 的行?

[英]How do I remove rows of a Pandas DataFrame based on a certain condition?

import yfinance as yf
import numpy as np
import pandas as pd

ETF_DB = ['QQQ', 'EGFIX']
fundsret = yf.download(ETF_DB, start=datetime.date(2020,12,31), end=datetime.date(2022,4,30), interval='1mo')['Adj Close'].pct_change()
df = pd.DataFrame(fundsret)
df

Gives me:给我: 在此处输入图像描述

I'm trying to remove the rows in the dataframe that aren't month end such as the row 2021-03-22.我正在尝试删除数据框中不是月末的行,例如行 2021-03-22。 How do I have the dataframe go through and remove the rows where the date doesn't end in '01'?如何让数据框通过并删除日期不以“01”结尾的行?

df.reset_index(inplace=True)

# Convert the date to datetime64
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')

#select only day = 1
filtered = df.loc[df['Date'].dt.day == 1]

Did you mean month start ?你是说月份开始吗?

You can use:您可以使用:

df = df[df.index.day==1]

reproducible example:可重现的例子:

df = pd.DataFrame(columns=['A', 'B'],
                  index=['2021-01-01', '2021-02-01', '2021-03-01',
                         '2021-03-22', '2021-03-31'])
df.index = pd.to_datetime(df.index, dayfirst=False)

output:输出:

              A    B
2021-01-01  NaN  NaN
2021-02-01  NaN  NaN
2021-03-01  NaN  NaN

end of month月底

for the end of month, you can add 1 day and check if this jumps to the next month:对于月底,您可以添加 1 天并检查是否会跳转到下个月:

end = (df.index+pd.Timedelta('1d')).month != df.index.month

df = df[end]

or add an offset and check if the value is unchanged:或添加偏移量并检查值是否未更改:

end = df.index == (df.index + pd.offsets.MonthEnd(0))

df = df[end]

output:输出:

              A    B
2021-03-31  NaN  NaN
  import pandas as pd
    import re
    
    # Dummy Dictionary
    dict={
    'Date': ['2021-01-01','2022-03-01','2023-04-22','2023-04-01'],
    'Name' : ['A','B','C','D']
    }
    
    # Making a DataFrame
    df=pd.DataFrame(dict)

 # Date Pattern Required
pattern= '(\d{4})-(\d{2})-01' 

new_df=df[df['Date'].str.match(r'((\d{4})-(\d{2})-01)')]
print(new_df)

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

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