logo
down
shadow

KeyError When I want try to plot


KeyError When I want try to plot

By : Shannon
Date : November 19 2020, 03:01 PM
To fix this issue I get an error whenever I try to perform actions on U objects. I always get a KeyError. I have tried many times to plot U (last statement.) , You want to use as_index=False in the groupby (or reset_index after):
code :
In [11]: df = pd.DataFrame([[1, 2], [1, 3], [2, 4]], columns=["A", "B"])

In [12]: df
Out[12]:
   A  B
0  1  2
1  1  3
2  2  4

In [13]: df.groupby("A").count()
Out[13]:
   B
A
1  2
2  1

In [14]: df.groupby("A", as_index=False).count()
Out[14]:
   A  B
0  1  2
1  2  1


Share : facebook icon twitter icon
KeyError when using for loop on dataframe to plot histograms

KeyError when using for loop on dataframe to plot histograms


By : CodeHunter24
Date : March 29 2020, 07:55 AM
may help you . I have a dataframe similar to: , Essentially you have two square brackets too much in your code.
code :
plt.hist([series])  # <- wrong
plt.hist(series)    # <- correct
for date in df.Date.unique(): 
    plt.hist(df[df.Date == '%s' %(date)]['Count'])
    plt.title('%s' %(date))
df.hist(by="Date")
KeyError while trying to plot a pandas pivot_table

KeyError while trying to plot a pandas pivot_table


By : J. Knee
Date : March 29 2020, 07:55 AM
should help you out I build a pivot_table out of a dataframe to get numbers distribution between years across states: , Why don't you transpose it?:
code :
data_table_years.T.plot()
Pandas df.plot() KeyError Thrown

Pandas df.plot() KeyError Thrown


By : user1864335
Date : March 29 2020, 07:55 AM
like below fixes the issue BIG EDIT: This error will not throw if I remove index_col = 1 from the read_csv function. Leaving this question up because I am curious why this happens.
code :
data = {'Agency': {0: 'NYPD', 1: 'NYPD', 2: 'NYPD', 3: 'NYPD'},
        'Division': {0: 'OPERATIONS',
                     1: 'EXECUTIVE MANAGEMENT',
                     2: 'SCHOOL SAFETY',
                     3: 'ADMINISTRATION-PERSONNEL'},
        'Expenditures ($000,000)': {0: 3331.0, 1: 489.4, 2: 279.6, 3: 263.9}}

df = pd.DataFrame.from_dict(data)

plt.figure(figsize=(10, 10))
plt.plot(df['Division'], df['Expenditures ($000,000)'])
plt.xticks(rotation='30')
plt.xlabel('NYPD Division')
plt.show()
df.plot('Division', 'Expenditures ($000,000)')
df.plot(x='Division', y='Expenditures ($000,000)')
df.plot(x=df['Division'], y=['Expenditures ($000,000)'])
df = pd.read_csv('Book1.csv', index_col=1)

df = 
                          Agency    Expenditures ($000,000)
Division        
OPERATIONS                  NYPD                     3331.0
EXECUTIVE MANAGEMENT        NYPD                      489.4
SCHOOL SAFETY               NYPD                      279.6
ADMINISTRATION-PERSONNEL    NYPD                      263.9
df.plot()
KeyError when attempting to plot METAR

KeyError when attempting to plot METAR


By : user3263502
Date : March 29 2020, 07:55 AM
should help you out The issue here is how the netCDF is written. It comes in the discrete sampling geometry (DSG) format, which is different than the typical gridded format. As a result, the mask computed here is only valid for the Lat and Long variables. For the data variables, a new mask has to be computed, based on the valid stations that remain after the initial mask is calculated. The following code adapts the original code to demonstrate this full process. Note that the loop is slow, and maybe could be refactored.
code :
metarfile = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/'
                       'nws/metar/ncdecoded/files/latest.xml')
latestmetar = metarfile.datasets[0]

file = latestmetar.remote_access(use_xarray=True)

parsed_temp = file.metpy.parse_cf('air_temperature')
parsed_td = file.metpy.parse_cf('dew_point_temperature')
parsed_mslp = file.metpy.parse_cf('air_pressure_at_sea_level')

parsed_temp = parsed_temp * 9/5 + 32
parsed_td = parsed_td * 9/5 + 32

prj = ccrs.LambertConformal(central_latitude=35,
                            central_longitude=-98,
                            standard_parallels=(30, 60))

points = prj.transform_points(ccrs.PlateCarree(), file['longitude'].values,
                                                  file['latitude'].values)

points[2477, 0:2] = [0,0]
mask = mpcalc.reduce_point_density(points, 100000)

mask_stations = []
for x in file['parent_index'].values:
    if x in file['station'][mask]:
        mask_stations.append(True)
    else:
        mask_stations.append(False)

fig = plt.figure(1, figsize=(10,10))
ax = fig.add_subplot(1, 1, 1, projection=prj)

ax.set_extent((-104.1, -95.5, 32.1, 39.1))

ax.add_feature(cfeature.STATES.with_scale('50m'),linewidth=.5,
                                                 edgecolor='black',
                                                 zorder=5)

metarplots = StationPlot(ax, file['longitude'].values[mask], file['latitude'].values[mask],
                             clip_on=True, transform=ccrs.PlateCarree(),
                             fontsize=12)

metarplots.plot_parameter('NW', file['air_temperature'][mask_stations].metpy.convert_units('degF'), color='red')
metarplots.plot_parameter('SW', file['dew_point_temperature'][mask_stations], color='green')
metarplots.plot_parameter('NE', file['air_pressure_at_sea_level'][mask_stations],
                                color='blue')
I get a KeyError when trying to plot these group of dataframes with Pandas

I get a KeyError when trying to plot these group of dataframes with Pandas


By : user3293003
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further The below solution works, it basically adds two things to your solution
a) Skip the first row from excel b) Rename the column names for df2 and df3
code :
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_excel('neurospheress.xlsx', sep='\s*,\s*', sheet_name = 'LS',skiprows=1)

df1 = data.iloc[:80,:2]
df2 = data.iloc[:80,2:4]
df3 = data.iloc[:80,4:]
dfs = [df1,df2,df3]

df2.rename(columns={'Force.1':'Force','Displacement.1':'Displacement'},inplace=True)
df3.rename(columns={'Force.2':'Force','Displacement.2':'Displacement'},inplace=True)

print(data.columns)
print(df1.columns)
print(df2.columns)

for i,df in enumerate(dfs):
    plt.plot(df['Displacement'], df['Force'], linestyle='--', alpha= 0.8, label='df{}'.format(i))
plt.legend(loc='best')
plt.show()
Related Posts Related Posts :
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • tkinter: assigning multiple functions to one button
  • flask-jwt-extended: Fake Authorization Header during testing (pytest)
  • Setting pandas dataframe value based on row and column conditions
  • swig char ** as a pointer to a char *
  • Confusion over `a` and `b` attributes from scipy.stats.uniform
  • How can I do groupy.apply() without sort my index?
  • Querying Google Cloud datastore with ancestor not returning anything
  • Read value from one thread in Python: queue or global variable?
  • Django - context process query being repeated 102 times
  • Convert a list of images and labels to np array to train tensorflow
  • Lambda not supporting NLTK file size
  • Numpy ndarray image pixel mean for pixel values greater than zero: Normalizing image
  • Understanding output of np.corrcoef for two matrices of different sizes
  • Finding longest perfect match between two strings
  • what is wrong with my cosine similarity? Tensorflow
  • How to manage user content in django?
  • Receiving unsupported operand error while comparing random number and user input.
  • How to wrap the process of creating start_urls in scrapy?
  • How to mark 'duplicated sequence' in pandas?
  • Boolean indexing on multidimensionnal array
  • Unmodified column name index in patsy
  • Cleaner way to unpack nested dictionaries
  • Importing a python module to enable a script to be run from command line
  • Maya Python read and set optionMenu value via variable
  • How can I bind a property to another property in Kivy?
  • Python extracting specific line in text file
  • How to implement n-body simulation with pymunk?
  • Python / matplotlib: print to resolution and without white space / borders / margins
  • Sum up the second value from one dictionary with all values from another dictionary
  • Robot Framework: Open a chrome browser without launching URL
  • Generate inline Bokeh scatterplots in Jupyter using a for loop
  • Group list of dictionaries python
  • Efficient way to apply multiple Boolean mask to set values in a column using pandas
  • Lazy evaluation of a Python dictionary
  • id of xpath is getting changed every time in selenium python 2.7 chrome
  • Matplotlib RuntimeWarning displaying a 3D plot
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org