Categories
Python Answers

How to delete a DataFrame row in Python Pandas based on column value?

To delete a DataFrame row in Python Pandas based on column value, we can set get the rows we want with a condition.

For instance, we write

df = df[df.line_race != 0]

to get the rows where the line_race column isn’t 0

Categories
Python Answers

How to expand the output display to see more columns of a Python Pandas DataFrame?

To expand the output display to see more columns of a Python Pandas DataFrame, we call the set_option method.

For example, we write

import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

to call set_option to set the values for max_rows, max_columns with width of each row.

Categories
Python Answers

How to write a Python Pandas DataFrame to CSV file?

To write a Python Pandas DataFrame to CSV file, we call the to_csv method on the data frame.

For instance, we write

df.to_csv(file_name, encoding='utf-8', index=False)

to call to_csv on the df data frame.

file_name is the path of the output file.

encoding sets the CSV encoding.

We hide the row index by setting index to false.

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.