簡體   English   中英

將 python 列表轉換為 pandas dataframe 從列表中選擇特定字符串

[英]Converting python list to pandas dataframe selecting specific strings from the list

我有以下 python 列表:

w=[[['I=427', 'PLAN=1'], 'A=0PDB'],
 [['I=427', 'PLAN=1'], 'B=40NGC'],
 [['I=427', 'PLAN=1'], 'C=21#NGA'],
 [['I=429', 'PLAN=1'], 'A=0PDB'],
 [['I=429', 'PLAN=1'], 'B=18C'],
 [['I=429', 'PLAN=1'], 'C=28TGD'],
 [['I=429', 'PLAN=1'], 'D=18TGA'],
 [['I=429', 'PLAN=1'], 'E=1A'],
 [['I=429', 'PLAN=2'], 'A=0PDB'],
 [['I=429', 'PLAN=2'], 'B=17C']]

如何將其轉換為以下 pandas DataFrame:

在此處輸入圖像描述

因此,從列表中的第二個字符串開始,我想要 select 第一個字符串、等號后面的數字和最后一個字符串。 例如在B=40NGC中,我想選擇B , 40 , C並將其放入 DataFrame。

這是一種方法:

稍微修改一下以創建一個列表列表並構建一個w然后從green_time列中提取一個數字:

out = []
for lst, s in w:
    phase, rest = s.split('=')
    green_time, next_phase = rest[:-1], rest[-1]
    out.append(lst + [phase, green_time, next_phase])
out = pd.DataFrame(out, columns=['site_no', 'plan', 'phase', 'green_time','next_phase'])
out['green_time'] = out['green_time'].str.extract('(\d+)')

或者,我們可以將w傳遞給 DataFrame 構造函數並使用str.extract提取列中的相關項目:

df = pd.DataFrame(w)
df = df.join(pd.DataFrame(df[0].tolist(), columns=['site_no', 'plan']))
df[['phase', 'green_time','next_phase']] = df[1].str.extract('(\w)=(\d+)([^0-9]+)')
df['next_phase'] = df['next_phase'].str[-1]
df = df.drop(columns=[0,1])

Output:

  site_no    plan phase green_time next_phase
0   I=427  PLAN=1     A          0          B
1   I=427  PLAN=1     B         40          C
2   I=427  PLAN=1     C         21          A
3   I=429  PLAN=1     A          0          B
4   I=429  PLAN=1     B         18          C
5   I=429  PLAN=1     C         28          D
6   I=429  PLAN=1     D         18          A
7   I=429  PLAN=1     E          1          A
8   I=429  PLAN=2     A          0          B
9   I=429  PLAN=2     B         17          C

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM