pol*_*lot 3 python lambda dictionary pandas data-science
我有以下场景。
import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [['apple'], [], ['romaine', 'potatoes']}
df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)
所以数据框是:
col1 col2
0 1 [apple]
1 2 []
2 3 [romaine, potatoes]
Run Code Online (Sandbox Code Playgroud)
我还有一本字典:
my_dict = {"apple" : "fruit", "potatoes" : "vegetable", "romaine" : "lettuce"}
Run Code Online (Sandbox Code Playgroud)
我想创建另一列“col3”,它将包含上面 my_dict 中的值列表:
col1 col2 col3
0 1 [apple] [fruit]
1 2 [] []
2 3 [romaine, potatoes] [lettuce, vegetable]
Run Code Online (Sandbox Code Playgroud)
我想使用apply、map、lambda编写一行代码来实现这一点:
df["col3"] = df.col2.apply(map(lambda x: pass if not x else condition_dict[x]))
Run Code Online (Sandbox Code Playgroud)
我真的被困住了,想知道是否有可能不编写单独的函数然后作为参数传递来应用。
.apply使用 alist-comprehension比.explode()使用快约 2.5 倍.groupby(),比使用 快一点(1.15 倍).map()。
NaN列中有 a ,则该行必须用 删除.dropna,或者可以用空 填充list。
.fillna([]) 不管用df.col2 = df.col2.fillna({i: [] for i in df.index})df['col3'] = df.col2.apply(lambda x: [my_dict.get(v) for v in x])
# display(df)
col1 col2 col3
1 [apple] [fruit]
2 [] []
3 [romaine, potatoes] [lettuce, vegetable]
Run Code Online (Sandbox Code Playgroud)
%timeit 测试# test data with 1M rows
d = {'col1': [1, 2, 3], 'col2': [['apple'], [], ['romaine', 'potatoes']]}
df = pd.DataFrame(d)
df = pd.concat([df]*333333)
%%timeit
df.col2.apply(lambda x: [my_dict.get(v) for v in x])
[out]:
453 ms ± 30.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
def scott(d, my_dict):
e = d.explode('col2')
e['col3'] = e['col2'].map(my_dict)
return e.groupby('col1', as_index=False)[['col3']].agg(list).merge(d)
%%timeit
scott(df, my_dict)
[out]:
1.17 s ± 23.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
df.col2.map(lambda x: list(map(my_dict.get, x)))
[out]:
519 ms ± 16.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
df['col2'].explode().map(my_dict).groupby(level=0).agg(list)
[out]:
909 ms ± 8.61 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |