Python 3:通过解析熊猫数据框构造变量

时间:2019-03-02 13:48:59

标签: python pandas dataframe

我具有以下数据帧,其中包含列idstartendname

A   7   340 string1
B   12  113 string2
B   139 287 string3
B   301 348 string4
B   379 434 string5
C   41  73  string6
C   105 159 string7

我正在使用pandas将其读入python3:

import pandas
df = pandas.read_csv("table", comment="#", header=None, names=["id", "start", "end", "name"])

现在,我需要解析df,并为每个idstartendname提取为以下格式的列表:< / p>

mylist = [GraphicFeature(start=XXX, end=YYY, color="#ffffff", label="ZZZ")]

XXXstartYYYendZZZ是“名称”。因此,列表中的项目与每个id的行数一样多。 GraphicFeature只是模块的成员名称。

我想到了像这样遍历数据框:

uniq_val = list(df["id"].unique())
for i in uniq_val:
    extracted = df.loc[df["id"] == i]

但是如何构造mylist? (构造列表后,还会有其他一些绘图命令。)

因此,我在循环中的预期“输出”是:

id A

mylist = [GraphicFeature(start=7, end=340, color="#ffffff", label="string1")]

id B

mylist = [GraphicFeature(start=12, end=113, color="#ffffff", label="string2"), GraphicFeature(start=139, end=287, color="#ffffff", label="string3"), GraphicFeature(start=301, end=348, color="#ffffff", label="string4"), GraphicFeature(start=379, end=434, color="#ffffff", label="string5")]

id C

mylist = [GraphicFeature(start=41, end=73, color="#ffffff", label="string6"), GraphicFeature(start=105, end=159, color="#ffffff", label="string7")]

2 个答案:

答案 0 :(得分:1)

使用循环

l=[[GraphicFeature(start=x[0], end=x[1], color="#ffffff", label=x[2])for x in zip(y.start,y.end,y.name) ] for _,y in df.groupby('id')]

答案 1 :(得分:0)

一种方法是让

mylists = df.groupby('id').apply(lambda group: group.apply(lambda row: GraphicFeature(start=row['start'], end=row['end'], color='#ffffff', label=row['name']), axis=1).tolist())

稍微说明一下,请注意,如果采用函数式编程方法,则熊猫操作往往最整齐地配合在一起;我们想将每一行变成一个GraphicFeature,然后又想将每一个具有相同id的行变成一个GraphicFeature的列表。因此,以上内容也可以扩展为

def row_to_graphic_feature(row):
    return GraphicFeature(start=row['start'], end=row['end'], color='#ffffff', label=row['name'])

def id_group_to_list(group):
    return group.apply(row_to_graphic_feature, axis=1).tolist()

mylists = df.groupby('id').apply(id_group_to_list)

带有示例数据:

In [38]: df
Out[38]:
  id  start  end     name
0  A      7  340  string1
1  B     12  113  string2
2  B    139  287  string3
3  B    301  348  string4
4  B    379  434  string5
5  C     41   73  string6
6  C    105  159  string7

In [39]: mylists = df.groupby('id').apply(id_group_to_list)

In [40]: mylists['A']
Out[40]: [GraphicFeature(start=7, end=340, color='#ffffff', label='string1')]

In [41]: mylists['B']
Out[41]:
[GraphicFeature(start=12, end=113, color='#ffffff', label='string2'),
 GraphicFeature(start=139, end=287, color='#ffffff', label='string3'),
 GraphicFeature(start=301, end=348, color='#ffffff', label='string4'),
 GraphicFeature(start=379, end=434, color='#ffffff', label='string5')]

In [42]: mylists['C']
Out[42]:
[GraphicFeature(start=41, end=73, color='#ffffff', label='string6'),
 GraphicFeature(start=105, end=159, color='#ffffff', label='string7')]