I’m trying to write a Python script that allows the user to input the name of a column and then prints the value counts of that column from a pandas DataFrame. Here's what I currently have:
def count_unique_values(df, column_list):
for col in column_list:
if col not in df.columns:
print(f"Column '{col}' not found in the DataFrame.\n")
continue
print(f"\nColumn: {col}")
counts = df[col].value_counts()
print(counts, "\n")
print(col=input("Input column name: ")
You should get col without print() and send this name as list to function (because it expects column_list) and it will print it
col = input("Input column name: ")
count_unique_values(df, [col])
If you want to input many columns then it may need to ask user to put names separated by i.e comma, and split them to create list of names.
It should work even with single column name.
(example input: id,name,age)
col = input("Input column names (separated by comma): ")
list_of_names = col.split(',')
count_unique_values(df, list_of_names)
But it doesn't allow to use spaces ie. id , name , age - it would need to run for-loop (or list comprehension) to remove spaces using strip()
list_of_names = [name.strip() for name in list_of_names]
col = input("Input column names (separated by comma): ")
# split text to list of names
list_of_names = col.split(',')
# remove spaces from names
list_of_names = [name.strip() for name in list_of_names]
count_unique_values(df, list_of_names)