lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a dataframe that looks like this : The actual dataframe is very large with multiple ids and years . I am trying to make a new dataframe that has the percents of 'yes 's and 'no 's grouped by year . I was thinking of grouping the dataframe by the year , which would then put the statuses per year in a list and the... | id status year 1 yes 20143 no 20132 yes 20144 no 2014 year yes_count no_count ratio_yes_to_toal 2013 0 1 0 % 2014 2 1 67 % | Grouping and pivoting DataFrame with additional column for ratio of counts |
Python | ( @ error : No solution found ) **** trying to figure out why is it giving no solution as an error # df_ret is a data frame with returns ( for stocks in position ) Df_ret looks like this # trying to maximize the sharpe ratio # w ( 1 to n ) are the weights with sum less than or equal to 1**** | positions = [ `` AAPL '' , `` NVDA '' , `` MS '' , '' CI '' , `` HON '' ] cov = df_ret.cov ( ) ret = df_ret.mean ( ) .valuesweights = np.array ( np.random.random ( len ( positions ) ) ) def maximize ( weights ) : std = np.sqrt ( np.dot ( np.dot ( weights.T , cov ) , weights ) ) p_ret = np.dot ( ret.T , weights ) sharpe... | Trying to maximize this simple non linear problem using # gekko but getting this error |
Python | I am trying to reorganize an excel table ( or csv ) so that dates are no longer column headers . I 'm using a limited knowledge of python to attempt to do this but for lack of knowing where to start I can use some assistance . Under each date is a record of what happened that day for a particular place . Null values ca... | Name,7/1/2009,7/2/2009,7/3/2009,7/4/2009 ... .. ( and so on to the present ) Place A , ,5,3 , Place B,0 , ,23 , -- Place C,1,2 , ,35 Name , Date , ReadingPlace A , 7/2/2009 , 5Place A , 7/3/2009 , 3Place B , 7/1/2009 , 0Place B , 7/4/2009 , 0 < -- - Even though this is a dash originally it can be converted to a 0 to ke... | Reorganize a CSV so Dates are not column Headers |
Python | I have the following dataframe : I need to take the first pair of Bid_price and Bid_volume ( 2999.0 and 786.7 ) and compare with ALL pairs of Ask_price and Ask_volume . As long as Bid_volume < Ask_volume AND Bid_price > Ask_price I jump to the next pair of Bid_price and Bid_volume and compare again with ALL pairs of As... | Row Bid_price Bid_volume Ask_price Ask_volume 2 2999.0 786.7 -500.0 1403.2 3 3000.0 786.7 -499.9 1407.2 4 2950.0 787.3 -250.1 1407.2 -- -- -- -- -- -- -- -- -- -- - 56 125.1 2691 36.9 3113.1 57 125 2691.1 37 3133.1 -- -- -- -- -- -- -- -- -- -- - 117 41.4 3029.7 2999 3835.7 118 40.05 3029.7 3000 3835.7 -- -- -- -- -- -... | Pandas- Finding first occurence in a row based on column values |
Python | I need a short function to return the answer to a string of multiplication/addition with pemdas . For example it should take `` 6*3+4 '' and return 22 or `` 7+3*10 '' and return 37 . Ideally it could easily be changed to include division/subtraction . I 've tried doing this with index operations . Works with 1st test c... | def pemdas ( s ) : mult = `` * '' add = `` + '' mi = s.index ( mult ) res = int ( s [ mi-1 ] ) *int ( s [ mi+1 ] ) s = s [ 0 : mi-1 : ] +s [ mi+2 : : ] s = s.replace ( add , '' '' ) res = res + int ( s ) return res | Evaluating a string of operations with standard python library no eval ( ) function |
Python | This is my code which has data in which I want to perform the task using pandas.DataFrame.groupbyI tried this and could only get this output.I 'm not able to get output like this ... Can you help me with this ? | import pandas as pddata = { 'employees_no ' : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 ] , 'employees_name ' : [ 'Jugal Sompura ' , 'Maya Rajput ' , 'Chaitya Panchal ' , 'Sweta Rampariya ' , 'Prakshal Patel ' , 'Dhruv Panchal ' , 'Prachi Desai ' , 'Krunal Gosai ' , 'Hemil Soni ' , 'Gopal Pithadia ' , 'Ja... | How I can aggregate employee based on their department and show average salary in each department using groupby pandas ? |
Python | I was wondering what is the fastest way in python to create an empty string to attach more strings to it later on . However , I found that interestingly it 's way faster to init a string via `` '' than str ( ) . Can someone shine a light on this ? I guess str ( ) is just coming with a lot of overhead like typecheck etc... | % timeit `` '' + '' a '' 7.63 ns ± 0.0376 ns per loop ( mean ± std . dev . of 7 runs , 100000000 loops each ) % timeit str ( ) + '' a '' 58.2 ns ± 0.253 ns per loop ( mean ± std . dev . of 7 runs , 10000000 loops each ) | Why is str ( ) + '' '' slower than `` '' + '' '' |
Python | I have a list of lists with a very specific structure , it looks like the following : I 'd like to transform this lol ( list of lists ) into a dictionary of the following form ( note that the second element of each list in the lol is supposed to be unique , thus a good key for my dict : I could do a for loop but i was ... | lol = [ [ 'geo ' , 'DS_11',45.3,90.1,10.2 ] , [ 'geo ' , 'DS_12',5.3,0.1,0.2 ] , [ 'mao ' , 'DS_14',12.3,90.1,1 ] , ... ] dict_lol = { 'DS_11 ' : [ 'geo ' , 'DS_11',45.3,90.1,10.2 ] , 'DS_12 ' : [ 'geo ' , 'DS_12',5.3,0.1,0.2 ] , 'DS_14 ' : [ 'mao ' , 'DS_14',12.3,90.1,1 ] , ... } | From a list of lists to a dictionary |
Python | I have the following code to create a button in Tkinter : When I hover my mouse over some parts of the button , the button rapidly resizes to the width of the window and then back to its initial size . Why does this happen ? Is a Tkinter button not allowed to have children ? Note : I am not planning on using a frame in... | button = Button ( self.parent_frame , width=100 , height=100 ) frame = Frame ( button ) label = Label ( frame , text= '' This is a button '' ) frame.pack ( fill=BOTH , expand=1 ) label.pack ( fill=BOTH , expand=1 ) | Can a Tkinter button have children ? |
Python | I was recently stepping through the CPython source code , specifically viewing the symbol table entry for a class during compilation . I bumped into the following entry for the typedef struct _symtable_entry structure : I really ca n't seem to understand it and ca n't find an example of python code that actually sets s... | [ -- other entries -- ] unsigned ste_needs_class_closure : 1 ; /* for class scopes , true if a closure over __class__ should be created */ [ -- other entries -- ] class foo : y = 30 def __init__ ( self ) : self.x = 50 def foobar ( self ) : def barfoo ( ) : print ( self.x ) print ( y ) return barfoo /* Check if any loca... | Closures over __class__ |
Python | How do I sort this list via the numerical values ? Is a regex required to remove the numbers or is there a more Pythonic way to do this ? Desired output is as follows : | to_sort [ '12-foo ' , ' 1-bar ' , ' 2-bar ' , 'foo-11 ' , 'bar-3 ' , 'foo-4 ' , 'foobar-5 ' , ' 6-foo ' , ' 7-bar ' ] 1-bar2-barbar-3foo-4foobar-56-foo7-barfoo-1112-foo | Sort list of mixed strings based on digits |
Python | I have a list of dicts with inner lists and dicts , I need to concatenate them in one big dict.The list is like this : I have tried some for loops and recursive functions , without great resultsBut I can obtain only this : but i need this : | [ { 'total ' : { 'last_day ' : ' 7 ' } } , { 'total ' : { 'progress ' : '07/04 ' } } , { 'total ' : { 'piecies ' : '3008 ' } } , { 'total ' : { 'week ' : [ '16.0 ' ] } } , { 'total ' : { 'week ' : [ '17.0 ' ] } } , { 'total ' : { 'week ' : [ '15.0 ' ] } } , { 'total ' : { 'week ' : [ '17.0 ' ] } } , { 'total ' : { 'wee... | How to concatenate a list of dicts with inner lists |
Python | Is there a solution to find out the missing values based on column for example : So here I want to know the missing values in the column Field_name and the Field_Type = 'M ' , Ignoring the missing values in Field_Type = ' C'Expected Output : Edit : Can we do this for a list of dataframes ? | Field_name Field_Type Field_IdMessage type identifier M 0Nan M 1Bitmap secondary C 1Nan C 2Processing code M 3Nan M 4Amount-Settlement C 5 Field_name Field_Type Field_IdNan M 1Nan M 4 data_list = [ df1 , df2 , df3 ] output : result [ [ missngvalues in df1 ] , [ missngvalues in df2 ] , [ missngvalues in df3 ] ] | Finding out the missing value in dataframe based on a column |
Python | I have built a zip object and by accident I noticed that if I apply list ( ) to this object twice , second time it will yield [ ] . My code is shown below : Output of the code is : I am new to Python so my terminology may not be 100 % accurate . I have tried finding the explanation online , but problem here is what is ... | coordinate = [ ' x ' , ' y ' , ' z ' ] values = [ 5 , 7 , 9 ] my_map = zip ( coordinate , values ) my_map_list_first = list ( my_map ) my_map_list_second = list ( my_map ) print ( my_map_list_first ) print ( my_map_list_second ) [ ( ' x ' , 5 ) , ( ' y ' , 7 ) , ( ' z ' , 9 ) ] [ ] | list ( ) applied to zip object twice in a row issue |
Python | Right now I am learning Python and struggling with a few concepts of OOP , one of that being how difficult it is ( to me ) to dynamically initialize class instances and assign them to a dynamically generated variable name and why I am reading that I should n't do that in the first place . In most threads with a similar... | LOE = [ `` graham '' , `` eric '' , `` terry_G '' , `` terry_J '' , `` john '' , `` carol '' ] class Employee ( ) : def __init__ ( self , name , job= '' comedian '' ) : self.name = name self.job = job employees = [ ] for name in LOE : emp = Employee ( name ) employees.append ( emp ) for emp in employees : if emp.name =... | Why should n't one dynamically generate variable names in python ? |
Python | I have a list of Point objects , each of which has an x and y property . I wish to calculate the maximum_x and maximum_y , without iterating through twice . I could do this : But of course , this will iterate twice . I could do it manually , but since finding the maximum is so simple , I fear it 'll increase clutter . ... | max_x = max ( points , key=lambda p : p.x ) max_y = max ( points , key=lambda p : p.y ) | Calculate two maximums at the same time ? |
Python | I 'm currently trying to pivot my pandas DataFrame by 'id ' on 'rank'Depending on the max ( 'rank ' ) , I want to create as many 'years ' columns and give them values according to the ascending rankI tried my own solution ( currently working , but I have ~2M rows and is not very effective ) I know that it is not the op... | print ( df ) id rank year 0 key0 1 2011 1 key0 2 2012 2 key0 3 2013 3 key1 1 2014 4 key1 2 2015 5 key1 3 2016 6 key2 1 2017 7 key2 2 2018 8 key2 3 2019 print ( df ) id rank1 year1 rank2 year2 rank3 year3 0 key0 1 2011 2 2012 3 20131 key1 1 2014 2 2015 3 2016 2 key2 1 2017 2 2018 3 2019 df2= df.melt ( id_vars= [ `` id '... | Pivoting pandas dataframe by rank on id |
Python | I 'm looking for a way to further simplify my code that I have : Dataset : What I wan na do is to replace dogs , lions & cats with `` animal '' . I can do them by writing this : Is there a way for the str.replace ( ) function to accept a list of strings instead of just one ? Example : | categorical_data = pd.Series ( [ `` dog '' , `` lion '' , `` cat '' , `` crustacean '' , `` dog '' , `` insect '' , `` insect '' , `` cat '' , `` crustacean '' ] ) categorical_data = categorical_data.str.replace ( `` dog '' , `` animal '' ) categorical_data = categorical_data.str.replace ( `` cat '' , `` animal '' ) ca... | replacing more than one old string value str.replace with one new string |
Python | I have a python script which runs a method in parallel.process_items is my method and items is a list of tuples with two elements to each tuple . The items list has around 100k items.process_items will then call a method depending on what parameters are given . My problem being maybe 70 % of the list I can run with hig... | parsers = { 'parser1 ' : parser1.process , 'parser2 ' : parser2.process } def process ( ( key , value ) ) : parsers [ key ] ( value ) pool = Pool ( 4 ) pool.map ( process_items , items ) | How to change number of parallel processes ? |
Python | Consider : Why is n't the warning fired for the second time ? I guess this has something to do with interning , but ca n't figure out what exactly.I 'd appreciate a cpython-source level explanation . | Python 2.7.5 ( default , Mar 9 2014 , 22:15:05 ) [ GCC 4.2.1 Compatible Apple LLVM 5.0 ( clang-500.0.68 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > 'abc ' == u'abc'True > > > 'ab\xDF ' == u'abc'__main__:1 : UnicodeWarning : Unicode equal comparison failed ... | UnicodeWarning fired only once |
Python | It is strange to see a piece of code using 'str in str in str ' syntax , e.g . : It seems the 'in ... in ... ' is similar to ' < ... < ... ' comparison . But a quick google did not guide me to the official answers . Any help ? | > > > 'test ' in 'testtest ' in 'testtesttest'True > > > 'test ' in 'testtest ' in 'tb3'False > > > 'test ' in 'testtesta ' in 'testtesttest'False > > > 'test ' in ( 'testtest ' in 'testtesttest ' ) Traceback ( most recent call last ) : File `` < input > '' , line 1 , in < module > 'test ' in ( 'testtest ' in 'testtest... | Python string in ... in syntax |
Python | In python I do n't want to write every single element into a file but a whole list as such . That means the text file should look like this for example : This is one examples to write each element from a list into a text file ( Writing a list to a file with Python ) . But I do n't need this , as I said.Can anyone help ... | [ `` elem1 '' , `` elem2 '' , `` elem3 '' ] [ `` elem1 '' , `` elem2 '' , `` elem3 '' ] [ `` elem1 '' , `` elem2 '' , `` elem3 '' ] | Writing a whole list AS SUCH to a text file in Python |
Python | I have two Pandas DataFrames that I would like to compare . For exampleandI want to find the index-column coordinates for any values that are shared , in this caseIs this possible ? | a b cA na na naB na 1 1C na 1 na a b cA 1 na 1B na na naC na 1 naD na 1 na bC 1 | Find same data in two DataFrames of different shapes |
Python | I have a question model : and an answer model related to it : I want to filter out all the questions with no answers . How can I do that in the view ? | class Question ( models.Model ) : ... . class Answer ( models.Model ) : user = models.ForeignKey ( User ) question = models.ForeignKey ( Question , on_delete=models.CASCADE ) | Django ; Querying the Database By Counts Of Related Objects |
Python | How can I detect whether a dictionary contains a back-edge aka back-reference that might end up in an infinite loop or cause a maximum recursion depth exception.So apparently python is smart enough to figure out back-edges and marks them by printing them as { ... } . Is there a way to access this information , so it ca... | x = { ' a':1 } x [ ' b ' ] = x # referencing same dict , creating back edgeprint ( x ) > { ' a ' : 1 , ' b ' : { ... } } | How do i check for Cycles/back edges in dictionaries ? { ... } |
Python | Using the `` re '' i compile the datas of a handshake like this : Then i print itI 'm unable to add image because i 'm new so this is the output : My question is , how can i take only the second piece of this data that is to say the `` hash_info '' ( the `` 606d47 ... '' ) ? I already tried with the group of re with th... | piece_request_handshake = re.compile ( '13426974546f7272656e742070726f746f636f6c ( ? P < reserved > \w { 16 } ) ( ? P < info_hash > \w { 40 } ) ( ? P < peer_id > \w { 40 } ) ' ) handshake = piece_request_handshake.findall ( hex_data ) root @ debian : /home/florian/Téléchargements # python script.py [ ( '000000000010000... | How to take an element after a re.compile ? |
Python | This one is causing me a headache , and I am having trouble to find a solution with a for-loop.Basically , my data looks like this : I would need to know how many times each number from each row in the short_list appears in each row of the long_list , and the comparison is NOT needed when both list indices are the same... | short_list = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] , [ 10 , 11 , 12 ] ] long_list = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 2 , 3 , 4 , 5 , 6 ] , [ 6 , 7 , 8 , 9 , 10 ] , [ 9 , 10 , 11 , 12 , 13 ] ] | Going through 2 lists with array data |
Python | Suppose I have the following array of arrays : Together with this Input array is the corresponding Label array for all input , so that : I need some way to check with all nested arrays of Input , to select ONLY the array with sufficient data points.By this I mean I want a way to eliminate ( or should I say delete ) all... | Input = np.array ( [ [ [ [ 17.63 , 0. , -0.71 , 29.03 ] , [ 17.63 , -0.09 , 0.71 , 56.12 ] , [ 0.17 , 1.24 , -2.04 , 18.49 ] , [ 1.41 , -0.8 , 0.51 , 11.85 ] , [ 0.61 , -0.29 , 0.15 , 36.75 ] ] ] , [ [ [ 0.32 , -0.14 , 0.39 , 24.52 ] , [ 0.18 , 0.25 , -0.38 , 18.08 ] , [ 0. , 0. , 0. , 0 . ] , [ 0. , 0. , 0. , 0 . ] , ... | Conditional filtering of ndarrays |
Python | I read here that it is recommended to use with open ( filename ) instead of using the pair open ( filename ) and filename.close ( ) ( at least for basic tasks ) and that it is also better to use try.Q1 : If my understanding is correct , what would be the proper order ? orQ2 : Which case is better if I want also to inse... | try : with open ( filename ) as f : do something , eg . match string with open ( filename ) as f : try : do something , eg . match string | Confused about the proper order of try and with in Python |
Python | The dataframe looks like : But I need output to be like : I understand that NaN is being treated as Object and those columns were being moved others . How can I detect columns even based on values in the column ? | col1 col2 col3 col4 col5 col6 col7points x1 0.6 ' 0 ' 'first ' 0.93 'lion ' 0.34 0.98x2 0.7 ' 1 ' 'second ' 0.47 'cat ' 0.43 0.76x3 NaN ' 0 ' 'third ' 0.87 'tiger ' 0.24 0.10x4 0.6 ' 0 ' 'first ' 0.93 'lion ' 0.34 0.98x5 0.5 ' 1 ' 'first ' 0.32 NaN 0.09 NaNx6 0.4 ' 0 ' 'third ' 0.78 'tiger ' 0.18 0.17x7 0.5 ' 1 ' 'seco... | How should i find the numeric columns in a dataframe which also contain Null values ? |
Python | I have a list of lists like : They all follow the same pattern ( one character string , 3 number strings , one character string , one number string ) . I would like to convert all of the number strings into integers and am having difficulties doing so.I have tried an exception loop , which does n't seem to be working (... | [ [ ' c ' , ' 2 ' , ' 3 ' , ' 4 ' , 'd ' , ' 1 ' ] , [ ' e ' , '14 ' , '16 ' , '18 ' , ' f ' , ' 1 ' ] , etc . ] rows = [ ] with open ( path ) as infile : for line in infile : line = line.strip ( ) if not line : continue try : [ [ int ( i ) for i in sub ] for i in rows for sub in i ] except ValueError : pass rows.appen... | How to convert only parts of a string list into integers |
Python | Whenever I run this code , python gives me : ValueError : not enough values to unpack ( expected 3 , got 2 ) I 'm trying to make a kind of an address book where you can add , delete and change information . I was trying to change the code in line 20 where there is a for-in loop ( this line is actually a source of probl... | members = { } class Member : def __init__ ( self , name , email , number ) : self.name = name self.email = email self.number = number def addmember ( name , email , number ) : members [ name ] = email , number print ( 'Member { 0 } has been added to addressbook'.format ( name ) ) def Check ( ) : print ( `` You 've got ... | Not enough values to unpack from dictionary items : expected 3 values , got 2 |
Python | I have an array : How do I select every b and c without a for loop ? Can I use slicing or anything else ? The resulting array should look like this : | [ a1 , b1 , c1 , d1 , a2 , b2 , c2 , d2 , a3 , b3 , etc ] [ b1 , c1 , b2 , c2 , b3 , c3 , etc ] | Extracting parts of array repeatedly |
Python | So I have a dict , which contains keys corresponding to a list , which contains str . I want to collect all the same values in said list and sum them together . Perhaps my explanation was confusing so I 'll provide an example : How would I create this function ? I was thinking of somehow making a for loop like this : I... | function_name ( { 'key1 ' : [ 'apple ' , 'orange ' ] , 'key2 ' : [ 'orange ' , 'pear ' } ) > > > { 'apple':1 , 'orange':2 , 'pear':1 } count = 0for fruit in dict_name : if food == 'apple ' count = count + fruit | How to return a list of frequencies for a certain value in a dict |
Python | For a while now I 'm mentally plagued by the clash of two design philosophies for physical systems modeling and I 'm wondering what kind of solutions the community came up for this.For complex ( er ) simulations , I love the abstraction of creating classes for objects and how object instances of classes can be identifi... | class Particle ( object ) : def __init__ ( self , x=0 , y=0 , z=0 ) : self.x = x self.y = y self.z = z def __repr__ ( self ) : return `` x= { } \ny= { } \nz= { } '' .format ( self.x , self.y , self.z ) def apply_lateral_wind ( self , dx , dy ) : self.x += dx self.y += dy start_values = np.random.random ( ( int ( 1e6 ) ... | How to combine class design and matrix math efficiently ? |
Python | Seeing the following code : it looks like python 's class variable is independent to each instance because change dog instance 's powers variable from no power to bark does not affect the cat instance 's powers variableHowever , by doing this : The example shows powers variable ( it is a list this time ) is static sinc... | class Super : powers = 'no power ' def __init__ ( self , name ) : self.name = name def add_power ( self , power ) : self.powers = powerdog = Super ( 'dog ' ) cat = Super ( 'cat ' ) dog.add_power ( `` bark '' ) print ( dog.powers ) # print barkprint ( cat.powers ) # print no power class Super : powers = [ `` no power ''... | Is Python class variable static ? |
Python | My JSON ( ~500mb ) file has multiple JSON objetcs , actually i just need to use the `` customer_id '' colunm . When i execute the code below , it gives memory error.Here is a example of an JSON object in `` online_pageviews.json '' Is there a way to only use the `` customer_id '' column ? What can i do to load this fil... | with open ( 'online_pageviews.json ' ) as f : online_pageviews = pd.DataFrame ( json.loads ( line ) for line in f ) { `` date '' : `` 2018-08-01 '' , '' visitor_id '' : `` 3832636531373538373137373 '' , '' deviceType '' : `` mobile '' , '' pageType '' : `` product '' , '' category_id '' : `` 6365313034 '' , '' on_produ... | Handling with large JSON data in python |
Python | Hi I have a pandas df similar to belowand I want to transform the df to another df like thisIn this case , the dictionary will be parse into single lines where size_weight_gram and contain the value.the code for df | information recordname applesize { 'weight ' : { 'gram':300 , 'oz':10.5 } , 'description ' : { 'height':10 , 'width':15 } } country Americapartiesrelated [ { 'nameOfFarmer ' : 'John Smith ' } , { 'farmerID ' : 'A0001 ' } ] information recordname applesize_weight_gram 300size_weight_oz 10.5size_description_height 10size... | Parsing a set of dictionary to single line pandas ( Python ) |
Python | Numpy 's sum function is returning the correct expected result , but the default python 's sum is not ( at least not for uint8 datatype , which makes it even more confusing ) : | In [ 1 ] : import numpy as np In [ 2 ] : x = np.random.randint ( 2 , size = ( 1000,100 ) ) In [ 3 ] : x Out [ 3 ] : array ( [ [ 1 , 1 , 0 , ... , 0 , 1 , 1 ] , [ 1 , 1 , 1 , ... , 0 , 0 , 0 ] , [ 1 , 1 , 0 , ... , 1 , 0 , 1 ] , ... , [ 1 , 0 , 0 , ... , 1 , 0 , 1 ] , [ 0 , 0 , 1 , ... , 0 , 1 , 1 ] , [ 1 , 1 , 0 , ... ... | Python 's sum not returning same result as NumPy 's numpy.sum |
Python | I am new to Python from R. I have recently spent a lot of time reading up on how everything in Python is an object , objects can call methods on themselves , methods are functions within a class , yada yada yada.Here 's what I do n't understand . Take the following simple code : If I want to know how many times the num... | mylist = [ 3 , 1 , 7 ] mylist.count ( 7 ) seven_counts = mylist.count ( 7 ) mylist.append ( 9 ) newlist = mylist.append ( 9 ) | How do you know in advance if a method ( or function ) will alter the variable when called ? |
Python | I want to use two for-loops inside a list-comprehension , but I want to use the name of the second as an index of the first iterable . How can I do that ? Example : Error : | l = [ [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ] [ x for x in l [ i ] for i in range ( len ( l ) ) ] Traceback ( most recent call last ) : File `` python '' , line 2 , in < module > NameError : name ' i ' is not defined | How can I use a nested name as the __getitem__ index of the previous iterable in list comprehensions ? |
Python | Overriding and inheritance is seeming to work differently than I expect , let me explain this situation . I have three classes : Card , Treasure , and Copper . Copper inherits from Treasure and Treasure inherits from Card . The only difference between Treasure and Card is a single method that Treasure overrides . The o... | class Card : normal_full_table = 6 pile_player_rate = 10 @ staticmethod def pile_setup ( player_count ) : pass from card.card import Cardfrom math import floorclass Treasure ( Card ) : @ staticmethod def pile_setup ( player_count ) : return ( floor ( player_count/Card.normal_full_table ) + 1 ) * Card.pile_player_rate f... | How to override class attribute two levels deep ? |
Python | So I think this question can be visualized the best as following , given a dataframe : So what I want to get is : I want to get the ID that has the second highest value for val_1 and highest value for true_val ( which is always the one with 1.0 ) and then return both corresponding ID 's for every label.Anyone have an i... | val_1 true_val ID label-0.0127894447 0.0 1 A0.9604560385 1.0 2 A0.0001271985 0.0 3 A0.0007419337 0.0 3 B0.3420448566 0.0 2 B0.1322384726 1.0 4 B label ID_val_1_second_highest ID_true_val_highestA 3 2B 4 4 label true_id top1_id_val_1 top2_id_val_1 top3_id_val_1 A 2 2 3 1 B 4 2 4 3 | How to get second highest value in a pandas column for a certain ID ? |
Python | I am currently reading Reinforcement Learning : An Introduction ( RL : AI ) and try to reproduce the first example with an n-armed bandit and simple reward averaging.AveragingIn order reproduce the graph from the PDF , I am generating 2000 bandit-plays and let different agents play 2000 bandits for 1000 steps ( as desc... | new_estimate = current_estimate + 1.0 / step * ( reward - current_estimate ) from abc import ABCfrom typing import Listimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom multiprocessing.pool import Poolclass Strategy ( ABC ) : def update_estimates ( self , step : int , estimates : np.ndarray , act... | Using simple averaging for reinforcment learning |
Python | I want to swap keys in a dictionary but keep the values the same.This script will be used to set end of service dates . In essence the release date of the newer version is the end of service date of the older one . I have an ordered dictionary containing the version as a key and the release date as its value . Looking ... | { '10.1.0 : '2019-01-01 ' , ' 9.3.0 ' : '2018-11-02 ' , ' 9.2.0 ' : '2018-06-20 ' , ' 9.1.0 ' : '2018-03-06 ' } { ' 9.3.0 ' : '2019-01-01 ' , ' 9.2.0 ' : '2018-11-02 ' , ' 9.1.0 ' : '2018-06-20 ' } | Swap keys in list of dicts in python |
Python | I 'm trying to write some dataframe to a csv file . However , the columns F to N should me empty . This is the dataframe im using : The letters are to clarify under which column the data should go . For example , ' c ' is going under the column C. However , with the current line ' o ' goes under the column F. Is there ... | data = [ [ ' a ' ] , [ ' b ' ] , [ ' c ' ] , [ 'd ' ] , [ ' e ' ] , [ ' o ' ] ] dataFrame = pandas.DataFrame ( data ) .transpose ( ) | Creating multiple empty list seperated by comma |
Python | I 'm trying to calculate the eigenvectors and eigenvalues of this matrixIf I set the dimensions of the matrix to n < 110 the output is fine . However , if I set it to n > = 110 both the eigenvalues and the eigenvector components become complex numbers with significant imaginary parts . Why does this happen ? Is it supp... | import numpy as npla = 0.02mi = 0.08n = 500d1 = np.full ( n , - ( la+mi ) , np.double ) d1 [ 0 ] = -lad1 [ -1 ] = -mid2 = np.full ( n-1 , la , np.double ) d3 = np.full ( n-1 , mi , np.double ) A = np.diagflat ( d1 ) + np.diagflat ( d2 , -1 ) + np.diag ( d3 , 1 ) e_values , e_vectors = np.linalg.eig ( A ) | Eigenvectors are complex but only for large matrices |
Python | I have a list of dict which is being converted to a dataframe . When I attempt to pass the columns argument the output values are all nan.Why is this happening ? | # This code does not result in desired outputl = [ { ' a ' : 1 , ' b ' : 2 } , { ' a ' : 3 , ' b ' : 4 } ] pd.DataFrame ( l , columns= [ ' c ' , 'd ' ] ) c d0 NaN NaN1 NaN NaN # This code does result in desired outputl = [ { ' a ' : 1 , ' b ' : 2 } , { ' a ' : 3 , ' b ' : 4 } ] df = pd.DataFrame ( l ) df.columns = [ ' ... | Assigning column names while creating dataframe results in nan values |
Python | I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.However , I can not figure out how to write the conditional that is commented in pseudo code above , without skipping ... | class A ( ) : def __init__ ( self ) : self.Blist = [ B ( 1 ) , B ( 2 ) , B ( 3 ) ] # where B ( 2 ) .is_bad ( ) is True , while the other .is_bad ( ) are False def __iter__ ( self ) : nextB = iter ( self.Blist ) # if nextB.next ( ) .is_bad ( ) : # return after skip # else : # return nextB | how to inquire an iterator in python without changing its pre-inquire state |
Python | The docs say that values views are not treated as set-like , but sometimes they are : Why implement set-returning set semantics but then fail with an actual set ? | > > > d = { 1 : 1 } > > > d.values ( ) | d.keys ( ) { 1 } > > > d.values ( ) & d.keys ( ) { 1 } > > > d.values ( ) - d.keys ( ) set ( ) > > > d.values ( ) - { 1 } TypeError : unsupported operand type ( s ) for - : 'dict_values ' and 'set ' | When can dict_values views be set-like ( and why ) ? |
Python | I made a simple code on python interpreter and run it . the result -0.19999999999999996 is weird . I think ... . it is caused by IEEE 754 rule . But when I try to run almost same code by file , result is a lot different.the result is `` -0.2 '' . IEEE 754 rule does not affect the result.what is the difference between f... | Python 3.5.3 ( v3.5.3:1880cb95a742 , Jan 16 2017 , 16:02:32 ) [ MSC v.1900 64 bit ( AMD64 ) ] on win32Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > import numpy as np > > > x=np.array ( [ 0,1 ] ) > > > w=np.array ( [ 0.5,0.5 ] ) > > > b=-0.7 > > > np.sum ( w*x ) +b-0.199... | why the result is different between running python interpreter and python code ? |
Python | From the following list of filenames I am trying to retrieve the highlighted parts : something something Ah6d8c.txtsomething Qd6h7s.txtsomethingAcKhJssomething.txt7h6c8c something.txtThe pattern is:6 characters longstarts with 2-9 or A K Q J T , both lower and uppercasethe second character is always h s c d , both lowe... | import osimport reroot = `` C : /root '' data = dict ( ) re_pattern = `` [ a-zA-Z|2-9 ] [ h|s|c|d ] [ a-zA-Z|2-9 ] [ h|s|c|d ] [ a-zA-Z|2-9 ] [ h|s|c|d ] '' for folder in os.listdir ( root ) : data [ folder ] = dict ( ) for item in os.listdir ( f '' { root } / { folder } '' ) : board_id = re.findall ( item , re_pattern... | Find an alternating ( letter or number ) + letter pattern in a file name |
Python | Havingwill execute bar even with from example import foo.I remember that long time ago I saw something like : but I 'm not sure if it 's the best way and now , when I am stuck with this , I ca n't find any info on how to deal with this behaviour.What is the correct way to have function call as a default function argume... | # example.pydef foo ( arg=bar ( ) ) : pass # example.pydef foo ( arg=lambda : bar ( ) ) : pass | Function call as a default function argument |
Python | long time reader first time asker.I am working on some vtt ( closed caption ) files that I need to edit the timestamps for . The format of the file is as follows : I have written the following code to read the file , calculate the new timestamps ( 5 % slower ) and spit out the new timestamps : The calculations work gre... | 17700:07:37.450 -- > 00:07:39.690- [ Liz ] How would you suggest an organization devise17800:07:39.690 -- > 00:07:41.719the accountabilities for culture ? 17900:07:41.719 -- > 00:07:43.690- [ Tamara ] It is a shared accountability from sys import argvscript , filename = argvadjustment = input ( `` Adjustment multiplier... | Reading , editing , and writing over every 4th line in a text file |
Python | I often need to do summations over certain rows or columns of a larger NumPy array . For example , take this array : Suppose I want to sum only where the row index is 0 or 2 , AND the column index is either 0 , 2 , 4 , or 5 . In other words , I want the sum of the subarrayI generally do this with NumPy 's incredibly us... | > > > c = np.arange ( 18 ) .reshape ( 3 , 6 ) > > > print ( c ) [ [ 0 1 2 3 4 5 ] [ 6 7 8 9 10 11 ] [ 12 13 14 15 16 17 ] ] [ [ 0 2 4 5 ] [ 12 14 16 17 ] ] > > > np.sum ( c [ np.ix_ ( [ 0,2 ] , [ 0,2,4,5 ] ) ] ) 70 e = np.arange ( 108 ) .reshape ( 2 , 3 , 3 , 6 ) new_sum = np.empty ( ( 2,3 ) ) for i in range ( 2 ) : fo... | Avoiding loops when using NumPy 's sum |
Python | Suppose I have a dataframe like so : I want to sum up the values for 4 elements of rows and columns for example . This would give me 1+5+4+7=17and 5+9+3+1=18 , 2+3+4+6=15 , ... outputHow do I do this in pandas ? | a b c d e f1 . 1 5 5 9 2 32 . 4 7 3 1 4 63 . 2 3 8 9 2 1 4 . 7 3 1 4 7 115 . 8 5 4 9 0 36 . 7 8 4 7 2 1 a b c 1 . 17 18 15 2 . 18 22 21 3 . 28 27 6 | sum DataFrame rows and columns |
Python | I have a Django model that looks something like this : I want to find the latest entry for all sets of combinations of ( field1 , field2 , field3 ) tuples , and grab the value of value from that row . For example lets say the table would has the following rows : I would want the result of my query to return rows 2,3,4I... | class MyModel ( Model ) : field_1 = IntegerField ( ) field_2 = IntegerField ( ) field_3 = IntegerField ( ) value = IntegerField ( ) time_stamp = DateTimeField ( ) Field1 , Field2 , Field3 , TimeStamp , Value1 , 1 , 1 , 1/1/2015 , 11 , 1 , 1 , 1/2/2015 , 21 , 1 , 2 , 1/1/2015 , 32 , 2 , 2 , 1/1/2015 , 4 dims = MyModel.o... | Get latest entry in django in multiple dimensions |
Python | I am building a CLI app with Python and the Click library.How do I achieve the following use case : First I only want the subcommand to be followed by an argument no options are required : This is straight forward.But how can I write the code that if argument2 is set that also some options are required ? For example : ... | $ myapp subcommand argument $ myapp subcommand argument2 -o1 abc -o2 def $ ./myapp.py install basic $ ./myapp.py install custom -o1 abc -o2 def | How require options for CLI app based on Python and Click |
Python | I have input data like this.i want to duplicate 5 times and change date by increasing yearsIs this possible to do using pandas repeat ? . | NAME | PLACE | DATE A | X | 2020-04-30 B | Y | 2019-04-30 NAME | PLACE | DATE A | X | 2020-04-30 A | X | 2021-04-30 A | X | 2022-04-30 A | X | 2023-04-30 A | X | 2024-04-30 A | X | 2025-04-30 B | Y | 2019-04-30 B | Y | 2020-04-30 B | Y | 2021-04-30 B | Y | 2022-04-30 B | Y | 2023-04-30 B | Y | 2024-04-30 | pandas series repeat n time and change column value |
Python | I am trying to recreate snake in pygame ( python 3 ) and what I am trying to do is every frame , check the velocity of the snake by checking keypress , but it very rarely realises that I am pressing a key , what am I doing wrong/what should I do instead ( code is below ) , I do n't see why this is n't working as everyt... | import pygamefrom pygame.locals import *import mathimport randompygame.init ( ) display = pygame.display.set_mode ( ( 512 , 512 ) ) pygame.display.set_caption ( `` Snake '' ) display.fill ( ( 255 , 255 , 255 ) ) def handle ( ) : global x , y for event in pygame.event.get ( ) : if event.type == QUIT : pygame.quit ( ) de... | Pygame loop checking velocity rarely |
Python | I have a list , the elements in the list is a dict type.For example , I want to define a new list with the name db_list.The db_list stores dict element likes this : The db_list removes the duplicate elements in da_list , and adds the frequency of each dictionary.How to do this ? | da_list = [ { 'Surface ' : 'APPLE ' , 'BaseForm ' : 'apple ' , 'PN':0.5 } , { 'Surface ' : 'BANANA ' , 'BaseForm ' : 'banana ' , 'PN':0.4 } , { 'Surface ' : 'ORANGE ' , 'BaseForm ' : 'orange ' , 'PN ' : -0.1 } , { 'Surface ' : 'APPLE ' , 'BaseForm ' : 'apple ' , 'PN':0.5 } , { 'Surface ' : 'BANANA ' , 'BaseForm ' : 'ba... | How to calculate the frequency of dictionary elements and remove duplicate dictionary elements in python list ? |
Python | I have a pandas DataFrame which is of the form : The column D is a raw-string column with multiple categories in each entry . The value of entry is calculated by dividing the last two values for each category . For example , in 2nd row : I need to split column D based on it 's categories and join them to my DataFrame .... | A B C DA1 6 7.5 NaNA1 4 23.8 < D1 0.0 6.5 12 4 , D2 1.0 4 3.5 1 > A2 7 11.9 < D1 2.0 7.5 10 2 , D3 7.5 4.2 13.5 4 > A3 11 0.8 < D2 2.0 7.5 10 2 , D3 7.5 4.2 13.5 4 , D4 2.0 7.5 10 2 , D5 7.5 4.2 13.5 4 > D1 = 12/4 = 3D2 = 3.5/1 = 3.5 A B C D1 D2 D3 D4 D5A1 6 7.5 NaN NaN NaN NaN NaNA1 4 23.8 3.0 3.5 NaN NaN NaNA2 7 11.9... | How to split variable sized string-based column into multiple columns in Pandas DataFrame ? |
Python | I have a python file in which i have two functions that each of them raise an exception.My question , is it possible to store these exceptions in a variable , like list for example -- [ e1 , e2 ] -- , in order to control the order of exceptions execution in another function , say h ? | def f ( ) : raise e1def g ( ) : raise e2 | How to report an exception for later |
Python | I have a C function that reads a binary file and returns a dynamically sized array of unsigned integers ( the size is based off metadata from the binary file ) : This answer appears to be saying that the correct way to pass the created array from C to Python is something like this : However , when I run the python wrap... | //example.c # include < stdio.h > # include < stdlib.h > __declspec ( dllexport ) unsigned int *read_data ( char *filename , size_t* array_size ) { FILE *f = fopen ( filename , `` rb '' ) ; fread ( array_size , sizeof ( size_t ) , 1 , f ) ; unsigned int *array = ( unsigned int * ) malloc ( *array_size * sizeof ( unsign... | How do you wrap a C function that returns a pointer to a malloc 'd array with ctypes ? |
Python | I have an unexpected behavior when adding a new row to a pre-allocated DataFrame after I added a new column to this DataFrame.I created the following minimal example ( using Python 3.6.5 and Panda 0.23.0 ) : First , I create a pre-allocated DataFrame with 3 columnsThen , I am adding a few rows , which works like expect... | import pandas as pddf = pd.DataFrame ( columns= ( ' A ' , ' B ' , ' C ' ) , index=range ( 5 ) ) # The resulting DataFrame df # A B C # 0 NaN NaN NaN # 1 NaN NaN NaN # 2 NaN NaN NaN # 3 NaN NaN NaN # 4 NaN NaN NaN new_row = { ' A':0 , ' B':0 , ' C':0 } df.loc [ 0 ] = new_rowdf.loc [ 1 ] = new_rowdf.loc [ 2 ] = new_row #... | Python Pandas adds column header as entry instead of actual data after adding new column |
Python | I have a dataframe like this , I want to make duplicate of n times for the same dataframe . to do that i used , pd.concat ( [ df ] *3 ) .reset_index ( drop=True ) But now i have a data frame like below , In this , I wan na do the same operation but column c should be added by one day.i.e. , I tried like this , My code ... | a b 0 c1 y 1 c2 n 2 c3 n 3 c4 y 4 c5 y a b c0 c1 y 2017-10-101 c2 n 2017-10-102 c3 n 2017-10-103 c4 y 2017-10-104 c5 y 2017-10-10 a b c0 c1 y 2017-10-101 c2 n 2017-10-102 c3 n 2017-10-103 c4 y 2017-10-104 c5 y 2017-10-100 c1 y 2017-10-111 c2 n 2017-10-112 c3 n 2017-10-113 c4 y 2017-10-114 c5 y 2017-10-110 c1 y 2017-10-... | Duplicate of dataframe but increasing date |
Python | I am trying to sort lines between patterns in Bash or in Python . I would like to sort the lines based on the second field with `` , '' as delimiter.Given the following text input file : I expect as output : I have tried to adapt this suggestion by glenn jackman found in another post but it only works for 2 pattern as ... | Sample1T1,64,0.65 MEDIUMT2,60,0.45 LOWT3,301,0.68 MEDIUMT4,65,0.75 HIGHT5,59,0.72 MEDIUMT6,51,0.82 HIGHSample2T1,153,0.77 HIGHT2,152,0.61 MEDIUMT3,154,0.67 MEDIUMT4,283,0.66 MEDIUMT5,161,0.65 MEDIUMSample3T1,147,0.71 MEDIUMT2,154,0.63 MEDIUMT3,45,0.63 MEDIUMT4,259,0.77 HIGH Sample1T6,51,0.82 HIGHT5,59,0.72 MEDIUMT2,60,... | Sort lines in text file between patterns |
Python | I 'm working from the book `` Program Arcade GamesWith Python And Pygame '' and working through the 'lab ' at the end of Chapter 12 : Introduction to Classes.This code I 've written for it randomises the coordinates size and movement direction for each shape created in 'my_list ' by calling its constructor but not the ... | import pygameimport random # Define some colorsBLACK = ( 0 , 0 , 0 ) WHITE = ( 255 , 255 , 255 ) GREEN = ( 0 , 255 , 0 ) RED = ( 255 , 0 , 0 ) class Rectangle ( ) : x = 0 y = 0 width = 10 height = 10 change_x = 2 change_y = 2 color = [ 0 , 0 , 0 ] def __init__ ( self ) : self.x = random.randrange ( 0 , 700 ) self.y = r... | Why does n't this code produce shapes with random colors ? |
Python | gives result ( new_name ) : :instead of : :..thanx in advance | pattern = r ' [ -\\ [ \\ ] ] 'regex = re.compile ( pattern ) name = '123 [ shiv'new_name = regex.sub ( ' _ ' , name ) '_____shiv ' '123__shiv ' | Unexpected Result in Regex |
Python | I have a list of urls ( unicode ) , and there is a lot of repetition.For example , urls http : //www.myurlnumber1.com and http : //www.myurlnumber1.com/foo+ % bar % baz % qux lead to the same place.So I need to weed out all of those duplicates.My first idea was to check if the element 's substring is in the list , like... | for url in list : if url [ :30 ] not in list : print ( url ) | Checking if element in list by substring |
Python | I see that the code below can check if a word is Now I want to check if a word in a list is in some other list as below : What 's the best way to check if words in list1 are in compSet , and doing something over non-existing elements , e.g. , appending 'and ' to compSet or deleting 'and ' from list1 ? _________________... | list1 = 'this'compSet = [ 'this ' , 'that ' , 'thing ' ] if any ( list1 in s for s in compSet ) : print ( list1 ) list1 = [ 'this ' , 'and ' , 'that ' ] compSet = [ 'check ' , 'that ' , 'thing ' ] myPath = '/some/my path/is here'if not any ( myPath in s for s in sys.path ) : sys.path.insert ( 0 , myPath ) myPaths = [ '... | comparing strings in list to strings in list |
Python | I am trying to do this : word test should be found in some text and be replaced with < strong > test < /strong > . but the thing is , Test should be also catched and be replaced with < strong > Test < /strong > . I tried this : but in this case , Someword is becoming someword . Am I using re somehow wrong ? I want < st... | word = `` someword '' text = `` Someword and many words with someword '' pattern = re.compile ( word , re.IGNORECASE ) result = pattern.sub ( ' < strong > '+word+ ' < /strong > ' , text ) | regular expression - string replacement `` as is '' |
Python | I 'm trying to figure out how to calculate the top 5 products with biggest change in unit sales over prior month . Below is a small slice of my data , here Vendor_SKU and Order_Month are both index created by pd.groupby.What I 'd like to achieve is to calculate all difference of the same product and find the ones with ... | amz = amz.groupby ( [ 'Vendor_SKU ' , 'Order_Month ' ] ) [ 'Quantity ' ] .sum ( ) Vendor_SKU Order_Month DLEBL140 2018-11-01 17.0 2018-12-01 13.0 DLEBL90 2018-11-01 29.0 2018-12-01 39.0 DLEBR160 2018-11-01 16.0 2018-12-01 17.0 DLEG180 2018-11-01 30.0 2018-12-01 20.0 DLER150 2018-11-01 22.0 2018-12-01 23.0 DLEW110 2018-... | Get largest difference within a group |
Python | I am working on a list of lists and accessing columns has been very confusing . Let 's assume x is defined as following : Now , both x [ 1 ] [ : ] and x [ : ] [ 1 ] yield the same result : Can someone explain why ? Thank you | x = [ [ int ( np.random.rand ( ) *100 ) for i in xrange ( 5 ) ] for x in xrange ( 10 ) ] pprint.pprint ( x ) [ [ 86 , 92 , 95 , 78 , 68 ] , [ 76 , 80 , 44 , 30 , 73 ] , [ 48 , 85 , 99 , 35 , 14 ] , [ 3 , 84 , 50 , 39 , 47 ] , [ 3 , 7 , 67 , 28 , 65 ] , [ 19 , 13 , 98 , 53 , 33 ] , [ 9 , 97 , 35 , 25 , 89 ] , [ 48 , 3 ,... | Why x [ i ] [ : ] =x [ : ] [ i ] where x is a list of lists ? |
Python | I 'm using python 2.7 , and I have been assigned ( self-directed assignment , I wrote these instructions ) to write a small static html generator , and I would like assistance finding new-to-python oriented resources for reading portions of files at a time . If someone provides code answers , that 's great , but I want... | # doctype to titlecopyLine = Falsefor line in template.readlines ( ) : if not ' < title > ' in line : copyLine = True if copyLine : outputhtml.write ( line ) copyLine = Falseelse : templateSeek = template.tell ( ) break # read name of messagetitleOut = message.readline ( ) print titleOut , `` is the title of the new pa... | Reading in parts of file , stopping and starting with certain words |
Python | The company I work at requires a list of all inaccessible images/shapes in a .pptx document ( do n't have alt-text and are n't decorative ) . To automate the process , I 'm writing a script that extracts all inaccessible images/shapes in a specified .pptx and compiles a list . So far , I 've managed to make it print ou... | < p : cNvPr id= '' 3 '' name= '' Picture 2 '' > < a : extLst > < a : ext uri= '' { FF2B5EF4-FFF2-40B4-BE49-F238E27FC236 } '' > < a16 : creationId xmlns : a16= '' http : //schemas.microsoft.com/office/drawing/2014/main '' id= '' { 77922398-FA3E-426B-895D-97239096AD1F } '' / > < /a : ext > < a : ext uri= '' { C183D7F6-B4... | Check if image is decorative in powerpoint using python-pptx |
Python | I have the following code setting up the logger : When I run it , I get output like : I presume the first one is the console output ? How do I get rid of the duplicate one ? UPDATEThanks guys for the answers , now I know why I get duplicates , the reason I did it this way because the default stream handler does not out... | import logginglogging.basicConfig ( format= ' % ( asctime ) s % ( levelname ) s : % ( message ) s ' , level=logging.INFO ) log = logging.getLogger ( ) handler = logging.StreamHandler ( sys.stdout ) log.addHandler ( handler ) log.info ( 'abc ' ) 2020-06-10 13:32:16,245 INFO : abcabc import sysimport logginglog = logging... | Python logging why outputing twice ? |
Python | I 'm wondering if there is any use for explicitly using the getter decorator for class properties : why would I ever explicitly use the getter here ? Does n't it render the code within p ( self ) unreachable ? Basically , is there any practical reason to use it ? | class A : @ property def p ( self ) : return self._p @ p.setter def p ( self , val ) : assert p < 1000 self._p = val @ p.getter def p ( self ) : return self._p | Is there any use for a python property getter ? |
Python | Reading the book `` Introduction to computer science using Python '' , by Charles Dierbach , I got a question : In page 210 , he says `` A reference is a value that references , or “ points to , ” the location of another entity . A variable ’ s reference value can be determined with built-in function id . `` So a refer... | > > > a = 3 > > > id ( a ) 4548344816 | How are a name and its reference value related ? |
Python | My NodeJS & Python scripts do n't return the same hash , what could cause this issue ? Node.jsPython3I guess it could be the extra = to avoid the incorrect padding but my key ends with a single = . | const { createHmac } = require ( `` crypto '' ) ; var message = 'v1:1583197109 : 'var key = 'Asjei8578FHasdjF85Hfjkasi875AsjdiAas_CwueKL='const digest = Buffer.from ( key , `` base64 '' ) ; const hash = createHmac ( `` sha256 '' , digest ) .update ( message ) .digest ( `` hex '' ) ; console.log ( hash ) > 7655b4f816dc7... | Node & python do n't return the same hash256 |
Python | I am using Grakn with the Python driver . I am trying a use case where the user can search for a song , for example Despacito , and then get recommendations of other similar songs . The result must contain songs of the same genre , and from the same producer . When I search for a song , I am able to get the related ent... | from grakn.client import GraknClienturi = `` localhost:48555 '' keyspace = `` grakn_demo '' client = GraknClient ( uri=uri ) session = client.session ( keyspace=keyspace ) tx = session.transaction ( ) .write ( ) graql = 'match $ s isa song , has producer `` Records X '' , song-name `` Despacito '' , singer `` Luis Fons... | Fetching data from Grakn with Python |
Python | I have a df like this : Trying to divide the elements in the lists in col1 and col2 together to get what 's in the result column : Tried a lot of different approaches - but always get an error.Attempts : Any ideas ? | col1 col2 [ 1,3,4,5 ] [ 3,3,6,2 ] [ 1,4,5,5 ] [ 3,8,4,3 ] [ 1,3,4,8 ] [ 8,3,7,2 ] col1 col2 result [ 1,3,4,5 ] [ 3,3,6,2 ] [ .33,1 , .66,2.5 ] [ 1,4,5,5 ] [ 3,8,4,3 ] [ .33 , .5,1.25,1.66 ] [ 1,3,4,8 ] [ 8,3,7,2 ] [ .33,1 , .57,4 ] # attempt1df [ 'col1 ' ] .div ( df [ 'col2 ' ] , axis=0 ) # attempt2from operator import... | Divide two pandas columns of lists by each other |
Python | I have been struggling to find the pandas solution to this without looping : input : output : I have tried so many different things over the past hour or so , and I know the solution will be an embarrassingly simple one-liner . Thanks for your help -- not my python day today ! | df = pd.DataFrame ( { ' A ' : [ [ 6,1,1,1 ] , [ 1,5,1,1 ] , [ 1,1,11,1 ] , [ 1,1,1,20 ] ] } ) A0 [ 6 , 1 , 1 , 1 ] 1 [ 1 , 5 , 1 , 1 ] 2 [ 1 , 1 , 11 , 1 ] 3 [ 1 , 1 , 1 , 20 ] A B0 [ 6 , 1 , 1 , 1 ] 61 [ 1 , 5 , 1 , 1 ] 52 [ 1 , 1 , 11 , 1 ] 113 [ 1 , 1 , 1 , 20 ] 20 | Return value from list according to index number |
Python | In Python 2 , is there a canonical way to document that a method may be more than one type ? Here 's how I 've done it : where I used the notation ( int or str ) to indicate that the argument may be either an integer or a string.How do Python 2 programs usually document that a method argument can be of more than one ty... | def __init__ ( self , work_order_number ) : `` '' '' This message communicates that a job is being rerun . Olio will forget everything it knows about the job . Args : work_order_number ( int or str ) : Work order number `` '' '' payload = { 'work_order_number ' : str ( work_order_number ) , } self.content = json.dumps ... | How to document argument that takes multiple types |
Python | I ca n't see why value_counts is giving me the wrong answer . Here is a small example : The only values that occur in these data are 0 and 100 . But value_counts tells me the range ( 20.0,40.0 ] has the most values and ( 80.0,100.0 ] has none.Of course my real data has more values , different keys , etc . but this illu... | In [ 81 ] : d=pd.DataFrame ( [ [ 0,0 ] , [ 1,100 ] , [ 0,100 ] , [ 2,0 ] , [ 3,100 ] , [ 4,100 ] , [ 4,100 ] , [ 4,100 ] , [ 1,100 ] , [ 3,100 ] ] , columns= [ 'key ' , 'score ' ] ) In [ 82 ] : dOut [ 82 ] : key score0 0 01 1 1002 0 1003 2 04 3 1005 4 1006 4 1007 4 1008 1 1009 3 100In [ 83 ] : g=d.groupby ( 'key ' ) [ ... | pandas value_counts with bins applied to a groupby produces incorrect results |
Python | I have a dataframe with mixed data types and I would like to change the values of str cells ( each consisting of two letters plus three numbers ) so that uneven number become even numbers but the number decreases . AB123 should become AB122 while not changing the letter before it . Here is an example dataframe with mix... | df = pd.DataFrame ( { 'Opportunity ' : [ 'AB122 ' , 'AB123 ' , 'AB125 ' , 'AB124 ' ] , 'Quantity ' : [ 2 , 3 , 4 , 1 ] , 'Member ' : [ `` AACC '' , `` AACC '' , `` AACC '' , 'DDEE ' ] } ) print ( df ) Opportunity Quantity Member0 AB122 2 AACC1 AB123 3 AACC2 AB121 4 AACC3 AB120 1 DDEE print ( df2 ) Opportunity Quantity ... | Change value of uneven to specific even numbers |
Python | Can someone explain this behavior to me ? I was expecting both indexing operations to return the same ( first ) result.Then I sort of got it : Now , I do n't know the internals of pandas and why it implicitly converts strings to dates when given a range but not when given a list , but my guess is that a range makes it ... | import pandas as pddates = pd.date_range ( ' 1/1/2000 ' , periods=8 ) df = pd.DataFrame ( np.random.randn ( 8 , 4 ) , index=dates , columns= [ ' A ' , ' B ' , ' C ' , 'D ' ] ) df.ix [ '2000-01-01 ' : '2000-01-02 ' , [ ' A ' , ' C ' ] ] # # Output : A C2000-01-01 0.224944 -0.6893822000-01-02 -0.824735 -0.805512df.ix [ [... | Unexpected result using .ix indexing with list vs range |
Python | Scenario : I retrieved 3 lists from a N-triples file , and now I am trying to combine them into a single , organized list.Original format : While looping the ntriples file , I produced 3 lists ( each is a column of the table above ) . I am now trying to match them into something like this : So far , I used the function... | + -- -- -- -- + -- -- -- -- -+ -- -- -- -- +| 100021 | hasdata | y |+ -- -- -- -- + -- -- -- -- -+ -- -- -- -- +| 100021 | name | USER1 |+ -- -- -- -- + -- -- -- -- -+ -- -- -- -- +| 100021 | extra1 | typer |+ -- -- -- -- + -- -- -- -- -+ -- -- -- -- +| 100021 | extra2 | reader |+ -- -- -- -- + -- -- -- -- -+ -- -- -- ... | Merging Lists by Index in Python |
Python | I am simply printing line by line list from the loop and my output is something like this : But in my excel output im just only getting the first line something like this : My expected result is these : My current Code is here : Any suggestion or comments . | [ ' 4.0\n ' , ' 17.2\n ' , ' 7.0\n ' ] [ ' 0.0\n ' ] [ ' 4.0\n ' , ' 16.7\n ' , ' 4.0\n ' ] [ ' 4.0\n ' , ' 16.7\n ' , ' 4.0\n ' ] [ ' 4.0\n ' , ' 16.7\n ' , ' 4.0\n ' ] [ ' 4.0\n ' , ' 16.7\n ' , ' 4.0\n ' ] [ ' 4.0\n ' , ' 16.4\n ' , ' 4.0\n ' ] count = 0 DataList = [ ] for line , file in enumerate ( PM2Line ) : if P... | How to get output line by line using xlsWriterr |
Python | I am displaying images from a 2D array with pyplot and have removed axis markings and padding . However , between rows of images , there is still whitespace which I would like to remove . The images themselves have no whitespace.The code yields something likeAny ideas on how I should deal with the issue ? | fig = plt.figure ( figsize= ( 10 , 10 ) ) for x in range ( quads_x ) : for y in range ( quads_y ) : # ADD IMAGES fig.add_subplot ( quads_y , quads_x , ( quads_x * x ) + y + 1 ) plt.imshow ( cv2.imread ( `` ./map/ '' + winning_maps [ x ] [ y ] , 0 ) ) # PYPLOT FORMATTING plt.subplots_adjust ( wspace=0 , hspace=0 ) ax = ... | Issues removing vertical white spaces between rows of images in matplotlib |
Python | In the Python console started by PyCharm , it looks like runfile is an imported function : Since it 's a name in the local scope , should n't it be listed in dir ( ) 's output ? | In [ 21 ] : runfileOut [ 21 ] : < function _pydev_bundle.pydev_umd.runfile ( filename , args=None , wdir=None , is_module=False , global_vars=None ) > In [ 22 ] : print ( dir ( ) ) [ 'In ' , 'Out ' , ' _ ' , '_12 ' , '_13 ' , '_14 ' , '_15 ' , '_16 ' , '_17 ' , '_18 ' , '_19 ' , '_21 ' , '_3 ' , '_5 ' , '_6 ' , '_7 ' ,... | Why are some functions omitted in ` dir ( ) ` output ? |
Python | Is it possible to wrap the method name in the definition of a function ? I have an exceptionally long method name and I 'm wondering if it 's possible to wrap it like so : I have tried doing this , but I get a syntax error : | # method name is my_really_long_method_name_wow_this_is_really_longdef my_really_long_method_name_ wow_this_is_really_long ( ) : pass def my_really_long_method_name_\ wow_this_is_really_long ( ) : pass | Wrapping method name in definition |
Python | I have pivoted the Customer ID against their most frequently purchased genres of performances : My desired result is to append the column names according to the rankings : I have looked up some threads but the closest thing I can find is idxmax . However that only gives me Rank1.Could anyone help me to get the result I... | Genre Jazz Dance Music TheatreCustomer 100000000001 0 3 1 2100000000002 0 1 6 2100000000003 0 3 13 4100000000004 0 5 4 1100000000005 1 10 16 14 Genre Jazz Dance Music Theatre Rank1 Rank2 Rank3 Rank4Customer 100000000001 0 3 1 2 Dance Theatre Music Jazz100000000002 0 1 6 2 Music Theatre Dance Jazz100000000003 0 3 13 4 M... | Get Rankings of Column Names in Pandas Dataframe |
Python | I 'm trying to save some data from a table in a CSV file . The error I 'm getting : | import requestsimport csvfrom bs4 import BeautifulSoup # Main functiondef getContent ( link ) : # Request content result1 = requests.get ( link ) # Save source in var src1 = result1.content # Activate soup soup = BeautifulSoup ( src1 , 'lxml ' ) # Look for table table = soup.find ( 'table ' ) # Save in csv with open ( ... | Why is my def function in Python not working ? |
Python | I have the following dict object : How would I combine it into a single set ? Currently I 'm doing it the verbose way of : | obj = { 'US ' : set ( ... ) , 'FR ' : set ( ... ) , 'BE ' : set ( ... ) } items = set ( list ( obj [ 'US ' ] ) + list ( obj [ 'FR ' ] ) + list ( obj [ 'BE ' ] ) ) | Combine set values into single set |
Python | I understand that how accessing elements in a list of lists usually works . I know that if you have a list L = [ [ ' a ' , ' b ' ] , [ ' c ' , d ' ] , [ ' e ' , ' f ' ] ] , you can access ' a ' using L [ 0 ] [ 0 ] . Still , I 'm not sure why the same thing is n't working in the following battleship game code : The prob... | from random import randintfrom random import choice # make a 5x5 boardboard = [ ] row = [ ' O ' ] *5for x in range ( 5 ) : board.append ( row ) def print_board ( ) : for item in board : print ' '.join ( item ) # check if input falls within 5x5 griddef check_valid ( guess_row , guess_column ) : return guess_row in range... | Ca n't figure out how to reassign an element in a list of lists in this Python code |
Python | First line once Python 2.7 interpreter is started on Windows : Having entered the dir ( ) command , the special variable _ should be defined : But , even after entering _ , it does not show up when I attempt to list all names in the interactive namespace using dir ( ) : How does the interpreter recognize this variable ... | > > > dir ( ) [ '__builtins__ ' , '__doc__ ' , '__name__ ' , '__package__ ' ] > > > _ [ '__builtins__ ' , '__doc__ ' , '__name__ ' , '__package__ ' ] > > > dir ( ) [ '__builtins__ ' , '__doc__ ' , '__name__ ' , '__package__ ' ] | Why does n't the last command variable `` _ '' appear in dir ( ) ? |
Python | I have a large dataset which has two columns Name , Value and it looks like this : OutputAnd I want some thing like that : In my dataset it reapts N time and i want to transform it to three columns code , classe , series . Thanks for your help in advance ! | import pandas as pddata = [ [ 'code',10 ] , [ 'classe',12 ] , [ 'series ' , ' B ' ] , [ 'code',12 ] , [ 'classe',1 ] , [ 'series ' , ' C ' ] , [ 'code',16 ] , [ 'classe',18 ] , [ 'series ' , ' A ' ] ] df1 = pd.DataFrame ( data , columns= [ 'Name ' , 'Value ' ] ) df1 Name Value0 code 101 classe 122 series B3 code 124 cl... | Transform rows to columns by the values of two rows in pandas |
Python | I have a data frame that looks like this : I want to fill the NaNs by continuing from the max value for that year ( i.e . increase incrementally based on the max value for each year ) . This is what I 'm trying to achieve : The only way I know how to apply something like this to each year separately is by creating sepa... | # datad = { 'year ' : { 0 : 2016 , 1 : 2016 , 2 : 2016 , 3 : 2016 , 4 : 2017 , 5 : 2017 , 6 : 2017 , 7 : 2017 , 8 : 2018 , 9 : 2018 , 10 : 2018 } , 'id ' : { 0 : 1015.0 , 1 : 1016.0 , 2 : nan , 3 : nan , 4 : 1035.0 , 5 : 1036.0 , 6 : nan , 7 : nan , 8 : 1005.0 , 9 : nan , 10 : nan } } # list of yearsyears = [ 2016,2017... | replace nans with max value plus 1 incrementally |
Python | I 'm still a bit new to Python , but , I feel really stupid right now 'cause I 've just spent an hour trying to figure out why this for loop is n't doing what I want . I should n't be spending an hour on a for loop . Anyway , I 'm trying to generate a list of dictionaries , and give them each a unique number , so I do ... | def initiate ( n ) : records = { 'num':0 , 'blah':0 , 'doubleblah':0 } x = [ ] for i in range ( n ) : x.append ( records ) x [ i ] [ 'num ' ] = i return xx = initiate ( 4 ) print ( x ) [ { 'num ' : 0 , 'doubleblah ' : 0 , 'blah ' : 0 } , { 'num ' : 1 , 'doubleblah ' : 0 , 'blah ' : 0 } , { 'num ' : 2 , 'doubleblah ' : ... | Weird Extra Looping |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.