创建一个dictoinary,其键和值是数据框中的数组

时间:2018-03-06 15:20:08

标签: python pandas numpy scipy

我是编程和Python的新手。 我有一个数据集x,y,z,binnumber,我想制作一个字典,哪些键是binnumber,值是x,y,z

example of the data
    x            y        z        binnumber
32618380.55  5984467.66 -2.57        516
32618380.54  5984467.73 -2.57        516
32618380.52  5984467.79 -2.57        516
32618380.51  5984467.88 -2.57        516
32618380.50  5984467.97 -2.57        516
32618380.49  5984468.05 -2.57        517
32618380.48  5984468.14 -2.57        517
32618380.46  5984468.23 -2.57        517
32618380.45  5984468.32 -2.57        517
32618380.44  5984468.41 -2.57        517
       ...         ...   ...        ...
32618375.44  5984470.89 -2.58        444
32618375.45  5984470.85 -2.58        444
32618375.45  5984470.83 -2.58        444
32618375.47  5984470.79 -2.57        444
32618375.46  5984470.77 -2.57        444
32618375.46  5984470.74 -2.57        444
32618375.48  5984470.72 -2.57        444
32618375.47  5984470.69 -2.57        444


Data = pd.read_csv(inputpath,  index_col=False, header= None, names =
['X','Y', 'Z','binnumber'],skip_blank_lines=True) 
Data = pd.DataFrame(Data)
d={}
for x in Data.X:
for y in Data.Y:
    for z in Data.Z:
        for bn in Data.binnumber:
            d[str(bn)]=[x,y,z]

所需的输出是

[[binnumber:[x,y,z],[x,y,z]],[binnumber:[x,y,z],[x,y,z],[x,y,z][ 
x,y,z]],......]

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这应该做:

InputTextLayout

答案 1 :(得分:0)

一种方法是通过collections.defaultdict

from collections import defaultdict

df['value'] = list(zip(df['x'], df['y'], df['z']))

d = defaultdict(list)

for idx, row in df.iterrows():
    d[row['binnumber']].append(row['value'])

# defaultdict(list,
#             {516: [(32618380.550000001,
#                5984467.6600000001,
#                -2.5699999999999998),
#               (32618380.539999999, 5984467.7300000004, -2.5699999999999998),
#               (32618380.52, 5984467.79, -2.5699999999999998),
#               (32618380.510000002, 5984467.8799999999, -2.5699999999999998),
#               (32618380.5, 5984467.9699999997, -2.5699999999999998)],
#              517: [(32618380.489999998,
#                5984468.0499999998,
#                -2.5699999999999998),
#               (32618380.48, 5984468.1399999997, -2.5699999999999998),
#               (32618380.460000001, 5984468.2300000004, -2.5699999999999998),
#               (32618380.449999999, 5984468.3200000003, -2.5699999999999998),
#               (32618380.440000001, 5984468.4100000001, -2.5699999999999998)]})