匿名函数
法一
In [1]:[i+100 for i in range(10)]
Out[1]:[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
法二
In [2]:def func(x):
return x + 100
In [3]:list(map(func, range(10)))
Out[3]:[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
法三
In [4]:# 函数简单,不经常使用,不值得取名时使用 lambda x: x+100代替定义函数
list(map(lambda x: x+100, range(10)))
Out[4]:[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
In [5]:df.apply(lambda x: x.数学+100, axis=1)
Out[5]:
0 176 1 187 2 166 3 197 4 186 5 169 dtype: int64
In [6]:# apply:根据多列生成新列的操作
df['new_score'] = df.apply(lambda x: x.数学+x.语文, axis=1)
In [7]:# 前几行
df.head(2)
# 最后几行
df.tail(2)
Out[7]:
序号 | 姓名 | 性别 | 语文 | 数学 | 英语 | 物理 | 化学 | 生物 | 数学分类 | new_score | |
---|---|---|---|---|---|---|---|---|---|---|---|
4 | 5 | mu | 女 | 55 | 86 | 95 | 72 | 76 | 79 | 优秀 | 141 |
5 | 6 | chen | 男 | 78 | 69 | 58 | 52 | 92 | 62 | 及格 | 147 |
pandas中的dataframe 的操作,很大一部分跟numpy中的二维数组的操作是近似的