使用每个值2个键将csv读入字典,并将第一个非零数字分配给字典值

时间:2020-02-26 20:24:25

标签: python pandas csv dictionary

我想将csv读入字典,其密钥为wellID,月份为1-12,其值为数据中的第一个非零值。我的输出仅捕获数据集中的第二个月(12):

 'Month': {},
 'MUN-1': {12.0: -292.1183432},
 'MUN-42': {12.0: -3566.994083},
 'MUN-57': {},

我的数据如下: enter image description here

df2 = pd.read_csv('wells.csv')
rows = df2.apply(lambda x: x.tolist(), axis=1)

lst = []
for i in rows:
    lst.append(i)

N=1
wellID = {words[0]:words[1:] for words in lst}

names = []
for i in wellID.keys():
    names.append(i)

namesdict = dict()
for name in names:
    namesdict[name]=dict()


timeseries=dict()
dict(itertools.islice(namesdict.items(),N))
idx=0
for month in wellID["Month"]:
    for well in wellID.keys():
        timeseries[well]=dict()
        if wellID[well][idx]<0:
            currentMonth=wellID["Month"][idx]
            timeseries[well][currentMonth]=dict()
            if currentMonth not in timeseries.keys():
                timeseries[well][currentMonth]=wellID[well][idx]
        idx=+1  

1 个答案:

答案 0 :(得分:0)

order = list(map(int, list(df2)[1:]))
answer = {}
for month in wellID.keys():
    index = next((i for i, x in enumerate(wellID[month]) if x), None)
    i = order[index]
    value = wellID[month][index]
    answer[month] = {index: value}

尝试用此替换最后一个for循环!