Categories
Python Answers

How to add a new Python Pandas column with mapped value from a dictionary?

To add a new Python Pandas column with mapped value from a dictionary, we can call the map method.

For instance, we write

import pandas as pd

equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
df["B"] = df["A"].map(equiv)

to create the df dataframe.

Then we call map with a dictionary to map the values from the keys’ values to the values’ values.

And then we assign them to the B column.

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 use the isin method.

For instance, we write

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

to create the df data frame.

Then we call isin with df['A'] to select the items from column A that’s in [3, 6].

So the rows with 3 or 6 are returned from column A.

Categories
Python Answers

How to convert DataFrame column type from string to datetime with Python Pandas?

To convert DataFrame column type from string to datetime with Python Pandas, we can use the to_datetime method.

For instance, we write

df['col'] = pd.to_datetime(df['col'])

to call to_datetime with df['col'] to covert the values in the col column to datetimes and assign them back to the col column.

Categories
Python Answers

How to replace NaN values by Zeroes in a column of a Python Pandas Dataframe?

To replace NaN values by Zeroes in a column of a Python Pandas Dataframe, we call the fillna method.

For instance, we write

df['column'] = df['column'].fillna(value)

to call fillna to fill the values in the column data frame column with the value to replace NaN.

Categories
Python Answers

How to annotate bars with values on Python Pandas bar plots?

To annotate bars with values on Python Pandas bar plots, we call the annotate metthod.

For instance, we write

for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

to loop through the axes ax patches with ax.patches with a for loop.

Then we call ax.annotate to add the anootation for each patch by calling it with the position of the annotation.