简体   繁体   English

将 python 列表转换为 pandas dataframe 从列表中选择特定字符串

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

I have the below python 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']]

How can I convert it to the below pandas DataFrame:如何将其转换为以下 pandas DataFrame:

在此处输入图像描述

So, from the second string in the list I want to select the first string, the number after equal sign and the last string.因此,从列表中的第二个字符串开始,我想要 select 第一个字符串、等号后面的数字和最后一个字符串。 For example in B=40NGC , I want to choose B , 40 , C and put it into the DataFrame.例如在B=40NGC中,我想选择B , 40 , C并将其放入 DataFrame。

Here's one approach:这是一种方法:

Rework w a bit to create a list of lists and build a DataFrame. Then extract a digits from green_time column:稍微修改一下以创建一个列表列表并构建一个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+)')

Alternatively, we could pass w to the DataFrame constructor and use str.extract to extract the relevant items in columns:或者,我们可以将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: 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