熊猫中数据帧的for循环中的KeyError

问题描述 投票:2回答:2

我正在将数据放入热图的bokeh布局中,但收到KeyError:'1'。它恰好发生在num_calls = pivot_table[m][y]行上,有人知道为什么会这样吗?

我正在使用的数据透视表如下:

pivot_table.head()
Out[101]: 
Month                            1    2    3    4    5    6    7    8    9   CompanyName                                                                   
Company 1                 182  270  278  314  180  152  110  127  129   
Company 2           163  147  192  142  186  231  214  130  112   
Company 3       126   88   99  139   97   97   96   37   79   
Company 4   84   89   71   95   80   89   83   88  104   
Company 5       91   96   94   66   81   77   87   83   68   

Month                            10   11   12  
CompanyName                                    
Company 1               117  127   81  
Company 2            117   93  101  
Company 3       116  111   95  
Company 4   93   78   64  
Company 5        83   95   65  

下面是导致错误的代码部分:

pivot_table = pivot_table.reset_index()
pivot_table['CompanyName'] = [str(x) for x in pivot_table['CompanyName']]
Companies = list(pivot_table['CompanyName'])
months = ["1","2","3","4","5","6","7","8","9","10","11","12"]
pivot_table = pivot_table.set_index('CompanyName')

# this is the colormap from the original plot
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce",
    "#ddb7b1", "#cc7878", "#933b41", "#550b1d" ]

# Set up the data for plotting. We will need to have values for every
# pair of year/month names. Map the rate to a color.
month = []
company = []
color = []
rate = []
for y in Companies:
    for m in months:
        month.append(m)
        company.append(y)
        num_calls = pivot_table[m][y]
        rate.append(num_calls)
        color.append(colors[min(int(num_calls)-2, 8)])

并且根据要求:

pivot_table.info()
<class 'pandas.core.frame.DataFrame'>
Index: 46 entries, Company1 to LastCompany
Data columns (total 12 columns):
1.0     46 non-null float64
2.0     46 non-null float64
3.0     46 non-null float64
4.0     46 non-null float64
5.0     46 non-null float64
6.0     46 non-null float64
7.0     46 non-null float64
8.0     46 non-null float64
9.0     46 non-null float64
10.0    46 non-null float64
11.0    46 non-null float64
12.0    46 non-null float64
dtypes: float64(12)
memory usage: 4.5+ KB

pivot_table.columns
Out[103]: Index([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0], dtype='object')

也是bokeh码在这里:http://docs.bokeh.org/en/latest/docs/gallery/unemployment.html

python for-loop pandas dataframe keyerror
2个回答
1
投票

我已经尝试以下代码,并且可以在我的PC上使用。我使用.loc的目的是避免潜在的键错误。

import pandas as pd
import numpy as np

# just following your previous post to simulate your data
np.random.seed(0)
dates = np.random.choice(pd.date_range('2015-01-01 00:00:00', '2015-06-30 00:00:00', freq='1h'), 10000)
company = np.random.choice(['company' + x for x in '1 2 3 4 5'.split()], 10000)
df = pd.DataFrame(dict(recvd_dttm=dates, CompanyName=company)).set_index('recvd_dttm').sort_index()
df['C'] = 1
df.columns = ['CompanyName', '']
result = df.groupby([lambda idx: idx.month, 'CompanyName']).agg({df.columns[1]: sum}).reset_index()
result.columns = ['Month', 'CompanyName', 'counts']
pivot_table = result.pivot(index='CompanyName', columns='Month', values='counts')




colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce",
    "#ddb7b1", "#cc7878", "#933b41", "#550b1d" ]

month = []
company = []
color = []
rate = []
for y in pivot_table.index:
    for m in pivot_table.columns:
        month.append(m)
        company.append(y)
        num_calls = pivot_table.loc[y, m]
        rate.append(num_calls)
        color.append(colors[min(int(num_calls)-2, 8)])

1
投票

尝试将循环更改为

for m in pivot_table.columns:

似乎您可以实现相同的功能,而无需任何循环。您正在遍历行索引和列索引以分别访问每个条目并将它们附加到列表中,因此rate只是数据框中所有元素的列表。您可以通过

来实现
rate= pivot_table.stack().astype(int).tolist()
color = [colours[min(x - 2, 8)] for x in rate]

我在这里想念东西吗?

© www.soinside.com 2019 - 2024. All rights reserved.