Home > Enterprise >  Adding a new column to DataFrame with different values in different row
Adding a new column to DataFrame with different values in different row

Time:11-28

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?

CodePudding user response:

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

CodePudding user response:

df = pd.DataFrame([i for i in range(28800)])
df["new_col"] = 1
zeros_bool = [(
    (i>=(2880-1) and i<5760) or (i>=(12960-1) and i<15840) or (i>=(23040-1) and i<25920)
) for i in range(28800)]
df.loc[zeros_bool,"new_col"] = 0
  • Related