首页 > 解决方案 > 将一列的每一行存储为字典值熊猫

问题描述

我是熊猫数据框的新手,我有一些棘手的任务来完成它。

我有一个这样的数据框。 数据框

文本格式:

SegmentUpper SegmentLower MaterialNumber LowerLimitAVLower LowerLimitAVUpper UpperLimitAVUpper UpperLimitAVLower RawSegments SiteID 参数 ParameterDesc

A 上 A 下 111 0 1 2 3 [] 2 P1 {'abc':'p1'}

B 上 B 下 111 1 2 3 4 [] 2 P1 {'abc':'p1'}

C 上 C 下 111 2 3 4 5 [] 2 P1 {'abc':'p1'}

D 上 D 下 111 3 4 5 6 [] 2 P1 {'abc':'p1'}

A 上 A 下 111 1 2 3 4 [] 2 P2 {'abc':'p2'}

B 上 B 下 111 3 2 3 4 [] 2 P2 {'abc':'p2'}

C 上 C 下 111 3 3 4 6 [] 2 P2 {'abc':'p2'}

D 上 D 下 111 2 4 5 7 [] 2 P2 {'abc':'p2'}

A 上 A 下 222 0 3 4 5 [] 2 P1 {'abc':'p1'}

B 上 B 下 222 3 5 7 9 [] 2 P1 {'abc':'p1'}

C 上 C 下 222 2 5 7 8 [] 2 P1 {'abc':'p1'}

D 上 D 下 222 3 8 6 9 [] 2 P1 {'abc':'p1'}

我必须创建一个列表类型的新列并将多个字典值存储到其中。

所以基本上如上图所示,我能够找到将列作为列表的方法,即使用以下代码的“ Rawsegment ”列:

DataDF['RawSegment'] = np.empty((len(DataDF), 0)).tolist()

现在棘手的部分是使用现有 Dataframe 中其他列的值向其中添加字典值

例如:我有一个名为 Segment Upper、Segment Lower、LowerLimitAVLower、LowerLimitAVUpper、UpperLimitAVLower、UpperLimitAVLower、MaterialNumber 的列

我希望最终输出为 最终数据框

对于每个材料编号和参数,将所有 A、B、C、D 上限值和下限值存储为字典并保留其他列。

任何帮助将不胜感激。

标签: python-2.7pandas

解决方案


首先将列转换MaterialNumber为索引和列,以便使用 3 列进行rename拆分,然后将 groupby 与和用于字典:_DataFramestackapplyto_dict

d = {'SegmentUpper':'Upper_Segment',
     'SegmentLower':'Lower_Segment',
     'LowerLimitAVLower':'Lower_LimitAVLower',
     'LowerLimitAVUpper':'Lower_LimitAVUpper',
     'UpperLimitAVUpper':'Upper_LimitAVUpper',
     'UpperLimitAVLower':'Upper_LimitAVLower'}
df = df.set_index('MaterialNumber').rename(columns=d)
df.columns = df.columns.str.split('_', expand=True)
df1 = (df.stack(0)[['Segment','LimitAVLower','LimitAVUpper']]
        .groupby(level=0).apply(lambda x: x.to_dict('r'))
        .reset_index(name='RawSegments'))
print (df1)
   MaterialNumber                                        RawSegments
0             111  [{'Segment': 'A Lower', 'LimitAVLower': 0.0, '...
1             222  [{'Segment': 'A Lower', 'LimitAVLower': 0.0, '...

推荐阅读