I am quite new to scripting, and here is my first code I wrote. The goal of the code is to extract a parent ID based on a child ID. I would appreciate some constructive criticism and aggressive checkup. The codes works and does what it's supposed to do. But how can I make it more pythonic? more passionate?
import codecs import numpy as np import pandas as pd def import_file(path): '''imports the .csv files as a pandas dataframe Args: path (csv file): Takes in the path for the .csv file Returns: Returns a pandas dataframe ''' with codecs.open(path, "r", encoding='utf-8', errors='ignore') as fdata: df = pd.read_csv(fdata) return df def appends_address_before_name(file): '''Appends the address before the name ID name Returns: Returns the file, with address appened to column name. ''' file['ID'] = [address + str(col) for col in file['ID']] return file def create_parent_name(file, column_name: str): '''This will create a parent name based on the ID column Args: file: takes in the dataFrame created from appends_address_before_name function column_name: Takes in the column name where the parent name will be extracted from.The logic is to split it on the last dot. [[parentname].[+ childname]] Returns: Returns a pandas dataframe with a new column called parentID ''' file['parentID'] = [ x.rsplit('.', 1) if '.' in x else x[:-1] for x in file[column_name] ] return file address = 'New_Jersey_' file_1 = import_file(r'C:\humans.csv') file_2= appends_address_before_name(file=file_1) file_3= create_parent_name(file=file_2 , column_name = 'ID') print(file_3)
The input CSV is a column of values separated with decimal places like the following:
ID 99.99.9 100.42.3
parentID New_Jersey_99.99 New_Jersey_100.42
Furthermore, I feel like the way I am passing variables between the functions at the end of the code seems quite basic and terrible. What can I improve in the above code and how can I improve it ?
A screenshot of the code working