[python]pandas.series method

I have two lists, and I use pandas.series method to make it into a table.
The table consists of the index column and the data column, the axis is on the top left most of the table which by default is empty, from the axis onwards will be the data column which the name can be change using pandas.DataFrame.Columns.

Here’s an example:

import pandas
from os import chdir

# two sets of data
hostname = ["R1", "R2", "R3"]
ip = ["", "", ""]

# change the working directory.
# the Series method accepts dictionary and iterables i.e. tuple and list.
# the zip function combines the hostname and ip together.
# the dictionary function then converts the zip object into a dictionary which
# looks like:
# "R1": "" and so on.
# The to_frame() method converts the Series object into a dataframe.
# Because dataframme object has to_html method for me to export data as html.
table = pandas.Series(data=dict(zip(hostname, ip))).to_frame()
# this change the column name, which is the column that has the ip address.
# the index column however will still be empty.
table.columns = ["IP ADDRESS"]
# to name the axis.
table = table.rename_axis("HOSTNAME", axis=1)

This will produce this:

If the dictionary is not passed into the Series method, I can pass in as list.
like this pandas.Series(data=ip, index=hostname)

A suggestion i found online recommended using pandas.DataFrame.index.name, but this only changes the index column, the axis still be empty and the presentation is odd. So replace this table = table.rename_axis("HOSTNAME", axis=1) with this table.index.name = "HOSTNAME".


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 )

Facebook photo

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

Connecting to %s