Skip to content

Instantly share code, notes, and snippets.

@thoroc
Created January 12, 2022 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoroc/2753e44526123e109de216469e29ccc0 to your computer and use it in GitHub Desktop.
Save thoroc/2753e44526123e109de216469e29ccc0 to your computer and use it in GitHub Desktop.
add weekday names to a csv file
import pandas as pd
df = pd.read_csv('message.csv', dtype=str)
# rename columns to lower case and replace spaces with underscores
columns = {col: col.lower().replace(' ', '_').replace('/','_') for col in list(df.columns)}
df.rename(columns, axis=1, inplace=True)
for col in list(df.columns):
# Ensuring that the column is always a string without spaces before or after
df[col] = df[col].astype(str).str.strip()
# in case this look like str formatted date (eg 02/12/2020)
if df[col].str.match("\d{2}/\d{2}/\d{4}", case=True).all():
# # convert to date
df[col] = pd.to_datetime(df[col], format="%d/%m/%Y")
# finding the index for the current column
index = list(df.columns).index(col)
# add new column as weekday name after the current column
df.insert(loc=index+1, column=f"{col}_weekday", value=df[col].dt.day_name())
# Save the file
df.to_csv('message_cleaned.csv', index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment