【发布时间】:2023-01-12 16:59:28
【问题描述】:
I have a part of dataframe which looks like this
我想要另一个数据框,其中的元素看起来像这样-Desired_Dataframe
Stem 1 和 Stem 2 分别包含来自原始 Stems 的文本
& 第 2 列包含所有由 ',' 分隔的选项
我尝试使用 for 循环进行迭代,但出现了一些系列和属性错误。
【问题讨论】:
-
请提供您的输入/输出作为可复制的文本,而不是图像
I have a part of dataframe which looks like this
我想要另一个数据框,其中的元素看起来像这样-Desired_Dataframe
Stem 1 和 Stem 2 分别包含来自原始 Stems 的文本
& 第 2 列包含所有由 ',' 分隔的选项
我尝试使用 for 循环进行迭代,但出现了一些系列和属性错误。
【问题讨论】:
使用带有 groupby.agg 和 cumsum 的自定义 groupby 聚合来生成普通石斑鱼
m = df['options'].eq('Stem')
out = (df.groupby(m.cumsum().astype(str).radd('Stem'))
.agg(All_4_Options_Appended=('text', ';'.join))
.rename_axis('Stems').reset_index()
)
输出:
Stems All_4_Options_Appended
0 Stem1 It's the beginning of the quarter, and you're ...
1 Stem2 It's the beginning of the quarter, and you're ...
【讨论】:
这里的主要技巧是,在您能够创建 g 为所需行创建分组列/系列之后,您将每个组中的所有 text 值组合为一个列表。然后你可以将它们与矢量化方法.str.join(' ')结合起来。
此方法应该比.agg或.apply方法更快
尝试以下操作。 (一步一步 - cmets中提到的解释) -
s = 'Stem' # Start group for string
g = df['options'].eq(s).cumsum() # Create groups based cumsum
o = df.groupby(g)['text'].apply(list).str.join(' ') # Groupby and combine text to list of texts
o = o.reset_index() # Reset index to get group column
o['options'] = s + o['options'].astype(str) # Prefix column with Stem
o.columns = ['Stems','All_4_options_Appended'] # Change column names
print(o)
Stems All_4_options_Appended
0 Stem1 It's the beginning of the quarter, and you're ...
1 Stem2 It's the beginning of the quarter, and you're ...
@Akshay Sehgal 的解决方案
%%timeit
s = 'Stem'
g = df['options'].eq(s).cumsum()
o = df.groupby(g)['text'].apply(list).str.join(' ')
o = o.reset_index()
o['options'] = s + o['options'].astype(str)
o.columns = ['Stems','All_4_options_Appended']
o
#686 µs ± 14.2 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
@Mozway 的解决方案
%%timeit
m = df['options'].eq('Stem')
out = (df.groupby(m.cumsum().astype(str).radd('Stem'))
.agg(All_4_Options_Appended=('text', ';'.join))
.rename_axis('Stems').reset_index()
)
out
#1.44 ms ± 8.22 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
【讨论】: