带有连续索引的Pandas DataFrame

3

I have the following code:

import pandas as pd
df = pd.DataFrame(
    {'Index' : ['1', '2', '5','7', '8', '9', '10'],
     'Vals' : [1, 2, 3, 4, np.nan, np.nan, 5]})

这给了我:
  Index  Vals
0     1   1.0
1     2   2.0
2     5   3.0
3     7   4.0
4     8   NaN
5     9   NaN
6    10   5.0

但是我想要的是像这样的东西:
  Index      Vals
0     1  1.000000
1     2  2.000000
2     3  NaN
3     4  NaN
4     5  3.000000
5     6  NaN
6     7  4.000000
7     8  NaN
8     9  NaN
9    10  5.000000

我尝试通过创建一个连续索引的新数据框来实现这一点。然后,我想分配已经拥有的值,但是如何做呢?到目前为止,我唯一拥有的就是:

clean_data = pd.DataFrame({'Index' : range(1,11)})

给我带来了:
   Index
0      1
1      2
2      3
3      4
4      5
5      6
6      7
7      8
8      9
9     10
2个回答

3
所以按照你的例子,它会像这样:
import pandas as pd
import numpy as np 

df = pd.DataFrame(
    {'Index' : ['1', '2', '5','7', '8', '9', '10'],
     'Vals' : [1, 2, 3, 4, np.nan, np.nan, 5]})
df['Index'] = df['Index'].astype(int)
clean_data = pd.DataFrame({'Index' : range(1,11)})
result = clean_data.merge(df,on="Index",how='outer')

结果是:

  Index Vals
0   1   1.0
1   2   2.0
2   3   NaN
3   4   NaN
4   5   3.0
5   6   NaN
6   7   4.0
7   8   NaN
8   9   NaN
9   10  5.0

非常感谢!这是一个非常好的解决方案,我学到了新东西 :-) - Ohumeronen

1
您可以将 Index 列放在索引中(在转换为整数后),选择行 110(这将创建适当的 NaN),然后重置索引。
import numpy as np
import pandas as pd

df = pd.DataFrame(
    {'Index' : ['1', '2', '5','7', '8', '9', '10'],
     'Vals' : [1, 2, 3, 4, np.nan, np.nan, 5]})
df['Index'] = df['Index'].astype(int)

df = df.set_index('Index').loc[range(1, 11)].reset_index()

输出:

   Index  Vals
0      1   1.0
1      2   2.0
2      3   NaN
3      4   NaN
4      5   3.0
5      6   NaN
6      7   4.0
7      8   NaN
8      9   NaN
9     10   5.0

太棒了,这甚至更好,非常简洁!谢谢你分享这个,祝你有愉快的一天! - Ohumeronen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接