Hashmatullah Noorzai
Hashmatullah Noorzai

Reputation: 790

Apply log2 transformation to a pandas DataFrame

I want to apply log2 with applymap and np2.log2to a data and show it using boxplot, here is the code I have written:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data = pd.read_csv('testdata.csv')
df = pd.DataFrame(data)

################################
    # a.
df.boxplot()
plt.title('Raw Data')

################################
    # b.
df.applymap(np.log2)
df.boxplot()
plt.title('Normalized Data')

and below is the boxplot I get for my RAW data which is okay, but I do get the same boxplot after applying log2 transformation !!! can anyone please tell me what I am doing wrong and what should be corrected to get the normalized data with applymap and np.log2 enter image description here

Upvotes: 3

Views: 18580

Answers (3)

Archie
Archie

Reputation: 2387

Pandas now has the transform() function, which in your case amounts to:

df = df.transform(lambda x: np.log2(x))

Upvotes: 2

cs95
cs95

Reputation: 402553

A much faster way to do this would be:

df = np.log2(df)

Don't forget to assign the result back to df.

Upvotes: 15

Shihe Zhang
Shihe Zhang

Reputation: 2771

According to API Reference DataFrame.applymap(func)

Apply a function to a DataFrame that is intended to operate elementwise, i.e. like doing map(func, series) for each series in the DataFrame

It won't change the DataFrame you need to get the return value and use it.

Upvotes: 3

Related Questions