我有一些数据框,月平均值如下:
Month,Value1,Value2
02,1,1
03,2,2
04,3,3
06,4,4
07,5,5
08,6,6
09,7,7
10,8,8
12,9,9
我的问题是那些数据框丢失了几个月,在随附的示例中,第 1、5 和 11 个月丢失了。
因此我想重新索引数据框并用 NaN 填充缺失值,如下所示:
Month,Value1,Value2
01,NaN,NaN
02,1,1
03,2,2
04,3,3
05,NaN,NaN
06,4,4
07,5,5
08,6,6
09,7,7
10,8,8
11,NaN,NaN
12,9,9
我做了这个小代码:
data = pd.read_csv("test.csv", index_col=[0])
new_index = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
data = data.reindex(new_index)
不幸的是,输出与期望值相去甚远,所有值现在都被 NaN 替换:
Month,Value1,Value2
01,NaN,NaN
02,NaN,NaN
03,NaN,NaN
04,NaN,NaN
05,NaN,NaN
06,NaN,NaN
07,NaN,NaN
08,NaN,NaN
09,NaN,NaN
10,NaN,NaN
11,NaN,NaN
12,NaN,NaN
有人知道为什么吗?以及如何解决?
请您参考如下方法:
当你读取csv时,索引是int64类型,你可以通过以下方式检查:
data = pd.read_csv("test3.csv", index_col=[0])
print(data.index.dtype)
结果:
int64
现在,当使用 reindex 时,如下所示:
new_index = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
data = data.reindex(new_index)
在上面,如果 new_index 都是 str 类型,它与现有索引不匹配,将产生新对象: 根据documentation :
Docstring:
Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False
因此,您可能想尝试使用类型为 int 而不是 str 的新索引:
new_index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
data = data.reindex(new_index)
