[python]Data processing with Pandas

I used to use the with context and the open function to open and save data into file, however the module Pandas truly amazed me… It has methods like read_csv, read_excel which reads from csv and excel files, and methods like to_csv which export the data to csv file.

from pandas import read_csv
from os import chdir

def get_data_frame(dir, filename, sep=None):
    # default separator is a comma, hence I did not specify separator.
    if sep:
        return read_csv(filename, sep=sep)
        return read_csv(filename)

if __name__ == '__main__':
    df = get_data_frame("D:\\temp", "Comma-Separated.txt")
    # match one or more space(s)
    df2 = get_data_frame("D:\\temp", "Space-Separated.txt", '\s+')

How it looks like
This file separated by comma, which can be exported to csv which looks like below.

This file separated by space, the data is the same as the comma separated, and the csv is the same as above.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s