Pandas对一列做运算
可以用apply
In [95]: df = pd.DataFrame(data = [[1,2,3,4],[5,6,7,8,]], columns=['a','b','c','
...: d'])
In [96]: df
Out[96]:
a b c d
0 1 2 3 4
1 5 6 7 8
In [97]: df['a'] = 1/df['a']
In [98]: df
Out[98]:
a b c d
0 1.0 2 3 4
1 0.2 6 7 8
In [99]: df['b'] = df['b'] * 2
In [100]: df['b']
Out[100]:
0 4
1 12
Name: b, dtype: int64
In [101]: df
Out[101]:
a b c d
0 1.0 4 3 4
1 0.2 12 7 8
In [102]: df['c'] = df['c']*10 + 1
In [103]: df
Out[103]:
a b c d
0 1.0 4 31 4
1 0.2 12 71 8
In [107]: def foo(x, y):
...: if x == 8:
...: return x
...: return x*y + 1
...:
In [108]: df['d'] = df['d'].apply(foo, args=(10,))
In [109]: df
Out[109]:
a b c d
0 1.0 4 31 41
1 0.2 12 71 8
版权声明:本文为lancegentry原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。