python - 我可以在删除每个组中的第一个和最后一个条目的同时使用 Pandas group by 吗?

标签 python pandas dataframe

我有一个代表我工作旅行的 pandas 数据框。每行是一次旅行,其中有一列是日期和行驶的公里数。

除了每天的第一天和最后一天(这些被视为上下类的普通旅行)之外,我每次旅行都会按公里获得报销。

所以我的数据框看起来像这样:

day, distance
1, 5
1, 2
1, 7
2, 11
2, 11
3, 4
3, 10
3, 5
3, 12

我想在此处添加一个列,用于标记除当天的第一次和最后一次行程之外的所有行程。如:

day, distance, claimable
1, 5, 0
1, 2, 1
1, 7, 0
2, 11, 0
2, 11, 0
3, 4, 0
3, 10, 1
3, 5, 1
3, 12, 0

假设我有一个包含上面列的数据框,有没有办法做这样的事情:

import pandas as pd

df = pd.DataFrame({'day':(1,1,1,2,2,3,3,3,3),
                   'dist':(5,2,7,11,11,4,10,5,12),
                  },)
df['claim'] = 0

# set the value of the "claimable" column to 1 on all 
# but the first and last trip of the day

df.groupby("day").nth(slice(1,-1)).loc[:, "claim"] = 1

最佳答案

您可以进行 transform 并取 firstlast 位置

g  = df.reset_index().groupby('day')['index']
con = (df.index == g.transform('first')) | (df.index == g.transform('last'))
df['new'] = (~con).astype(int)
df
Out[117]: 
   day  dist  new
0    1     5    0
1    1     2    1
2    1     7    0
3    2    11    0
4    2    11    0
5    3     4    0
6    3    10    1
7    3     5    1
8    3    12    0

关于python - 我可以在删除每个组中的第一个和最后一个条目的同时使用 Pandas group by 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71670205/

相关文章:

python - fancyimpute 的 SoftImpute 是否需要归一化数据?

python - 使用 python 静默捕获网络摄像头快照

python - 如果日期在另一个数据帧的日期范围内且项目相等,则在一个数据帧中分配值

python - Pandas:如何在函数内将 sum() 或 mean() 分配给 df.groupby?

python - 在 python 中命名数据集的列

python - Python:将传感器数据转换为连续的调频音频

python - 使用 np.nan 而不导入 numpy

R:为什么我在将列转换为因子后没有得到类型或类 "factor"?

python - 将 NumPy 数组与 pandas DataFrame 连接(加入)

从列表中的所有数据框中删除带有 NA 的列