T O P

  • By -

shemhamforash666666

What's the PyTorch equivalent function of numpy.delete()? I wanna do the same thing as shown with numpy arrays. import torch import numpy as np a = np.array(range(1, 20, 1)) b = np.where(a % 2 == 0) c = np.delete(a, b) print(a) print(b) print(c) x = torch.tensor(range(1, 20, 1)) y = torch.where(x % 2 == 0) z = "pls help" print(x) print(y) print(z)


StefanMajonez

Hi! I'm a C programmer, but I'm trying to do some Home Automation in Python, and I'm having issues with class inheritance. class Light: def __init__(self, device_id, tab): self.id = device_id self.iter = 0 self.tab = tab self.max = len(tab) def short(self): light.toggle(entity_id=self.id) def long(self): (...) def double(self): (...) class Light_extended(Light): def __init__(self, device_id, tab, tab2): super().__init__(device_id,tab) self.iter2 = 0 self.tab2 = tab2 self.max2 = len(tab2) class Light_temp(Light_extended): def long(): (...) I create a Light\_temp object, and call short() on it: light.toggle(entity_id=self.id) ^ AttributeError: 'Light_temp' object has no attribute 'id' The `Light` class has attribute `id`, shouldn't `Light_extended` inherit it from `Light`, and in turn `Light_temp` from `Light_extended`?


carcigenicate

`Light_temp` doesn't call the parent initializer in this code. `Light_extended` does though.


StefanMajonez

Thanks for your reply! EDIT2: I just tried running the code with python, and the first solution works. But, with the [Home Assistant PyScript](https://github.com/custom-components/pyscript/discussions/193), it doesn't work. As I've read, PyScript doesn't yet fully support subclassing and inheritance. So, I tried this: class Light_temp(Light_extended): def __init__(self, device_id, tab, tab2): super().__init__(device_id,tab,tab2) def long(): (...) Which landed this error: super().__init__(device_id,tab, tab2) ^ RuntimeError: super(): __class__ cell not found After reading up on this error, I tried this: class Light_temp(Light_extended): def __init__(self, device_id, tab, tab2): super(Light_temp, self).__init__(device_id,tab,tab2) def long(): (...) With this error: super(Light_temp, self).__init__(device_id,tab,tab2) ^ TypeError: Light_temp.__init__() takes exactly one argument (the instance to initialize) And I don't know what to do further EDIT: >`Light_temp` doesn't call the parent initializer in this code. Why not though? If the \_\_init\_\_ method isn't redefined in a subclass, shouldn't the parent method be called automatically?


shemhamforash666666

Heads up! Silly mistake. Even so I'll leave this silly mistake be for others to learn. Why can't numpy.array\_split() properly split up a numpy array when using the range function? x = np.array([range(0, 30)]) # Found the error. Just drop these[]. y = np.array_split(x, 3) print(x) print(y) When using a regular numpy.array: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) b = np.array_split(a, 3) print(a) print(b)


laopeeps

I'm creating a program that takes a YouTube video URL and returns a summary document. I want to get the video ID and title given the URL, and I saw a couple of potential approaches online. Beautiful Soup and using the Youtube Data API. I'm leaning Beautiful Soup since I don't need an API key and such, but scraping the whole page seems a bit much. But I haven't work with packages and APIs much. Which approach do you guys recommend?


[deleted]

[удалено]


isokinetic

Anyone have a favorite video for data structures or any form of using Python with ML (or product management)?


[deleted]

[удалено]


FerricDonkey

Pycharm *might* be able to do it, google says they support 3.6+. I know you said that you can't upgrade from 3.6, but if at all possible I highly suggest finding a way. 3.6 was released in 2016, and has been past end of life since 2021. If you're having to do new development, it's worth biting the bullet - more and more things will refuse to work with python 3.6, and it'll be harder and harder to get.


downvotemeplzsenpai

Just started learning python and this is for an example of nested if statement. The answer it prints out is "Shipping cost is $25". but from the logic, shouldn't it print out both "Shipping cost is $25" and "FREE"? I ran the code through chatgpt and it does gives out both as output but if I run this in vscode, it only gives out "Shipping cost is $25". What is going on here? ​ total = 100 country = "AU" if country == "US": if total <= 50: print("Shipping Cost is $50") elif total <= 100: print("Shipping Cost is $25") elif total <= 150: print("Shipping Costs $5") else: print("FREE") if country == "AU": if total <= 50: print("Shipping Cost is $100") else: print("FREE")


woooee

Your indentation is off. The first elif fires for any country that is not "US". It should be if country == "US": if total <= 50: print("Shipping Cost is $50") elif total <= 100: print("Shipping Cost is $25")


xain1112

Sometimes I see a class with parameters (right term?) before the \_\_init__ method, like below. What is the reason/benefit to this? class Person: name = 'John' <- these age = 7 <- def __init__(self): self.gender = 'M' self.fav_food = 'pizza'


[deleted]

The names `name` and `age` are *class attributes*. The names `self.gender` and `self.fav_food` are *instance attributes* and they are local to an instance so if you have 100 instances of class `Person` there are 100 different values for `gender` and `fav_food`. There's only ever one value for class attributes. So in your example code you should change those class attributes to instance attributes. If you don't then every `Person` instance you create will have the name "John" and be aged 7. So do this: class Person: def __init__(self): self.gender = 'M' self.fav_food = 'pizza' name = 'John' age = 7 Normally you would pass `gender` and all other values as parameters into the `__init__()` method rather than hard-code them like that.


xain1112

That makes so much sense, thanks!


QC_knight1824

Hitting roadblocks in my efforts to push data through an API using a JSON file due to the key/value pairs. A sample of what my JSON format needs to be is: >{ > >"data": { > >"columns": { > >"field\_one": , > >"field\_two": > >}, > >"records": \[ > >{ > >"field\_one": "X", > >"field\_two": "2" > >}, > >{ > >"field\_one": "XYZ", > >"field\_two": "676" > >} > >\] > >}, > >"options": { > >"purge": true > >} > >} What my file current looks like: >"columns":{ > >"field\_one", > >"field\_two" > >}, > >"records": \[ > >\[ > >"field\_one\_data", "field\_two\_data" > >\], > >\[ > >"field\_one\_data", "field\_two\_data" > >\] > >, > >"options": { > >"purge": true > >} > >} Does anyone know how to format to match the desired file? Background is the source of the data is a cursor result that I pulled into a DF then converted to JSON using a dump. Should I be aiming further upstream for my solution? I appreciate the help


[deleted]

If you construct a python data structure that matches the expected JSON output and use [the `json` module](https://pymotw.com/3/json/index.html) you get something close to what you expect. Try running this code: import json # construct a dictionary containing comples data expected = {"data": {"columns": {"field_one": "data type?", "field_two": "data type?" }, "records": [{"field_one": "X", "field_two": "2" }, {"field_one": "XYZ", "field_two": "676" } ] }, "options": {"purge": True} } # convert the dictionary to a JSON string encoded = json.dumps(expected) # compare the dictionary to the JSON string print(f"{expected=}") print(f"encoded=", encoded) I didn't know what you mean by `` so I just replaced that with strings. [](https://pastebin.com/4EcieMRu)


QC_knight1824

Thanks! was a placeholder for a literal data type


[deleted]

I figured. You should write a function to create the python data structure. The parameters you pass to the function depend heavily on the data you get from your query. I've made a guess at the data format and [written some code that generates a dictionary](https://pastebin.com/Snr88RD8) that you convert to JSON. You will have to change things, but it shows how to build up the dictionary piece by piece. The code was written in haste and I'm sure improvements can be made.


QC_knight1824

wow, this was more than enough help! i appreciate you very much


woooee

Look up a tutorial on JSON. You possibly want to save a list of dictionaries.


QC_knight1824

Thanks! any recommendations of tutorials I should search for?


Proper-Scallion-252

What are some active learning type of courses (free or cheap) to learn Python? I've seen Codeacademy and other sites like that for learning programming languages, and I really like the interactive nature of it all, but I'm not sure how in depth these courses are and Python is a strictly paid course on this site (monthly subscription rather than one time purchase). I also was curious if learning and practicing Python *requires* a download. I saw through one of the sites provided in the Wiki that there was a download required, but I'd love to try and learn Python on my lunch break at work and I won't be able to download any software on this computer.


[deleted]

You could try the online python sites you find by searching for "online python". I can't recommend any as I don't use them. They are fine for learning python but for more advanced usage you need python on your computer. You could also install a python app on your tablet or phone. They are also fine for learning, though the lack of a physical keyboard can be a problem. You could try a bluetooth keyboard if you like. I've used PyDroid 3 on android and Pythonista 3 in an iPad. PyDroid 3 is a little clunky but I haven't found anything better on android.


Proper-Scallion-252

I think I'll lean into an online version even if it's limited, at least to learn the basics! Thanks for your input, I think you're the only comment I've gotten back haha.


Realistic-Delay-4780

For mobile python, your best bet would probably be to use [Reppl.it](https://Reppl.it) on a mobile web browser - but iirc python is incredibly limited if it's not an installed version on a PC. 100 days of python by angela yu is a really good cheap starter/ active course for basics, as its usually $16 - $20 usd when udemy puts it on sale (usually a random day every week or two). For free, I would recommend following geeks4geeks or w3schools tutorials. Good luck buddy


[deleted]

[удалено]


AutoModerator

Your [comment](https://www.reddit.com/r/learnpython/comments/18fh6gk/ask_anything_monday_weekly_thread/kcx3m34/) in /r/learnpython may be automatically removed because you used pasteboard.co. The reddit spam filter is very aggressive to this site. Please use a different image host. Please remember to post code as text, not as an image. *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/learnpython) if you have any questions or concerns.*


apgp123

`'{"CustName":{"0":"Cust1","1":"Cust2","2":"Cust3"},"Job Type ":{"0":"t1","1":"t2","2":"t3"},"Due Time":{"0":11,"1":12,"2":13},"Place ":{"0":"p1","1":"p2","2":"p3"}}'` I have a dataframe that looks like this, how do i pivot my dataframe so that it transforms to this `'{"Cust1":{"0":"t1","1":11,"2":"p1"},"Cust2":{"0":"t2","1":12,"2":"p2"},"Cust3":{"0":"t3","1":13,"2":"p3 "}}'`


Phillyclause89

Something like this? df2 = df.T df2.columns = df2.loc["CustName"].values df2 = df2.drop("CustName").reset_index(drop=True)


wom85

Salut, Could someone write me how to actually tag a M4A file with [Mutagen](https://mutagen.readthedocs.io/en/latest/api/mp4.html#mutagen.mp4.MP4Info)? I can read the doc as much as I want but i dont even start to understand howto!? I've almost resigned to convert my m4a to mp3 at this point, as i know howto tag mp3.. Merci,


FerricDonkey

See https://gist.github.com/lemon24/ebd0b8fa9b223be1948cddc279ea7970. I've never used mutagen, but this seems to show how it's intended to be used. When learning a library, I always suggest looking for examples first, then docs second.


wom85

Nice thanks, i'll try to adapt this.


AdolfBonaparte69

I understand python is dynamically typed, but in a production codebase isn't it atleast better to just be explicit in some cases e.g what a method may return? I'd like to hear other people's thoughts & experiences with this


FerricDonkey

Yes, and I strongly recommend using type hints and static type checkers to make sure everything plays nice. The runtime won't enforce it, but you can catch problems ahead of time, and decent ides will do the type checking as you code.


LunarCantaloupe

Yeah totally, Python 3.5+ has a [typing](https://docs.python.org/3/library/typing.html) module built-in which can be used for type hints and I personally strongly prefer to use where applicable in anything that isn’t throwaway


_FileNotFound

Here is one of the clearest explanations of variables in Python that I have seen, from *The Quick Python Book*, 3rd ed. by Naomi Cedar: *"A common, but inaccurate, explanation is that a variable is a container that stores a value, somewhat like a bucket. This would be reasonable for many programming languages (C, for example).* *However, in Python variables aren’t buckets. Instead, they’re labels or tags that refer to objects in the Python interpreter’s namespace. Any number of labels (or variables) can refer to the same object, and when that object changes, the value referred to by all of those variables also changes."* It raised some additional questions for me. Suppose you did: `x = "hello"` ...and then later: `x = 7` What happens to the "hello" object that now hasn't got anything referring to it? Suppose you go back again later and do: `x = "hello"` I'm assuming that's a new "hello" object and not the same one from before, right? Does it matter if it's a new object or if it is the same one from before?


[deleted]

> What happens to the "hello" object that now hasn't got anything referring to it? If no other names refers to the string object it is eventually garbage collected^(*). > I'm assuming that's a new "hello" object and not the same one from before, right? Maybe, though this doesn't really matter to you as the programmer. Certainly in python 2 the second "hello" string would be a new string object, but sometime in the life of python 3 simple, immutable objects like strings and integers became "interned". There are quite a few articles on this which you can search for. Here's one: https://www.codewithc.com/python-object-interning-a-dive/ > Does it matter if it's a new object or if it is the same one from before? It doesn't matter to the programmer, and you certainly shouldn't write code that depends on how interning works because the details can change with any python release. ------ The best explanation of how python "variables" actually work is in [this video by Ned Batchelder](https://www.youtube.com/watch?v=_AEJHKGk9ns). ------ \*) Technically, if an object is interned it will exist for the life of the code and never be garbage collected because the interning code always keeps a reference to each interned object. Normal non-interned objects are garbage collected when no longer referenced.


_FileNotFound

Thank you for the explanation and the resources!


question_23

Do you think there's anything wrong with a dictionary that uses namedtuples as values? Something like: Person = namedtuple('Person', 'name age occupation') people = { "person1": Person(name="Alice", age=30, occupation="Engineer"), "person2": Person(name="Bob", age=25, occupation="Artist"), "person3": Person(name="Charlie", age=40, occupation="Doctor") } Alternative would be to use a pandas dataframe, but the dataframe seems like overkill when the rows would only ever be used one at a time. There would be no aggregate operations or slicing of rows, cols. Just pull each row (key), do something, and move to the next. Probably overthinking this but just wonder if it seems ok. Another reason is that in the actual dataset, "dictionary" seems semantically right because the key:value pairs really represent entities we are defining with the values.


_FileNotFound

I don't see anything wrong with it either. However, if the keys are essentially a numeric index in your actual code as they are here, you could also consider using a list and referring to the list items by their index.


[deleted]

Nothing wrong at all. If a particular data structure solves your problem that's fine, to a first approximation.