pandas dataframe:对列执行计算

时间:2017-08-25 21:46:30

标签: python pandas dataframe

Pandas新手和新的stackoverflow(真的),任何建议都非常感谢!

我有这个数据框df:

            col1     col2     col3
Date                                        
2017-08-24   100      101      105
2017-08-23   102      102      107
2017-08-22   101      100      106
2017-08-21   103       99      106
2017-08-18   103       98      108
...

现在,我想对每列的值进行一些计算,例如:计算每个值的对数。

我认为循环列并使用生成的列创建新的临时数据框是一个好主意。 这个新数据框应如下所示:

            col1       RN      LOG
Date                                        
2017-08-24   100        1      2
2017-08-23   102        2      2,008600
2017-08-22   101        3      2,004321
2017-08-21   103        4      2,012837
2017-08-18   103        5      2,012837

所以我尝试了这个for循环:

for column in df:
    tmp_df = df[column]
    tmp_df['RN'] = range(1, len(tmp_df) + 1) # to create a new column with the row number
    tmp_df['LOG'] = np.log(df[column]) # to create a new column with the LOG

但是,这并不会在col1旁边打印新列,而是在另一个下面打印新列。结果如下:

Name: col1, Length: 86, dtype: object
Date
2017-08-24 00:00:00                                                100
2017-08-23 00:00:00                                                102
2017-08-22 00:00:00                                                101
2017-08-21 00:00:00                                                103
2017-08-18 00:00:00                                                103
RN,"range(1, 86)"
LOG,"Date
2017-08-24    2
2017-08-23    2,008600
2017-08-22    2,004321
2017-08-21    2,012837
2017-08-18    2,012837

00:00:00被添加到第一部分的日期...

我也尝试过分配:

tmp_df = tmp_df.assign(LN=np.log(df[column]))

但这会导致"属性错误:"'系列'对象没有属性'分配'""

如果有人能指出我正确的方向,那真的很棒。 谢谢!

2 个答案:

答案 0 :(得分:1)

你的for循环是一个好主意,但你需要以这种方式在新列中创建pandas系列:

for column in df:
    df['RN ' + column] = pd.Series(range(1, len(df[column]) + 1))
    df['Log ' + column] = pd.Series(np.log(df[column]))

答案 1 :(得分:0)

现在我明白了。 :)

import pandas as pd
import numpy as np
...
for column in df:
    tmp_res=pd.DataFrame(data=df[column])
    newcol=range(1, len(df) + 1)
    tmp_res=tmp_res.assign(RN=newcol)
    newcol2=np.log(df[column])
    tmp_res=tmp_res.assign(LN=newcol2)

这会打印彼此相邻的所有列:

            col1       RN      LOG
Date                                        
2017-08-24   100        1      2
2017-08-23   102        2      2.008600
2017-08-22   101        3      2.004321
2017-08-21   103        4      2.012837
2017-08-18   103        5      2.012837

现在我可以继续处理它们或将它们全部放在csv / excel文件中。 谢谢你的所有建议!

相关问题