简体   繁体   English

python数据框填充

[英]python dataframe fill up

     1   
0   an     
1   df     
2   0       
3   sdg    
4   gd     
5   dg     
6   0       
7   dc     
8   0      
9   dcd    
10  ds      
11  1    
12  sdg  
13  ds   
14  1    
15  sd   
16  sg   
17  2    
18  dsg  
19  sdg  
20  dfg  
21  2    

I want to ask how to use the above dataframe to generate the following dataframe, according to the first column to generate second column. 我想问一下如何根据上面的数据框生成下面的数据框,根据第一列生成第二列。 (just like fill up in excel, but many times) (就像填写Excel一样,但是很多次)

     1   2
0   an   0  
1   df   0  
2   0    0   
3   sdg  0  
4   gd   0  
5   dg   0  
6   0    0   
7   dc   0  
8   0    0  
9   dcd  1  
10  ds   1   
11  1    1
12  sdg  1
13  ds   1
14  1    1
15  sd   2
16  sg   2
17  2    2
18  dsg  2
19  sdg  2
20  dfg  2
21  2    2 

Here's just some example, the maximum number in the second column is 520, and the number in the second column is consecutive and in order. 这只是一些示例,第二列中的最大数量为520,第二列中的最大数量是连续且有序的。

Assuming your break points are the numbers and you want to fill the values for the strings: 假设您的断点是数字,并且您想填充字符串的值:

df[2] = pd.to_numeric(df[1], errors='coerce').bfill().astype('int')

df
Out: 
      1  2
0    an  0
1    df  0
2     0  0
3   sdg  0
4    gd  0
5    dg  0
6     0  0
7    dc  0
8     0  0
9   dcd  1
10   ds  1
11    1  1
12  sdg  1
13   ds  1
14    1  1
15   sd  2
16   sg  2
17    2  2
18  dsg  2
19  sdg  2
20  dfg  2
21    2  2

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

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