简体   繁体   中英

How to do columnwise operations in pandas?

I have a dataframe that looks something like:

 sample parameter1 parameter2 parameter3
 A      9           6         3        
 B      4           5         7
 C      1           5         8

and I want to do an operation that does something like:

for sample in dataframe:
    df['new parameter'] = df[sample, parameter1]/df[sample, parameter2]

so far I have tried:

df2.loc['ratio'] = df2.loc['reads mapped']/df2.loc['raw total sequences']

but I get the error:

KeyError: 'the label [reads mapped] is not in the [index]'

when I know well that it is in the index, so I figure I am missing some concept somewhere. Any help is much appreciated!

I should add that the parameter values are floats, just in case that is a problem as well!

The method .loc first expects row indices, then column indices, so the following should work, since you wanted to do column-wise operations:

 df2['ratio'] = df2.loc[:, 'reads mapped'] / df2.loc[:, 'raw total sequences']

You can find more info in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM