Shan
Shan

Reputation: 55

Mathematical operations with dataframe column names

In general terms, the problem I'm having is that I have numerical column names for a dataframe and struggling to use them.

I have a dataframe (df1) like this:

    3.2  5.4  1.1
1   1.6  2.8  4.0
2   3.5  4.2  3.2

I want to create another (df2) where each value is:

(the corresponding value in df1 minus the value to the left) / (the column number in df1 minus the column number to the left)

This means that the first column of df2 is nan and, for instance, the second row, second column is: (4.2-3.5)/(5.4-3.2)

I think maybe this is problematic because the column names aren't of the appropriate type: I've searched elsewhere but haven't found anything on how to use the column names in the way required.

Any and all help appreciated, even if it involves a workaround!

Upvotes: 1

Views: 1076

Answers (2)

Allen Qin
Allen Qin

Reputation: 19957

You can first transpose the DF and get the rowwise diff. Then divide each column with the column diff. Finally transpose the DF back.

df2 = df.T.assign(c=lambda x: x.index.astype(float)).diff()
df2.apply(lambda x: x.div(df2.c)).drop('c',1).T
Out[367]: 
   3.2       5.4       1.1
1  NaN  0.545455 -0.279070
2  NaN  0.318182  0.232558

Upvotes: 0

piRSquared
piRSquared

Reputation: 294478

v = np.diff(df1.values, axis=1) / np.diff(df1.columns.values.astype(float))
df2 = pd.DataFrame(v, df1.index, df1.columns[1:]).reindex_like(df1)

df2

   3.2       5.4       1.1
1  NaN  0.545455 -0.279070
2  NaN  0.318182  0.232558

Upvotes: 1

Related Questions