我有2个系列,索引不同,但长度相同,均为638。
系列
fc
的输出是
1888 4.899912
1889 4.900162
1890 4.900141
1891 4.900142
1892 4.900142
...
2521 4.900142
2522 4.900142
2523 4.900142
2524 4.900142
2525 4.900142
Name: predicted_mean, Length: 638, dtype: float64
和系列
fc_series
的输出是
Date
2020-12-16 NaN
2020-12-17 NaN
2020-12-18 NaN
2020-12-21 NaN
2020-12-22 NaN
..
2023-06-26 NaN
2023-06-27 NaN
2023-06-28 NaN
2023-06-29 NaN
2023-06-30 NaN
Name: predicted_mean, Length: 638, dtype: float64
我尝试使用此代码行
fc_series = pd.Series(fc, index=test_data.index)
我想要
fc
的值代替 fc_series
中的 NaN 值。我正在努力解决这方面的索引部分,非常感谢您的帮助。
示例
import pandas as pd
data1 = {1888: 4.899912, 1889: 4.900162, 1890: 4.900141, 1891: 4.900142, 1892: 4.900142}
s1 = pd.Series(data1)
data2 = {'2020-12-16': float('nan'), '2020-12-17': float('nan'), '2020-12-18': float('nan'),
'2020-12-21': float('nan'), '2020-12-22': float('nan')}
s2 = pd.Series(data2)
s1
1888 4.899912
1889 4.900162
1890 4.900141
1891 4.900142
1892 4.900142
dtype: float64
s2
2020-12-16 NaN
2020-12-17 NaN
2020-12-18 NaN
2020-12-21 NaN
2020-12-22 NaN
dtype: float64
代码
如果 s2 全部为 NaN,请使用此代码。
s1.set_axis(s2.index)
输出:
2020-12-16 4.899912
2020-12-17 4.900162
2020-12-18 4.900141
2020-12-21 4.900142
2020-12-22 4.900142
dtype: float64
如果 s2 中的某些值是 NaN,并且您只想在它们为 NaN 时才用 s1 中的值填充它们,请使用此代码。
s2.fillna(s1.set_axis(s2.index))
你就快到了。
问题是,从另一个系列创建一个系列并传递索引将执行索引对齐,而这恰恰是您不想要的。
相反,只需传递
fc
的值即可:
out = pd.Series(fc.to_numpy(), index=fc_series.index)
输出:
2020-12-16 4.899912
2020-12-17 4.900162
2020-12-18 4.900141
2020-12-21 4.900142
2020-12-22 4.900142
...
2023-06-26 4.900142
2023-06-27 4.900142
2023-06-28 4.900142
2023-06-29 4.900142
2023-06-30 4.900142
dtype: float64