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

时间:2014-11-27 08:45:06

标签: python python-2.7 pandas

我有下表:

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

如何将函数应用于dataframes索引?我想对索引为“c”的每一列的数字进行舍入。

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

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

对于基于标签的索引,请使用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

答案 1 :(得分:0)

要对列c的值进行舍入:

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

要对行c的值进行舍入:

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