对于大型数据帧,使用分隔符连接pandas字符串列



我有一个大的数据框(~ 100万行),有20个字符串列,我试图用分隔符连接成一个单列,在途中放弃NA值。(每行具有可变数量的有效条目和NA值。)

根据这里的解决方案,我可以使用df.apply获得我需要的输出,但它非常慢:

raw['combined'] = raw.loc[:, 'record_1':'record_20'].apply(lambda x: '|'.join(x.dropna().values), axis=1)

是否有更快的方法来做这个连接,或者我被困在df.apply?

agg比apply快得多。使用agg代替。

import time
import timeit
from pandas import DataFrame
import numpy as np
import pandas as pd
from datetime import datetime

df = pd.DataFrame({
'date' : ['05/9/2023', '07/10/2023', '08/11/2023', '06/12/2023'],
'A' : [1,  np.nan,4, 7],
'B' : [2, np.nan, 5, 8],
'C' : [3, 6, 9, np.nan]
}).set_index('date')
print(df)
"""
A    B    C
date                     
05/9/2023   1.0  2.0  3.0
07/10/2023  NaN  NaN  6.0
08/11/2023  4.0  5.0  9.0
06/12/2023  7.0  8.0  NaN
"""
start_time = datetime.now()
df['Without_NAN'] = df[df.columns].agg(lambda x: ','.join(x.dropna().astype(str)),axis=1)
print(df)
"""
A    B    C  Without_NAN
date                                  
05/9/2023   1.0  2.0  3.0  1.0,2.0,3.0
07/10/2023  NaN  NaN  6.0          6.0
08/11/2023  4.0  5.0  9.0  4.0,5.0,9.0
06/12/2023  7.0  8.0  NaN      7.0,8.0
"""
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))

最新更新