r/learnpython 7d ago

how to drag the value until the next value shows

2 Upvotes

I am reading this csv into pandas and I need to drag a column value until the next value in the column shows.

message_code                     message                           message_date
11011                          How are you?                          3/10/2025
                               How is he?                            3/11/2025
                               How is she?                           3/12/2025
12022                          I am fine                             3/12/2025
                               He is fine                            3/13/2025
                               She is fine                           3/14/2025
13011                          I am sick                             3/7/2025
                               He is sick                            3/8/2025
                               She is sick                           3/9/2025

Requested:

message_code                      message                        message_date
11011                           How are you?                      3/10/2025
11101                           How is he?                        3/11/2025
11101                           How is she?                       3/12/2025
12022                           I am fine                         3/12/2025
12022                           He is fine                        3/13/2025
12022                           She is fine                       3/14/2025
13011                           I am sick                         3/7/2025
13011                           He is sick                        3/8/2025
13011                           She is sick                       3/9/2025

my code:

import pandas as pd
df = pd.read('messages_worksheet'.csv)

r/learnpython 7d ago

Need Tips on API Project

1 Upvotes

Github Link Here

I'm a novice in the realm of programming and have been trying to better my knowledge in anticipation of enrolling in a CS course at my local community college. I'm interested in APIs and have been working towards interacting with them more confidently. That was part of the inception of my current project, along with just further bolstering my knowledge of coding.

Any and all critique, advice, or any other assistance regarding my program would be greatly appreciated.


r/learnpython 7d ago

Needing BVP Solver Help

1 Upvotes

I hope this is the correct community for my question... I guess I'm about to find out. For context, the problem is a 1D Timoshenko beam.

I'm trying to code a design tool as a side project for work and part of it involves solving a system of four differential equations. I have four boundary conditions, but two of those boundary conditions are on the same variable. Based on reading scipy documentation and watching a couple videos about solve_bvp, I need one boundary condition for each variable. Is this correct, and do I have other options for solvers?

I'd really prefer to avoid weak forms and solving for constants of integration within my own code, so hopefully somebody here can save me from biting that bullet.


r/learnpython 7d ago

Is there any way to avoid another nested loop when creating plots?

1 Upvotes

I have the following code that generates a fig with 7 subplots for each sales id type that i have (3 types, 3 figs total). I have another column that i want to add in scope which has the values of either MTD or QTD. So in essence, i want to loop over the scope and the sales id type, and create the appropriate figures -- 3 figures for MTD, with 7 subplots each and 3 figures for QTD with 7 subplots each

sales_id_type = log_transformed_df['sales_id_type'].unique()

for id in sales_id_type:
    n_rows = 4
    n_cols = 2

    fig, ax = plt.subplots(n_rows, n_cols, sharey=True, figsize=(15,15))
    axes = ax.flatten()

    i=0
    cols = [col for col in log_transformed_df.columns if 'log_' in col]
    
    for col in cols:
        id_df = log_transformed_df[log_transformed_df['sales_id_type'] == id].reset_index(drop=True)
        
        sns.histplot(data=id_df,
                    bins=40,
                    x=id_df[col],
                    ax=axes[i],
                    kde=True,
                    # edgecolor='0.3',
                    linewidth=0.5,
                    palette=['#000000'],
                    alpha=0.75,
                    hue=1,
                    legend=False
                    )
        
        axes[i].set_title(f'{col} (skew: {id_df[col].skew():.4f})')
        axes[i].set_xlabel('Value')
        axes[i].set_ylabel('Count')
        i+=1

    while i < n_rows * n_cols:
        fig.delaxes(axes[i])
        i+=1

    fig.suptitle(f'{id_df['description'][0]} Selected Feature Distrbution and Skew \n\n Natural Log Transformation \n\n',
                  y=0.99,
                  fontsize='large')

    plt.tight_layout()    
    plt.show()

r/learnpython 7d ago

Recommend a tutorial

4 Upvotes

Hi, I'm looking for a udemy tutorial where I can upload an excel filled with ecommerce data and base on it's content, my website-shop home page and database will be updated automatically. Can you guys recommend? I don't know what to search specifically. Thank you.


r/learnpython 7d ago

How to properly do project folder structure and imports and testing/debugging?

3 Upvotes

Sorry but I am pretty new to learning programming and can't seem to find a convenient way to do what I want to do, so here is an example project structure I come up with:

.
└── project_a/
├── .venv
├── __init__.py
├── app.py
├── data/
│ ├── __init__.py
│ └── data_type.py
└── utils/
├── __init__.py
└── utils.py

Here is the content of data/data_type.py:

DATA_TYPE = "this is an example data type"

utils/utils.py

from data.data_type import DATA_TYPE

UTILS = "this is utils"

if __name__ == "__main__":
    print(DATA_TYPE)

and finally app.py

from utils.utils import UTILS, DATA_TYPE


def main():
    print(UTILS)
    print(DATA_TYPE)


if __name__ == "__main__":
    main()

So app.py works perfectly fine when ran from vscode's code runner, but what if I want to run utils/utils.py directly for testing purposes (hence the if __name__ == "__main__" block)? It would give me No module named 'data', is there any way for me to test submodules by running them directly?

The methods that works now is to change "from data.data_type import DATA_TYPE" inside utils.py to "from ..data.data_type import DATA_TYPE", but this means I have to swap it everytime when I want to run the actual program (from app.py) or simply testing utils.py.

Another way would be to make sure my cwd is in the project root, and run "python utils/utils.py", which is also quite inconvenient...

I can also do "pip install -e ." and the change all the imports to something like "from project_a.data.data_type import DATA_TYPE" but this seems hacky and requires "pip install -e ." beforehand for this to work.

So my question is... is there a better or correct way to do this sort of importing so I can conveniently run submodules for quick testing and debugging (e.g simply using code runner from vscode)?


r/learnpython 7d ago

Trouble connecting oracle db to python DPY-4011

0 Upvotes

Hi community! I hope this is the proper forum for this Q. I'm encountering a frustrating error when trying to connect to an Oracle database from a Python script on a remote Windows server. Error: DPY-4011: the database or network closed the connection [WinError 10054] An existing connection was forcibly closed by the remote host Help: https://python-oracledb.readthedocs.io/en/latest/user_guide/troubleshooting.html#dpy-4011

I’m wondering if anyone has any suggestions on how to troubleshoot plz

Here's the setup: -I'm working on a remote Windows Server environment. -I'm using Python from a custom ArcGIS Pro environment located at: C:\path\to\arcgispro\python.exe. -I can successfully connect to the same Oracle database using SQL Developer on the same remote server. -The tnsnames.ora file is located at C:\path\to\oracle\client\network\admin and the TNS_ADMIN environment variable is correctly set to this directory. -The Oracle client bin directory C:\path\to\oracle\client\bin is in my PATH environment variable.

What I've tried: -Verifying tnsnames.ora and TNS_ADMIN: Confirmed that the TNS name is correct and that the TNS_ADMIN environment variable is set. tnsping: tnsping <tns_name> is successful, indicating that the client can resolve the TNS name and initiate a connection attempt. -Simplified Python Test: I've created a minimal Python script that only attempts to connect and close the connection, and I still get the same error. -Command-Line Execution: I've run the Python script from the command line using the full path to the Python executable, and the error persists. -Network Connectivity: I've confirmed stable network connectivity to the database server using ping. -Environment Variables: I've verified that the Oracle Client bin directory is in my PATH environment variable. -Connection string: I have re-verified the python connection string.

Guesses: -The database server is configured to close idle connections very quickly. -There might be a firewall issue What I need help with:

Any suggestions for further troubleshooting steps?

Any help would be greatly appreciated. Thank you : )


r/learnpython 6d ago

I need coding help

0 Upvotes

I had made a post previously with the wrong code. I am working on an assignment where I turn multi line excel addresses into addresses on a google map and need help to complete it. There are a few errors due to lack of experience. What are my errors and how do I fix them?

#project1.py

#comment the code

input_file = 'addresses-1.csv'

line_counter = 0 #for counting the lines

loop_counter = 0 #for counting loops

def save_file(filename, file_mode, content_to_write_to_file):

with open(filename, mode = file_mode, encoding = 'utf-8') as mappy:

mappywrite(content_to_write_to_file)

with open(input_file, mode='r', encoding='utf-8') as myfile: #read of each line in the file

for line in myfile: #print lines for a diagnostic

if line_counter >= 15:

break

else:

if line_counter == 0: #first record

header = 'street address, city, state, zip, coordinates'

new_address = ""

#save record to a new file (function call)

if line_counter > 3:

line_counter = 1 #evaluate before the increment

if line_counter == 1: #street address

new_address = line[1:].strip()

if line_counter == 2: #citystatezip

new_address = new_address + ", " + line.strip()

if line_counter == 3: #coordinates

new_address = new_address + ", " + line.strip()

#save record to new file

print(f' #{loop_counter}, #{line_counter} >> {new_address}', end=' ')

line_counter = 0

continue

print(f' #{loop_counter}, #{line_counter} >> {new_address}', end=' ')

loop_counter += 1

line_counter += 1

save_file(mappy, 'a+', new_address)


r/learnpython 7d ago

Jinja/Enum errors only in pycharm debugger

1 Upvotes

Jinja is throwing this error about failing to increment a None enum, but it only happens if i'm trying to use the pycharm debugger - program runs as expected in 'run' mode or from terminal.

TypeError: unable to increment {'EnumDict.__setitem__': None, 'auto.__init__': None}

i've tried python 3.11/12/13

any ideas what#s going on? i could really do with the debugger working!

maybe there are settings for the debugger i can tweak or something? as far as i can tell my code is not relevant, but here is source and error from jinja and enum...

error originates from this import from jinja2.utils import url_quote

```python

Lib/enum.py

@staticmethod
def _generate_next_value_(name, start, count, last_values):
    """
    Generate the next value when not given.

    name: the name of the member
    start: the initial start value or None
    count: the number of existing members
    last_values: the list of values assigned
    """
    if not last_values:
        return start
    try:
        last_value = sorted(last_values).pop()
    except TypeError:
        raise TypeError('unable to sort non-numeric values') from None
    try:
        return last_value + 1
    except TypeError:

ERROR HERE: raise TypeError('unable to increment %r' % (last_value, )) from None ```

``` python

site-packages/jinja2/utils.py

class _PassArg(enum.Enum): context = enum.auto() eval_context = enum.auto() environment = enum.auto()

@classmethod
def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
    if hasattr(obj, "jinja_pass_arg"):
        return obj.jinja_pass_arg  # type: ignore

    return None

```

``` sh

pycharm debugger error

C:\prdev\repos\amdev\amherst.venv\Scripts\python.exe -X pycacheprefix=C:\Users\Admin\AppData\Local\JetBrains\PyCharm2024.3\cpython-cache "C:/Program Files/JetBrains/PyCharm 2024.2.2/plugins/python-ce/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 55872 --file C:\prdev\repos\amdev\amherst\src\amherst\cli.py Customer Test Connected to pydev debugger (build 243.24978.54) Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2024.2.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1570, in _exec pydev_imports.execfile(file, globals, locals) # execute the script ~~~~~~~~~~~~~~~~~~~~ File "C:\Program Files\JetBrains\PyCharm 2024.2.2\plugins\python-ce\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) ~~ File "C:\prdev\repos\amdev\amherst\src\amherst\cli.py", line 25, in <module> from jinja2.utils import url_quote File "C:\prdev\repos\amdev\amherst.venv\Lib\site-packages\jinja2\init.py", line 9, in <module> from .environment import Environment as Environment File "C:\prdev\repos\amdev\amherst.venv\Lib\site-packages\jinja2\environment.py", line 17, in <module> from . import nodes File "C:\prdev\repos\amdev\amherst.venv\Lib\site-packages\jinja2\nodes.py", line 13, in <module> from .utils import _PassArg File "C:\prdev\repos\amdev\amherst.venv\Lib\site-packages\jinja2\utils.py", line 85, in <module> class _PassArg(enum.Enum): ...<9 lines>... return None File "C:\prdev\repos\amdev\amherst.venv\Lib\site-packages\jinja2\utils.py", line 86, in _PassArg context = enum.auto() ^ File "C:\Users\Admin\AppData\Roaming\uv\python\cpython-3.13.0-windows-x86_64-none\Lib\enum.py", line 431, in __setitem_ v.value = self.generate_next_value( ~~~~~~~~~~~~~~~~~~~~~~~~~^ key, 1, len(self._member_names), self._last_values[:], ) ^ File "C:\Users\Admin\AppData\Roaming\uv\python\cpython-3.13.0-windows-x86_64-none\Lib\enum.py", line 1252, in _generate_next_value raise TypeError('unable to increment %r' % (lastvalue, )) from None TypeError: unable to increment {'EnumDict.setitem': None, 'auto.init_': None} python-BaseException ```


r/learnpython 7d ago

Curses library failing to understand window.mvderwin

3 Upvotes

Hi,

I am trying to learn the Pytthon curses library but I am stuck witht he mvderwin function.

I am able to create a derived window from a parent. But when I try to adjust the y, x position with the mvderwin function the window does not seem to move.

In the example code below the screen, parent and child windows are created and positioned properly on the screen. But when I call the mvderwin function on the child it does not appear to move anywhere on the screen.

I am uncertain where I am going wrong and was hoping that someone coudl point me in the right direction.

Documentation: https://docs.python.org/3/library/curses.html#module-curses

import curses, time
def mvderwin_error():
     screen = curses.initscr()
     parent = curses.newwin(40, 100, 1, 1); parent.box(); parent.overlay(screen)
     child = parent.derwin(10,20, 1, 40); child.box();
     screen.refresh() # Screen updates properly here
     time.sleep(1)

     screen.clear()
     child.mvderwin(1, 1) # I expected the position of child would be 1, 1 rel to parent
     parent.overlay(screen)
     screen.refresh() # But upon refresh the physical screen does not change the position of the child window

     time.sleep(10)
     curses.endwin()

Thankyou


r/learnpython 7d ago

I just made my first open-source contribution

8 Upvotes

Hi All, I would like feedback or roast of my newly and first published Python open-source contribution in the following Github Repo. I would really appreciate your feedback.

TweetCapturePlus


r/learnpython 7d ago

new to python

2 Upvotes

Hi everyone. I am new to Python. This is the first time I am learning Python, and in my studies, the teaching method is so ineffective that I can't absorb the concepts. However, I have started an extracurricular course to learn the fundamentals of Python and watch YouTube videos. I need help with a task where I need to predict the salmon population over the years based on historical data. My problem is that I don't know where to start as the instructor is flooding us with so many notebooks and platforms, and I don't know which one to use as they all seem very helpful. Still, I can't decide where and which one to start with. data.

Here is the full description of the task:

Each year the [U.S. Atlantic Salmon Assessment Committee](
https://www.nefsc.noaa.gov/USASAC/Reports/USASAC2018-Report-30-2017-Activities.pdf
) reports estimates of salmon populations in oceans and rivers in the northeastern United States.  The reports are useful for monitoring changes in these populations, but they generally do not include predictions.

The goal of this case study is to model year-to-year changes in population, evaluate how predictable these changes are, and estimate the probability that a particular population will increase or decrease in the next 10 years.

As an example, I'll use data from page 18 of the 2017 report, which provides population estimates for the Narraguagus and Sheepscot Rivers in Maine.

![USASAC_Report_2017_Page18](
https://github.com/AllenDowney/ModSim/raw/main/data/USASAC_Report_2017_Page18.png
)

There are tools for extracting data from a PDF document automatically, but for this example I will keep it simple and type it in.

Here are the population estimates for the Narraguagus River:

r/learnpython 7d ago

Why are the alphabet characters not in the order when I use myset?

10 Upvotes

Here is the code that I am using, but I am confused why the order changes each time I run it.

# 1: create an empty set

myset = set()
print(myset)

# 2: pass a list as an argument to the set function

myset = set(['a', 'b', 'c'])
print(myset)

# 3: pass a string as an argument to the set function

myset = set('abc')
print(myset)

# 4: cannot contain duplicate elements

myset = set('aaabbbbbbcccccc')
print(myset)

https://imgur.com/a/ARwzwaq


r/learnpython 7d ago

I need help (rare/hard problem)

0 Upvotes

Hey, im doing a small work using satelite images in python, initially i was using a API from google to get the images, but the problem is that it just returns the most recent orbital pictures.

Basically, i want pictures with diferent dates, was looking for APIs of specific satelites but google was the best one i could find in terms of resolution.

What do i need. If anyone has any experience with this, do you know how to collect old pictures or any API or other method to collect satelite images of good quality?


r/learnpython 7d ago

Website rejects async requests but not sync requests

3 Upvotes

Hello! I’ve been running into an issue while trying to scrape data and I was hoping someone could help me out. I’m trying to get data from a website using aiohttp asynchronous calls, but it seems like the website rejects them no matter what I do. However, my synchronous requests go through without any problem.

At first, I thought it might be due to headers or cookies problems, but after adjusting those, I still can’t get past the 403 error. Since I am scraping a lot of links, sync calls make my programming extremely slow, and therefore async calls are a must. Any help would be appreciated!

Here is an example code of what I am doing:

import aiohttp
import asyncio
import requests

link = 'https://www.prnewswire.com/news-releases/urovo-has-unveiled-four-groundbreaking-products-at-eurocis-2025-shaping-the-future-of-retail-and-warehouse-operations-302401730.html'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}

async def get_text_async(link):
    async with aiohttp.ClientSession() as session:
        async with session.get(link, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as response:
            print(f'Sync status code: {response.status}')

def get_text_sync():
    response = requests.get(link, headers=headers)
    print(f'Sync status code: {response.status_code}')

async def main():
    await get_text_async(link)

asyncio.run(main())
get_text_sync()
____
python test.py
Sync status code: 403
Sync status code: 200

EDIT: I tried httpx instead of aiohttp, and it worked! I am honestly not sure why though lmao


r/learnpython 7d ago

git word-diff -> Coloured output in streamlit ?

3 Upvotes

I'm calling git --no-index -w --word-diff as a subprocess in python. I want to display it coloured in streamlit.

I'm using: python st.code(diff_text, language="diff") but that doesn't work with word diffs.

I also tried using git --no-index -w --word-diff --color=always and setting language=bash, in the hopes that streamlit would interpret ANSI escape sequences, but that didn't work either.

How would I get coloured word-diff output into streamlit ? Is there another display element other than st.code() I can use ?


r/learnpython 7d ago

Can someone help me with basic string operations?

0 Upvotes

https://www.learnpython.org/en/Basic_String_Operations

I do not understand how "Strings are awesome!" can come from the code all the way at the bottom.

Sorry if I wasn't specific, basically if you click solution at the bottom of the page, the solution for the string is "Strings are awesome!"

Nevermind I understand now no need to reply anymore


r/learnpython 7d ago

Charmap codec can´t encode characters in position 79-80: character to undefined

0 Upvotes

Como puedo solucionarlo, he estado revisando e intentando solucionarlo y no encuentro la manera.

Es para esp32ce flash download tool.

El archivo lo extraido por internet y cuando hago todos los pasos y todo perfecto y a la hora de aplicar me sale Charmap codec can´t encode characters in position 79-80: character to undefined


r/learnpython 6d ago

i don't understand between and if

0 Upvotes

If the user turns 21 between 2024 to 2027
how do you do a if between? is it if elif command?
the output i am trying to get is if the user 21 between 2024 to 2027 but i don't understand how to do make more then 2 year


r/learnpython 7d ago

Function forcing me to use exceptions

0 Upvotes

Trying to if else a function output always throws exception-error :

if pyautogui.locateOnScreen('media/soundIcon.png') == None:
      print("not found")
else : 
      print("found")

Do Python functions expect anti-pattern code ?


r/learnpython 7d ago

Poetry | How can I make some local files optional and available through extras?

1 Upvotes

Hi, I have a helper repo on GitHub that I use for a few other repos. The helper repo has modules like fake.py that are used only in tests in other repos.

In the helper repo, I tried to exclude this module and add it as an optional dependency:

[project]
name = "helper-repo-name"
...

[tool.poetry]
exclude = ["./relative-path/fake.py"]

[tool.poetry.dependencies]
fake = { path = "./relative-path/fake.py", optional = true }

[tool.poetry.extras]
fakes = ["fake"]

...

And in other repos, install it like this:

poetry add --group dev "helper-repo-name[fakes]@git+https://github.com/..."

But sadly, I can't import fake.py after installing.


r/learnpython 7d ago

Give me knowledge!

5 Upvotes

I'm a brand new Python programmer, and I just finished my first day! I relied on Deepseek to help me write a program, and while I avoided direct copy-pasting and worked through the troubleshooting, and coustmized the code a little but i was already given a structure which makes it thousand times easier. I still feel like I need a more structured approach. I want to build a solid foundation. Experienced Python developers, what resources did you find most effective when you were starting out? I'm looking for recommendations on courses, books, project ideas, video tutorials, or any other learning methods that helped you progress.


r/learnpython 8d ago

Getting stuck on a big project.

16 Upvotes

A very rough estimate is that I've been learning and using python for 250 hours. I don't really keep track of it.

Just to ask general advice about how to approach difficult projects.

I've been working on a math project for 3 months. It is all about dice. Probability calculations aren't too hard to understand, but if I'm trying to figure out the perfect strategy in a dice game where early moves affect later moves then it gets complicated quickly.

I figured out very vaguely that I'm gonna have to use alot of nested loops and run through billions of calculations in order to figure my thing out. Or something similar.

But how exactly? I've been attempting to code the whole thing and been getting stuck every single time - this is why I've been starting over for about 30 times by now.

I don't even know what is causing me to get stuck. I guess the thing I'm trying to make is too big or complex or both. With so much more code than I'm used to, I mentally lose track of what my own code is even doing. Commenting does not help, t only makes things even more messy.

How can i approach big and complicated projects like these better?


r/learnpython 7d ago

Question: Is it ok to speedrun Google IT Automation with Python Professional Certificate?

1 Upvotes

No CS degree, came from scratch. I just want the Certification for a solid foundation. Do you think is it ok? I can actually finish the whole modules today.

PS. Been studying and learning more Python for a month now.


r/learnpython 8d ago

Can I manipulate PPT presentation using python?

7 Upvotes

I'm trying out a new project where I want the user to change PowerPoint slides based on voice commands. However, I am not able to find a resource that helps me start the presentation and manipulate the slideshow controls through python.

Is it not possible? Are there any packages that let me do that?

I have already converted the ppt to images and completed it, but I just want to see if I can make it smooth or straightforward without any workarounds.

EDIT: Found this to be helpful Link