Questions tagged [python]

532110 questions
1

votes
1

answer
1.6k

Views

Python- How to make an if statement between x and y? [duplicate]

This question already has an answer here: How do I check whether an int is between the two numbers? 7 answers I've recently been breaching out to Python, as C++ is fun and all, but python seems kinda cool. I want to make Python do something as long as the input is between a certain number range....
Nate Dukes
1

votes
1

answer
338

Views

Conditions on django filter backend in django rest framework?

I am using Django filter backend on few fields which is working very good. But i want to filter fields when i get specific condition Like if user_type is basic get filter query otherwise get all objects from model. Mine code for filters is here: http_method_names = ['get'] serializer_class = SearchS...
Salman Ahmed
1

votes
1

answer
2.1k

Views

Plot percentiles using matplotlib

I have three dataframes df1, df2 and df3. I combine these into one dataframe df. Now i want to find the min, 5 percentile, 25 percentile, median, 90 percentile and max for each date in the dataframe and plot it (line graph for each date) where X axis has the percentiles and Y axis has the values. df...
Sun
1

votes
1

answer
6.5k

Views

Python - Pandas delete specific rows/columns in excel

i have the following excel file, and i would like to clean specific rows/columns so that i can further process the file. I have tried this, but i have not managed to remove any of the blank lines, i ve only managed to trim from those containing data. Here, i was trying to only save the data from the...
onlyf
1

votes
2

answer
1.2k

Views

Hamming Window, python 2.7

Hi I have a FFT which is quite noisy. How to apply to my code Hamming window to make it less noisy. Look at my code: plt.subplot(212) plt.title('Fast Fourier Transform') plt.ylabel('Power [a.u.]') plt.xlabel('Frequency Hz') fft1 = (Bx[51:-14]) fft2 = (By[1:-14]) for dataset in [fft1]: dataset = np.a...
Hiddenguy
1

votes
1

answer
269

Views

python pandas non-unique dict keys

I have an Excel file with data like this Fruits Description oranges This is an orange apples This is an apple oranges This is also oranges plum this is a plum plum th...
jumpman8947
1

votes
3

answer
2.7k

Views

Python how convert single quotes to double quotes to format as json string

I have a file where on each line I have text like this (representing cast of a film): [{'cast_id': 23, 'character': 'Roger 'Verbal' Kint', 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast...
revy
1

votes
2

answer
1.3k

Views

AWS Lambda boto3: Filter Instances by Launch Time = today

I'm trying to automatically backup my EC2 instances through AWS Lambda. I used these 2 scripts and they work just fine. https://gist.github.com/bkozora/724e01903a9ad481d21e https://gist.github.com/bkozora/d4f1cf0e5cf26acdd377 But I would like to add the functionality that the scripts only delete or...
T. Moser
1

votes
2

answer
377

Views

How to split a string with regexp without keeping capture groups?

I want to split text with a regular expression with backreference in Python. rexp = re.compile(r'([`]{1,})ABC\1') rexp.split('blahblah``ABC``blahblah') I got ['blahblah', '``', 'blahblah'] but expected ['blahblah', 'blahblah']. How can I split string without keeping capture groups?
Zz Tux
1

votes
1

answer
37

Views

How to combine strings in one DataFrame

I am processing inbound user data. I receive DataFrame h that is supposed to contain all float but has some strings: >>> h = pd.DataFrame(np.random.rand(3, 2), columns=['a', 'b']) >>> h.loc[0, 'a'] = 'bad' >>> h.loc[1, 'b'] = 'robot' >>> h a b 0 bad 0.747314 1 0.921919 ro...
Jason Strimpel
0

votes
4

answer
34

Views

How to get the maximum value in a matrix and its row number

I would like to get the maxim value of a matrix and just its row position in the matrix. How to do that? Thanks again. I can get the maximum value in the matrix with the following code; but, I am not sure how to get its row index position. To be noticed that the matrix could also has equal values f...
chrisis
1

votes
1

answer
24

Views

Compare every element between two dataframes

Assuming that I have two dataframes: # df1 +-----------------------+ | Name_1 |Age| Location | +-----------------------+ | A | 18 | UK | | B | 19 | US | +-----------------------+ # df2 +-------------------------+ | Name_2 | Age | Location | +-------------------------+ | A | 18...
Old-School
0

votes
1

answer
21

Views

Ignore “temp” files?

I've had a script for a while that has been running without issues however recently had a 'hitch' with a temporary file that was within a directory. The file in question started with '~$' on a windows PC so the script was erroring out on this file as it is not a proper DOCX file. The file in questio...
TrueSlawter
-2

votes
2

answer
30

Views

Question: Howto change a funtion to a class in python

I want to create a class with methods, so that I do not have to create multiple functions. Below is my code, I want to get a class with two methods. Method 1: SQL Query, method 2: sql insert. Any tipp is greatly appreciated. Stefan def dbconnect(): dbconn = pymysql.connect(host='192.168.1.2', port=3...
Stefan
1

votes
3

answer
28

Views

Running a external program using Python

I want to launch a external program like notepad.exe using python. I want to have a script that just runs Notepad.exe.
Calvin
0

votes
0

answer
22

Views

Applying a function to every row in a dataframe in Python

I have a dataframe of 2 rows and D P h O Q SD LT 80 27 0.37 50 2 3 1.51 50 10 0.25 5 10 12 0.03 I have a function that I want to apply to every row, but I get the same result for every row I have tried to iter over rows with the following code: from scipy.stats im...
0

votes
2

answer
21

Views

fastest way to minimize n as per given condition in python

how can i make the following code faster? the input is a binary string and i am converting it to a number. possibly i need to use the binary string instead of the number? the algorithm may only divide by 2 or subtract 1 from the input. I tried the code below and it is not fast enough. I tried the b...
zelda1234
0

votes
0

answer
20

Views

Is there a method similar to lag (in R) or shift (in Python) for the javascript framework data-forge?

I have a code like this: const dataForge = require('data-forge'); var df = new dataForge.DataFrame({columns: {col1: [1,2,3,4,5]}}); console.log(df.toString()); with this result: __index__ col1 --------- ---- 0 1 1 2 2 3 3 4 4 5 in R and in Python like n...
EFA
0

votes
0

answer
26

Views

Invalid syntax error in Django Model Class

I am creating my first model with Django. The codes in models.py is as below. from django.db import models Class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name But I am getting a syntax error as below. Class Topic(models.Model):...
dinku33
0

votes
0

answer
16

Views

Creating a Python module with its dependencies self contained

When creating a Python module, you can specify dependencies of your module by using the install_requires List. Lets look at this basic example. setup(name='some_module', version='0.0.1', packages=find_packages(), install_requires=[ 'requests==2.21.0' ]) I package my module python3 setup.py sdist and...
chasez0r
-1

votes
1

answer
19

Views

how to build function for following simple problem?

I have multiple data frames. I need to merge them all and then set one by one column from all df. I make it simple for you.i have multiple lists .like l1=[a,b,c] l2=[d,e,f] l3=[g,h,i] I want my list such that give below. list=[a,d,g,b,e,h,c,f,i]
Aamir Siddiqui
-1

votes
0

answer
16

Views

How to print items of class including os('clear')?

Can somebody explain to me why the menu() function in the code below does not print the attributes of the class person while menu2() does? Thank you import os class person(): def __init__(self, name, age): self.name = name self.age = age def printAttr(self): print([self.name, self.age]) def menu(tit...
user10161844
1

votes
1

answer
15

Views

Get href links & Text in python loop

I need to scrape informations from the apple store, I have a hashmap hashmap_genre_link with genre and a URL ( {'Games': 'https://itunes.apple.com/us/genre/ios-games/id6014?mt=8' ; ...} ), I want to create for each key an other hashmap with iOS apps (text) and app url as a value : games_apps:{'Pokem...
userHG
-2

votes
0

answer
14

Views

Efficient way to calculate matrix cell distance from arbitrary coordinate in numpy

I am looking for an efficient numpy solution to the following problem: I have a N by N numpy matrix. Given an arbitrary i,j coordinate (can be decimal) of the matrix and an arbitrary range, I need to calculate the value of each cell of the matrix divided by its euclidian distance to the coordinate w...
Jakobovski
-3

votes
0

answer
14

Views

How to make background image when python GUI getting started

I want make the background image of welcome like blender.
time machine
0

votes
0

answer
15

Views

How do I dynamically change a dataframe in my site by user input? (for example maybe rearrange the same column by value? from max to min?)

I want to have an option in the table in my site that allows the user to rearrange the table by min or max value in a specific column, but couldn't find anything about this. The dataset I am using is this: https://raw.githubusercontent.com/plotly/datasets/master/bubble_chart_tutorial.csv I want the...
Dat Guy
5

votes
0

answer
137

Views

FactoryBoy - nested factories / max depth?

I am writing tests for a large Django application, as part of this process I am gradually creating factories for all models of the different apps within the Django project. However, I've run into some confusing behavior with FactoryBoy where it almost seems like SubFactories have an max depth beyond...
Jasper
0

votes
0

answer
5

Views

How to handle big textual data to create WordCloud?

I have a huge textual data that I need to create its word cloud. I am using a Python library named word_cloud in order to create the word cloud which is quite configurable. The problem is that my textual data is really huge, so a high-end computer is not able to complete the task even for long hours...
talha06
0

votes
0

answer
4

Views

How to connect to a server with a certificate and rsa key

I am very new to python programming. I have a certificate and RASkey . and i want to write a python ssl socket client program to send message to server.I know server ip address and port. I have been trying below code. Please guide me.
Nouman Yosuf
0

votes
0

answer
3

Views

using google storage and google vision API

I have the follow function that passes a image url to google vision service and returns the letters and numbers (characters) in the image. It works fine with general web urls but I'm calling it to access files stored in Google storage, it doesn't work. How can i get this to work? I've looked at ex...
resolver101
0

votes
0

answer
8

Views

How to stack columns of a time series data in python

I have a dataframe containing time series feature. In that, I would like to stack 5 features from this dataframe, each of shape(129,300). to extract one feature alone I use: Feature=df.iloc[:,start:end] #df is the dataframe containing the complete dataset This retreives me that particular channel o...
hakuna_code
1

votes
0

answer
9

Views

python 'environments have crashed'

I'm just getting started with using universe in python to learn how to make a game bot. I'm using a demo code to start with. However I get the same error after I run the code on PyCharm. import gym import universe env = gym.make('flashgames.DuskDrive-v0') env.configure(remotes='vnc://localhost:5900+...
Daniel dos Santos
1

votes
1

answer
7

Views

Crispy_forms_tags not fill form with instance in my update view

My problem about Update View On my UpdateView when I use {{form.as_p}} , Its work. But when I use {% load crispy_forms_tags %} Form not fill with instance. My View.py; def ayarlar (request): userinstance=get_object_or_404(kullaniciBilgileri,id=1) form = KullaniciForm(request.POST or None, instance...
Dany
0

votes
0

answer
10

Views

Subset-AVG - Finding a subset of List Which Matches Known Rational Number

I've asked this on math overflow and used comments to clarify/overstate my question. I hope it has the intended effect and doesn't come off as jarring. I'm attempting to find what subset of numbers reach a known average. I have a list of known values, negative and possible decimals. They look somet...
Raymond Johnson
0

votes
0

answer
4

Views

How to get the directory git detail from repo in GitPython?

I would like to get the number of commit of a directory(called module) from a repo(project) in GitPython. > print('before',modulePath) > repo = Repo(modulePath) > print(len(list(repo.iter_commits()))) When I'm trying to print the directory amount of commits, It says the repo is...
Get Rept
0

votes
0

answer
2

Views

opencv Python PPF detector crash

I´ve noticed that the PPF3DDetector is now available in Python too. So I´ve tried to run this piece of sample code: ppf_load_match, but Python keeps chrashing when 'matching'. It takes a while to train the model, but you can increase the first argument of 'cv.ppf_match_3d_PPF3DDetector' to run it...
ZZM
0

votes
0

answer
3

Views

how to use eager execution to save and restore in TensorFlow?

We always use tf.train.Saver() to save and restore weights, like the following example(https://www.tensorflow.org/guide/saved_model). But how to use eager execution to save? how to change the following example? Another question, is it a good idea to use eager? I fond tf.contrib.eager.Saver in (ht...
andy
1

votes
2

answer
277

Views

How to run SageTeX on Windows?

I want to use Sage in LaTeX, how do I do that running Sagemath 8.0 on Windows? I use the MikTeX distribution. I followed the instructions from Sagemath but they are for linux. I included the sagetex package, which generates a myfile.sage file but when I start the Sage shell and run sage myfile.sage...
PHPirate
1

votes
1

answer
888

Views

Feature scaling using python StandardScaler produces negative values

I am a newbie in Machine learning. I am trying to use feature scaling on my input training and test data using the python StandardScaler class. However, when I see the scaled values some of them are negative values even though the input values do not have negative values. Is this normal or am I miss...
Amit Rastogi
1

votes
2

answer
2.5k

Views

Flask - 404 not found

I am a newbie in the flask development this is my first program in the flask but it shows me this error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. & this is my code from flask import Flask app = Flask(__name__) @app.rout...
Roxas Zohbi

View additional questions