我们有时候在对组数进行操作时候,偶尔会出现这个问题.
比如:
#coding:utf-8
import pandas as pd
import numpy as np
if __name__ == '__main__':
np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['weight'])
df['pct_change'] = df.weight.pct_change()
df['w_log'] = np.log(np.asarray(df['weight']+2 , dtype=object))
print df['w_log']
会出现这个问题:
df['w_log'] = np.log(np.asarray(df['weight']+2 , 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-8
import pandas as pd
import numpy as np
if __name__ == '__main__':
np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['weight'])
df['pct_change'] = df.weight.pct_change()
df['w_log'] = np.log(np.asarray(df['weight']+2 , dtype=float))
print df['w_log']
将object对象,改成base类型就可以了.
结果:
0 4.642120
1 4.645969
2 4.655321
3 4.676410
4 4.693652
5 4.684666
6 4.693403
7 4.692016
8 4.691069
9 4.694830
10 4.696146
11 4.709337
12 4.716171
完.