Search code examples
pythonpandasdataframedata-analysis

Adding a new column to DataFrame with different values in different row


I have a DataFrame df which has 50 columns in it and it has 28800 rows. I want to add a new column col_new which will have value 0 in every rows from 2880 to 5760 ,12960 to 15840 and 23040 to 25920. And all other rows will have value 1.

How could I do that?


Solution

  • Believe what you are looking for is actually answered here: Add column in dataframe from list

    myList = [1,2,3,4,5]
    print(len(df)) # 50
    df['new_col'] = mylist
    print(len(df)) # 51
    

    Alternatively, you could set the value of a slice of the list like so:

    data['new_col'] = 1
    data.loc[2880:5760, 'new_col'] = 0
    data.loc[12960:15840, 'new_col'] = 0
    data.loc[23040:25920, 'new_col'] = 0