![]() |
Adding a new column to a dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Adding a new column to a dataframe (/thread-32006.html) |
Adding a new column to a dataframe - lokhtar - Jan-14-2021 Hello, I am working with covid-19 data, and I am trying to add a new column to the dataframe based on the datetime, converting it to a day of the week. import pandas as pd url='https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv' data = pd.read_csv(url) data.head()The output of that looks like this: What I want to do, is to add a column called 'dow' that converts the date into the actual day of week.So I tried this: data['DOW'] = datetime.date(data['date']).strftime('%A')But that is giving me this error: I would appreciate any help!
RE: Adding a new column to a dataframe - buran - Jan-14-2021 import pandas as pd url='https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv' data = pd.read_csv(url, parse_dates=['date']) data['DOW'] = data['date'].apply(lambda x: x.strftime('%A')) # if you don't want to convert date columne: # data = pd.read_csv(url) # data['DOW'] = pd.to_datetime(data['date']).apply(lambda x: x.strftime('%A')) print(data.head()) In the example I convert date column to datetime object when I read the csv file. In the comments - example if you do not want to convert it
RE: Adding a new column to a dataframe - buran - Jan-14-2021 Also data['DOW'] = data['date'].dt.strftime('%A')or data['DOW'] = data['date'].dt.day_name()where date columns is already converted to datetime
|