Categories
Python Answers

How to pretty-print an entire Python Pandas Series or DataFrame?

To pretty-print an entire Python Pandas Series or DataFram, we use the print method in the pd.option_context with statement.

For instance, we write

with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)

to call pd.option_context to set some options for printing.

We make Pandas display all the rows and columns with display.max_rows and display.max_columns.

And then we call print with df to print the values of the series or data frame.

Categories
Python Answers

How to convert list of dictionaries to a Python Pandas DataFrame?

To convert list of dictionaries to a Python Pandas DataFrame, we can use the pd.DataFrame class.

For instance, we write

df = pd.DataFrame(d)

to convert dictionary d to a data frame with pd.DataFrame.

Categories
Python Answers

How to use a list of values to select rows from a Python Pandas dataframe?

To use a list of values to select rows from a Python Pandas dataframe, we call the isin method.

For instanmce, we write

df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
r = df[df['A'].isin([3, 6])]

to create the df data frame and get the values from column 'A' that’s in rows 3 to 6 with isin.

We can also get the rows that aren’t in 3 to 6 with

df[~df['A'].isin([3, 6])]
Categories
Python Answers

How to drop rows of a Python Pandas DataFrame whose value in a certain column is NaN?

To drop rows of a Python Pandas DataFrame whose value in a certain column is NaN, we call the notna method.

For instance, we write

df = df[df['EPS'].notna()]

to drop the rows where the 'EPS' column isn’t NaN by calling notna on the column.

Categories
Python Answers

How to add a new column to an existing Python Pandas DataFrame?

To add a new column to an existing Python Pandas DataFram, we can the assign method.

For instance, we write

df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values)

to call assign on the df1 data frame.

We add values to it by setting e to pd.Series(np.random.randn(sLength)).values.