Kiran
Kiran

Reputation: 45

Is there a way to reduce this repetitive code?

def frame(dt_type, start_year, end_year, columns_req):
  frame = pd.DataFrame()
  for i in range (start_year, end_year):
    file_name = f"{dt_type} {i}"
    dataframe = pd.read_csv(BytesIO(uploaded["%s.csv"%file_name]))
    if len(columns_req) == 1:
      df = pd.DataFrame(data, columns= [columns_req[0])
    if len(columns_req) == 2:
      df = pd.DataFrame(data, columns= [columns_req[0], columns_req[1]])
    if len(columns_req) == 3:
      df = pd.DataFrame(data, columns= [columns_req[0], columns_req[1], columns_req[2])
    if len(columns_req) == 4:
      df = pd.DataFrame(data, columns= [columns_req[0], columns_req[1], columns_req[2], columns_req[3]])
    frame = frame.append(dataframe, ignore_index=True)
  return (frame)

As you can see, the if loop is repetitive and feels odd. I am new to programming. Is there anyway to reduce that whole bunch of code?

Upvotes: 0

Views: 48

Answers (1)

Der Keeper
Der Keeper

Reputation: 168

you could do this

df = pd.DataFrame(data, columns = colums_req)

instead of all those if - conditions

Upvotes: 2

Related Questions