如何在Google Sheets中用Lambda结合Reduce实现行指定次数重复
解决方案
方法1:Pandas原生高效实现(推荐)
这种方式利用Pandas的向量化操作,效率远高于逐行处理,是最优解:
import pandas as pd # 构造输入数据 df = pd.DataFrame({ 'Unique ID': [123, 456], 'Some other Info': ['Some Info', 'Some Info'], 'How many times to repeat': [2, 3] }) # 按指定次数展开Unique ID expanded_df = df.loc[df.index.repeat(df['How many times to repeat']), ['Unique ID']].reset_index(drop=True) print(expanded_df)
输出结果:
Unique ID 0 123 1 123 2 456 3 456 4 456
方法2:Reduce结合Lambda实现(满足你的需求)
如果一定要用reduce+lambda的方式,可以逐行构建数据并累加:
import pandas as pd from functools import reduce # 构造输入数据 df = pd.DataFrame({ 'Unique ID': [123, 456], 'Some other Info': ['Some Info', 'Some Info'], 'How many times to repeat': [2, 3] }) # 使用Reduce+Lambda展开 expanded_df = reduce( lambda acc, row: acc.append(pd.DataFrame({'Unique ID': [row['Unique ID']] * row['How many times to repeat']})), df.to_dict('records'), pd.DataFrame(columns=['Unique ID']) ).reset_index(drop=True) print(expanded_df)
输出结果和方法1完全一致。
注意:
reduce+lambda是逐行循环处理,数据量大时效率会低于Pandas原生的向量化操作,适合小数据量场景使用。
内容的提问来源于stack exchange,提问作者Mike P
相关产品推荐
相关产品推荐

