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?
df = pd.DataFrame([i for i in range(28800)])
df["new_col"] = 0
ones = [i for i in range(2880,5760)]+[i for i in range(12960,15840)]+[i for i in range(23040,25920)]
ones_bool = [i in ones for i in range(len(df))]
df.loc[ones,"new_col"] = 1
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.