Pandas 重建索引 - 用缺失值填充列
Pandas Reindex - Fill Column with Missing Values
我尝试了这个主题的几个例子,但没有结果。我正在读取一个 DataFrame,例如:
Code,Counts
10006,5
10011,2
10012,26
10013,20
10014,17
10015,2
10018,2
10019,3
如何获得另一个 DataFrame,例如:
Code,Counts
10006,5
10007,NaN
10008,NaN
...
10011,2
10012,26
10013,20
10014,17
10015,2
10016,NaN
10017,NaN
10018,2
10019,3
基本上填补了'Code'列的缺失值?我尝试了 df.reindex()
方法,但我不知道它是如何工作的。非常感谢。
我将索引设置为您的 'Code' 列,然后 reindex
by passing in a new array based on your current index, arange
accepts a start and stop param (you need to add 1 to the end) and then reset_index
这假设您的 'Code' 值已经排序:
In [21]:
df.set_index('Code', inplace=True)
df = df.reindex(index = np.arange(df.index[0], df.index[-1] + 1)).reset_index()
df
Out[21]:
Code Counts
0 10006 5
1 10007 NaN
2 10008 NaN
3 10009 NaN
4 10010 NaN
5 10011 2
6 10012 26
7 10013 20
8 10014 17
9 10015 2
10 10016 NaN
11 10017 NaN
12 10018 2
13 10019 3
我尝试了这个主题的几个例子,但没有结果。我正在读取一个 DataFrame,例如:
Code,Counts
10006,5
10011,2
10012,26
10013,20
10014,17
10015,2
10018,2
10019,3
如何获得另一个 DataFrame,例如:
Code,Counts
10006,5
10007,NaN
10008,NaN
...
10011,2
10012,26
10013,20
10014,17
10015,2
10016,NaN
10017,NaN
10018,2
10019,3
基本上填补了'Code'列的缺失值?我尝试了 df.reindex()
方法,但我不知道它是如何工作的。非常感谢。
我将索引设置为您的 'Code' 列,然后 reindex
by passing in a new array based on your current index, arange
accepts a start and stop param (you need to add 1 to the end) and then reset_index
这假设您的 'Code' 值已经排序:
In [21]:
df.set_index('Code', inplace=True)
df = df.reindex(index = np.arange(df.index[0], df.index[-1] + 1)).reset_index()
df
Out[21]:
Code Counts
0 10006 5
1 10007 NaN
2 10008 NaN
3 10009 NaN
4 10010 NaN
5 10011 2
6 10012 26
7 10013 20
8 10014 17
9 10015 2
10 10016 NaN
11 10017 NaN
12 10018 2
13 10019 3