Ginger
Ginger

Reputation: 8630

Pandas Multiple Column Division

I am trying to do a division of column 0 by columns 1 and 2. From the below, I would like to return a dataframe of 10 rows, 3 columns. The first column should all be 1's. Instead I get a 10x10 dataframe. What am I doing wrong?

data = np.random.randn(10,3)
df = pd.DataFrame(data)

df[0] / df

Upvotes: 2

Views: 1800

Answers (2)

Andrew Gross
Andrew Gross

Reputation: 46

You need to match the dimension of the Series with the rows of the DataFrame. There are a few ways to do this but I like to use transposes.

    data = np.random.randn(10,3)
    df = pd.DataFrame(data)

    (df[0] / df.T).T

       0          1         2
    0  1  -0.568096 -0.248052
    1  1  -0.792876 -3.539075
    2  1 -25.452247  1.434969
    3  1  -0.685193 -0.540092
    4  1   0.451879 -0.217639
    5  1  -2.691260 -3.208036
    6  1   0.351231 -1.467990
    7  1   0.249589 -0.714330
    8  1   0.033477 -0.004391
    9  1  -0.958395 -1.530424

Upvotes: 1

Viktor Kerkez
Viktor Kerkez

Reputation: 46586

First you should create a 10 by 3 DataFrame with all columns equal to the first column and then divide it with your DataFrame.

df[[0, 0, 0]] / df.values

or

df[[0, 0, 0]].values / df

If you want to keep the column names.

(I use .values to avoid reindexing which will fail due to duplicate column values.)

Upvotes: 2

Related Questions