Python Forum
Newbie question to add columns in dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie question to add columns in dataframe
#1
Hello:
I have a CSV file (C:\Temp\NameList.CSV), it has exactly 20,000 records, like this:
First Name, Last Name (Field names)
John, Doe
......
Xyz, Fini

I want to read the CSV and convert it to dataframe, containing all 20000 records.
But I also want to add 2 columns to the dataframe.
One column, I want to add the 'index' to the records, for example, the first record in the CSV, get 1,
the second record in the CSV, get 2; ... until the last one record in the CSV, get 20000.
Another column, I want to add a 'Record Date', which is the date of today, and all 20000 records will get the same record.
Please advise how to code this in Python.
Thanks,
Reply
#2
You can do it like this:

import csv
from datetime import datetime


data_frame = []
row_index = 1
record_date = datetime.now().strftime("%Y-%m-%d")

with open("./name_list.csv") as csv_file:
    name_list_reader = csv.reader(csv_file, delimiter=",")
    for row in name_list_reader:
        data_frame.append({
            "index": row_index,
            "first_name": row[0].strip(),
            "last_name": row[1].strip(),
            "record_date": record_date
        })
        row_index += 1

print(str(data_frame))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 690 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 674 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Newbie question about switching between files - Python/Pycharm Busby222 3 589 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  Question on pandas.dataframe merging two colums shomikc 4 814 Jun-29-2023, 11:30 AM
Last Post: snippsat
  Newbie.... run for cover. OpenCV question Stevolution2023 2 959 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  numpy newbie question bcwilly_ca 4 1,170 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,364 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,690 Aug-19-2022, 11:07 AM
Last Post: dm222
  Apply fillna to multiple columns in dataframe rraillon 2 2,410 Aug-05-2021, 01:11 PM
Last Post: rraillon
  Question from complete python's newbie Davicom 3 2,355 Jun-09-2021, 06:09 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020