2

假设您有一个这样的数据框:

>>> df = pd.DataFrame({
        'epoch_minute': [i for i in reversed(range(25090627,25635267))],
        'count': [random.randint(11, 35) for _ in range(25090627,25635267)]})
>>> df.head()
   epoch_minute  count
0      25635266     12
1      25635265     20
2      25635264     33
3      25635263     11
4      25635262     35

和一些像这样的相对纪元分钟增量:

day = 1440
week = 10080
month = 302400

如何完成此代码块的等效项:

for i,r in df.iterrows():
    if r['epoch_minute'] - day in df['epoch_minute'].values and \
            r['epoch_minute'] - week in df['epoch_minute'].values and \
            r['epoch_minute'] - month in df['epoch_minute'].values:
        # do stuff

使用这种语法:

valid_rows = df.loc[(df['epoch_minute'] == df['epoch_minute'] - day) &
                    (df['epoch_minute'] == df['epoch_minute'] - week) &
                    (df['epoch_minute'] == df['epoch_minute'] - month]

我理解为什么loc选择不起作用,但我只是问是否存在一种更优雅的方法来选择有效行而不遍历数据框的行。

4

1 回答 1

1

添加括号和用于&检查成员资格:bitwise ANDisin

valid_rows = df[(df['epoch_minute'].isin(df['epoch_minute'] - day)) &
                (df['epoch_minute'].isin(df['epoch_minute'] - week)) &
                (df['epoch_minute'].isin(df['epoch_minute'] - month))]

valid_rows = df[((df['epoch_minute'] - day).isin(df['epoch_minute'])) &
                ((df['epoch_minute']- week).isin(df['epoch_minute'] )) &
                ((df['epoch_minute'] - month).isin(df['epoch_minute']))]
于 2018-09-28T06:49:00.157 回答