![](/img/trans.png)
[英]apply lambda or define a function to return 1 else 0 in dask dataframe
[英]apply a lambda function to a dask dataframe
我希望將lambda
函數應用於 dask 數據框以更改列中的標簽,如果它小於某個百分比。 我使用的方法適用於 Pandas 數據幀,但相同的代碼不適用於 dask 數據幀。 代碼如下。
df = pd.DataFrame({'A':['ant','ant','cherry', 'bee', 'ant'], 'B':['cat','peach', 'cat', 'cat', 'peach'], 'C':['dog','dog','roo', 'emu', 'emu']})
ddf = dd.from_pandas(df, npartitions=2)
df:
輸出:
A B C
0 ant cat dog
1 ant peach dog
2 cherry cat roo
3 bee cat emu
4 ant peach emu
ddf.compute()
輸出:
A B C
0 ant cat dog
1 ant peach dog
2 cherry cat roo
3 bee cat emu
4 ant peach emu
list_ = ['B','C']
df.apply(lambda x: x.mask(x.map(x.value_counts(normalize=True))<.5, 'other') if x.name not in list_ else x)
輸出:
A B C
0 ant cat dog
1 ant peach dog
2 other cat roo
3 other cat emu
4 ant peach emu
對 dask 數據框執行相同操作:
ddf.apply(lambda x: x.mask(x.map(x.value_counts(normalize=True))<.5, 'other') if x.name not in list_ else x,axis=1).compute()
輸出(給出警告而不是所需的輸出):
/home/michael/env/lib/python3.5/site-packages/dask/dataframe/core.py:3107: UserWarning: `meta` is not specified, inferred from partial data. Please provide `meta` if the result is unexpected.
Before: .apply(func)
After: .apply(func, meta={'x': 'f8', 'y': 'f8'}) for dataframe result
or: .apply(func, meta=('x', 'f8')) for series result
warnings.warn(msg)
A B C
0 other other other
1 other other other
2 other other other
3 other other other
4 other other other
有人可以幫助我獲得 dask 數據幀實例所需的輸出。
謝謝
邁克爾
在 pandas 和 dask 情況下,您沒有執行相同的操作:對於后者,您有axis=1
,因此您最終會替換給定行中出現少於兩次的任何值,這就是全部。
如果您更改為axis=0
,您將看到您收到異常。 這是因為要計算第一個分區,您還需要將整個數據幀傳遞給 lambda 函數 - 否則如何獲得 value_counts?
您的問題的解決方案是分別獲取值計數。 您可以顯式地計算它(結果很小)或將其傳遞給 lambda。 此外請注意,走這條路意味着您可以避免使用apply
來支持map
並使事情更加明確。 在這里我專門選擇一列,你可以循環。
vc = ddf.A.value_counts().compute()
vc /= vc.sum() # because dask's value_count doesn't normalise
def simple_map(df):
df['A'] = df['A'].map(lambda x: x if vc[x] > 0.5 else 'other')
return df
ddf.map_partitions(simple_map, meta=df[:0]).compute()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.