简体   繁体   English

用 Python 中上一行的内容覆盖 csv 文件中一行的内容

[英]Overwrite contents of a row in a csv file with contents from the row above in Python

I have a csv file that contains a timestamp and data for each stamp.我有一个 csv 文件,其中包含每个邮票的时间戳和数据。 It basically looks like this:它基本上看起来像这样:

Timestamp,Column_1,Column_2,Column_3,Column_4,Column_5
2021-04-13 11:03:13+02:00,3,3,3,12,12
2021-04-13 11:03:14+02:00,999,999,999,999,999
2021-04-13 11:03:15+02:00,999,999,999,999,999
2021-04-13 11:03:17+02:00,3,48,3,3,3
2021-04-13 11:03:18+02:00,999,999,999,999,999

So now I want to run through the file and check if one of the values is "999" (since that is only a placeholder).所以现在我想遍历文件并检查其中一个值是否为“999”(因为这只是一个占位符)。 If that is the case, I want the contents of the row above to overwrite the "999"'s.如果是这种情况,我希望上面行的内容覆盖“999”。 That should go through until it reaches a row where the contens aren't "999", since in that case it should save those values for the next time it finds a "999" row, to overwrite it with.这应该 go 直到它到达内容不是“999”的行,因为在这种情况下,它应该保存这些值以供下次找到“999”行时覆盖它。

I already tried with the standard csv library but I just can't get anything to work.我已经尝试过使用标准的 csv 库,但我什么也做不了。

Any help would be very much appreciated!任何帮助将不胜感激!

Read the file in pandas读取 pandas 中的文件

df = pd.read_csv(<file_name>)

Then replace all entries having value as 999 with np.NaN然后用 np.NaN 替换所有值为 999 的条目

df = df.replace(999, np.NaN)

And then do the fillna with 'ffill'然后用'ffill'做fillna

df = df.fillna(method='ffill')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM