r/pythonhelp • • Aug 25 '26

Problem with Coolprop

2 Upvotes

Hi! i'm beginner, and I have a problem with this code, I guess that I installed the library correctly, but i'm not sure.

Error using stringsource>string.from_py.__pyx_convert_string_from_py_std__in_string (line 15)
Python Error: TypeError: expected bytes, NoneType found

Error in CoolProp/CoolProp.PropsSI (line 462)

Error in CoolProp/CoolProp.PropsSI (line 384)

Altough I don't have more than 106 lines


r/pythonhelp • • May 27 '26

Python Web Scraping & Automation Engineer Looking for Remote Work

2 Upvotes

Hi everyone,

I’m a Python Automation & Web Scraping Engineer with experience building large-scale scraping pipelines and automation systems for US-based clients.

Skills include:

• Selenium / Playwright

• APIs & data extraction

• Python automation

• ETL workflows

• Linux servers & cron jobs

• CSV/JSON/XLSX exports

Looking for remote freelance, contract, or long-term work related to web scraping, automation, or data engineering.

Feel free to DM me if you’re hiring or need help with a project.


r/pythonhelp • • May 14 '26

Hi im trying to get started and i have hit a snag

2 Upvotes

i need some help. so i don't know what did wrong i got python installed, i got pygame_ce installed but it seems something is wrong. the link is to a screenshot of me trying to use Sublime text i hope that helps https://cdn.discordapp.com/attachments/1115340096242204792/1504384590880444576/image.png?ex=6a06cad4&is=6a057954&hm=31d60171b7142ca179c312bba4652cb7137c385d37243e1cbc8a49591d30a7e7&


r/pythonhelp • • Apr 27 '26

How to add a string to a list, and then remove it if the string if it is not found in a second list

2 Upvotes

I'm pretty new to Python, and I'm trying to make a rudimentary "therapy chatbot" (something a little more in depth than Eliza, made more so as practice of simple concepts). I'm trying to have the user input an emotion, and then pop up with some text that it wasn't found in the majorEmotionTypes list, and then try again. I know my code is pretty far from what I want, but I'll be going back later to edit a few things.

The main issue is that it can't find 'i' in the majorEmotionTypes list. Any help would be deeply appreciated!

majorEmotionTypes = ["Sad", "Scared", "Mad", "Happy", "Disgusted", "Surprised"]
currentMajorEmotions = []
capCurrentMajorEmotions = []


for i in range(1, 3):
    currentMajorEmotions.append(input("Which of these emotions are you feeling?:
").capitalize())
    if i not in majorEmotionTypes:
        currentMajorEmotions.remove(i)
        print("Not a valid entry")
        currentMajorEmotions.append(input("Try again: ").capitalize())

r/pythonhelp • • Feb 09 '26

Google custom search API not working.

2 Upvotes

Hey guys, i am a student in india and pls forgive me for asking such dumb questions. i was making a website in python Flask, HTML CSS and i was using the Google Custom Search API key to give live data to My model. It was working perfectly but the next when i opened it suddenly i start getting error messages. The error message shows this: {

"error": {

"code": 403,

"message": "This project does not have the access to Custom Search JSON API.",

"errors": [

{

"message": "This project does not have the access to Custom Search JSON API.",

"domain": "global",

"reason": "forbidden"

}

],

"status": "PERMISSION_DENIED"

}

} But when i go to cloud console to check it shows that my API is enabled and has 1000 queries per day limit of which i have utilized 0.5%. There are no restrictions on my API too. My service account also has authorization. Even my search engine is enabled and has access to all sites. I doubled the check and matched the API keys too. I have selected the correct project also. Pls help me, i have to submit it tomrw. I have worked really hard on this. I dont know whats wrong.


r/pythonhelp • • Dec 31 '25

Internet Connection

2 Upvotes

Hello everyone im looking to get some assistance connecting my Python script to the internet but i keep getting an error saying "No Module named ' requests'" additionally im using Sublime Text if that is of any importance


r/pythonhelp • • Dec 30 '25

How can I sort a library's text format book database report for better efficiency?

2 Upvotes

Tl;dr: I work at a library and we run a daily report to know which books to pull off shelves; how can I sort this report better, which is a long text file?

----

I work at a library. The library uses a software called "SirsiDynix Symphony WorkFlows" for their book tracking, cataloguing, and circulation as well as patron check-outs and returns. Every morning, we run a report from the software that tells us which books have been put on hold by patrons the previous day and we then go around the library, physically pulling those books off the shelf to process and put on the hold shelf for patrons to pick up.

The process of fetching these books can take a very long time due to differences between how the report items are ordered and how the library collection is physically laid out in the building. The report sorts the books according to categories that are different than how they are on the shelves, resulting in a lot of back and forth running around and just a generally inefficient process. The software does not allow any adjustment of settings or parameters or sorting actions before the report is produced.

I am looking for a way to optimize this process by having the ability to sort the report in a better way. The trouble is that the software *only* lets us produce the report in text format, not spreadsheet format, and so I cannot sort it by section or genre, for example. There is no way in the software to customize the report output in any useful way. Essentially, I am hoping to reduce as much manual work as possible by finding a solution that will allow me to sort the report in some kind of software, or convert this text report into a spreadsheet with proper separation that I can then sort, or some other solution. Hopefully the solution is elegant and simple so that the less techy people here can easily use it and I won't have to face corporate resistance in implementing it. I am envisioning loading the report text file into some kind of bat file or something that spits it out nicely sorted. The report also requires some manual "clean up" that takes a bit of time that I would love to automate.

Below I will go into further details.

General

  • The software (SirsiDynix Symphony WorkFlows) generates a multi-page report in plain text format (the software does have an option to set it to produce a spreadsheet file but it does not work. IT's answer is that yes, this software is stupid, and that they have been waiting for the new software from headquarters to be implemented for 5 years already)

  • The report is opened in LibreOffice Writer to be cleaned up (no MS Office is available on the desktops). I have tried pasting it into librecalc (spreadsheet software) and playing around with how to have the text divided into the cells by separators but was not able to get it to work.

  • ‎The report is a list of multi-line entries, one entry per book. The entry lists things like item title, item ID (numerical), category, sub-category, type, etc. Some of these are on their own line, some of them share a line. Here is one entry from the report (for one book) as an example:

CON   Connolly, John, 1968-   The book of lost things / John Connolly      copy:1     item ID:################    type:BOOK        location:FICTION      Pickup library:"LIBRARY LOCATION CODE"                        Date of discharge:MM/DD/YYYY  
  • The report is printed off and stapled, then given to a staff member to begin the book fetching task

File Clean-Up

  • The report contains repeating multi-line headings (report title, date, etc) that repeat throughout the document approximately every 7 entries, and must be removed except for the very first one, because they will sometimes be inserted in the middle of an entry, cutting it into two pieces (I have taught my colleagues how to speed up this process somewhat using find and replace, but it is still not ideal. That's the extent of the optimization I have been able to bring in thus far)

  • Because of taking an unpaginated text file into a paginated word doc, essentially, some entries end up being partially bumped over to the next page, e.g. their first half is on page 1 and their second half is on page 2. This is also manually fixed using line breaks so that no entries are broken up.

  • Some entries are manually deleted if we know that a different department is going to be taking care of fetching those (eg. any young adult novels)

Physical Book Fetching

  • The library's fiction section has books that are labelled as general fiction and also books that are labelled with sub-categories such as "Fiction - Mystery", "Fiction - Romance" and "Fiction - SciFi". The report sorts these by category and then by author. That would be fine except that all of the fiction books are placed on the shelves all together in the fiction section, sorted by author. There is no separate physical mystery fiction section or romance fiction session. That means that a staff member goes through the shelves from A - Z, pulling off the books for general fiction, then having to go back to A again to pull the mystery books from the same section from A - Z, and back again for romance, etc etc. It would be wonderful if we could just sort by author and ignore the genre subcategories so that we could pull all of the books in one sweep. The more adept staff do look further through the report to try and pull all the books they can while they are physically at that shelf, but flipping through a multi-page report is still manual work that takes time and requires familiarity with the system that newer staff do not typically possess.

  • The library's layout is not the same as the order of the report. The report might show entries in the order "Kids section - Adult non-fiction - Young Adult fiction - Adult DVD's" - but these sections are not physically near each other in the library. That means a staff member is either going back and forth in the library if they were to follow the report, or they skip over parts of the report in order to go through the library in a more physically optimized manner, in the order that sections are physically arranged. The former requires more time and energy, and the latter requires familiarity with the library's layout, which newer staff do not yet possess, making training longer. It would be amazing if we could order the report in accordance to the layout of the library, so that a person simply needs to start at one end of the building and finish at the other.

Here is a link to an actual report (I have removed some details for privacy purposes). I have shortened it considerably while keeping the features that I have described above such as the interrupting headings and the section divisions.

We have no direct access to the database and there is no public API.

Our library does as much as possible to help out the community and make services and materials as accessible as possible, such as making memberships totally free of charge and removing late fines, so I am hoping someone is able to help us out! :)


r/pythonhelp • • Aug 24 '25

Question about Spiderfoot

2 Upvotes

Hello, I’m running SpiderFoot on Windows 11 with Python 3.13.5. I installed all dependencies (lxml, cherrypy, cherrypy-cors, cryptography, dnspython, netaddr, pyopenssl, publicsuffixlist, requests, urllib3, idna, certifi).When I run python sf.py -l 5001, the server doesn’t start and shows:ModuleNotFoundError: No module named 'networks'.netaddr is installed, and I’ve tried all pip installs, but the error persists. Any idea how to fix this on Windows 11?


r/pythonhelp • • Jun 04 '25

How can i print text with my printer in python

2 Upvotes

So i have a bluethoot Low energy printer its a gatson portable mini printer with bluethoot and the exact model name i think is: MXW01 i am trying to print text with it using python but it did not work i tried multiple ways and modules but did not find anything that works with the printer the app that the printer is using is called: Fun Print

I tried using python and nodejs and it could fetch the battery and printer status but printing anything just would not work is there someone that can try to make some code or module to let it work

I hope it will work soon with your help!


r/pythonhelp • • May 12 '25

How do I go about learning Python or starting to learn some type of coding

2 Upvotes

I have been wanting to learn how to cold for years now I'm finally free enough to start my adventure in doing so any advice or tips where to start I have a laptop


r/pythonhelp • • May 05 '25

Please improve my python code which is having retry logic for api rate limit

2 Upvotes
from google.cloud import asset_v1
from google.oauth2 import service_account
import pandas as pd
from googleapiclient.discovery import build
from datetime import datetime
import time

`
def get_iam_policies_for_projects(org_id):
        json_root = "results"
        projects_list = pd.DataFrame()
        credentials = service_account.Credentials.from_service_account_file("/home/mysa.json")
        service = build('cloudasset', 'v1', credentials=credentials)
        try:
            request = service.v1().searchAllIamPolicies(scope=org_id)
            data = request.execute()
            df = pd.json_normalize(data[json_root])
            for attempt in range(5):
                try:                                                                
                    while request is not None:
                        request = service.v1().searchAllIamPolicies_next(request, data)
                        if (request is None):
                            break
                        else:
                            data = request.execute()
                            df = pd.concat([df, pd.json_normalize(data[json_root])])
                    df['extract_date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    projects_list = pd.concat([projects_list, df])
                except Exception as e:
                    print(f"Attempt {attempt + 1} failed: {e}")
                    print("Retrying in 60 seconds...\n")
                    time.sleep(60)  # Fixed delay of 60 seconds    
        except KeyError:
            pass

        projects_list.rename(columns=lambda x: x.lower().replace('.', '_').replace('-', '_'), inplace=True)
        projects_list.reset_index(drop=True, inplace=True)
        return projects_list
iams_full_resource = get_iam_policies_for_projects("organizations/12356778899")
iams_full_resource.to_csv("output.csv", index=True)    
print(iams_full_resource)

i am keeping the attempts to retry the api call, which is the request.execute() line. It will call the api with the next page number/token. if the request is none(or next page token is not there it will break). If it hits the rate limit of the api it will come to the exception and attempt retry after 60 seconds.

Please help me in improving the retry section in a more pythonic way as I feel it is a conventional way


r/pythonhelp • • Apr 10 '25

Will Mimo alone teach me python?

2 Upvotes

I’m a total beginner right now and I’m using Mimo to learn how to code in Python because it’s the only free app I could find and I’m unsure whether to proceed using it or find another free app or website to teach me python 3


r/pythonhelp • • Apr 03 '25

on key press???

2 Upvotes

I'm trying to make a variable that is signed to whatever you press on the keyboard via on key press, however I can't get it to listen to every key instead of just 1 key, any help is appreciated


r/pythonhelp • • Mar 29 '25

How to deal with text files on an advanced level

2 Upvotes

Hello everyone i am currently trying to deal with text files and trying to use things like for loops and trying to find and extract certain key words from a text file and if any if those keywords were to be found then write something back in the text file and specify exactly where in the text file Everytime i try to look and find where i can do it the only thing i find is how to open,close and print a text file which is driving me insane


r/pythonhelp • • Jan 24 '25

Problem in odc-stac when reading geospacial satellite data

2 Upvotes

I ran into this error when trying to do this. Can anyone tell me what's wrong?

data = stac_load(
    items,
    bands=["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"],
    crs="EPSG:4326",  # Latitude-Longitude
    resolution=scale,  # Degrees
    chunks={"x": 2048, "y": 2048},
    dtype="uint16",
    patch_url=planetary_computer.sign,
    bbox=bounds
)
The error message says 
ValueError: The asset must have the following fields (from the projection extension): shape, transform, and one of an epsg, wkt2, or projjson

r/pythonhelp • • Jan 20 '25

SOLVED I'm not getting the right values

2 Upvotes

Hi,

Could anyone help me with this code? I'm a beginner and unable to understand why I am only getting output for 1 name in the list 'friends' but not the other.

No result for the name ''neha" in the list friends.

favourite_languages={
    'priya' : 'c',
    'ramesh' : 'c++',
    'neha' : 'python',
    'raju' : 'java',
    }
friends=['neha','raju']
for name in favourite_languages.keys():
    print (f"Hi {name.title()}")

if name in friends:
    language=favourite_languages[name].title()
    print (f"\t{name.title()}, I see you like {language}")

Output:
Hi Priya

Hi Ramesh

Hi Neha

Hi Raju

Raju, I see you like Java


r/pythonhelp • • Jan 20 '25

What should I do?

2 Upvotes

Hello everyone,

I some how formatted one of my drive on my windows computer in which i downloaded python , and now when i am trying to install it new drive it show the Modify Setup dialog box , but if try to uninstall , modify or repair it ends up with errors like 0x80070643 and 0x80070641. I already tried running it as an administrator and repairing my .NET Framework. What can i do to run Python again.


r/pythonhelp • • Jan 04 '25

Script for matching columns in multiple txt files vs a CSV file

2 Upvotes

I have this code (below), four txt files with either 23andMe or AncestryDNA data, and a CSV file with 21 million rows of gene mutations. The goal is to match chromosome and position of the txt files to the chromosome and position of the csv file. If they match, the script puts "found" in a new column labelled "Found". and copy the rsID from the txt file into the csv file in a column labelled rsID. I need it to use the text file as the file it uses to read and the csv file to use to find and add because the CSV file is so long. (What have I gotten myself into, I know). It may find the same chromosome+position up to three times, so it needs to keep checking until it hits the three times or it reaches the end of the CSV.

After it tries to find all the chromosome and position matches, it needs to delete all the rows of the CSV file that do not contain the word "found".

This is my header plus first row for the txt files:

rsid chromosome position allele1 allele2

rs369202065 1 569388 G G

This is my header plus first row of the CSV:

#CHROM,POS,REF,ALT,genome,uniprot_id,transcript_id,protein_variant,am_pathogenicity,am_class

12,8192694,T,A,hg19,Q9P0K8,ENST00000162391.3,L89H,1.0,pathogenic

This is my code (Note I have tried #CHROM and CHROM):

# -*- coding: utf-8 -*-

"""

Created on Sat Jan 4 13:25:47 2025

@author: hubba

"""

import pandas as pd

def process_dna_files(dna_files, csv_file, output_csv):

csv_data = pd.read_csv(csv_file, delimiter=",", comment="#") # Adjust delimiter and handle comments

csv_data.columns = csv_data.columns.str.lstrip("#")

for dna_file in dna_files:

# Locate the start of the data in the DNA file

with open(dna_file, 'r') as f:

lines = f.readlines()

start_line = 0

for i, line in enumerate(lines):

if line.strip().startswith("rsid"):

start_line = i

break

dna_data = pd.read_csv(dna_file, delimiter="\t", skiprows=start_line, low_memory=False)

csv_data["Found"] = False

csv_data["rsID"] = ""

for _, dna_row in dna_data.iterrows():

# Extract chromosome and position

chromosome = dna_row["chromosome"]

position = dna_row["position"]

matches = csv_data[(csv_data["#CHROM"] == chromosome) & (csv_data["POS"] == position)]

for index in matches.index:

csv_data.at[index, "Found"] = True

csv_data.at[index, "rsID"] = dna_row["rsid"]

csv_data = csv_data[csv_data["Found"] == True]

csv_data.to_csv(output_csv, index=False, sep=",")

print(f"Updated CSV saved to: {output_csv}")

dna_files = ["Example1.txt", "Example2.txt", "Example3.txt", "Example4.txt", "Example5.txt", "Example6.txt"]

csv_file = "GeneticMutations.csv"

output_csv = "GeneticMutationsplusRSID.csv"

process_dna_files(dna_files, csv_file, output_csv)

Here is the error message I am getting:

%runfile C:/Users/hubba/OneDrive/Desktop/untitled12.py --wdir

Traceback (most recent call last):

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\indexes\base.py:3805 in get_loc

return self._engine.get_loc(casted_key)

File index.pyx:167 in pandas._libs.index.IndexEngine.get_loc

File index.pyx:196 in pandas._libs.index.IndexEngine.get_loc

File pandas\_libs\\hashtable_class_helper.pxi:7081 in pandas._libs.hashtable.PyObjectHashTable.get_item

File pandas\_libs\\hashtable_class_helper.pxi:7089 in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '#CHROM'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\spyder_kernels\customize\utils.py:209 in exec_encapsulate_locals

exec_fun(compile(code_ast, filename, "exec"), globals)

File c:\users\hubba\onedrive\desktop\untitled12.py:67

process_dna_files(dna_files, csv_file, output_csv)

File c:\users\hubba\onedrive\desktop\untitled12.py:47 in process_dna_files

matches = csv_data[(csv_data["#CHROM"] == chromosome) & (csv_data["POS"] == position)]

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\frame.py:4102 in __getitem__

indexer = self.columns.get_loc(key)

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\indexes\base.py:3812 in get_loc

raise KeyError(key) from err

KeyError: '#CHROM'

If it matters, Im using Spyder

What am I doing wrong???? Im losing my mind lol


r/pythonhelp • • Dec 20 '24

i cant install curses

2 Upvotes

it installed pygame but when i tried to install curses it said "Defaulting to user installation because normal site-packages is not writeable

ERROR: Could not find a version that satisfies the requirement windows-curses (from versions: none) ERROR: No matching distribution found for windows-curses"


r/pythonhelp • • Nov 26 '24

How would I go about optimizing this code?

2 Upvotes

I'm making a basic currency exchange tool and would like to know how to optimize this code if possible. "win" is just a way I went about detecting if the user actually exchanged the currency.

rate = 0
win = False
in_europe = ["Austria", "Belgium", "Croatia", "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "The Netherlands", "Portugal", "Slovakia", "Slovenia", "Spain"]
while True:
    cur = input("USD to what currency? (name of county): ")
    if cur.lower() == "canada":
        rate = 1.41
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == .4:
            added = "0"
        elif value_check < .4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.title() in in_europe:
        rate = 0.96
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.lower() == "japan":
        rate = 154.08
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.lower() == "mexico":
        rate = 20.61
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.lower() == "cuba":
        rate = 24.06
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.lower() == "russia":
        rate = 104
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    elif cur.lower() == "switzerland":
        rate = 0.89
        amnt = float(input("Amount of USD? (no dollar sign): "))
        amnt *= rate
        amnt = round(amnt, 2)
        value_check = len(str(amnt))
        if value_check == 4:
            added = "0"
        elif value_check < 4:
            added = "00"
        else:
            added = ""
        print("You have $" + str(amnt) + added + " USD in " + cur.title())
        win = True
    else:
        print("Invalid!")
        True
    if win == True:
        again = input("More? (y / n): ")
        if again == "n":
            break
        else:
            True
    else:
        True

r/pythonhelp • • Oct 27 '24

Python script to read FPS

2 Upvotes

Is there anyone out there that is familiar with afterburner/RTSS that can help me. I have been trying for days to come up with a script that will grab my FPS value from shared memory and send it to my project. no matter what I do it get either 0 or the wrong values. I have thrown it through all the AI's available, but it cant find the correct value and i am at a dead end. any help would be appreciated. I get the correct values on my Overlay in games and in afterburner, RivaTunerStatisticServer, so i know there is a way to extract the value, but I just cant get it to cooperate. here is a pastebin of code

https://pastebin.com/BgxMW1Ct


r/pythonhelp • • Oct 15 '24

matplotlib boxplot and barplot not aligned

2 Upvotes

Hi,

I'm trying to plot a data set using boxplots. I want to label the mean of each category and the least-effort way I found was using a bar plot, using pyplot.bar_label() and ploting a boxplot on top. Unfortunatly, my plots don't align on their categories. Do you have any idea what's going on?

Here are my bar plot, boxplot and the combined plot : https://youtu.be/JoEuFSIH9s0 (I'm not allowed pictures, for some reason)

Here is my code for plotting :

    # I have df1, a DataFrame containing the mean Exam_Score for each category
    #   and df2, a DataFrame containing the category of each individual in the first 
    #   column and its Exam_Score in the second one

    # Plotting the bar plot
    # Ordering the categories
    categories_set = set(df1.index)
    categories = ["Male","Female"]  # This is used to order the categories

    # Order the values of Exam_Score in the same order as categories
    values = []
    for i in range(len(categories)):
        values.append(df1.iat[df1.index.tolist().index(categories[i]),0])

    # Plot bar plot
    ax = plt.bar(categories,values)
    plt.bar_label(ax)  # Add mean value labels
    
    # Plotting the boxplot
    # Make a 2D array of which each column only contains values of a certain category
    #  and which has the same column order as categories[]
    plots = []
    for i in range(len(categories)):
        plots.append(df2[df2[df2.columns[0]] == categories[i]][df2.columns[1]])

    # Plot boxplot
    ax = plt.boxplot(plots, tick_labels=categories)

    # Configure appearance
    plt.title(name) # name is declared earlier
    plt.xticks(rotation=45)
    plt.gca().set_ylim(ymin = 50)
    plt.grid()
    plt.show()

P.S. I know there are other ways to acheive what I want, but I'm not very used to working with matplotlib or python and this is for an issagnement due in a short time, so I don't hav time to dive deep in configuration functions. And besides, it would still be very helpful to know why theses don't align.


r/pythonhelp • • Oct 01 '24

What's Your Biggest Challenge or Frustration with Writing Tests and Pytest?

2 Upvotes

When it comes to writing tests and Pytest, what's your biggest challenge or frustration?


r/pythonhelp • • Sep 16 '24

Win5 - Access Denied

2 Upvotes

Feels Like from my searching this is a older issue. Anyway was running a bot script through python/tesseract which worked fine previously and now I'm being hit by the Win5 rubbish. As a novice experienced python user I have researched for last two days and attempted a few of the fixes which none seemed to help.

Running in

C:\WINDOWS\System32\cmd.exe

" PermissionError: [WinError 5] Access is denied scan complete"

C:\Users\Lenova66\Desktop\Tracker>Pause

Press any key to continue...

This bot is using ABS > Python subprocesses.py > Tesseract (pytesseract)

It's a player point tracker to keep track of kills deaths using bluestacks 5, and all settings within bluestacks are as required. No other file changes or program changes from last time it ran fine till now. Like mention, the Windows update is the only thing that MAYBE triggered something... to others, this exact bot within Python is working. So whatever occurred from last use till now has triggered it. If I over explained the situation, I apologize. Trying explain as much as I can due to being unable upload an image no other line in the script appears to be triggering a issue once can upload image I will.

-Thanks in advance

.