我有一个数据像素,total_time,我想:
。
pixel total_time total_time_one
1 218.835 218.835 #projected times of pixel 1 onto all valyues
1 218.835 218.835
1 218.835 218.835
2 219.878 218.835
2 219.878 218.835
2 219.878 218.835
3 220.911 218.835
3 220.911 218.835
3 220.911 218.835
1 230.189 230.189 #value changes cause pixel 1 shows up again
1 230.189 230.189
1 230.189 230.189
2 231.441 230.189
2 231.441 230.189
2 231.441 230.189以上资料如下:
uniqueone = df.query("pixel==1").total_time.unique()
mask = df["total_time"].isin(uniqueone)
df["total_time_one"] = (df[mask]["total_time"])#putting it here isn't working: .fillna(method='ffill')
df["total_time_one"] = df["total_time_one"].fillna(method='ffill')然而,代码很长,并且重复自己,是否有更适合自己的函数?还是更好的解决方案?
我也不知道为什么我说:
df["total_time_one"] = (df[mask]["total_time"].fillna(method='ffill')它不起作用了,我得多加一句:
df["total_time_one"] = df["total_time_one"].fillna(method='ffill')使它发挥作用
发布于 2021-03-07 22:39:20
使用where对不是'pixel'==1的值进行NaN,然后使用ffill。从技术上讲,这将填充每个组的最后一个值,但您的值在每个像素组中都是静态的。
df['total_time_one'] = df['total_time'].where(df.pixel.eq(1)).ffill() pixel total_time total_time_one
0 1 218.835 218.835
1 1 218.835 218.835
2 1 218.835 218.835
3 2 219.878 218.835
4 2 219.878 218.835
5 2 219.878 218.835
6 3 220.911 218.835
7 3 220.911 218.835
8 3 220.911 218.835
9 1 230.189 230.189
10 1 230.189 230.189
11 1 230.189 230.189
12 2 231.441 230.189
13 2 231.441 230.189
14 2 231.441 230.189如果您希望在每个组中使用first值(与最后一个组相反),或者说取平均值,然后使用ffill,则可以使用groupby + transform。使用1比较的累积和标记连续组的!=。
df['total_time_one'] = (df['total_time'].where(df.pixel.eq(1))
.groupby(df.pixel.ne(1).cumsum())
.transform('first')
.ffill())https://stackoverflow.com/questions/66522183
复制相似问题