Can not decide. We have:

df1 (he has a second column filled with numbers and sometimes letters in the upper part) df1

it is necessary to get the table in this form, that is, we stretch the numbers across the entire column as an "accordion" along the entire length, forming approximately equal distances between the numbers. It is possible not to reach the "accordion" to the very end, since it will not work out, but make the maximum step so that all values ​​fit.

df2 enter image description here

  • Where there are empty places - do you have an empty string or NaN? - MaxU
  • there stands naN yes, - Alexandr Kosolapov

1 answer 1

Source DataFrame:

import numpy as np import pandas as pd df = pd.DataFrame({'ID':np.arange(1, 21)}) df.loc[:6, 'val'] = [11,10,9,8,7,6,5] 

 In [41]: df Out[41]: ID val 0 1 11.0 1 2 10.0 2 3 9.0 3 4 8.0 4 5 7.0 5 6 6.0 6 7 5.0 7 8 NaN 8 9 NaN 9 10 NaN 10 11 NaN 11 12 NaN 12 13 NaN 13 14 NaN 14 15 NaN 15 16 NaN 16 17 NaN 17 18 NaN 18 19 NaN 19 20 NaN 

decision:

 def stretch(s, step): # create a series of NaN's ret = pd.Series([np.nan] * len(s), s.index) # extract not-NaN values vals = s.loc[:s.isnull().idxmax()-1].values # stretch not-NaN values over the series ret.iloc[::step] = vals return ret df['val'] = stretch(df['val']) 

result:

 In [45]: df Out[45]: ID val 0 1 11.0 1 2 NaN 2 3 NaN 3 4 10.0 4 5 NaN 5 6 NaN 6 7 9.0 7 8 NaN 8 9 NaN 9 10 8.0 10 11 NaN 11 12 NaN 12 13 7.0 13 14 NaN 14 15 NaN 15 16 6.0 16 17 NaN 17 18 NaN 18 19 5.0 19 20 NaN 
  • one
    Maxim, you did a very useful job for my work. Thank you very much! - Alexandr Kosolapov