我想知道是否可以從列表列表創建數據框,其中 index_list 中的每個項目都作為索引附加到 lst 中的每個值:index_list = ['phase1', 'phase2', 'phase3']lst = [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]感謝您的任何幫助??!編輯:內部列表的大小不一定相同。
2 回答

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
你可以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)

滄海一幻覺
TA貢獻1824條經驗 獲得超5個贊
這個問題看起來類似于 R 的函數,并且在pandas cookbook(頁面底部)中expand.grid()列出。此函數允許您使用給定輸入值的所有組合創建數據框。
首先定義一個函數:
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']]})
添加回答
舉報
0/150
提交
取消