Using a Series

Consider the following series:

In [12]: currDict={'US' : 'dollar', 'UK' : 'pound', 'Germany': 'euro', 'Mexico':'peso', 'Nigeria':'naira', 'China':'yuan', 'Japan':'yen'}
In [13]: currSeries = pd.Series(currDict)
Out[13]:
US dollar
UK pound
Germany euro
Mexico peso
Nigeria naira
China yuan
Japan yen
Name: Currency, dtype: object

Here, the series has a defined index and name. When being converted to a DataFrame, this index is retained and the name of the Series gets assigned as a column name:

currDF = pd.DataFrame(currSeries)

The following is the output:

There are also alternative constructors for DataFrames; they can be summarized as follows:

  • DataFrame.from_dict: It takes a dictionary of dictionaries or sequences and returns a DataFrame. It slightly differs from the method discussed earlier due to an argument to specify order. While the other method always converts keys of dictionaries to columns, this constructor provides an option to convert the keys to row labels:
# Default setting
pd.DataFrame.from_dict(algos, orient = "columns")

The following is the output:

Another method to do this is as follows:

pd.DataFrame.from_dict(algos, orient = "index", columns = ["A", "B", "C", "D", "E"])

The following is the output:

  • DataFrame.from_records: It takes a list of tuples or structured ndarray to construct a DataFrame. Unlike the method mentioned earlier for structured arrays, this function allows you to set one of the fields of the array as an index:
pd.DataFrame.from_records(memberData, index="Name")

The following is the output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset