简体   繁体   中英

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)

     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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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