How to fill a DataFrame till specific row?

Viewed 481

I have a data frame like the one below and I want to add a new column to it. So that this column has a value up to a certain row and another value for the rest. How can I do this?

    f1       f2       f3  ...     f10000
0  0.037026  0.037026  0.037026  ...  0.000000
1  0.000000  0.000000  0.000000  ...  0.000000
2  0.000000  0.000000  0.000000  ...  0.004047
...

I know I can add columns using the following command, but I do not know how to specify that the value change after a specific row (for example row 1).

df['new_col'] = '1'

What I get:

    f1       f2       f3  ...     f10000       new_col
0  0.037026  0.037026  0.037026  ...  0.000000  1
1  0.000000  0.000000  0.000000  ...  0.000000  1
2  0.000000  0.000000  0.000000  ...  0.004047  1
...

What I want:

    f1       f2       f3  ...     f10000       new_col
0  0.037026  0.037026  0.037026  ...  0.000000  1
1  0.000000  0.000000  0.000000  ...  0.000000  0
2  0.000000  0.000000  0.000000  ...  0.004047  0
...
2 Answers

You can use index for compare values, here is set 1 if index is less like 1 else 0 in numpy.where:

N = 0
df['new_col'] = np.where(df.index <= N, 1, 0)

Or:

df['new_col'] = (df.index <= N).astype(int)

Another idea is compare array created by length of DataFrame:

arr = np.arange(len(df))
df['new_col'] = np.where(arr <= 0, 1, 0)

Or:

df['new_col'] = (arr <= N).astype(int)

You might assign list rather than single value which is then broadcast. Length of said list must be equal to number of records in your DataFrame, consider following example:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df['new_col'] = [1]+[0]*2
print(df)

Output

   A  B  new_col
0  1  4        1
1  2  5        0
2  3  6        0

Explanation: I harnessed python's ability to multiply list by positive integer to get desired number of repetition of list then contatenated [1] with such created list (this give same effect as doing df['new_col'] = [1,0,0])

Related