简体   繁体   中英

Pandas: subtracting 2 specific rows on a dataframe

I have a dataframe that look like this:

WW XX YY ZZ
a  10 20 30
b  4  5  6
c  7  8  9 

I would like to subtract row c from row a, and add a new row 'd' at the end to display the result

The expected result should look like this:

WW XX YY ZZ
a  10 20 30
b  4  5  6
c  7  8  9 
d  3  12 21 

I've tried transposing the dataframe and use the df['a'] - df['c'] method, but figure there should be a better way.

Any thoughts / pointers are much appreciated. Thanks!

assuming WW is the index (if not use: df.set_index("WW")), try:

df.loc['d'] = df.loc['a'] - df.loc['c']

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