Issue
In the following code, I can store only up to two user inputs in the dictionary and concatenate them to a single dataframe. And if the same function is called again with different input, it overwrites the data entered before. How can I add multiple user input data to a single dataframe whenever the loop is running? class CreateMarklist:
def __init__(self):
self.student_name=None
self.student_marks=None
self.df_1 = None
self.df_2 = None
self.df_3 = None
self.dict_1=None
def student_record(self):
n=int(input("Enter number of students"))
for i in rage(n):
self.student_name=input("Enter student name")
self.student_marks=int(input("Enter marks")
self.df_1=pd.Dataframe([dict_1])
self.dict_1= {
"Student Name" :self.student_name,
"Marks" : self.student_marks}
self.df_2=pd.Dataframe([self.dict_1]),index=[1])
self.df_3=pd.concat([self.df_1,self.df_2])
print(self.df_3)
obj=CreateMarklist()
obj.student_record()
Solution
Finally I found the answer guys,
import pandas as pd
class CreateMarklist:
def __init__(self):
self.student_name = None
self.student_marks = None
self.df_1 = None
self.df_2 = None
self.df_3 = None
self.dict_1 = None
def student_record(self):
n = int(input("Enter number of students"))
for i in range(n):
self.student_name = input("Enter student name")
self.student_marks = int(input("Enter marks"))
self.dict_1= {
"Student Name" :self.student_name,
"Marks" : self.student_marks
}
self.df_1 = pd.DataFrame([self.dict_1])
self.df_2 = pd.read_excel("excel_name.xlsx", sheet_name='Sheet1')
self.df_2 = pd.concat([self.df_2, self.df_1], ignore_index=True)
self.df_2.to_excel("excel_name.xlsx", sheet_name='Sheet1', index=False)
self.df_3 = pd.read_excel("excel_name.xlsx", sheet_name='Sheet1')
print(self.df_3)
obj = CreateMarklist()
obj.student_record()
This will append data whenever the loop is called, and when you run the script again, your data will get appended to excel having data from previous runs.
Answered By - Thinesh Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.