AttributeError: 'int' object has no attribute 'log'

时间:2023-03-08 17:42:48

我们有时候在对组数进行操作时候,偶尔会出现这个问题.

比如:

#coding:utf-
import pandas as pd
import numpy as np if __name__ == '__main__':
np.random.seed()
df = pd.DataFrame( + np.random.randn().cumsum(), columns=['weight'])
df['pct_change'] = df.weight.pct_change()
df['w_log'] = np.log(np.asarray(df['weight']+ , dtype=object))
print df['w_log']

会出现这个问题:

   df['w_log'] = np.log(np.asarray(df['weight']+ , dtype=object))
AttributeError: 'float' object has no attribute 'log'

这个问题的原因是object没有log操作:上述操作等同于

np.log(np.array([x], dtype=object)) <-> np.array([x.log()], dtype=object)

那么我们该怎么样来修正呢?
#coding:utf-
import pandas as pd
import numpy as np if __name__ == '__main__':
np.random.seed()
df = pd.DataFrame( + np.random.randn().cumsum(), columns=['weight'])
df['pct_change'] = df.weight.pct_change()
df['w_log'] = np.log(np.asarray(df['weight']+ , dtype=float))
print df['w_log']

将object对象,改成base类型就可以了.

结果:

     4.642120
4.645969
4.655321
4.676410
4.693652
4.684666
4.693403
4.692016
4.691069
4.694830
4.696146
4.709337
4.716171

完.