apply&字典

大家好,好久不见,再次介绍下本人。中山大学,医学生+计科学生的集合体,机器学习爱好者。又开始进入万年记不住的字典坑了,加上apply用法,双坑齐下,特此总结。

import pandas as pd
data=pd.DataFrame({'ct':[1,1,2,2,3],'1_tf':[10,20,30,40,50]})
co_1f_dict = data.groupby('ct')['1_tf'].mean().to_dict()

一列(加不加reset_index不影响df类型)
part1:表明只能是列做字典映射

a = data['ct'].reset_index(drop=True)
print(a)
# 0    1
# 1    1
# 2    2
# 3    2
# 4    3
# Name: ct, dtype: int64
print(a.iloc[0])
#1
print(co_1f_dict[a.iloc[0]])
#15


b = data['ct']
print(b)
# 0    1
# 1    1
# 2    2
# 3    2
# 4    3
# Name: ct, dtype: int64
print(b.iloc[0])
#1
print(co_1f_dict[b.iloc[0]])
#15


c = data[['ct']]
print(c)
#    ct
# 0              1
# 1              1
# 2              2
# 3              2
# 4              3
print(c.iloc[0])
#ct    1
# Name: 0, dtype: int64
print(co_1f_dict[c.iloc[0]])
#报错

一列(加不加reset_index不影响df类型)
part2:表明只能是df做apply字典映射

d = data[['ct']].apply(lambda x: x.iloc[0], axis=1)
print(d)
# 0    1
# 1    1
# 2    2
# 3    2
# 4    3
# dtype: int64
d1 = data[['ct']].apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(d1)
# 0    15
# 1    15
# 2    35
# 3    35
# 4    50
# dtype: int64


e = data['ct'].apply(lambda x: x.iloc[0], axis=1)
print(e)
e1 = data['ct'].apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(e1)
#报错


f = data['ct'].reset_index(drop=True).apply(lambda x: x.iloc[0], axis=1)
print(f)
f1 = data['ct'].reset_index(drop=True).apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(f1)
#报错

两列
part3:表明多列只能用df用apply能做字典映射

A = data['ct','1_tf'].reset_index(drop=True)
print(A)
print(A.iloc[0])
print(co_1f_dict[A.iloc[0]])
#报错


B = data['ct','1_tf']
print(B)
print(B.iloc[0])
print(co_1f_dict[B.iloc[0]])
#报错


C = data[['ct','1_tf']]
print(C)
#    ct  1_tf
# 0              1           10
# 1              1           20
# 2              2           30
# 3              2           40
# 4              3           50
print(C.iloc[0])
# ct     1
# 1_tf      10
# Name: 0, dtype: int64
print(co_1f_dict[C.iloc[0]])
#报错


D = data[['ct','1_tf']].apply(lambda x: x.iloc[0], axis=1)
print(D)
# 0    1
# 1    1
# 2    2
# 3    2
# 4    3
# dtype: int64
D1 = data[['ct','1_tf']].apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(D1)
# 0    15
# 1    15
# 2    35
# 3    35
# 4    50
# dtype: int64


E = data['ct','1_tf'].apply(lambda x: x.iloc[0], axis=1)
print(E)
E1 = data['ct','1_tf'].apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(E1)
#报错


F = data['ct','1_tf'].reset_index(drop=True).apply(lambda x: x.iloc[0], axis=1)
print(F)
F1 = data['ct'].reset_index(drop=True).apply(lambda x: co_1f_dict[x.iloc[0]], axis=1)
print(F1)
#报错

感觉永远都搞不清楚字典和apply的用法,希望此文能加深理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值