本文介绍了ValueError:在 pandas 数据框上使用itertuples()时,解包的值太多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据我在这里找到的答案,尝试将简单的pandas数据框转换为嵌套的JSON文件:

I am trying to convert a simple pandas dataframe into a nested JSON file based on the answer I found here: pandas groupby to nested json

我分组的数据框如下所示:

My grouped dataframe looks like this:

                  firstname lastname  orgname         phone        mobile  email
teamname members
1        0            John      Doe     Anon  916-555-1234          none   [email protected]
         1            Jane      Doe     Anon  916-555-4321  916-555-7890   [email protected]
2        0          Mickey    Moose  Moosers  916-555-0000  916-555-1111   [email protected]
         1           Minny    Moose  Moosers  916-555-2222          none   [email protected]

我的代码是:

data = pandas.read_excel(inputExcel, sheetname = 'Sheet1', encoding = 'utf8')
grouped = data.groupby(['teamname', 'members']).first()

results = defaultdict(lambda: defaultdict(dict))

for index, value in grouped.itertuples():
    for i, key in enumerate(index):
        if i ==0:
            nested = results[key]
        elif i == len(index) -1:
            nested[key] = value
        else:
            nested = nested[key]

print json.dumps(results, indent = 4)

在第一个"for"循环中出现以下错误.在这种情况下是什么导致此错误?如何修复该错误以输出嵌套的json?

I get the following error on the first "for" loop. What causes this error in this circumstance and what would it take to fix it to output the nested json?

    for index, value in grouped.itertuples():
ValueError: too many values to unpack

推荐答案

使用 itertuples() ,该索引作为元组的一部分包含在内,因此for index, value in grouped.itertuples():并没有任何意义.实际上,itertuples()使用 namedtuple 和是名字之一.

When using itertuples(), the index is included as part of the tuple, so the for index, value in grouped.itertuples(): doesn't really make sense. In fact, itertuples() uses namedtuple with Index being one of the names.

请考虑以下设置:

data = {'A': list('aabbc'), 'B': [0, 1, 0, 1, 0], 'C': list('vwxyz'), 'D': range(5,10)}
df = pd.DataFrame(data).set_index(['A', 'B'])

产生以下数据框:

     C  D
A B
a 0  v  5
  1  w  6
b 0  x  7
  1  y  8
c 0  z  9

然后在df.itertuples()中打印每个元组将产生:

Then printing each tuple in df.itertuples() yields:

Pandas(Index=('a', 0), C='v', D=5)
Pandas(Index=('a', 1), C='w', D=6)
Pandas(Index=('b', 0), C='x', D=7)
Pandas(Index=('b', 1), C='y', D=8)
Pandas(Index=('c', 0), C='z', D=9)

因此,您可能想做的事情类似于下面的代码,将value替换为t[1:]:

So, what you'll probably want to do is something like the code below, with value being replaced by t[1:]:

for t in grouped.itertuples():
    for i, key in enumerate(t.Index):
        ...

如果要访问namedtuple的组件,则可以按位置或按名称访问内容.因此,对于您的DataFrame,t[1]t.firstname应该等效.请记住,t[0]是索引,所以第一列从1开始.

If you want to access components of the namedtuple, you can access things positionally, or by name. So, in the case of your DataFrame, t[1] and t.firstname should be equivalent. Just remember that t[0] is the index, so your first column starts at 1.

这篇关于ValueError:在 pandas 数据框上使用itertuples()时,解包的值太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 03:03