PANDAS DATAFRAMES AND RANDOM NUMBERS
Listing 3.4 displays the contents of pandas_random_df.py that illustrates how to create a Pandas DataFrame with random numbers.
LISTING 3.4: pandas_random_df.py
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1, 5, size=(5, 2)), columns=['a','b'])
df = df.append(df.agg(['sum', 'mean']))
print("Contents of data frame:")
print(df)
Listing 3.4 defines the Pandas DataFrame df that consists of 5 rows and 2 columns of random integers between 1 and 5. Notice that the columns of df are labeled “a” and “b.” In addition, the next code snippet appends two rows consisting of the sum and the mean of the numbers in both columns. The output of Listing 3.4 is here:
a b 0 1.0 2.0 1 1.0 1.0 2 4.0 3.0 3 3.0 1.0 4 1.0 2.0 sum 10.0 9.0 mean 2.0 1.8
Listing 3.5 displays the contents of pandas_combine_df.py that illustrates...