python/pandas: convert month int to month name
You can do this efficiently with combining calendar.month_abbr
and df[col].apply()
import calendar
df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])
Convert month name into number and join it with year in python dataframe
You can use pd.to_datetime
and concat like this
df['month_year'] = pd.to_datetime(df.Month, format='%B').dt.month.astype(str) +"_"+ df.Year
df['month_year']
#output
0 1_2019
1 2_2021
2 3_2021
Name: month_year, dtype: object
Update from comment:
Not sure why you get float, but you can try to convert it explicitly to int by adding astype(int) before string
pd.to_datetime(df.Month , format='%B').dt.month.astype(int).astype(str) +"_"+ df.Year
Convert month number to name in python pandas df
You can use pd.Series.dt.strftime
.
Python's strftime directives is a useful resource for constructing datetime
string formats.
import pandas as pd
from io import StringIO
mystr = StringIO("""Date
01-01-2018
02-02-2018
03-04-2018""")
# if necessary, read data and convert to datetime
df = pd.read_csv(mystr)
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
# apply string formatting
df['Date'] = df['Date'].dt.strftime('%d-%b-%Y')
print(df)
Date
0 01-Jan-2018
1 02-Feb-2018
2 03-Apr-2018
Extract month name from date column pandas
Check this
https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month_name.html
df['month'] = pd.DatetimeIndex(df['Date']).month_name()
How to convert month number to month name in an array
If I understand your problem correctly, you are getting an error stating: "list indices must be integers or slices, not list".
To circumvent this issue, try:
import calendar
X=[1,2,3]
def int_to_month(x):
return calendar.month_name[x]
Y = [int_to_month(x) for x in X[:]]
This way you can return the month_name
for each element in your X
list.
The above script should return: ['January', 'February', 'March']
EDIT:
If X is a pandas Series, you may convert it to a list using the to_list
method:
import calendar
import pandas as pd
mycolumn1=[1, 2, 3]
mycolumn2=["foo", "bar", "foo"]
mydata = {"col1":mycolumn1, "col2":mycolumn2}
df=pd.DataFrame(data=mydata)
X = df['col1'].to_list()
def int_to_month(x):
return calendar.month_name[x]
Y = [int_to_month(x) for x in X[:]]
month name to month number and vice versa in python
Create a reverse dictionary using the calendar
module (which, like any module, you will need to import):
{month: index for index, month in enumerate(calendar.month_abbr) if month}
In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do
dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)
Related Topics
Python Replace Empty Strings in a List With Values from a Different List
Colon (:) in Python List Index
Python) I Wanna Add Two Lists Which Are Different Order of Len
Exception Has Occurred: Filenotfounderror [Errno 2] No Such File or Directory: 'Data.Json'
Better Way to Extract Only 2Nd Column of a Txt File in Python
Is There a Proper Variable to Track How Many Times a Loop Has Looped
Pandas Fill in Missing Date Within Each Group With Information in the Previous Row
Increment Values in a List of Lists Starting from 1
Get the Mean Across Multiple Pandas Dataframes
Ioerror: [Errno 32] Broken Pipe When Piping: 'Prog.Py | Othercmd'
How to Wait Until I Receive Data Using a Python Socket
Pick Dictionary Keys:Values Randomly
Run a Python Script from Another Python Script, Passing in Arguments
Exclude First Row When Importing Data from Excel into Python
Check to See If Python Script Is Running
How Can Draw a Line Using the X and Y Coordinates of Two Points