How to write the value in a column for specific rows?

I have a excel file, i need to write the specific value in a set of specific row: For Ex: i have 20 rows and 5 columns i need to add new column, and write the new column value(as x in first 5 rows, next 5 values (y) in next 5 rows and so on). may i know how to achieve it?

col1    col2    col3   col4     
1       a1      b1     c1       
2       a2      *   *   
3   a3  *   *   
4   a4  *   *       
5   a5  *   *       
6   a6  *   *       
7   a7  *   *       
8   a8  *   *       
9   a9  *   *
10  a10 *   *
11  a11 *   *
12  a12 *   *
13  a13 *   *
14  a14 *   *
15  a15 *   *
16  a16 *   c16
17  a17 *   c17
18  a18 *   c18
19  a19 *   c19

I need output like this:

col1    col2    col3   col4    colnew
1       a1      b1     c1   aa
2       a2      *   *   aa  
3   a3  *   *   aa
4   a4  *   *   aa  
5   a5  *   *   aa  
6   a6  *   *   bb  
7   a7  *   *   bb  
8   a8  *   *   bb  
9   a9  *   *   bb
10  a10 *   *   bb
11  a11 *   *   cc
12  a12 *   *   cc
13  a13 *   *   cc
14  a14 *   *   cc
15  a15 *   *   cc
16  a16 *   c16 dd
17  a17 *   c17 dd
18  a18 *   c18 dd
19  a19 *   c19 dd

Upvotes: 0

Views: 209

Answers (1)

jezrael
jezrael

Reputation: 862681

Use floor division by 5 first and then map by dictionary - if some value is missing in dict get NaNs in output column:

vals = ['aa','bb','cc','dd','ee']
d = dict(enumerate(vals))
print (d)
{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd', 4: 'ee'}

#default range index 
df['new'] = (df.index // 5).map(d.get)
#general solution
#df['new'] = pd.Series(np.arange(len(df)) // 5, index=df.index).map(d)
print (df)
    col1 col2 col3 col4 new
0      1   a1   b1   c1  aa
1      2   a2    *    *  aa
2      3   a3    *    *  aa
3      4   a4    *    *  aa
4      5   a5    *    *  aa
5      6   a6    *    *  bb
6      7   a7    *    *  bb
7      8   a8    *    *  bb
8      9   a9    *    *  bb
9     10  a10    *    *  bb
10    11  a11    *    *  cc
11    12  a12    *    *  cc
12    13  a13    *    *  cc
13    14  a14    *    *  cc
14    15  a15    *    *  cc
15    16  a16    *  c16  dd
16    17  a17    *  c17  dd
17    18  a18    *  c18  dd
18    19  a19    *  c19  dd

Upvotes: 1

Related Questions