[英]Attach index from list to a list of lists to create pandas df
您可以在此處使用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
時間結果:
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)
這個問題看起來類似於 R 的expand.grid()
function 並列在此pandas 食譜中(頁面底部)。 這個 function 允許您使用給定輸入值的所有組合創建 dataframe。
首先定義一個function:
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']]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.