我有一个数据集,其中包含“日期”作为索引,并且每一列都是以计数为值的项目的名称。我试图弄清楚如何过滤每列,其中连续三天以上的时间对每个不同的列计数为零。我正在考虑使用for循环,任何帮助表示赞赏。我正在为此项目使用python。
我对python还是很陌生,到目前为止,我尝试使用for循环,但没有以任何方式使其工作。
for i in a.index:
if a.loc[i,'name']==3==df.loc[i+1,'name']==df.loc[i+2,'name']:
print(a.loc[i,"name"])
在没有频率的情况下无法向时间戳添加整数值。
答案 0 :(得分:0)
如果在问题中包含示例数据框和所需的输出,效果会更好。请下次再做。这样,我不得不猜测您的数据是什么样子,可能无法回答您的问题。我假设这些值是整数。您的数据框每天都有一行吗?我将假设情况并非如此。我将这样做,以便最近 delta 天的每一天都有一行。我创建了一个示例数据框,如下所示:
import pandas as pd
import numpy as np
import datetime
# Here I am just creating random data from your description
delta = 365
start_date = datetime.datetime.now() - datetime.timedelta(days=delta)
end_date = datetime.datetime.now()
datetimes = [end_date - diff for diff in [datetime.timedelta(days=i) for i in range(delta,0,-1)]]
# This is the list of dates we will have in our final dataframe (includes all days)
dates = pd.Series([date.strftime('%Y-%m-%d') for date in datetimes], name='Date', dtype='datetime64[ns]')
# random integer dataframe
df = pd.DataFrame(np.random.randint(0, 5, size=(delta,4)), columns=['item' + str(i) for i in range(4)])
df = pd.concat([df, dates], axis=1).set_index('Date')
# Create a missing day
df = df.drop(df.loc['2019-08-01'].name)
# Reindex so that index has all consecutive days
df = df.reindex(index=dates)
现在我们有了一个示例数据框,其余的将很简单。我将检查数据帧中的值是否等于0,然后使用4(> 3)的窗口进行rolling求和。这样我可以避免for循环。所得数据帧具有所有行,其中至少一项对于4个连续行的值为0。如果连续超过 window 行的值为0,它将显示为两行,其中日期之间只有一天的间隔。我希望这是有道理的。
# custom function as I want "np.nan" returned if a value does not equal "test_value"
def equals(df_value, test_value=0):
return 1 if df_value == test_value else np.nan
# apply the function to every value in the dataframe
# for each row, calculate the sum of four subsequent rows (>3)
df = df.applymap(equals).rolling(window=4).sum()
# if there was np.nan in the sum, the sum is np.nan, so it can be dropped
# keep the rows where there is at least 1 value
df = df.dropna(thresh=1)
# drop all columns that don't have any values
df = df.dropna(thresh=1, axis=1)