如何通过数据框中的列循环功能并将其添加到新列

时间:2018-10-27 12:45:09

标签: python python-3.x pandas

我将创建一些测试数据:

import numpy as np
import pandas as pd
test_df = pd.DataFrame(np.random.randn(10,4), columns=['a','b','c','d'])

我要传递给列变量的函数是:

def standard(x):
    return (x - x.mean()) / x.std()

然后我要做的是使用for循环在每个列变量上运行函数standard,并将新列添加到具有标准化数据的数据框中。

但是,除了使for循环简单之外,我之前从未真正做过这样的事情。因此,任何指针将不胜感激。

3 个答案:

答案 0 :(得分:1)

您可以这样做:

for column in test_df:
    print(standard(test_df[column]))

答案 1 :(得分:1)

您可以将函数应用于每个列,如下所示:

std_df = test_df.apply(standard,axis = 1)]

您可以像这样将其隐藏在原始框架中:

big_df = pd.concat([ test_df, std_df], axis = 1)

为简化起见,您可以将它们同时运行:

test_df = pd.concat([ test_df, test_df.apply(standard,axis = 1)], axis = 1)

答案 2 :(得分:1)

如果要使用一行,这里确实在原始/源数据帧上应用了该函数,那么lambda函数将完成技巧(,将匿名函数作为参数传递给apply() ):

test_df.apply(lambda x: (x - x.mean()) / x.std(), axis =1)
Out:

           a         b            c          d
0     -0.381437   0.090135    -1.038400   1.329702
1     -0.722698   0.902806    0.817258    -0.997366
2     -0.521621   1.375428    -0.912505   0.058698
3     0.161679    0.900105    0.363529    -1.425313
4     -0.605061   0.527289    -1.045744   1.123515
5     -1.271155   0.481572    -0.253487   1.043071
6     -0.473747   -0.471403   -0.553750   1.498901
7     0.161580    1.335381    -0.935835   -0.561127
8     1.355149    -0.372754   0.029416    -1.011811
9     -1.065852   1.253947    0.276011    -0.464105
     
     

对于:“如何通过数据框的列循环功能并添加到新列”,您可以使用pandas.DataFrame.join将源数据框test_df与新列standardized form columns连接起来将具有新名称:

test_df.join(test_df.apply(lambda x: (x - x.mean()) / x.std(), axis =1), rsuffix='_std')
          a          b            c          d           a_std       b_std        c_std      d_std
0     -0.142156   0.239129    -0.673335   1.241366    -0.381437   0.090135    -1.038400   1.329702
1     -0.726785   0.668620    0.595182    -0.962573   -0.722698   0.902806    0.817258    -0.997366
2     -1.212991   0.384315    -1.542113   -0.724365   -0.521621   1.375428    -0.912505   0.058698
3     0.366151    0.897416    0.511373    -0.775619   0.161679    0.900105    0.363529    -1.425313
4     -0.248543   0.830104    -0.668326   1.398053    -0.605061   0.527289    -1.045744   1.123515
5     -1.001275   0.695089    -0.016333   1.238530    -1.271155   0.481572    -0.253487   1.043071
6     -0.850323   -0.848182   -0.923375   0.950963    -0.473747   -0.471403   -0.553750   1.498901
7     0.337371    0.688291    0.009287    0.121310    0.161580    1.335381    -0.935835   -0.561127
8     1.976673    -0.953941   -0.271841   -2.037817   1.355149    -0.372754   0.029416    -1.011811
9     -1.795365   0.058748    -0.722873   -1.314415   -1.065852   1.253947    0.276011    -0.464105

pandas.Series.apply

pandas.DataFrame.apply

相关问题