Add column to existing panas dataframe with values as ‘Top’ and ‘Bottom’

Tags: , ,

I want to create a column in the existing dataframe with values as ‘Top’ and Bottom’, catch is, size of the dataframe changes according to calculations.

For example:

if dataframe has 4 rows then:
Top    - Row1
Bottom - Row2
Top    - Row3
Bottom - Row4

I will always have even number of rows.

Please suggest a solution, thanks!


I don’t know exactly how your data is, but you can try something like this:

Hypothetical data:

data = {'A':['12345','12345','67890','12345', '', '12345']}
df = pd.DataFrame(data)

Creating the new column

df['B']= ['Top' if i%2==0 else 'Bottom' for i,_ in df.iterrows() ]

      A     B
0   12345   Top
1   12345   Bottom
2   67890   Top
3   12345   Bottom
4   12345   Top

Source: stackoverflow