![](/img/trans.png)
[英]How to get the previous value of the same row (previous column) from the pandas dataframe?
[英]How can I copy the value of a previous row, on the same column in a DataFrame?
我有以下 DataFrame:
日期 | 追踪 | 表面 | 光栅 | 马号 | 沙田最后的FGrating,草 |
---|---|---|---|---|---|
2017-09-03 | 沙田 | 草 | 110 | 1736 | |
2017-09-16 | 沙田 | 草 | 124 | 1736 | 110 |
2017-10-14 | 沙田 | 草 | 118 | 1736 | 124 |
2017-11-11 | 沙田 | 草 | 107 | 1736 | 118 |
2018-03-28 | 欢乐谷 | 草 | 117 | 1736 | |
2018-04-11 | 欢乐谷 | 草 | 114 | 1736 | |
2018-09-22 | 沙田 | 草 | 124 | 1736 | 107 |
如你所见,沙田的最后一次 FGrating,grass有空间。 这些空间有两个原因:
到目前为止,根据这段代码,我只完成了填充部分:
def return_mask_and_text_from_tracks(data, track_no, metric):
if track_no == 0: # Sha Tin - grass
mask = (data.Track == 'Sha Tin') & (data.Surface == 'Grass')
text = str(metric) + ' at Sha-Tin Grass'
if track_no == 1: # Sha Tin - dirt
mask = (data.Track == 'Sha Tin') & (data.Surface == 'Dirt')
text = str(metric) + ' at Sha-Tin Dirt'
if track_no == 2: # Happy Valley - grass
mask = (data.Track == 'Happy Valley') & (data.Surface == 'Grass')
text = str(metric) + ' at Happy Valley Grass'
return mask, text
def compute_last_fgrating(data, mask=''):
if len(mask) == 0:
return data.groupby('HorseId')['FGrating'].apply(lambda x: x.shift(1))
else:
return data.loc[mask][['HorseId', 'FGrating']].groupby('HorseId')['FGrating'].apply(lambda x: x.shift(1))
for i in range(3):
mask, text = return_mask_and_text_from_tracks(featured_data, i, 'Last FGrating')
featured_data[text] = compute_last_fgrating(featured_data, mask=mask)
我正在寻找用以下值填充最右边一列的方法:
决赛桌应如下所示:
日期 | 追踪 | 表面 | 光栅 | 马号 | 沙田最后的FGrating,草 |
---|---|---|---|---|---|
2017-09-03 | 沙田 | 草 | 110 | 1736 | 0(不存在之前的 FGrating) |
2017-09-16 | 沙田 | 草 | 124 | 1736 | 110 |
2017-10-14 | 沙田 | 草 | 118 | 1736 | 124 |
2017-11-11 | 沙田 | 草 | 107 | 1736 | 118 |
2018-03-28 | 欢乐谷 | 草 | 117 | 1736 | 118(此时最后一次在沙田草地上打草) |
2018-04-11 | 欢乐谷 | 草 | 114 | 1736 | 118 |
2018-09-22 | 沙田 | 草 | 124 | 1736 | 107 |
我该怎么做?
在这里你只需要
df["Last FGrating at Sha Tin, grass"] = df["Last FGrating at Sha Tin, grass"].fillna(method="ffill").fillna(0)
第一个fillna
用可用的最新值( method="ffill"
)填充 NaN 然后你在第一行只剩下一个 NaN ,你可以用0
填充它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.