Created
January 12, 2022 12:43
-
-
Save thoroc/2753e44526123e109de216469e29ccc0 to your computer and use it in GitHub Desktop.
add weekday names to a csv file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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