[英]Dask - Merge multiple columns into a single column
我有一個 dask 數據框,如下所示:
Column1 Column2 Column3 Column4 Column5
0 a 1 2 3 4
1 a 3 4 5
2 b 6 7 8
3 c 7 7
我想有效地將所有列合並為一個。 我希望每一行都是一個字符串。 像下面這樣:
Merged_Column
0 a,1,2,3,4
1 a,3,4,5
2 b,6,7,8
3 c,7,7,7
我見過這個問題,但它似乎效率不高,因為它使用了 apply 函數。 我怎樣才能盡可能高效地實現這一目標? (速度 + 內存使用) Or is apply 並不像我認為的那樣有問題,因為這是 dask,而不是 Pandas。
這是我嘗試過的。 看起來它正在工作,但我擔心大數據幀的速度。
cols= df.columns
df['combined'] = df[cols].apply(func=(lambda row: ' '.join(row.values.astype(str))), axis=1, meta=('str'))
df = df.drop(cols, axis=1)
我還需要去掉列標題。
當您必須加入字符串時,@saravanan saminathan 方法勝出。 這里有一些時間與dask
import dask.dataframe as dd
import numpy as np
import pandas as pd
N = int(1e6)
df = pd.DataFrame(np.random.randint(0,100,[N,10]))
df = dd.from_pandas(df, npartitions=4)
df = df.astype("str")
df_bk = df.copy()
%%time
df["comb"] = df.apply(lambda x:",".join(x), axis=1,meta=("str"))
df = df.compute()
CPU times: user 44.4 s, sys: 925 ms, total: 45.3 s
Wall time: 44.6 s
df = df_bk.copy()
%%time
df["comb"] = df[0]+","+df[1]+","+df[2]+","+df[3]+","+df[4]+","+\
df[5]+","+df[6]+","+df[7]+","+df[8]+","+df[9]
df = df.compute()
CPU times: user 8.95 s, sys: 860 ms, total: 9.81 s
Wall time: 9.56 s
如果您有很多列並且您不想寫下所有列
df = df_bk.copy()
%%time
df["comb"] = ''
for col in df.columns:
df["comb"]+=df[col]+","
df = df.compute()
CPU times: user 11.6 s, sys: 1.32 s, total: 12.9 s
Wall time: 12.3 s
Lambda 函數將占用每一行,因此可能會影響進程的速度
所以如果我們按列應用操作會很快
df = df.astype(str)
df["Column1"]+","+df["Column2"]+","+df["Column3"]+","+df["Column4"]+","+df["Column5"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.