亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將列表中的索引附加到列表列表以創建 pandas df

將列表中的索引附加到列表列表以創建 pandas df

明月笑刀無情 2023-01-04 10:26:55
我想知道是否可以從列表列表創建數據框,其中 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.repeatnp.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)


查看完整回答
反對 回復 2023-01-04
?
滄海一幻覺

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']]})


查看完整回答
反對 回復 2023-01-04
  • 2 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號