简体   繁体   English

使用索引值将函数应用于特定行

[英]Apply a function to a specific row using the index value

I have the following table: 我有下表:

import pandas as pd
import numpy as np

#Dataframe with random numbers and with an a,b,c,d,e index
df = pd.DataFrame(np.random.randn(5,5), index = ['a','b','c','d','e'])

#Now i name the columns the same
df.columns = ['a','b','c','d','e']

#Resulting dataframe:
        a         b         c         d         e
a  2.214229  1.621352  0.083113  0.818191 -0.900224
b -0.612560 -0.028039 -0.392266  0.439679  1.596251
c  1.378928 -0.309353 -0.651817  1.499517  0.515772
d -0.061682  1.141558 -0.811471  0.242874  0.345159
e -0.714760 -0.172082  0.205638  0.220528  1.182013

How can i apply a function to the dataframes index? 如何将函数应用于数据帧索引? I want to round the numbers for every column where the index is "c". 我想舍入索引为“ c”的每一列的数字。

#Numbers to round to 2 decimals: 
       a         b         c         d         e
c  1.378928 -0.309353 -0.651817  1.499517  0.515772

What is the best way to do this? 做这个的最好方式是什么?

For label based indexing use loc : 对于基于标签的索引,请使用loc

In [22]:

df = pd.DataFrame(np.random.randn(5,5), index = ['a','b','c','d','e'])

#Now i name the columns the same
df.columns = ['a','b','c','d','e']
df
Out[22]:
          a         b         c         d         e
a -0.051366  1.856373 -0.224172 -0.005668  0.986908
b -1.121298 -1.018863  2.328420 -0.117501 -0.231463
c  2.241418 -0.838571 -0.551222  0.662890 -1.234716
d  0.275063  0.295788  0.689171  0.227742  0.091928
e  0.269730  0.326156  0.210443 -0.494634 -0.489698
In [23]:

df.loc['c'] = np.round(df.loc['c'],decimals=2)
df
Out[23]:
          a         b         c         d         e
a -0.051366  1.856373 -0.224172 -0.005668  0.986908
b -1.121298 -1.018863  2.328420 -0.117501 -0.231463
c  2.240000 -0.840000 -0.550000  0.660000 -1.230000
d  0.275063  0.295788  0.689171  0.227742  0.091928
e  0.269730  0.326156  0.210443 -0.494634 -0.489698

To round values of column c: 舍入列c的值:

df['c'].round(decimals=2)

To round values of row c: 舍入c行的值:

df.loc['c'].round(decimals=2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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