2 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以pd.Series.explode
在這里使用。
pd.Series(lst,index=index_list).explode() phase1 a phase1 b phase1 c phase2 d phase2 e phase2 f phase2 g phase3 h phase3 i phase3 j dtype: object
另一種解決方案使用np.repeat
和np.concatenate
r_len = [len(r) for r in lst] pd.Series(np.concatenate(lst), index=np.repeat(index_list,r_len)) phase1 a phase1 b phase1 c phase2 d phase2 e phase2 f phase2 g phase3 h phase3 i phase3 j dtype: object
時(shí)間結(jié)果:
In [501]: %%timeit ...: pd.Series(lst,index=index_list).explode() ...: ...:363 μs ± 16.5 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [503]: %%timeit ...: r_len = [len(r) for r in lst] ...: pd.Series(np.concatenate(lst), index=np.repeat(index_list,r_len)) ...: ...: 236 μs ± 17.8 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
這個(gè)問(wèn)題看起來(lái)類似于 R 的函數(shù),并且在pandas cookbook(頁(yè)面底部)中expand.grid()列出。此函數(shù)允許您使用給定輸入值的所有組合創(chuàng)建數(shù)據(jù)框。
首先定義一個(gè)函數(shù):
def expand_grid(data_dict):
rows = itertools.product(*data_dict.values())
return pd.DataFrame.from_records(rows, columns=data_dict.keys())
然后你可以像這樣使用它:
df = expand_grid({'index': ['phase1', 'phase2', 'phase3'],
'Col1': [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]})
添加回答
舉報(bào)