skip to Main Content

I have a requirment where i need to pass different dataframes and print the rows in dataframes to the csv file and the name of the file needs to be the dataframe name. Example Below is the data frame

 **Dataframe**

  | Students | Mark | Grade |
  | -------- | -----|------ |
  | A        | 90   | a     |
  | B        | 60   | d     |
  | C        | 40   | b     |
  | D        | 45   | b     |
  | E        | 66   | d     |
  | F        | 80   | b     |
  | G        | 70   | c     |   

A_Grade=df.loc[df['grade']=='a']

B_Grade=df.loc[df['grade']=='b']

C_Grade=df.loc[df['grade']=='c']

D_Grade=df.loc[df['grade']=='d']

E_Grade=df.loc[df['grade']=='e']

F_Grade=df.loc[df['grade']=='f']

each of these dataframes A_Grade,B_Grade,C_Grade etc needs to be created in separate file with name A_Grade.csv,B_Grade.csv,C_Grade.csv.
i wanted to use a for loop and pass the dataframe so to create it rather than writing separate lines to create the files as number of dataframe varies . This also sends msg using telegram bot.so the code snippet i tried is below. but it didnt work. in short the main thing is dynamically create the csv file with the dataframe name.

 for df in (A_Grade,B_Grade,C_Grade):
  if(len(df))
    dataframeitems.to_csv(f'C:Documents'+{df}+'{dt.date.today()}.csv',index=False)
    bot.send_message(chat_id=group_id,text='##{dfname.name} ##')

The solution given @Ynjxsjmh by work. Thanks @Ynjxsjmh. but i have another senario where in a function as below has dataframe passed as argument and the result on the dataframe needs to be saved as csv with dataframe name.

def func(dataframe):
  ...
  ...
  ...
  dataframe2=some actions and operations on dataframe
  result = dataframe2

result.to_csv(params.datafilepath+f'ResultFolder{dataframe}_{dt.date.today()}.csv',index=False)

The file needs to be saved as per the name of the dataframe.csv

2

Answers


  1. Chosen as BEST ANSWER

    I could get using below code

    def get_df_name(df):
       name =[x for x in globals() if globals()[x] is df][0]
       return name
    
    filename=get_df_name(dataframe)
    print(filename)
    

  2. Your f-string is weird, you can use Series.unique() to get unique values in Series.

    for grade in df['Grade'].unique():
        grade_df = df[df['Grade'].eq(grade)]
        grade_df.to_csv(f'C:Documents{grade.upper()}_Grade_{dt.date.today()}.csv', index=False)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search