简体   繁体   English

Pandas Reindex-用缺失值填充列

[英]Pandas Reindex - Fill Column with Missing Values

I tried several examples of this topic but with no results. 我尝试了几个有关此主题的示例,但没有结果。 I'm reading a DataFrame like: 我正在读取一个DataFrame像:

Code,Counts
10006,5
10011,2
10012,26
10013,20
10014,17
10015,2
10018,2
10019,3

How can I get another DataFrame like: 我如何获得另一个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

Basically filling the missing values of the 'Code' Column? 基本上是填写“代码”列的缺失值? I tried the df.reindex() method but I can't figure out how it works. 我尝试了df.reindex()方法,但无法弄清楚它是如何工作的。 Thanks a lot. 非常感谢。

I'd set the index to you 'Code' column, then 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 this assumes that your 'Code' values are already sorted: 我想设置索引为您“代码”栏,然后reindex通过传递根据您目前的指数新阵列, arange接受一个启动和停止参数(需要1添加到末尾),然后reset_index这个假设您的“代码”值已经排序:

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

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

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