[英]Compare master and child dataframe and extract new rows base on two column values only
[英]"Reindex" only fills the first two rows with new values
我是 stackoverflow 的新手。 我希望我能清楚地提出我的問題。
我正在使用reindex
來填寫 pandas dataframe 中缺失的日期:
df = pd.read_csv('myfile.dat', skiprows=1)
print(df)
output:
TIME A B C D
0 2022-04-28 00:02:00 0 2 1 5
1 2022-04-28 00:03:00 0 2 2 5
2 2022-04-28 00:05:00 0 2 3 5
3 2022-04-28 00:06:00 0 2 4 5
4 2022-04-28 00:09:00 0 2 5 5
5 2022-04-28 00:10:00 0 2 6 5
6 2022-04-28 00:12:00 0 2 8 5
7 2022-04-28 00:15:00 0 2 10 5
做的:
#Change data type to datetime
date_format = '%Y-%m-%d %H:%M:%S'
df['TIME'] = pd.to_datetime(df['TIME'], format=date_format)
#define index and round it (The math. floor() method rounds a number DOWN to the nearest integer)
idx = pd.date_range(start='2022-04-28 00:00:00', end='2022-04-28 00:15:00', freq='60S').floor('60S')
#Set index on 'TIME' from 'df'
df = df.set_index('TIME')
#Use 'resample()' as a convenience method for frequency conversion and resampling of time series
df = df.resample('60S').sum()
#Reindex and setting new values to 0
df = df.reindex(idx, fill_value=1000)
print(df)
輸出是:
A B C D
2022-04-28 00:00:00 1000 1000 1000 1000
2022-04-28 00:01:00 1000 1000 1000 1000
2022-04-28 00:02:00 0 2 1 5
2022-04-28 00:03:00 0 2 2 5
2022-04-28 00:04:00 0 0 0 0
2022-04-28 00:05:00 0 2 3 5
2022-04-28 00:06:00 0 2 4 5
2022-04-28 00:07:00 0 0 0 0
2022-04-28 00:08:00 0 0 0 0
2022-04-28 00:09:00 0 2 5 5
2022-04-28 00:10:00 0 2 6 5
2022-04-28 00:11:00 0 0 0 0
2022-04-28 00:12:00 0 2 8 5
2022-04-28 00:13:00 0 0 0 0
2022-04-28 00:14:00 0 0 0 0
2022-04-28 00:15:00 0 2 10 5
我的問題是:為什么reindex
創建新日期(它應該如此)但只將前兩行的值設置為 1000 而不是所有新行?
感謝您的幫助!
為什么 reindex 創建新日期(它應該如此)但只將前兩行的值設置為 1000 而不是所有新行?
因為reindex的 fill_value 參數是用於缺失值的值。 默認為 NaN,但可以是任何“兼容”值。
我建議您只刪除 fill_value=1000 並在重新索引后將 1000 分配給所有列。
如果仔細觀察,您會發現,在重新采樣df
之后,索引范圍是從02:00
到15:00
,但您創建的idx
的范圍是從0:00
到15:00
。 重新索引時唯一缺少的值是前兩行,這就是為什么只有這兩行會填充您定義的fill_value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.