'how to write a value in a column under condition?

I've to write different values in a specific column under a condition. Here a visual example of the problem:

In the column D, I have to add a value XX if the time range is between 10:00 and 10:30

I've tried in this way

def function (df, name=['column'], name_app1=['column1']): 
    for row in df[name]:
        if [(df[name].dt.hour >= 10) & (df[name].dt.hour <= 11)]:
          df[name_app1].append('0.400') 

but I obtain always an error TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid



Solution 1:[1]

df[name_app1].append('0.400') 

In this line you are trying to write single value to complete column. This is the error.

Use this

def function (df, name=['column'], name_app1=['column1']): 
    for i,row in df.iterrows():
        if [(df.loc[i,name].dt.hour >= 00) & (df.loc[i,name].dt.hour <= 3)]:
          df.loc[i, name_app1] = '0.400'

Let me know if you need further help

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akash garg