content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Looking for any matching terms from file I have a file that has a large list of Countries, years, and ages of living expectancies. I cannot figure out how to make sure the user is only allowed to input a year that actually exists. After figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How can I do this? import pathlib cwd = pathlib.Path(__file__).parent.resolve() data_file = f'{cwd}/life-expectancy.csv' with open(data_file) as f: while True: user_year = input('Enter the year of interest: ') for lines in f: cat = lines.strip().split(',') country = cat[0] code = cat[1] year = cat[2] age = cat[3] if any( [year in user_year for year in cat[2]] ): print(f'Your year is {user_year}. That is one of our known years.') print(year) print() continue else: print('Please enter a valid year (1751-2019)') print('test') A: One could use DataFrames to handle such cases. To know more information on dataframe, take a look into Pandas.DataFrame To select specific column contents from the dataframe: df[[<col_1>, <col_2>]] Considering the data fetched could produce the following. import pandas as pd df = pd.read_csv("Life Expectancy Data.csv") year = int(input("Enter the year of interest: ")) df = df[["Country", "Year", "Life expectancy "]] if year in df["Year"].values: print(f'Your year is {year}. That is one of our known years.') display(df.loc[df["Year"] == year]) else: print("Please enter a valid year (2000-2015)") A: Solution 1 If all the dates from 1751 to 2019 are in your file, then you don't need to read your file to check that, you can simply do that: # Ask the user for the year prompt_text = "Enter the year of interest: " user_year = int(input(prompt_text)) while not 1751 <= user_year <= 2019: print("Please enter a valid year (1751-2019)") user_year = int(input(prompt_text)) After that you can read your file and store the data only if the years are matching: # Get the data for the asked year # Example of final data: [("France", "FR", 45), ("Espagne", "ES", 29)] data = [] with open(data_file, "r", encoding="utf-8") as file: for line in file: country, code, year, age = line.strip().split(",") if int(year) == user_year: data.append((country, code, int(age))) Solution 2 If you really need to check the year in your file, e.g. because 1845 is not in it, then read the file once and store all the data in a dictionary indexed by the year and return the data of the asked year if it is present: data = {} with open(data_file, "r", encoding="utf-8") as file: for line in file: country, code, year, age = line.strip().split(",") year = int(year) if year in data: data[year].append((country, code, int(age))) else: data[year] = [(country, code, int(age))] prompt_text = "Enter the year of interest: " user_year = int(input(prompt_text)) while user_year not in data: print("The year is not present in the file") user_year = int(input(prompt_text)) print(data[user_year]) A: Your question includes two questions. 1. Question and answer I cannot figure out how to make sure the user is only allowed to input a year that actually exists. Your range of accepted years is 1751-2019. You could create a list with these integers and check that the user input is within that range. E.g. allowed_answers = list(range(1751, 2019, 1)) There are multiple ways to check the user input and the one you want to use depends on how you want the user interaction to be. Here are few examples: 1.Stop the program immediately if user input is invalid user_year = input('Enter the year of interest: ') allowed_answers = list(range(1751, 2019, 1)) assert user_year in allowed_answers, "User input is invalid" ... 2.Ask user to input number until it is accepted allowed_answers = list(range(1751, 2019, 1)) user_year = 0 while int(user_year) not in allowed_answers: print('Please enter a valid year (1751-2019)') user_year = input('Enter the year of interest: ') 3.Combining the two solutions to have a limit of prompts. allowed_answers = list(range(1751, 2019, 1)) user_year = 0 for i in range(0,5): print('Please enter a valid year (1751-2019)') user_year = input('Enter the year of interest: ') if int(user_year) in allowed_answers: input_valid = True break else: input_valid = False assert input_valid, "No correct input after five tries." Note that all these solutions only handle inputs that can be converted into integer. To go around that, you might need some try... except clauses for the data transformation from string to integer, or transform the list items of allowed_answers into strings. 2. Question and answer After figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How can I do this? I would read the file only once a make it into a dictionary. Then you only need to do the indexing once and search from there as long as your program is running. See https://docs.python.org/3/tutorial/datastructures.html#dictionaries . With these suggestions I would do the data reading and transformation into dictionary outside (and before) your while loop.
Looking for any matching terms from file
I have a file that has a large list of Countries, years, and ages of living expectancies. I cannot figure out how to make sure the user is only allowed to input a year that actually exists. After figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How can I do this? import pathlib cwd = pathlib.Path(__file__).parent.resolve() data_file = f'{cwd}/life-expectancy.csv' with open(data_file) as f: while True: user_year = input('Enter the year of interest: ') for lines in f: cat = lines.strip().split(',') country = cat[0] code = cat[1] year = cat[2] age = cat[3] if any( [year in user_year for year in cat[2]] ): print(f'Your year is {user_year}. That is one of our known years.') print(year) print() continue else: print('Please enter a valid year (1751-2019)') print('test')
[ "One could use DataFrames to handle such cases. To know more information on dataframe, take a look into Pandas.DataFrame\nTo select specific column contents from the dataframe: df[[<col_1>, <col_2>]]\nConsidering the data fetched could produce the following.\nimport pandas as pd\n\ndf = pd.read_csv(\"Life Expectancy Data.csv\")\n\nyear = int(input(\"Enter the year of interest: \"))\n\n\ndf = df[[\"Country\", \"Year\", \"Life expectancy \"]]\n\nif year in df[\"Year\"].values:\n print(f'Your year is {year}. That is one of our known years.')\n display(df.loc[df[\"Year\"] == year])\nelse:\n print(\"Please enter a valid year (2000-2015)\")\n\n", "Solution 1\nIf all the dates from 1751 to 2019 are in your file, then you don't need to read your file to check that, you can simply do that:\n# Ask the user for the year\nprompt_text = \"Enter the year of interest: \"\nuser_year = int(input(prompt_text))\nwhile not 1751 <= user_year <= 2019:\n print(\"Please enter a valid year (1751-2019)\")\n user_year = int(input(prompt_text))\n\nAfter that you can read your file and store the data only if the years are matching:\n# Get the data for the asked year\n# Example of final data: [(\"France\", \"FR\", 45), (\"Espagne\", \"ES\", 29)]\ndata = []\nwith open(data_file, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n country, code, year, age = line.strip().split(\",\")\n if int(year) == user_year:\n data.append((country, code, int(age)))\n\nSolution 2\nIf you really need to check the year in your file, e.g. because 1845 is not in it, then read the file once and store all the data in a dictionary indexed by the year and return the data of the asked year if it is present:\ndata = {}\nwith open(data_file, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n country, code, year, age = line.strip().split(\",\")\n year = int(year)\n if year in data:\n data[year].append((country, code, int(age)))\n else:\n data[year] = [(country, code, int(age))]\n\nprompt_text = \"Enter the year of interest: \"\nuser_year = int(input(prompt_text))\nwhile user_year not in data:\n print(\"The year is not present in the file\")\n user_year = int(input(prompt_text))\nprint(data[user_year])\n\n", "Your question includes two questions.\n1. Question and answer\n\nI cannot figure out how to make sure the user is only allowed to\ninput a year that actually exists.\n\nYour range of accepted years is 1751-2019. You could create a list with these integers and check that the user input is within that range. E.g.\nallowed_answers = list(range(1751, 2019, 1))\n\nThere are multiple ways to check the user input and the one you want to use depends on how you want the user interaction to be. Here are few examples:\n1.Stop the program immediately if user input is invalid\nuser_year = input('Enter the year of interest: ')\nallowed_answers = list(range(1751, 2019, 1))\nassert user_year in allowed_answers, \"User input is invalid\"\n...\n\n2.Ask user to input number until it is accepted\nallowed_answers = list(range(1751, 2019, 1))\nuser_year = 0\n\nwhile int(user_year) not in allowed_answers:\n print('Please enter a valid year (1751-2019)')\n user_year = input('Enter the year of interest: ')\n\n3.Combining the two solutions to have a limit of prompts.\nallowed_answers = list(range(1751, 2019, 1))\nuser_year = 0\n\nfor i in range(0,5):\n print('Please enter a valid year (1751-2019)')\n user_year = input('Enter the year of interest: ')\n if int(user_year) in allowed_answers:\n input_valid = True \n break\n else:\n input_valid = False\n\nassert input_valid, \"No correct input after five tries.\"\n\nNote that all these solutions only handle inputs that can be converted into integer. To go around that, you might need some try... except clauses for the data transformation from string to integer, or transform the list items of allowed_answers into strings.\n2. Question and answer\n\nAfter figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How can I do this?\n\nI would read the file only once a make it into a dictionary. Then you only need to do the indexing once and search from there as long as your program is running. See https://docs.python.org/3/tutorial/datastructures.html#dictionaries .\nWith these suggestions I would do the data reading and transformation into dictionary outside (and before) your while loop.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074557873_python.txt
Q: How to match two dataframes precisely and get the output as 1 if matched and 0 if not matched? The dataframe is as follows: df1: name | age | state | number | score ------------------------------------------------------ A 23 AZ 5434567 92.1 B 54 AZ 1234543 87.6 C 32 AZ 7654344 89.9 D 44 GA 8765433 72.4 df2: name | age | state | number | score ------------------------------------------------------ A 23 GA 5434567 92.1 D 54 AZ 1234543 76.4 C 33 AZ 7654344 99.9 D 46 GA 8765433 72.4 The desired dataframe is as follows: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 1 The code I tried is: outputdf = df1.eq(df2) and outputdf = df1.ne(df2) But neither of them seem to work correctly. wrong output after using the eq line: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 0 0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 wrong output after using the ne line: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 0 0 1 Could anyone please help me out here? Thank you A: direct comparison of the dataframes should work, just cast from bool to integer: df1.eq(df2).astype(int) # or (df1 == df2).astype(int) output: name age state number 0 1 1 0 1 1 0 1 1 1 2 1 0 1 1 3 1 0 1 1 A: Could your issue be due to floating point approximation? You can round the numerical columns before comparison: out = (df1.select_dtypes('number').round(2) # use the desired precision .eq(df2.select_dtypes('number').round(2)) .astype(int) ) Output: age number score 0 1 1 1 1 1 1 0 2 0 1 0 3 0 1 1 If this was the issue and you want the output with all columns, you can correct your initial output with: # initial output out = df1.eq(df2).astype(int) # correction to account for floating point approximation # use the atol/rtol parameters if needed cols = list(df1.select_dtypes('number')) out[cols] = np.isclose(df1[cols], df2[cols]).astype(int) # or correction with round # out[cols] = df1[cols].round(2).eq(df2[cols].round(2)).astype(int) Output: name age state number score 0 1 1 0 1 1 1 0 1 1 1 0 2 1 0 1 1 0 3 1 0 1 1 1 A: Because float columns precision problem is possible exctract them and compare separately with numpy.isclose, then add all another columns in concat: cols = df1.select_dtypes('floating').columns cols1 = df1.columns.difference(cols) df3 = pd.DataFrame(np.isclose(df1[cols], df2[cols]).astype(int), columns=cols) df4 = df1[cols1].eq(df2[cols1]).astype(int) df = pd.concat([df3, df4], axis=1).reindex(df1.columns, axis=1) print (df) name age state number score 0 1 1 0 1 1 1 0 1 1 1 0 2 1 0 1 1 0 3 1 0 1 1 1 A: The problem you are having is likely to be due to the way the dataframes are constructed. For example, if I generate the dataframes as indicated in the example inputs above - then I get the expected outputs using: outputdf = df1.eq(df2).astype(int) Here is an example of the code: df1 = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D'], 'age': [23, 54, 32, 44], 'state': ['AZ', 'AZ', 'AZ', 'GA'], 'number': [5434567, 1234543, 7654344, 8765433], 'score': [92.1, 87.6, 89.9, 72.4]}) df2 = pd.DataFrame({ 'name': ['A', 'D', 'C', 'D'], 'age': [23, 54, 33, 46], 'state': ['GA', 'AZ', 'AZ', 'GA'], 'number': [5434567, 1234543, 7654344, 8765433], 'score': [92.1, 76.4, 99.9, 72.4]}) outputdf = df1.eq(df2).astype(int) print(outputdf) OUTPUT: name age state number score 0 1 1 0 1 1 1 0 1 1 1 0 2 1 0 1 1 0 3 1 0 1 1 1
How to match two dataframes precisely and get the output as 1 if matched and 0 if not matched?
The dataframe is as follows: df1: name | age | state | number | score ------------------------------------------------------ A 23 AZ 5434567 92.1 B 54 AZ 1234543 87.6 C 32 AZ 7654344 89.9 D 44 GA 8765433 72.4 df2: name | age | state | number | score ------------------------------------------------------ A 23 GA 5434567 92.1 D 54 AZ 1234543 76.4 C 33 AZ 7654344 99.9 D 46 GA 8765433 72.4 The desired dataframe is as follows: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 1 The code I tried is: outputdf = df1.eq(df2) and outputdf = df1.ne(df2) But neither of them seem to work correctly. wrong output after using the eq line: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 0 0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 wrong output after using the ne line: name | age | state | number | score ------------------------------------------------------- 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 0 0 1 Could anyone please help me out here? Thank you
[ "direct comparison of the dataframes should work, just cast from bool to integer:\ndf1.eq(df2).astype(int)\n# or (df1 == df2).astype(int)\n\noutput:\n name age state number\n0 1 1 0 1\n1 0 1 1 1\n2 1 0 1 1\n3 1 0 1 1\n\n", "Could your issue be due to floating point approximation?\nYou can round the numerical columns before comparison:\nout = (df1.select_dtypes('number').round(2) # use the desired precision\n .eq(df2.select_dtypes('number').round(2))\n .astype(int)\n)\n\nOutput:\n age number score\n0 1 1 1\n1 1 1 0\n2 0 1 0\n3 0 1 1\n\nIf this was the issue and you want the output with all columns, you can correct your initial output with:\n# initial output\nout = df1.eq(df2).astype(int)\n\n# correction to account for floating point approximation\n# use the atol/rtol parameters if needed\ncols = list(df1.select_dtypes('number'))\nout[cols] = np.isclose(df1[cols], df2[cols]).astype(int)\n\n# or correction with round\n# out[cols] = df1[cols].round(2).eq(df2[cols].round(2)).astype(int)\n\nOutput:\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n\n", "Because float columns precision problem is possible exctract them and compare separately with numpy.isclose, then add all another columns in concat:\ncols = df1.select_dtypes('floating').columns\ncols1 = df1.columns.difference(cols)\n\ndf3 = pd.DataFrame(np.isclose(df1[cols], df2[cols]).astype(int), columns=cols)\ndf4 = df1[cols1].eq(df2[cols1]).astype(int)\n\ndf = pd.concat([df3, df4], axis=1).reindex(df1.columns, axis=1)\nprint (df)\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n\n", "The problem you are having is likely to be due to the way the dataframes are constructed. For example, if I generate the dataframes as indicated in the example inputs above - then I get the expected outputs using:\n\noutputdf = df1.eq(df2).astype(int)\n\n\n\nHere is an example of the code:\ndf1 = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D'],\n 'age': [23, 54, 32, 44],\n 'state': ['AZ', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 87.6, 89.9, 72.4]})\n\ndf2 = pd.DataFrame({ 'name': ['A', 'D', 'C', 'D'],\n 'age': [23, 54, 33, 46],\n 'state': ['GA', 'AZ', 'AZ', 'GA'],\n 'number': [5434567, 1234543, 7654344, 8765433],\n 'score': [92.1, 76.4, 99.9, 72.4]})\n\noutputdf = df1.eq(df2).astype(int)\nprint(outputdf)\n\nOUTPUT:\n name age state number score\n0 1 1 0 1 1\n1 0 1 1 1 0\n2 1 0 1 1 0\n3 1 0 1 1 1\n\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "dataframe", "match", "pandas", "python" ]
stackoverflow_0074557900_dataframe_match_pandas_python.txt
Q: Jenkins - how to capture a Boolean value in groovy I'm looking for a way to capture a boolean value based on the python script. Basically, I've a python script that is triggered from the Jenkins file, it searches out a few articles. If the article is not found it should print an error msg at Jenkins. I've tried as follows, here is my Jenkins file: stage('running test') { steps { script { try{ echo 'env creation' boolean rslt = sh(script: "python3 -u test.py config/desktop", returnStd: true) } catch(e){ echo $rslt } } if expression (rslt != true) { echo 'article is not found' } } } Here is my python file: if __name__ == "__main__": ''' ''' for rslt in rslts: if "abc" in rslt['art']: func(rslt['id']) else: print("No article found") Once my python code hits the else part it should print article is not found as mentioned at jenkins file. A: I'm not familiar with phyton, but if you are 100% sure that your returned value is a boolean, you can perform this (it will convert to boolean whatever you send): def rslt = sh(script: "python3 -u test.py config/desktop", returnStd: true) /* Other code Here */ if (!rslt.toBoolean()) { echo 'article is not found' }
Jenkins - how to capture a Boolean value in groovy
I'm looking for a way to capture a boolean value based on the python script. Basically, I've a python script that is triggered from the Jenkins file, it searches out a few articles. If the article is not found it should print an error msg at Jenkins. I've tried as follows, here is my Jenkins file: stage('running test') { steps { script { try{ echo 'env creation' boolean rslt = sh(script: "python3 -u test.py config/desktop", returnStd: true) } catch(e){ echo $rslt } } if expression (rslt != true) { echo 'article is not found' } } } Here is my python file: if __name__ == "__main__": ''' ''' for rslt in rslts: if "abc" in rslt['art']: func(rslt['id']) else: print("No article found") Once my python code hits the else part it should print article is not found as mentioned at jenkins file.
[ "I'm not familiar with phyton, but if you are 100% sure that your returned value is a boolean, you can perform this (it will convert to boolean whatever you send):\ndef rslt = sh(script: \"python3 -u test.py config/desktop\", returnStd: true)\n/* Other code Here */\nif (!rslt.toBoolean()) {\n echo 'article is not found'\n}\n\n" ]
[ 0 ]
[]
[]
[ "groovy", "jenkins", "jenkins_groovy", "jenkins_pipeline", "python" ]
stackoverflow_0074556651_groovy_jenkins_jenkins_groovy_jenkins_pipeline_python.txt
Q: How to extract a single row table data from a pdf using python? I need to extract tabular data from pdfs. Some tables in the pdf comprise of only a single row. I have been trying to extract the data using camelot library. Code for extraction using Camelot: pip install camelot-py[cv] tabula-py here import camelot file = 'xyz.pdf' tables = camelot.read_pdf(file,pages ="all") tables[6].df The above code is not able to extract a single row table info. For instance, in the pdf: https://www.nirfindia.org/nirfpdfcdn/2022/pdf/Engineering/IR-E-U-0306.pdf, the tool is not able to detect the last table(under the heading Faculty Details) as it consists of only one row. Can someone suggest a workaround? A: As you can understand from the docs, if you want to detect smaller lines, you should increase line_scale parameter (default: 15). In your case, this command works fine: tables = camelot.read_pdf(file, pages ="all", line_scale=80)
How to extract a single row table data from a pdf using python?
I need to extract tabular data from pdfs. Some tables in the pdf comprise of only a single row. I have been trying to extract the data using camelot library. Code for extraction using Camelot: pip install camelot-py[cv] tabula-py here import camelot file = 'xyz.pdf' tables = camelot.read_pdf(file,pages ="all") tables[6].df The above code is not able to extract a single row table info. For instance, in the pdf: https://www.nirfindia.org/nirfpdfcdn/2022/pdf/Engineering/IR-E-U-0306.pdf, the tool is not able to detect the last table(under the heading Faculty Details) as it consists of only one row. Can someone suggest a workaround?
[ "As you can understand from the docs,\nif you want to detect smaller lines, you should increase line_scale parameter (default: 15).\nIn your case, this command works fine:\ntables = camelot.read_pdf(file, pages =\"all\", line_scale=80)\n\n" ]
[ 0 ]
[]
[]
[ "ocr", "pdf", "python", "python_camelot", "tabula_py" ]
stackoverflow_0074533410_ocr_pdf_python_python_camelot_tabula_py.txt
Q: networkx subgraph does not return the correct order of the edges Does anyone know if there is a built-in function that is similar to subgraph but gives the correct order of the edges? I try to create subgraph = G.subgraph(path) but this returns me an incorrect order of the edges which later returns me an incorrect order of the edge attributes when I use nx.get_edge_attribute(subgraph). import networkx as nx import matplotlib.pyplot as plt G= nx.MultiGraph() for i in relations: G.add_edge(i[0], i[1], relation = i[2]) relations = [ ('x3', 'x100', 'friend'),('x1', 'x2', 'friend'), ('x4', 'x12200', 'friend'),('x3', 'x2', 'friend'),('P20', 'P3', 'friend'),('x4', 'x3', 'friend'),('x4', 'x5', 'friend'),('x1', 'x0', 'friend'),('P1', 'P2', 'friend'),('P1', 'P0', 'friend'), ('P4', 'P5', 'friend'), ('A', 'B', 'friend'), ('B', 'C', 'coworker'), ('C', 'F', 'coworker'), ('C', 'F', 'friend'), ('F', 'G', 'coworker'), ('F1', 'F2', 'coworker'),('F3', 'F2', 'friend'), ('F3', 'F4', 'friend'),('F6', 'F4', 'friend'), ('F5', 'F6', 'coworker'),('F6', 'F1', 'coworker'), ('F', 'G', 'family'), ('C', 'lo', 'friend'), ('E', 'lo', 'friend'),('E', 'D', 'family'),('J', 'D', 'family'), ('E', 'I', 'coworker'), ('E', 'I', 'neighbour'), ('I', 'J', 'coworker'),('P3', 'P2', 'friend'), ('E', 'J', 'friend'), ('P5', 'P6', 'coworker'),('P7', 'P6', 'coworker'),('E', 'H', 'coworker'),('V', 'L', 'friend'),('M', 'L', 'friend'),('M', 'N', 'friend'), ('N', 'O', 'coworker'),('N', 'P', 'friend'), ('L', 'N', 'coworker')] path=list(nx.dfs_preorder_nodes(G, source="P0")) print("path", path) print(G.subgraph(path).edges()) attribute = nx.get_edge_attributes((G.subgraph(path)), "relation") print("attribute", attribute.values() # path ['P0', 'P1', 'P2', 'P3', 'P20'] # [('P1', 'P2'), ('P1', 'P0'), ('P2', 'P3'), ('P20', 'P3')] # ['friend', 'friend', 'hey', 'friend', 'friend'] # Expectation # path ['P0', 'P1', 'P2', 'P3', 'P20'] # [('P0', 'P1'), ('P1', 'P2'), ('P2', 'P3'), ('P20', 'P3')] # order of the nodes inside the edges does not have to be in order # ['friend', 'friend', 'friend', 'friend', 'hey'] Screenshot of how the graph looks A: Using subgraph on a path does not guarantee that the edges will be returned in the same order as along the path. Instead of creating subgraphs, it's possible to get the edge attributes directly from the original graph: for s, d in zip(path, path[1:]): print(s,d, G[s][d][0]['relation']) # P0 P1 friend # P1 P2 friend # P2 P3 friend # P3 P20 friend
networkx subgraph does not return the correct order of the edges
Does anyone know if there is a built-in function that is similar to subgraph but gives the correct order of the edges? I try to create subgraph = G.subgraph(path) but this returns me an incorrect order of the edges which later returns me an incorrect order of the edge attributes when I use nx.get_edge_attribute(subgraph). import networkx as nx import matplotlib.pyplot as plt G= nx.MultiGraph() for i in relations: G.add_edge(i[0], i[1], relation = i[2]) relations = [ ('x3', 'x100', 'friend'),('x1', 'x2', 'friend'), ('x4', 'x12200', 'friend'),('x3', 'x2', 'friend'),('P20', 'P3', 'friend'),('x4', 'x3', 'friend'),('x4', 'x5', 'friend'),('x1', 'x0', 'friend'),('P1', 'P2', 'friend'),('P1', 'P0', 'friend'), ('P4', 'P5', 'friend'), ('A', 'B', 'friend'), ('B', 'C', 'coworker'), ('C', 'F', 'coworker'), ('C', 'F', 'friend'), ('F', 'G', 'coworker'), ('F1', 'F2', 'coworker'),('F3', 'F2', 'friend'), ('F3', 'F4', 'friend'),('F6', 'F4', 'friend'), ('F5', 'F6', 'coworker'),('F6', 'F1', 'coworker'), ('F', 'G', 'family'), ('C', 'lo', 'friend'), ('E', 'lo', 'friend'),('E', 'D', 'family'),('J', 'D', 'family'), ('E', 'I', 'coworker'), ('E', 'I', 'neighbour'), ('I', 'J', 'coworker'),('P3', 'P2', 'friend'), ('E', 'J', 'friend'), ('P5', 'P6', 'coworker'),('P7', 'P6', 'coworker'),('E', 'H', 'coworker'),('V', 'L', 'friend'),('M', 'L', 'friend'),('M', 'N', 'friend'), ('N', 'O', 'coworker'),('N', 'P', 'friend'), ('L', 'N', 'coworker')] path=list(nx.dfs_preorder_nodes(G, source="P0")) print("path", path) print(G.subgraph(path).edges()) attribute = nx.get_edge_attributes((G.subgraph(path)), "relation") print("attribute", attribute.values() # path ['P0', 'P1', 'P2', 'P3', 'P20'] # [('P1', 'P2'), ('P1', 'P0'), ('P2', 'P3'), ('P20', 'P3')] # ['friend', 'friend', 'hey', 'friend', 'friend'] # Expectation # path ['P0', 'P1', 'P2', 'P3', 'P20'] # [('P0', 'P1'), ('P1', 'P2'), ('P2', 'P3'), ('P20', 'P3')] # order of the nodes inside the edges does not have to be in order # ['friend', 'friend', 'friend', 'friend', 'hey'] Screenshot of how the graph looks
[ "Using subgraph on a path does not guarantee that the edges will be returned in the same order as along the path.\nInstead of creating subgraphs, it's possible to get the edge attributes directly from the original graph:\nfor s, d in zip(path, path[1:]):\n print(s,d, G[s][d][0]['relation'])\n\n# P0 P1 friend\n# P1 P2 friend\n# P2 P3 friend\n# P3 P20 friend\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "networkx", "python" ]
stackoverflow_0074553711_dictionary_networkx_python.txt
Q: What is the "if __name__ == '__main__'" block called? I saw someone on a Python post refer to it in some way, but I cannot for the life of me find it again. It was a pretty short, colloquial term, something like "gutter" or "blunk". Is it a Python thing or do other languages call it something too? A: In the documentation up to Python 3.3 it's referred to as a "conditional script" stanza: It is this environment in which the idiomatic “conditional script” stanza causes a script to run: if __name__ == "__main__": main() This term is gone since 3.4: a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: if __name__ == "__main__": # execute only if run as a script main()
What is the "if __name__ == '__main__'" block called?
I saw someone on a Python post refer to it in some way, but I cannot for the life of me find it again. It was a pretty short, colloquial term, something like "gutter" or "blunk". Is it a Python thing or do other languages call it something too?
[ "In the documentation up to Python 3.3 it's referred to as a \"conditional script\" stanza:\n\nIt is this environment in which the idiomatic “conditional script” stanza causes a script to run:\nif __name__ == \"__main__\":\n main()\n\n\nThis term is gone since 3.4:\n\na common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074558528_python.txt
Q: When should I use dataclasses in Python? This is what it says in the document: This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. Accordingly, I can use dataclass in every class, but should I really use ? I really don't understand when should I use it, I'm curious about your ideas. A: To me, dataclasses are best for simple objects (sometimes called value objects) that have no logic to them, just data. For example: @dataclass class StockItem: sku: str name: str quantity: int This then benefits from not having to implement init, which is nice because it would be trivial. It also means, with repr, you can print the object to the shell and copy-paste it to get another identical instance of the object, which is handy.
When should I use dataclasses in Python?
This is what it says in the document: This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. Accordingly, I can use dataclass in every class, but should I really use ? I really don't understand when should I use it, I'm curious about your ideas.
[ "To me, dataclasses are best for simple objects (sometimes called value objects) that have no logic to them, just data. For example:\n@dataclass\nclass StockItem:\n sku: str\n name: str\n quantity: int\n\nThis then benefits from not having to implement init, which is nice because it would be trivial. It also means, with repr, you can print the object to the shell and copy-paste it to get another identical instance of the object, which is handy.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074558619_python.txt
Q: Calculate result without entering python shell Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner: tail file.txt -n `python 123*456` instead of having to calculate 123*456 in a separate step. A: I don't understand your question: you say "I would like to do something using Python", but when you show what you want to do, Python seems not to be needed for achieving that. Let me show you: what you want to achieve, can be done as follows: tail -f file.txt -n $((123*456)) The $((...)) notation is capable of performing integer calculations, as you can imagine. Is this what you are looking for, or are you really forced to use Python, and if so, why do you think that? A: You can try the -c option. For e.g, tail test_log.txt -n `python -c "print(1 + 2)"`
Calculate result without entering python shell
Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner: tail file.txt -n `python 123*456` instead of having to calculate 123*456 in a separate step.
[ "I don't understand your question: you say \"I would like to do something using Python\", but when you show what you want to do, Python seems not to be needed for achieving that.\nLet me show you: what you want to achieve, can be done as follows:\ntail -f file.txt -n $((123*456))\n\nThe $((...)) notation is capable of performing integer calculations, as you can imagine.\nIs this what you are looking for, or are you really forced to use Python, and if so, why do you think that?\n", "You can try the -c option. For e.g, tail test_log.txt -n `python -c \"print(1 + 2)\"` \n" ]
[ 3, 1 ]
[]
[]
[ "linux", "python", "shell" ]
stackoverflow_0074558107_linux_python_shell.txt
Q: Print some of list by for in python I have 4 lists and I want to print them, but it returns name of list. list1 = ["a", "b", "c", "d"] list2 = ["a", "b", "c"] list3 = ["a", "b"] list4 = ["a"] for i in range(1,5): print(list[i]) It shows: list[1] list[2] list[3] list[4] I need, for example ["a", "b", "c", "d"] for list1. A: You could make a list of lists if you want to print them like you are trying to do: list1 = [ ["a", "b", "c", "d"], ["a", "b", "c"], ["a", "b"], ["a"] ] for i in range(len(list1)): print(list1[i]) A: Variables don't work that way. If you need a similar kind of approach, you can use a dictionary. dict_ = { "list1" : ["a", "b", "c", "d"], "list2" : ["a", "b", "c"], "list3" : ["a", "b"], "list4" : ["a"], } for i in range(1, 5): print(dict_["list"+str(i)]) A: if you want to print them in a loop, you need to put them in a "container" first (the container is noting but a list of its own). list1 = ["a", "b", "c", "d"] list2 = ["a", "b", "c"] list3 = ["a", "b"] list4 = ["a"] container = [list1, list2, list3, list4] for list in container: print(list)
Print some of list by for in python
I have 4 lists and I want to print them, but it returns name of list. list1 = ["a", "b", "c", "d"] list2 = ["a", "b", "c"] list3 = ["a", "b"] list4 = ["a"] for i in range(1,5): print(list[i]) It shows: list[1] list[2] list[3] list[4] I need, for example ["a", "b", "c", "d"] for list1.
[ "You could make a list of lists if you want to print them like you are trying to do:\nlist1 = [\n [\"a\", \"b\", \"c\", \"d\"],\n [\"a\", \"b\", \"c\"],\n [\"a\", \"b\"],\n [\"a\"]\n]\n\nfor i in range(len(list1)):\n print(list1[i])\n\n", "Variables don't work that way. If you need a similar kind of approach, you can use a dictionary.\ndict_ = {\n \"list1\" : [\"a\", \"b\", \"c\", \"d\"],\n \"list2\" : [\"a\", \"b\", \"c\"],\n \"list3\" : [\"a\", \"b\"],\n \"list4\" : [\"a\"],\n}\n\nfor i in range(1, 5):\n print(dict_[\"list\"+str(i)])\n\n", "if you want to print them in a loop, you need to put them in a \"container\" first (the container is noting but a list of its own).\nlist1 = [\"a\", \"b\", \"c\", \"d\"]\nlist2 = [\"a\", \"b\", \"c\"]\nlist3 = [\"a\", \"b\"]\nlist4 = [\"a\"]\n\ncontainer = [list1, list2, list3, list4]\nfor list in container:\n print(list)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074558443_for_loop_list_python.txt
Q: How to get uploaded file in views? I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error FileNotFoundError: [Errno 2] No such file or directory: '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx but I have that file. How can I fix that? upload = Upload(file=f) content = ScanDocument(upload.file.path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text Note if I use url instead of path then it returns: FileNotFoundError: [Errno 2] No such file or directory: '/media/Meeting%20notes%20notes%20%(1).docx' A: If you check your file path in error it's invalid if it's uploaded inside media directory. '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx' Just change your code like this: import os from django.conf import settings upload = Upload(file=f) file_path = os.path.join(settings.MEDIA_ROOT, upload.file.path) content = ScanDocument(file_path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text
How to get uploaded file in views?
I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error FileNotFoundError: [Errno 2] No such file or directory: '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx but I have that file. How can I fix that? upload = Upload(file=f) content = ScanDocument(upload.file.path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text Note if I use url instead of path then it returns: FileNotFoundError: [Errno 2] No such file or directory: '/media/Meeting%20notes%20notes%20%(1).docx'
[ "If you check your file path in error it's invalid if it's uploaded inside media directory.\n'/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx'\n\nJust change your code like this:\nimport os\nfrom django.conf import settings\n\n\nupload = Upload(file=f)\nfile_path = os.path.join(settings.MEDIA_ROOT, upload.file.path)\ncontent = ScanDocument(file_path)\nupload.save()\n\n\ndef ScanDocument(file_path):\n text = docx2txt.process(file_path)\n return text\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074558552_django_python.txt
Q: Using Flask-SQLAlchemy without Flask I had a small web service built using Flask and Flask-SQLAlchemy that only held one model. I now want to use the same database, but with a command line app, so I'd like to drop the Flask dependency. My model looks like this: class IPEntry(db.Model): id = db.Column(db.Integer, primary_key=True) ip_address = db.Column(db.String(16), unique=True) first_seen = db.Column(db.DateTime(), default = datetime.datetime.utcnow ) last_seen = db.Column(db.DateTime(), default = datetime.datetime.utcnow ) @validates('ip') def validate_ip(self, key, ip): assert is_ip_addr(ip) return ip Since db will no longer be a reference to flask.ext.sqlalchemy.SQLAlchemy(app), how can I convert my model to use just SQLAlchemy. Is there a way for the two applications (one with Flask-SQLAlchemy the other with SQLAlchemy) to use the same database? A: you can do this to replace db.Model: from sqlalchemy import orm from sqlalchemy.ext.declarative import declarative_base import sqlalchemy as sa base = declarative_base() engine = sa.create_engine(YOUR_DB_URI) base.metadata.bind = engine session = orm.scoped_session(orm.sessionmaker())(bind=engine) # after this: # base == db.Model # session == db.session # other db.* values are in sa.* # ie: old: db.Column(db.Integer,db.ForeignKey('s.id')) # new: sa.Column(sa.Integer,sa.ForeignKey('s.id')) # except relationship, and backref, those are in orm # ie: orm.relationship, orm.backref # so to define a simple model class UserModel(base): __tablename__ = 'users' #<- must declare name for db table id = sa.Column(sa.Integer,primary_key=True) name = sa.Column(sa.String(255),nullable=False) then to create the tables: base.metadata.create_all() A: That is how to use SQLAlchemy without Flask (for example to write a bulk of objects to PostgreSQL database): from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # Define variables DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME SQLALCHEMY_DATABASE_URI = f'postgresql://{DB_USERNAME}:{DB_PASSWORD}@{DB_HOST}: {DB_PORT}/{DB_NAME}' # ----- This is related code ----- engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=True) Base = declarative_base() Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) Session.configure(bind=engine) session = Session() # ----- This is related code ----- class MyModel(Base): __tablename__ = 'my_table_name' id = Column(Integer, primary_key=True) value = Column(String) objects = [MyModel(id=0, value='a'), MyModel(id=1, value='b')] session.bulk_save_objects(objects) session.commit() A: Check this one github.com/mardix/active-alchemy Active-Alchemy is a framework agnostic wrapper for SQLAlchemy that makes it really easy to use by implementing a simple active record like api, while it still uses the db.session underneath. Inspired by Flask-SQLAlchemy A: The sqlalchemy docs has a good tutorial with examples that sound like what you want to do. Shows how to connect to a db, mapping, schema creation, and querying/saving to the db. A: There is a great article about Flask-SQLAlchemy: how it works, and how to modify models to use them outside of Flask: http://derrickgilland.com/posts/demystifying-flask-sqlalchemy/ A: Flask (> 1.0) attempt to provide helpers for sharing code between an web application and a command line interface; i personally think it might be cleaner, lighter and easier to build libraries unbound to flask, but you might want to check: https://flask.palletsprojects.com/en/2.1.x/cli/ https://flask.palletsprojects.com/en/2.1.x/api/#flask.Flask.cli A: This does not completely answer your question, because it does not remove Flask dependency, but you can use SqlAlchemy in scripts and tests by just not running the Flask app. from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import MetaData test_app = Flask('test_app') test_app.config['SQLALCHEMY_DATABASE_URI'] = 'database_uri' test_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False metadata = MetaData(schema='myschema') db = SQLAlchemy(test_app, metadata=metadata) class IPEntry(db.Model): pass One difficulty you may encounter is the requirement of using db.Model as a base class for your models if you want to target the web app and independent scripts using same codebase. Possible way to tackle it is using dynamic polymorphism and wrap the class definition in a function. def get_ipentry(db): class IPEntry(db.Model): pass return IPEntry As you construct the class run-time in the function, you can pass in different SqlAlchemy instances. Only downside is that you need to call the function to construct the class before using it. db = SqlAlchemy(...) IpEntry = get_ipentry(db) IpEntry.query.filter_by(id=123).one() A: Create database and table import os from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base if os.path.exists('test.db'): os.remove('test.db') Base = declarative_base() class Person(Base): __tablename__ = 'person' id = Column(Integer(), primary_key=True) name = Column(String()) engine = create_engine('sqlite:///test.db') Base.metadata.create_all(engine) Using Flask_SQLAlchemy directly from flask import Flask from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app, metadata=MetaData()) class Person(db.Model): __tablename__ = 'person' id = Column(Integer(), primary_key=True) name = Column(String()) person = Person(name='Bob') db.session.add(person) db.session.commit() print(person.id)
Using Flask-SQLAlchemy without Flask
I had a small web service built using Flask and Flask-SQLAlchemy that only held one model. I now want to use the same database, but with a command line app, so I'd like to drop the Flask dependency. My model looks like this: class IPEntry(db.Model): id = db.Column(db.Integer, primary_key=True) ip_address = db.Column(db.String(16), unique=True) first_seen = db.Column(db.DateTime(), default = datetime.datetime.utcnow ) last_seen = db.Column(db.DateTime(), default = datetime.datetime.utcnow ) @validates('ip') def validate_ip(self, key, ip): assert is_ip_addr(ip) return ip Since db will no longer be a reference to flask.ext.sqlalchemy.SQLAlchemy(app), how can I convert my model to use just SQLAlchemy. Is there a way for the two applications (one with Flask-SQLAlchemy the other with SQLAlchemy) to use the same database?
[ "you can do this to replace db.Model:\nfrom sqlalchemy import orm\nfrom sqlalchemy.ext.declarative import declarative_base\nimport sqlalchemy as sa\n\nbase = declarative_base()\nengine = sa.create_engine(YOUR_DB_URI)\nbase.metadata.bind = engine\nsession = orm.scoped_session(orm.sessionmaker())(bind=engine)\n\n# after this:\n# base == db.Model\n# session == db.session\n# other db.* values are in sa.*\n# ie: old: db.Column(db.Integer,db.ForeignKey('s.id'))\n# new: sa.Column(sa.Integer,sa.ForeignKey('s.id'))\n# except relationship, and backref, those are in orm\n# ie: orm.relationship, orm.backref\n# so to define a simple model\n\nclass UserModel(base):\n __tablename__ = 'users' #<- must declare name for db table\n id = sa.Column(sa.Integer,primary_key=True)\n name = sa.Column(sa.String(255),nullable=False)\n\nthen to create the tables:\n base.metadata.create_all()\n\n", "That is how to use SQLAlchemy without Flask (for example to write a bulk of objects to PostgreSQL database): \nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n# Define variables DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME \nSQLALCHEMY_DATABASE_URI = f'postgresql://{DB_USERNAME}:{DB_PASSWORD}@{DB_HOST}: \n{DB_PORT}/{DB_NAME}'\n\n# ----- This is related code -----\nengine = create_engine(SQLALCHEMY_DATABASE_URI, echo=True)\nBase = declarative_base()\nBase.metadata.create_all(engine)\nSession = sessionmaker(bind=engine)\nSession.configure(bind=engine)\nsession = Session()\n# ----- This is related code -----\n\nclass MyModel(Base):\n __tablename__ = 'my_table_name'\n\n id = Column(Integer, primary_key=True)\n value = Column(String)\n\nobjects = [MyModel(id=0, value='a'), MyModel(id=1, value='b')]\nsession.bulk_save_objects(objects)\nsession.commit()\n\n", "Check this one github.com/mardix/active-alchemy\n\nActive-Alchemy is a framework agnostic wrapper for SQLAlchemy that makes it really easy to use by implementing a simple active record like api, while it still uses the db.session underneath. Inspired by Flask-SQLAlchemy\n\n", "The sqlalchemy docs has a good tutorial with examples that sound like what you want to do.\nShows how to connect to a db, mapping, schema creation, and querying/saving to the db. \n", "There is a great article about Flask-SQLAlchemy: how it works, and how to modify models to use them outside of Flask:\nhttp://derrickgilland.com/posts/demystifying-flask-sqlalchemy/\n", "Flask (> 1.0) attempt to provide helpers for sharing code between an web application and a command line interface; i personally think it might be cleaner, lighter and easier to build libraries unbound to flask, but you might want to check:\n\nhttps://flask.palletsprojects.com/en/2.1.x/cli/\nhttps://flask.palletsprojects.com/en/2.1.x/api/#flask.Flask.cli\n\n", "This does not completely answer your question, because it does not remove Flask dependency, but you can use SqlAlchemy in scripts and tests by just not running the Flask app.\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import MetaData\n\ntest_app = Flask('test_app')\ntest_app.config['SQLALCHEMY_DATABASE_URI'] = 'database_uri'\ntest_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\nmetadata = MetaData(schema='myschema')\ndb = SQLAlchemy(test_app, metadata=metadata)\n\nclass IPEntry(db.Model):\n pass\n\nOne difficulty you may encounter is the requirement of using db.Model as a base class for your models if you want to target the web app and independent scripts using same codebase. Possible way to tackle it is using dynamic polymorphism and wrap the class definition in a function.\ndef get_ipentry(db):\n class IPEntry(db.Model):\n pass\n return IPEntry\n\nAs you construct the class run-time in the function, you can pass in different SqlAlchemy instances. Only downside is that you need to call the function to construct the class before using it.\ndb = SqlAlchemy(...)\nIpEntry = get_ipentry(db)\nIpEntry.query.filter_by(id=123).one()\n\n", "Create database and table\nimport os\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nif os.path.exists('test.db'):\n os.remove('test.db')\n\nBase = declarative_base()\n\n\nclass Person(Base):\n __tablename__ = 'person'\n\n id = Column(Integer(), primary_key=True)\n name = Column(String())\n\n\nengine = create_engine('sqlite:///test.db')\nBase.metadata.create_all(engine)\n\nUsing Flask_SQLAlchemy directly\nfrom flask import Flask\nfrom sqlalchemy import MetaData\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import Column, Integer, String\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'\ndb = SQLAlchemy(app, metadata=MetaData())\n\n\nclass Person(db.Model):\n __tablename__ = 'person'\n\n id = Column(Integer(), primary_key=True)\n name = Column(String())\n\n\nperson = Person(name='Bob')\ndb.session.add(person)\ndb.session.commit()\nprint(person.id)\n\n" ]
[ 11, 4, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0030115010_flask_sqlalchemy_python_sqlalchemy.txt
Q: Calculate cumulative ocupation from variable by date ranges (summation) Let it be the following python pandas DataFrame where each row represents a person's stay in a hotel. | entry_date | exit_date | days | other_columns | | ---------- | ---------- | ------ | ------------- | | 2022-02-01 | 2022-02-05 | 5 | ... | | 2022-02-02 | 2022-02-03 | 2 | ... | | 2022-04-10 | 2022-04-13 | 4 | ... | | 2022-04-11 | 2022-04-12 | 2 | ... | | 2022-04-12 | 2022-04-13 | 2 | ... | | 2022-11-10 | 2022-11-15 | 6 | ... | I want to make a DataFrame from the previous one, where it represents for each day, the occupancy of the hotel at that moment. I am not taking into account the nights, just the days variable. | date | ocupation | | ---------- | ---------- | | 2022-02-01 | 1 | | 2022-02-02 | 2 | | 2022-02-03 | 2 | | 2022-02-04 | 1 | | 2022-02-05 | 1 | | 2022-04-10 | 1 | | 2022-04-11 | 2 | | 2022-04-12 | 3 | | 2022-04-13 | 2 | | 2022-11-10 | 1 | | 2022-11-11 | 1 | | 2022-11-12 | 1 | | 2022-11-13 | 1 | | 2022-11-14 | 1 | | 2022-11-15 | 1 | A: You can use date_range and value_counts: # ensure datetime # for year-day-month df[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=True) # for year-month-day df[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=False) (pd.Series([d for start, end in zip(df['entry_date'], df['exit_date']) for d in pd.date_range(start, end, freq='D')], name='date') .value_counts(sort=False) .reset_index(name='ocupation') ) Output: index ocupation 0 2022-02-01 1 1 2022-02-02 2 2 2022-02-03 2 3 2022-02-04 1 4 2022-02-05 1 5 2022-04-10 1 6 2022-04-11 2 7 2022-04-12 3 8 2022-04-13 2 9 2022-11-10 1 10 2022-11-11 1 11 2022-11-12 1 12 2022-11-13 1 13 2022-11-14 1 14 2022-11-15 1 A: Use: #convert column to datetimes df['entry_date'] = pd.to_datetime(df['entry_date']) #repeat rows by days column df = df.loc[df.index.repeat(df['days'])] #create days timedeltas td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d') #add timedeltas by datetiems and count to 2 columns DataFrame df1 = (df['entry_date'].add(td) .value_counts() .sort_index() .rename_axis('date') .reset_index(name='ocupation')) print (df1) date ocupation 0 2022-02-01 1 1 2022-02-02 2 2 2022-02-03 2 3 2022-02-04 1 4 2022-02-05 1 5 2022-04-10 1 6 2022-04-11 2 7 2022-04-12 3 8 2022-04-13 2 9 2022-11-10 1 10 2022-11-11 1 11 2022-11-12 1 12 2022-11-13 1 13 2022-11-14 1 14 2022-11-15 1 Performance: Sample data repeated 1000 times: df = pd.concat([df] * 1000, ignore_index=True) def jez(df): #convert column to datetimes df['entry_date'] = pd.to_datetime(df['entry_date'], dayfirst=True) #repeat rows by days column df = df.loc[df.index.repeat(df['days'])] #create days timedeltas td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d') #add timedeltas by datetiems and count to 2 columns DataFrame return (df['entry_date'].add(td) .value_counts() .sort_index() .rename_axis('date') .reset_index(name='ocupation')) def moz(df): return (pd.Series([d for start, end in zip(df['entry_date'], df['exit_date']) for d in pd.date_range(start, end, freq='D')], name='date') .value_counts(sort=False) .reset_index(name='ocupation') ) In [122]: %timeit jez(df) 15.3 ms ± 470 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [123]: %timeit moz(df) 2.31 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Calculate cumulative ocupation from variable by date ranges (summation)
Let it be the following python pandas DataFrame where each row represents a person's stay in a hotel. | entry_date | exit_date | days | other_columns | | ---------- | ---------- | ------ | ------------- | | 2022-02-01 | 2022-02-05 | 5 | ... | | 2022-02-02 | 2022-02-03 | 2 | ... | | 2022-04-10 | 2022-04-13 | 4 | ... | | 2022-04-11 | 2022-04-12 | 2 | ... | | 2022-04-12 | 2022-04-13 | 2 | ... | | 2022-11-10 | 2022-11-15 | 6 | ... | I want to make a DataFrame from the previous one, where it represents for each day, the occupancy of the hotel at that moment. I am not taking into account the nights, just the days variable. | date | ocupation | | ---------- | ---------- | | 2022-02-01 | 1 | | 2022-02-02 | 2 | | 2022-02-03 | 2 | | 2022-02-04 | 1 | | 2022-02-05 | 1 | | 2022-04-10 | 1 | | 2022-04-11 | 2 | | 2022-04-12 | 3 | | 2022-04-13 | 2 | | 2022-11-10 | 1 | | 2022-11-11 | 1 | | 2022-11-12 | 1 | | 2022-11-13 | 1 | | 2022-11-14 | 1 | | 2022-11-15 | 1 |
[ "You can use date_range and value_counts:\n# ensure datetime\n# for year-day-month\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=True)\n# for year-month-day\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=False)\n\n\n(pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n)\n\nOutput:\n index ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n\n", "Use:\n#convert column to datetimes\ndf['entry_date'] = pd.to_datetime(df['entry_date'])\n\n#repeat rows by days column\ndf = df.loc[df.index.repeat(df['days'])]\n\n#create days timedeltas\ntd = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n\n#add timedeltas by datetiems and count to 2 columns DataFrame\ndf1 = (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\nprint (df1)\n\n date ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n\nPerformance: Sample data repeated 1000 times:\ndf = pd.concat([df] * 1000, ignore_index=True)\n\ndef jez(df):\n #convert column to datetimes\n df['entry_date'] = pd.to_datetime(df['entry_date'], dayfirst=True)\n \n #repeat rows by days column\n df = df.loc[df.index.repeat(df['days'])]\n \n #create days timedeltas\n td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n \n #add timedeltas by datetiems and count to 2 columns DataFrame\n return (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\n \n\n\ndef moz(df):\n return (pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n )\n\n\nIn [122]: %timeit jez(df)\n15.3 ms ± 470 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [123]: %timeit moz(df)\n2.31 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n" ]
[ 4, 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074558578_dataframe_pandas_python.txt
Q: GCP Dataflow Kafka and missing SSL certificates I'm trying to fetch the data from Kafka to Bigquery using GCP Dataflow. My Dataflow template is based on Python SDK 2.42 + Container registry + apache_beam.io.kafka. There is my pipeline: def run( bq_dataset, bq_table_name, project, pipeline_options ): with Pipeline(options=pipeline_options) as pipeline: kafka = pipeline | ReadFromKafka( consumer_config={ 'bootstrap.servers': 'remote.kafka.aws', 'security.protocol': "SSL", 'ssl.truststore.location': "/usr/lib/jvm/java-11-openjdk-amd64/lib/security/cacerts", 'ssl.truststore.password': "changeit", 'ssl.keystore.location': "/opt/apache/beam/kafka.keystore.jks", 'ssl.keystore.password': "kafka", "ssl.key.password": "kafka", "ssl.client.auth": "required" }, topics=["mytopic"] ) kafka | beam.io.WriteToBigQuery(bq_table_name, bq_dataset, project) if __name__ == "__main__": logger = get_logger('beam-kafka') import argparse parser = argparse.ArgumentParser() parser.add_argument( '--bq_dataset', type=str, default='', help='BigQuery Dataset to write tables to. ' 'If set, export data to a BigQuery table instead of just logging. ' 'Must already exist.') parser.add_argument( '--bq_table_name', default='', help='The BigQuery table name. Should not already exist.') known_args, pipeline_args = parser.parse_known_args() pipeline_options = PipelineOptions( pipeline_args, save_main_session=True, streaming=True) project = pipeline_options.view_as(GoogleCloudOptions).project if project is None: parser.print_usage() print(sys.argv[0] + ': error: argument --project is required') sys.exit(1) run( known_args.bq_dataset, known_args.bq_table_name, project, pipeline_options ) Here is how I execute and run this pipeline: python stream_kafka.py \ --bq_dataset=test_ds \ --bq_table_name=test_topic_data \ --project=xxxx \ --region=us-east4 \ --runner=DataflowRunner \ --experiments=use_runner_v2 \ --sdk_container_image=$IMAGE \ --job_name="test_kafka" \ --no_use_public_ips \ --disk_size_gb=100 All the certificates I added to Dockerfile: COPY --chmod=0755 truststore.der /etc/ssl/certs/truststore.der COPY --chmod=0755 kafka.keystore.p12 /opt/apache/beam/kafka.keystore.p12 RUN keytool -import -trustcacerts -file truststore.der -keystore $JAVA_HOME/lib/security/cacerts -alias kafka \ -deststorepass changeit -noprompt RUN keytool -importkeystore -srckeystore kafka.keystore.p12 \ -srcstorepass kafka \ -srcstoretype pkcs12 \ -destkeystore /opt/apache/beam/kafka.keystore.jks \ -deststorepass kafka \ -keypass kafka \ -deststoretype jks The issue is when I'm trying to run Dataflow, it couldn't find kafka.keystore.jks: org.apache.kafka.common.network.SslChannelBuilder.configure(SslChannelBuilder.java:69) ... 43 more Caused by: org.apache.kafka.common.KafkaException: Failed to load SSL keystore /opt/apache/beam/kafka.keystore.jks of type JKS org.apache.kafka.common.security.ssl.SslEngineBuilder$SecurityStore.load(SslEngineBuilder.java:292) org.apache.kafka.common.security.ssl.SslEngineBuilder.createSSLContext(SslEngineBuilder.java:144) ... 46 more Caused by: java.nio.file.NoSuchFileException: /opt/apache/beam/kafka.keystore.jks java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92) A: I found the solution. You should ingest certificates into Java SDK, not into Python. So, I created one more docker image but based on Java SDK: FROM openjdk:11 COPY --from=apache/beam_java11_sdk:2.42.0 /opt/apache/beam /opt/apache/beam COPY ./ca.txt /usr/src/ca.txt COPY ./cert.txt /usr/src/cert.txt COPY ./key.txt /usr/src/key.txt ENV CA_CERTS="/usr/local/openjdk-11/lib/security/cacerts" ENV ROOT_FILE=/usr/src/ca.txt ENV CERT_FILE=/usr/src/cert.txt ENV KEY_FILE=/usr/src/key.txt COPY ./entrypoint.sh /scripts/entrypoint.sh RUN chmod +x /scripts/entrypoint.sh ENTRYPOINT [ "/scripts/entrypoint.sh" ] After that, I implemented converting my certificates into Java format(JKS) inside entrypoint.sh file. And use an additional parameter while running dataflow to overwrite Java(harness) image: --sdk_harness_container_image_overrides=".*java.*,${IMAGE_JAVA}" Hope it will help anyone.
GCP Dataflow Kafka and missing SSL certificates
I'm trying to fetch the data from Kafka to Bigquery using GCP Dataflow. My Dataflow template is based on Python SDK 2.42 + Container registry + apache_beam.io.kafka. There is my pipeline: def run( bq_dataset, bq_table_name, project, pipeline_options ): with Pipeline(options=pipeline_options) as pipeline: kafka = pipeline | ReadFromKafka( consumer_config={ 'bootstrap.servers': 'remote.kafka.aws', 'security.protocol': "SSL", 'ssl.truststore.location': "/usr/lib/jvm/java-11-openjdk-amd64/lib/security/cacerts", 'ssl.truststore.password': "changeit", 'ssl.keystore.location': "/opt/apache/beam/kafka.keystore.jks", 'ssl.keystore.password': "kafka", "ssl.key.password": "kafka", "ssl.client.auth": "required" }, topics=["mytopic"] ) kafka | beam.io.WriteToBigQuery(bq_table_name, bq_dataset, project) if __name__ == "__main__": logger = get_logger('beam-kafka') import argparse parser = argparse.ArgumentParser() parser.add_argument( '--bq_dataset', type=str, default='', help='BigQuery Dataset to write tables to. ' 'If set, export data to a BigQuery table instead of just logging. ' 'Must already exist.') parser.add_argument( '--bq_table_name', default='', help='The BigQuery table name. Should not already exist.') known_args, pipeline_args = parser.parse_known_args() pipeline_options = PipelineOptions( pipeline_args, save_main_session=True, streaming=True) project = pipeline_options.view_as(GoogleCloudOptions).project if project is None: parser.print_usage() print(sys.argv[0] + ': error: argument --project is required') sys.exit(1) run( known_args.bq_dataset, known_args.bq_table_name, project, pipeline_options ) Here is how I execute and run this pipeline: python stream_kafka.py \ --bq_dataset=test_ds \ --bq_table_name=test_topic_data \ --project=xxxx \ --region=us-east4 \ --runner=DataflowRunner \ --experiments=use_runner_v2 \ --sdk_container_image=$IMAGE \ --job_name="test_kafka" \ --no_use_public_ips \ --disk_size_gb=100 All the certificates I added to Dockerfile: COPY --chmod=0755 truststore.der /etc/ssl/certs/truststore.der COPY --chmod=0755 kafka.keystore.p12 /opt/apache/beam/kafka.keystore.p12 RUN keytool -import -trustcacerts -file truststore.der -keystore $JAVA_HOME/lib/security/cacerts -alias kafka \ -deststorepass changeit -noprompt RUN keytool -importkeystore -srckeystore kafka.keystore.p12 \ -srcstorepass kafka \ -srcstoretype pkcs12 \ -destkeystore /opt/apache/beam/kafka.keystore.jks \ -deststorepass kafka \ -keypass kafka \ -deststoretype jks The issue is when I'm trying to run Dataflow, it couldn't find kafka.keystore.jks: org.apache.kafka.common.network.SslChannelBuilder.configure(SslChannelBuilder.java:69) ... 43 more Caused by: org.apache.kafka.common.KafkaException: Failed to load SSL keystore /opt/apache/beam/kafka.keystore.jks of type JKS org.apache.kafka.common.security.ssl.SslEngineBuilder$SecurityStore.load(SslEngineBuilder.java:292) org.apache.kafka.common.security.ssl.SslEngineBuilder.createSSLContext(SslEngineBuilder.java:144) ... 46 more Caused by: java.nio.file.NoSuchFileException: /opt/apache/beam/kafka.keystore.jks java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
[ "I found the solution. You should ingest certificates into Java SDK, not into Python. So, I created one more docker image but based on Java SDK:\nFROM openjdk:11\n\nCOPY --from=apache/beam_java11_sdk:2.42.0 /opt/apache/beam /opt/apache/beam\n\nCOPY ./ca.txt /usr/src/ca.txt\nCOPY ./cert.txt /usr/src/cert.txt\nCOPY ./key.txt /usr/src/key.txt\n\nENV CA_CERTS=\"/usr/local/openjdk-11/lib/security/cacerts\" \n\nENV ROOT_FILE=/usr/src/ca.txt\nENV CERT_FILE=/usr/src/cert.txt\nENV KEY_FILE=/usr/src/key.txt\nCOPY ./entrypoint.sh /scripts/entrypoint.sh\nRUN chmod +x /scripts/entrypoint.sh\nENTRYPOINT [ \"/scripts/entrypoint.sh\" ]\n\nAfter that, I implemented converting my certificates into Java format(JKS) inside entrypoint.sh file. And use an additional parameter while running dataflow to overwrite Java(harness) image: --sdk_harness_container_image_overrides=\".*java.*,${IMAGE_JAVA}\"\nHope it will help anyone.\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "google_cloud_dataflow", "google_cloud_platform", "python", "ssl" ]
stackoverflow_0074335221_apache_kafka_google_cloud_dataflow_google_cloud_platform_python_ssl.txt
Q: Flask-SQLalchemy AttributeError: 'NoneType' object has no attribute "" I am trying to query couple of tables , and using for loops I am adding filters to queries. new_list = [] query = { "search_word": "Home", "exact": False, "tags": ["N"], "next_words": [ {"pos": 1, "tags": ["verb"]}, {"pos": 2, "tags": ["anim"]} ] } if query["search_word"]: if query["exact"]: db_query = Cases.query.filter(Cases.gramatical_case == query["search_word"]) else: db_query = Cases.query.filter(Cases.gramatical_case.ilike(f'%' + query["search_word"] + '%')) for tag in query["tags"]: db_query = db_query.filter(Cases.grammer.contains(tag)) for words in query["next_words"]: tagging = words['tags'] # list of values for rg in tagging: db_query = db_query.filter(Cases.pos.contains(rg)) filter2=Case_Sentences.query.with_entities(Case_Sentences.st_id).filter_by(gc_id=db_query.first().gc_id).all() for r in filter2: new_list.append(r.st_id) filter3 = Sentences.query.filter(Sentences.sn_id.in_(new_list)).paginate(per_page=12,page=page_num,error_out=False) Goal is, using for loops add filters to query and at the end call it and fetch it all. And the error I am getting : filter2=Case_Sentences.query.with_entities(Case_Sentences.st_id).filter_by(gc_id=db_query.first().gc_id).all() AttributeError: 'NoneType' object has no attribute 'gc_id' Why do I get this error message, even tho everything seems to be correct A: The problem was in : for words in query["next_words"]: tagging = words['tags'] # list of values for rg in tagging: db_query = db_query.filter(Cases.pos.contains(rg)) This query was returning Empty Object for a reason, Queries done here was wrong.
Flask-SQLalchemy AttributeError: 'NoneType' object has no attribute ""
I am trying to query couple of tables , and using for loops I am adding filters to queries. new_list = [] query = { "search_word": "Home", "exact": False, "tags": ["N"], "next_words": [ {"pos": 1, "tags": ["verb"]}, {"pos": 2, "tags": ["anim"]} ] } if query["search_word"]: if query["exact"]: db_query = Cases.query.filter(Cases.gramatical_case == query["search_word"]) else: db_query = Cases.query.filter(Cases.gramatical_case.ilike(f'%' + query["search_word"] + '%')) for tag in query["tags"]: db_query = db_query.filter(Cases.grammer.contains(tag)) for words in query["next_words"]: tagging = words['tags'] # list of values for rg in tagging: db_query = db_query.filter(Cases.pos.contains(rg)) filter2=Case_Sentences.query.with_entities(Case_Sentences.st_id).filter_by(gc_id=db_query.first().gc_id).all() for r in filter2: new_list.append(r.st_id) filter3 = Sentences.query.filter(Sentences.sn_id.in_(new_list)).paginate(per_page=12,page=page_num,error_out=False) Goal is, using for loops add filters to query and at the end call it and fetch it all. And the error I am getting : filter2=Case_Sentences.query.with_entities(Case_Sentences.st_id).filter_by(gc_id=db_query.first().gc_id).all() AttributeError: 'NoneType' object has no attribute 'gc_id' Why do I get this error message, even tho everything seems to be correct
[ "The problem was in :\nfor words in query[\"next_words\"]:\n tagging = words['tags'] # list of values\n for rg in tagging:\n db_query = db_query.filter(Cases.pos.contains(rg))\n\nThis query was returning Empty Object for a reason, Queries done here was wrong.\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "flask_sqlalchemy", "non_type", "python", "sqlalchemy" ]
stackoverflow_0074551733_attributeerror_flask_sqlalchemy_non_type_python_sqlalchemy.txt
Q: Python date string conversion fail I am trying to convert the following string '1.12.22 14:16UTC+01:00' in Pandas to December 1st 2022 my_date = '1.12.22 14:16UTC+01:00' new_date = pd.to_datetime(my_date) Timestamp('2022-01-12 14:16:00-0100', tz='pytz.FixedOffset(-60)') It inverts month with day only in specific cases. I am trying to use format="%d.%m.%Y %H:%M%z" but it says that the string is not matching the format. time data '1.12.22 14:16UTC+01:00' does not match format '%d.%m.%Y %H:%M%z' (match) Thanks for your help. A: >>> pd.to_datetime('01.12.22 14:16UTC', format='%d.%m.%y %H:%M%Z') Timestamp('2022-12-01 14:16:00+0000', tz='UTC') I am not sure if this is what you are looking for, but your placeholders are wrong, check this page to know what they stand for. A: have you tried adding a zero? my_date = '01.12.22 14:16UTC+01:00'
Python date string conversion fail
I am trying to convert the following string '1.12.22 14:16UTC+01:00' in Pandas to December 1st 2022 my_date = '1.12.22 14:16UTC+01:00' new_date = pd.to_datetime(my_date) Timestamp('2022-01-12 14:16:00-0100', tz='pytz.FixedOffset(-60)') It inverts month with day only in specific cases. I am trying to use format="%d.%m.%Y %H:%M%z" but it says that the string is not matching the format. time data '1.12.22 14:16UTC+01:00' does not match format '%d.%m.%Y %H:%M%z' (match) Thanks for your help.
[ ">>> pd.to_datetime('01.12.22 14:16UTC', format='%d.%m.%y %H:%M%Z')\nTimestamp('2022-12-01 14:16:00+0000', tz='UTC')\n\nI am not sure if this is what you are looking for, but your placeholders are wrong, check this page to know what they stand for.\n", "have you tried adding a zero?\nmy_date = '01.12.22 14:16UTC+01:00'\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074558762_python.txt
Q: Scatterplots using csv files I want to create a 3-D scatterplot using only two variables of the csv file, I tried plotting a simple 2-D one and I keep getting a KeyError. How can I fix my problem. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("C:/Users/theet/Desktop/ITMLA/Assignment/merka_agri_corn_experiment.csv") df[:] x= df["fertilizer_addition"] y = df["corn_weight"] plt.scatter(x,y) plt.title("30 day experiment: Relation between fertilizer quantity and corn weight.") plt.xlabel("Fertilizer Amount") plt.ylabel("Corn Weight") plt.show() A: You're trying to find the key "fertilizr addition", which looks like a spelling mistake - I'm assuming you meant "fertilizer addition" which is why it's saying the key doesn't exist. Also, please post your code in your question.
Scatterplots using csv files
I want to create a 3-D scatterplot using only two variables of the csv file, I tried plotting a simple 2-D one and I keep getting a KeyError. How can I fix my problem. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("C:/Users/theet/Desktop/ITMLA/Assignment/merka_agri_corn_experiment.csv") df[:] x= df["fertilizer_addition"] y = df["corn_weight"] plt.scatter(x,y) plt.title("30 day experiment: Relation between fertilizer quantity and corn weight.") plt.xlabel("Fertilizer Amount") plt.ylabel("Corn Weight") plt.show()
[ "You're trying to find the key \"fertilizr addition\", which looks like a spelling mistake - I'm assuming you meant \"fertilizer addition\" which is why it's saying the key doesn't exist.\nAlso, please post your code in your question.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074558698_jupyter_notebook_python.txt
Q: Python + Selenium WebDriver, work with Pseudo-elements Please help. I need to activate the checkbox, but I don't understand how to refer to this pseudo-element ::before. Please, check this image enter image description here The checkbox should look like this, so you can go to the next page enter image description here The item is there, but I don't know how to activate the checkbox so that it changes color. I know I need to refer to the styles, but I don't know how to do that checkbox = driver.find_element(By.CSS_SELECTOR, 'body > main > div > div > div > div.account-page > div.account-content.account-part > div > div.tab-content > div.race-event-general > div:nth-child(9) > div.checkbox > label > span') checkbox.click() time.sleep(5) A: You do not need to access that pseudo element. Try clicking the label element there. Also you have to improve your locators. Absolute locators are extremely breakable.
Python + Selenium WebDriver, work with Pseudo-elements
Please help. I need to activate the checkbox, but I don't understand how to refer to this pseudo-element ::before. Please, check this image enter image description here The checkbox should look like this, so you can go to the next page enter image description here The item is there, but I don't know how to activate the checkbox so that it changes color. I know I need to refer to the styles, but I don't know how to do that checkbox = driver.find_element(By.CSS_SELECTOR, 'body > main > div > div > div > div.account-page > div.account-content.account-part > div > div.tab-content > div.race-event-general > div:nth-child(9) > div.checkbox > label > span') checkbox.click() time.sleep(5)
[ "You do not need to access that pseudo element. Try clicking the label element there.\nAlso you have to improve your locators. Absolute locators are extremely breakable.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074558803_python_selenium_selenium_webdriver.txt
Q: Python benchmark: Why for in loop is faster than simple while? I was trying to optimize simple character counting function. After few changes I decided to check the timings and expected the function using basic 'while' loop to be faster than 'for in' loop. But to my surprise while loop was almost 30% slower than for in here! Shouldn't be simple 'while' loop which has lower abstraction (doing less internally) be much faster than 'for in'? import timeit def faster_count_alphabet(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() for chars in a: l[ord(chars)] += 1 return l def faster_count_alphabet2(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() i = 0 size = len(a) while(i<size): l[ord(a[i])] += 1 i+=1 return l if __name__ == "__main__": print timeit.timeit("faster_count_alphabet('connect.log')", setup="from __main__ import faster_count_alphabet", number = 10) print timeit.timeit("faster_count_alphabet2('connect.log')", setup="from __main__ import faster_count_alphabet2", number = 10) Here is the timings I am getting: 7.087787236 9.9472761879 A: While Loop Well in your while loop the interpreter has to check every iteration whether your expression is true therefore it has to access both elements i and size and compare them. For Loop The for loop on the other hand has no need for that since the for loop is optimized as Chris_Rands already pointed out A: There are the result of my testing with python2.7: For Loop test1 python -mtimeit -s"d='/Users/xuejiang/go/src/main'.split('/')" "for i in range(len(d)):k=('index:',i,'value:',d[i])" result: 1000000 loops, best of 3: 0.747 usec per loop test2: python -mtimeit -s"d='/Users/xuejiang/go/src/main'.split('/');i=0" "for v in d:k=('index:',i,'value:',v);i+=1" result: 1000000 loops, best of 3: 0.524 usec per loop While Loop test python -mtimeit -s"d='/Users/xuejiang/go/src/main'.split('/');i=0" "while i <len(d):k=('index:',i,'value:',d[i]);i+=1" result: 10000000 loops, best of 3: 0.0658 usec per loop That is: while loop is much faster A: Your code should represent same functionality, I have modified it for you to re-run your test. I can see you even use the optimised version of the foreach loop instead of the normal for loop while you are benchmarking. def faster_count_for_loop(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() size = len(a) for i in range(size): l[ord(a[i])] += 1 return l def faster_count_while_loop(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() i = 0 size = len(a) while(i < size): l[ord(a[i])] += 1 i += 1 return l
Python benchmark: Why for in loop is faster than simple while?
I was trying to optimize simple character counting function. After few changes I decided to check the timings and expected the function using basic 'while' loop to be faster than 'for in' loop. But to my surprise while loop was almost 30% slower than for in here! Shouldn't be simple 'while' loop which has lower abstraction (doing less internally) be much faster than 'for in'? import timeit def faster_count_alphabet(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() for chars in a: l[ord(chars)] += 1 return l def faster_count_alphabet2(filename): l = [0] * 128 # all ascii values 0 to 127 with open(filename) as fh: a = fh.read() i = 0 size = len(a) while(i<size): l[ord(a[i])] += 1 i+=1 return l if __name__ == "__main__": print timeit.timeit("faster_count_alphabet('connect.log')", setup="from __main__ import faster_count_alphabet", number = 10) print timeit.timeit("faster_count_alphabet2('connect.log')", setup="from __main__ import faster_count_alphabet2", number = 10) Here is the timings I am getting: 7.087787236 9.9472761879
[ "While Loop\nWell in your while loop the interpreter has to check every iteration whether your expression is true therefore it has to access both elements i and size and compare them.\nFor Loop\nThe for loop on the other hand has no need for that since the for loop is optimized as Chris_Rands already pointed out\n", "There are the result of my testing with python2.7:\nFor Loop\ntest1\npython -mtimeit -s\"d='/Users/xuejiang/go/src/main'.split('/')\" \"for i in range(len(d)):k=('index:',i,'value:',d[i])\"\n\nresult:\n1000000 loops, best of 3: 0.747 usec per loop\n\ntest2:\npython -mtimeit -s\"d='/Users/xuejiang/go/src/main'.split('/');i=0\" \"for v in d:k=('index:',i,'value:',v);i+=1\"\n\nresult:\n1000000 loops, best of 3: 0.524 usec per loop\n\nWhile Loop\ntest\npython -mtimeit -s\"d='/Users/xuejiang/go/src/main'.split('/');i=0\" \"while i <len(d):k=('index:',i,'value:',d[i]);i+=1\"\n\nresult:\n10000000 loops, best of 3: 0.0658 usec per loop\n\nThat is: while loop is much faster\n", "Your code should represent same functionality, I have modified it for you to re-run your test.\nI can see you even use the optimised version of the foreach loop instead of the normal for loop while you are benchmarking.\ndef faster_count_for_loop(filename):\nl = [0] * 128 # all ascii values 0 to 127\nwith open(filename) as fh:\n a = fh.read()\n size = len(a)\n for i in range(size):\n l[ord(a[i])] += 1\nreturn l\n\ndef faster_count_while_loop(filename):\nl = [0] * 128 # all ascii values 0 to 127\nwith open(filename) as fh:\n a = fh.read()\n i = 0\n size = len(a)\n while(i < size):\n l[ord(a[i])] += 1\n i += 1\nreturn l\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "benchmarking", "performance", "python" ]
stackoverflow_0053812334_benchmarking_performance_python.txt
Q: How to add a QVideoWidget in Qt Designer? I want to insert video in blue box(ui image) but I don't know how to insert video file. My code is here. I don't know how to add video... Just know example that make video player ... import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import uic from PyQt5 import QtCore from PyQt5.QtCore import QDir, Qt, QUrl, pyqtSlot from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget) dir_audience='' dir_movie = '' dir_export = '' select_emotion = 'happy' class Form(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) self.ui = uic.loadUi("highlight_export_form.ui", self) self.ui.show() self.ui.load_audience.clicked.connect(self.load_audience_clicked) self.ui.load_movie.clicked.connect(self.load_movie_clicked) self.ui.start_recog.clicked.connect(self.start_recog_clicked) self.ui.radio_happy.toggled.connect(self.on_radio_button_toggled) self.ui.radio_surprised.toggled.connect(self.on_radio_button_toggled) def load_audience_clicked(self, event): dir_audience, _ = QFileDialog.getOpenFileName(self, "Open Audience", QDir.homePath()) self.path_audience.setText(dir_audience) def load_movie_clicked(self, event): dir_movie, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath()) self.path_movie.setText(dir_movie) def start_recog_clicked(self, event): self.check_1.setText("start_recognition") def on_radio_button_toggled(self): if self.radio_happy.isChecked(): select_emotion='happy' self.check_3.setText(select_emotion) elif self.radio_surprised.isChecked(): select_emotion='surprised' self.check_3.setText(select_emotion) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = Form() sys.exit(app.exec()) Thank you for reading my question. A: Qt Designer does not show all the Qt widget, and often we want to add our own widget through Qt, for that there are at least 2 solutions, the first is to create a plugin and load it to Qt Designer, and the other is simpler. promote the widget, the latter is what I will show in this answer. For this you must make certain minimum changes, I do not know what type of widget is the one you use in the blue box but you must change it to the Widget type that is in the sub-menu of the containers as shown in the following image: after them you must right click on the widget and select Promote to ..., then a dialogue will appear, in the part of Promoted class name you must place QVideoWidget, and in the part of Header File you must place PyQt5.QtMultimediaWidgets, then press the add button and then Promote: After that you will be able to use QVideoWidget within your application. In the following link there is an example A: Answer from here was clearer to me: QWebKit was removed in Qt 5.6. So QWebView is no longer available. Use QWebEngineView as a replacement. In Qt Designer, just add a QWidget to your form and promote it to QWebEngineView (base class: QWidget, header: QWebEngineView). Don't forget to add webenginewidgets to your project file. A: Simlar issue: want add QWebEngineView into Qt Designer for later PySide6 to import and use .ui, exported by Qt Designer Solution: add QWidget then Promoted to QWebEngineView Steps drag a new QWidget into your main ui (window) right click QWidget -> Promoted to new popup window, input Base class Name: QWidget Promoted class Name: QWebEngineView Header File: PySide6.QtWebEngineWidgets == parent class Global Include: not selected -> Screenshot click: Add click: Promote
How to add a QVideoWidget in Qt Designer?
I want to insert video in blue box(ui image) but I don't know how to insert video file. My code is here. I don't know how to add video... Just know example that make video player ... import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import uic from PyQt5 import QtCore from PyQt5.QtCore import QDir, Qt, QUrl, pyqtSlot from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget) dir_audience='' dir_movie = '' dir_export = '' select_emotion = 'happy' class Form(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) self.ui = uic.loadUi("highlight_export_form.ui", self) self.ui.show() self.ui.load_audience.clicked.connect(self.load_audience_clicked) self.ui.load_movie.clicked.connect(self.load_movie_clicked) self.ui.start_recog.clicked.connect(self.start_recog_clicked) self.ui.radio_happy.toggled.connect(self.on_radio_button_toggled) self.ui.radio_surprised.toggled.connect(self.on_radio_button_toggled) def load_audience_clicked(self, event): dir_audience, _ = QFileDialog.getOpenFileName(self, "Open Audience", QDir.homePath()) self.path_audience.setText(dir_audience) def load_movie_clicked(self, event): dir_movie, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath()) self.path_movie.setText(dir_movie) def start_recog_clicked(self, event): self.check_1.setText("start_recognition") def on_radio_button_toggled(self): if self.radio_happy.isChecked(): select_emotion='happy' self.check_3.setText(select_emotion) elif self.radio_surprised.isChecked(): select_emotion='surprised' self.check_3.setText(select_emotion) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = Form() sys.exit(app.exec()) Thank you for reading my question.
[ "Qt Designer does not show all the Qt widget, and often we want to add our own widget through Qt, for that there are at least 2 solutions, the first is to create a plugin and load it to Qt Designer, and the other is simpler. promote the widget, the latter is what I will show in this answer.\nFor this you must make certain minimum changes, I do not know what type of widget is the one you use in the blue box but you must change it to the Widget type that is in the sub-menu of the containers as shown in the following image:\n\nafter them you must right click on the widget and select Promote to ..., then a dialogue will appear, in the part of Promoted class name you must place QVideoWidget, and in the part of Header File you must place PyQt5.QtMultimediaWidgets, then press the add button and then Promote:\n\nAfter that you will be able to use QVideoWidget within your application.\nIn the following link there is an example\n", "Answer from here was clearer to me:\n\nQWebKit was removed in Qt 5.6. So QWebView is no longer available. Use QWebEngineView as a replacement. In Qt Designer, just add a QWidget to your form and promote it to QWebEngineView (base class: QWidget, header: QWebEngineView). Don't forget to add webenginewidgets to your project file.\n\n", "\nSimlar issue: want add QWebEngineView into Qt Designer\n\nfor later PySide6 to import and use .ui, exported by Qt Designer\n\n\nSolution: add QWidget then Promoted to QWebEngineView\n\nSteps\n\ndrag a new QWidget into your main ui (window)\nright click QWidget -> Promoted to\nnew popup window, input\n\nBase class Name: QWidget\nPromoted class Name: QWebEngineView\nHeader File: PySide6.QtWebEngineWidgets\n\n== parent class\n\n\nGlobal Include: not selected\n-> Screenshot\n\n\n\n\n\n\nclick: Add\nclick: Promote\n\n\n\n\n\n" ]
[ 24, 0, 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qt_designer", "qvideowidget" ]
stackoverflow_0047259825_pyqt_pyqt5_python_qt_designer_qvideowidget.txt
Q: How to add python panel date range slider on_change event? I am trying to use a dateRangeSlider to pick start and end dates and plot the graph accordingly using plotly in python. Here, whenever I change the slider, how can I know that slider is updated (return currently selected date-range as tuple) and I need to update the plot X and Y axis ranges? Is there any event handler or a way to use a callback function? Basically I want to know if dateRangeSlider is changed/updated and then I will pick the data in that range from a DataFrame and plot it using plotly. EDIT: Added code with output image import datetime as dt import panel as pn import yfinance as yf pn.extension() # Data part vix_tickers = ['AUDJPY=X'] df = yf.download(vix_tickers, auto_adjust=True, #only download adjusted data progress=False, ) df = df[["Close"]] # Date Range Slider date_range_slider = pn.widgets.DateRangeSlider( name='Date Range Slider', sizing_mode="stretch_width", margin = [10,40], bar_color = "blue", start=df.index[0], end=df.index[-1], value=(df.index[0], df.index[-1]), ) # A Plot import plotly.graph_objs as go fig = go.Figure() df.sort_index(ascending=True, inplace=True) trace = go.Scatter(x=list(df.index), y=list(df.Close)) fig.add_trace(trace) fig.update_layout( dict( title="Time series with range slider and selectors", xaxis=dict( rangeselector=dict( buttons=list( [ dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(step="all"), ] ) ), rangeslider=dict(visible=False), type="date", ), ) ) fig.show() date_range_slider A: Please use ipywidgets instead of panel, it is easier and more powerful: import datetime as dt import pandas as pd import yfinance as yf import plotly.graph_objs as go from ipywidgets import interact from ipywidgets import widgets # Data part vix_tickers = ['AUDJPY=X'] df = yf.download(vix_tickers, auto_adjust=True, #only download adjusted data progress=False, ) df = df[["Close"]] df.sort_index(ascending=True, inplace=True) widgets.SelectionRangeSlider( options=df.index, description='Dates', orientation='horizontal', layout={'width': '1000px'} @interact def read_values( slider = widgets.SelectionRangeSlider( options=df.index, index=(0, len(df.index) - 1), description='Dates', orientation='horizontal', layout={'width': '500px'}, continuous_update=False ) ): fig = go.Figure() trace = go.Scatter(x=list(df.index), y=list(df.Close)) fig.add_trace(trace) fig.update_xaxes(range=[slider[0], slider[1]]) go.FigureWidget(fig.to_dict()).show() Output
How to add python panel date range slider on_change event?
I am trying to use a dateRangeSlider to pick start and end dates and plot the graph accordingly using plotly in python. Here, whenever I change the slider, how can I know that slider is updated (return currently selected date-range as tuple) and I need to update the plot X and Y axis ranges? Is there any event handler or a way to use a callback function? Basically I want to know if dateRangeSlider is changed/updated and then I will pick the data in that range from a DataFrame and plot it using plotly. EDIT: Added code with output image import datetime as dt import panel as pn import yfinance as yf pn.extension() # Data part vix_tickers = ['AUDJPY=X'] df = yf.download(vix_tickers, auto_adjust=True, #only download adjusted data progress=False, ) df = df[["Close"]] # Date Range Slider date_range_slider = pn.widgets.DateRangeSlider( name='Date Range Slider', sizing_mode="stretch_width", margin = [10,40], bar_color = "blue", start=df.index[0], end=df.index[-1], value=(df.index[0], df.index[-1]), ) # A Plot import plotly.graph_objs as go fig = go.Figure() df.sort_index(ascending=True, inplace=True) trace = go.Scatter(x=list(df.index), y=list(df.Close)) fig.add_trace(trace) fig.update_layout( dict( title="Time series with range slider and selectors", xaxis=dict( rangeselector=dict( buttons=list( [ dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(step="all"), ] ) ), rangeslider=dict(visible=False), type="date", ), ) ) fig.show() date_range_slider
[ "Please use ipywidgets instead of panel, it is easier and more powerful:\nimport datetime as dt\nimport pandas as pd\nimport yfinance as yf\nimport plotly.graph_objs as go\nfrom ipywidgets import interact\nfrom ipywidgets import widgets\n\n\n# Data part\nvix_tickers = ['AUDJPY=X']\n\ndf = yf.download(vix_tickers,\n auto_adjust=True, #only download adjusted data\n progress=False,\n )\ndf = df[[\"Close\"]]\n\ndf.sort_index(ascending=True, inplace=True)\n\nwidgets.SelectionRangeSlider(\n options=df.index,\n description='Dates',\n orientation='horizontal',\n layout={'width': '1000px'}\n \n \n@interact\ndef read_values(\n slider = widgets.SelectionRangeSlider(\n options=df.index,\n index=(0, len(df.index) - 1),\n description='Dates',\n orientation='horizontal',\n layout={'width': '500px'},\n continuous_update=False\n)\n):\n fig = go.Figure()\n trace = go.Scatter(x=list(df.index), y=list(df.Close))\n fig.add_trace(trace)\n fig.update_xaxes(range=[slider[0], slider[1]])\n go.FigureWidget(fig.to_dict()).show()\n\nOutput\n\n" ]
[ 1 ]
[]
[]
[ "panel", "plotly", "python", "python_3.x" ]
stackoverflow_0074557353_panel_plotly_python_python_3.x.txt
Q: How to delete class object in python TypeError: 'employee' object cannot be interpreted as an integer I AM GETTING THIS TYPE OF ERROR name = input("Enter name you want to delete : ") for i in lst: if name in i.name: lst.pop(i) print("Employee deleted!") I was expecting that the object would get deleted But it Showing type error TypeError: 'employee' object cannot be interpreted as an integer A: From python documentation the method list.pop except an integer as parameter with give the position of the element to remove in the list. From your code, the list lst seems to contain objects of the employee class and this isn't an integer. For your case, the list.remove function will be the one to use since it work with the objects inside the list rather than the position in it. You should also implement the __eq__ method in your employee class if it's not already done, this is what python will use to compare the employee object in your list and the one to delete. A last point, if you really want to use the list.pop method instead of list.remove you can do it by using list.index first to get the position of the object to remove from the list. lst.pop(lst.index(i))
How to delete class object in python
TypeError: 'employee' object cannot be interpreted as an integer I AM GETTING THIS TYPE OF ERROR name = input("Enter name you want to delete : ") for i in lst: if name in i.name: lst.pop(i) print("Employee deleted!") I was expecting that the object would get deleted But it Showing type error TypeError: 'employee' object cannot be interpreted as an integer
[ "From python documentation the method list.pop except an integer as parameter with give the position of the element to remove in the list.\nFrom your code, the list lst seems to contain objects of the employee class and this isn't an integer. For your case, the list.remove function will be the one to use since it work with the objects inside the list rather than the position in it.\nYou should also implement the __eq__ method in your employee class if it's not already done, this is what python will use to compare the employee object in your list and the one to delete.\nA last point, if you really want to use the list.pop method instead of list.remove you can do it by using list.index first to get the position of the object to remove from the list.\nlst.pop(lst.index(i))\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074558820_python.txt
Q: Is there any way I can download the pre-trained models available in PyTorch to a specific path? I am referring to the models that can be found here: https://pytorch.org/docs/stable/torchvision/models.html#torchvision-models A: As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally called when you load a pre-trained model. More specifically, the method: torch.utils.model_zoo.load_url() is being called every time a pre-trained model is loaded. The documentation for the same, mentions: The default value of model_dir is $TORCH_HOME/models where $TORCH_HOME defaults to ~/.torch. The default directory can be overridden with the $TORCH_HOME environment variable. This can be done as follows: import torch import torchvision import os # Suppose you are trying to load pre-trained resnet model in directory- models\resnet os.environ['TORCH_HOME'] = 'models\\resnet' #setting the environment variable resnet = torchvision.models.resnet18(pretrained=True) I came across the above solution by raising an issue in the PyTorch's GitHub repository: https://github.com/pytorch/vision/issues/616 This led to an improvement in the documentation i.e. the solution mentioned above. A: Yes, you can simply copy the urls and use wget to download it to the desired path. Here's an illustration: For AlexNet: $ wget -c https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth For Google Inception (v3): $ wget -c https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth For SqueezeNet: $ wget -c https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth For MobileNetV2: $ wget -c https://download.pytorch.org/models/mobilenet_v2-b0353104.pth For DenseNet201: $ wget -c https://download.pytorch.org/models/densenet201-c1103571.pth For MNASNet1_0: $ wget -c https://download.pytorch.org/models/mnasnet1.0_top1_73.512-f206786ef8.pth For ShuffleNetv2_x1.0: $ wget -c https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth If you want to do it in Python, then use something like: In [11]: from six.moves import urllib # resnet 101 host url In [12]: url = "https://download.pytorch.org/models/resnet101-5d3b4d8f.pth" # download and rename the file to `resnet_101.pth` In [13]: urllib.request.urlretrieve(url, "resnet_101.pth") Out[13]: ('resnet_101.pth', <http.client.HTTPMessage at 0x7f7fd7f53438>) P.S: You can find the download URLs in the respective python modules of torchvision.models A: There is a script available that will output a list of URLs across the entire package. From within the pytorch/vision package execute the following: python scripts/collect_model_urls.py . # ... # https://download.pytorch.org/models/swin_v2_b-781e5279.pth # https://download.pytorch.org/models/swin_v2_s-637d8ceb.pth # https://download.pytorch.org/models/swin_v2_t-b137f0e2.pth # https://download.pytorch.org/models/vgg11-8a719046.pth # https://download.pytorch.org/models/vgg11_bn-6002323d.pth # ...
Is there any way I can download the pre-trained models available in PyTorch to a specific path?
I am referring to the models that can be found here: https://pytorch.org/docs/stable/torchvision/models.html#torchvision-models
[ "As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally called when you load a pre-trained model.\nMore specifically, the method: torch.utils.model_zoo.load_url() is being called every time a pre-trained model is loaded. The documentation for the same, mentions:\n\nThe default value of model_dir is $TORCH_HOME/models where\n $TORCH_HOME defaults to ~/.torch. \nThe default directory can be overridden with the $TORCH_HOME\n environment variable.\n\nThis can be done as follows:\nimport torch \nimport torchvision\nimport os\n\n# Suppose you are trying to load pre-trained resnet model in directory- models\\resnet\n\nos.environ['TORCH_HOME'] = 'models\\\\resnet' #setting the environment variable\nresnet = torchvision.models.resnet18(pretrained=True)\n\nI came across the above solution by raising an issue in the PyTorch's GitHub repository:\nhttps://github.com/pytorch/vision/issues/616\nThis led to an improvement in the documentation i.e. the solution mentioned above.\n", "Yes, you can simply copy the urls and use wget to download it to the desired path. Here's an illustration:\nFor AlexNet:\n$ wget -c https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth\n\nFor Google Inception (v3):\n$ wget -c https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth\n\nFor SqueezeNet:\n$ wget -c https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth\n\nFor MobileNetV2:\n$ wget -c https://download.pytorch.org/models/mobilenet_v2-b0353104.pth\n\nFor DenseNet201:\n$ wget -c https://download.pytorch.org/models/densenet201-c1103571.pth\n\nFor MNASNet1_0:\n$ wget -c https://download.pytorch.org/models/mnasnet1.0_top1_73.512-f206786ef8.pth\n\nFor ShuffleNetv2_x1.0:\n$ wget -c https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth\n\n\nIf you want to do it in Python, then use something like:\nIn [11]: from six.moves import urllib\n\n# resnet 101 host url\nIn [12]: url = \"https://download.pytorch.org/models/resnet101-5d3b4d8f.pth\"\n\n# download and rename the file to `resnet_101.pth`\nIn [13]: urllib.request.urlretrieve(url, \"resnet_101.pth\")\nOut[13]: ('resnet_101.pth', <http.client.HTTPMessage at 0x7f7fd7f53438>)\n\nP.S: You can find the download URLs in the respective python modules of torchvision.models\n", "There is a script available that will output a list of URLs across the entire package.\nFrom within the pytorch/vision package execute the following:\npython scripts/collect_model_urls.py .\n\n# ...\n# https://download.pytorch.org/models/swin_v2_b-781e5279.pth\n# https://download.pytorch.org/models/swin_v2_s-637d8ceb.pth\n# https://download.pytorch.org/models/swin_v2_t-b137f0e2.pth\n# https://download.pytorch.org/models/vgg11-8a719046.pth\n# https://download.pytorch.org/models/vgg11_bn-6002323d.pth\n# ...\n\n" ]
[ 31, 8, 0 ]
[ "TL;DR: No, it is not possible directly, but you can easily adapt it.\nI think what you want to do is to look at torch.utils.model_zoo, which is internally called when you load a pre-trained model:\nIf we look at the code for the pre-trained models, for example AlexNet here, we can see that it simply calls the previously mentioned model_zoo function, but without the saved location. You can either modify the PyTorch source to specify this (that would actually be a great addition IMO, so maybe open a pull request for that), or else simply adopt the code in the second link to your own liking (and save it to a custom location under a different name), and then manually insert the relevant location there.\nIf you want to regularly update PyTorch, I would heavily recommend the second method, since it doesn't involve directly altering PyTorch's code base, and potentially throw errors during updates.\n" ]
[ -1 ]
[ "deep_learning", "pre_trained_model", "python", "pytorch", "torchvision" ]
stackoverflow_0052628270_deep_learning_pre_trained_model_python_pytorch_torchvision.txt
Q: OpenGL Canvas. how to move an object inside a canvas I want to move the following red cross in the canvas with the mouse events. it should only move when we click on it and drag it with the move. it should stop moving when we release the mouse. I do get the events of the mouse. but I don't know how i can detect that I clicked on the object to make it move. also for example i can't set self.plot1.pos to change its position. we don't have access to that attribute. does anybody have an idea? I am using python 3.5 and OpenGL Canvas with vispy and a QtWidgets window. import sys from PySide2 import QtWidgets from vispy import scene from PySide2.QtCore import QMetaObject from PySide2.QtWidgets import * import numpy as np class my_canvas(scene.SceneCanvas): def __init__(self): super().__init__(keys="interactive") self.unfreeze() self.view = self.central_widget.add_view() self.view.bgcolor = '#ffffff' # set the canva to a white background window_size_0 = 800, 400 window_center = window_size_0[0] / 2, window_size_0[1] / 2 crosshair_max_length = 50 data_1 = np.random.normal(size=(2, 2)) data_1[0] = window_center[0] - crosshair_max_length, window_center[1] data_1[1] = window_center[0] + crosshair_max_length, window_center[1] data_2 = np.random.normal(size=(2, 2)) data_2[0] = window_center[0], window_center[1] - crosshair_max_length data_2[1] = window_center[0], window_center[1] + crosshair_max_length self.plot1 = scene.Line(data_1, parent=self.view.scene, color="r") self.plot2 = scene.Line(data_2, parent=self.view.scene, color="r") self.selected_object = None self.freeze() def on_mouse_press(self, event): if event.button == 1: print("pressed left") if event.button == 2: print("pressed right") def on_mouse_move(self, event): pass class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(748, 537) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.groupBox = QGroupBox(self.centralwidget) self.groupBox.setObjectName("groupBox") self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) QMetaObject.connectSlotsByName(MainWindow) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # OpenGL drawing surface self.canvas = my_canvas() self.canvas.create_native() self.canvas.native.setParent(self) self.setWindowTitle('MyApp') def main(): import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui') app = QtWidgets.QApplication([]) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() A: i found the solution for the ones who are interested. self.plot1.set_data(pos=...) with this method we can move it easily
OpenGL Canvas. how to move an object inside a canvas
I want to move the following red cross in the canvas with the mouse events. it should only move when we click on it and drag it with the move. it should stop moving when we release the mouse. I do get the events of the mouse. but I don't know how i can detect that I clicked on the object to make it move. also for example i can't set self.plot1.pos to change its position. we don't have access to that attribute. does anybody have an idea? I am using python 3.5 and OpenGL Canvas with vispy and a QtWidgets window. import sys from PySide2 import QtWidgets from vispy import scene from PySide2.QtCore import QMetaObject from PySide2.QtWidgets import * import numpy as np class my_canvas(scene.SceneCanvas): def __init__(self): super().__init__(keys="interactive") self.unfreeze() self.view = self.central_widget.add_view() self.view.bgcolor = '#ffffff' # set the canva to a white background window_size_0 = 800, 400 window_center = window_size_0[0] / 2, window_size_0[1] / 2 crosshair_max_length = 50 data_1 = np.random.normal(size=(2, 2)) data_1[0] = window_center[0] - crosshair_max_length, window_center[1] data_1[1] = window_center[0] + crosshair_max_length, window_center[1] data_2 = np.random.normal(size=(2, 2)) data_2[0] = window_center[0], window_center[1] - crosshair_max_length data_2[1] = window_center[0], window_center[1] + crosshair_max_length self.plot1 = scene.Line(data_1, parent=self.view.scene, color="r") self.plot2 = scene.Line(data_2, parent=self.view.scene, color="r") self.selected_object = None self.freeze() def on_mouse_press(self, event): if event.button == 1: print("pressed left") if event.button == 2: print("pressed right") def on_mouse_move(self, event): pass class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(748, 537) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.groupBox = QGroupBox(self.centralwidget) self.groupBox.setObjectName("groupBox") self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) QMetaObject.connectSlotsByName(MainWindow) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # OpenGL drawing surface self.canvas = my_canvas() self.canvas.create_native() self.canvas.native.setParent(self) self.setWindowTitle('MyApp') def main(): import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui') app = QtWidgets.QApplication([]) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
[ "i found the solution for the ones who are interested.\nself.plot1.set_data(pos=...)\nwith this method we can move it easily\n" ]
[ 0 ]
[]
[]
[ "pyqt", "pyside", "python", "vispy" ]
stackoverflow_0074557847_pyqt_pyside_python_vispy.txt
Q: AttributeError: 'NoneType' object has no attribute 'list_middleware' in masonite\routes\Route.py", line 166 Upon running python craft migration create_a_table --create a_table I received the following traceback: Traceback (most recent call last): File "SOMEPATH\craft", line 8, in <module> from wsgi import application File "SOMEPATH\wsgi.py", line 11, in <module> application.register_providers(Kernel, ApplicationKernel) File "SOMEPATH\venv\lib\site-packages\masonite\foundation\Application.py", line 32, in register_providers provider.register() File "SOMEPATH\Kernel.py", line 29, in register self.register_routes() File "SOMEPATH\Kernel.py", line 72, in register_routes Route.group( File "SOMEPATH\venv\lib\site-packages\masonite\routes\Route.py", line 166, in group middleware = route.list_middleware AttributeError: 'NoneType' object has no attribute 'list_middleware' I've had a check with the debugger and for some reason it seems that the routes don't get loaded from the routes/web.py file is there something I am missing here A: It turns out that one of the dependencies I had somewhere had a missing dependency. I found out that the load function called in Kernel.register_routes silenced a ModuleNotFoundError. For some reason this error didn't get silenced in a fresh project that also was missing a dependency of a module. I am guessing that it is something to do with the configuration I have on this project. For someone else that also has this error, using a debugger, set a breakpoint in masonite\utils\structures.py in the load function after except Exception as e: and you can read out the exception message to see what module is missing
AttributeError: 'NoneType' object has no attribute 'list_middleware' in masonite\routes\Route.py", line 166
Upon running python craft migration create_a_table --create a_table I received the following traceback: Traceback (most recent call last): File "SOMEPATH\craft", line 8, in <module> from wsgi import application File "SOMEPATH\wsgi.py", line 11, in <module> application.register_providers(Kernel, ApplicationKernel) File "SOMEPATH\venv\lib\site-packages\masonite\foundation\Application.py", line 32, in register_providers provider.register() File "SOMEPATH\Kernel.py", line 29, in register self.register_routes() File "SOMEPATH\Kernel.py", line 72, in register_routes Route.group( File "SOMEPATH\venv\lib\site-packages\masonite\routes\Route.py", line 166, in group middleware = route.list_middleware AttributeError: 'NoneType' object has no attribute 'list_middleware' I've had a check with the debugger and for some reason it seems that the routes don't get loaded from the routes/web.py file is there something I am missing here
[ "It turns out that one of the dependencies I had somewhere had a missing dependency. I found out that the load function called in Kernel.register_routes silenced a ModuleNotFoundError. For some reason this error didn't get silenced in a fresh project that also was missing a dependency of a module. I am guessing that it is something to do with the configuration I have on this project.\nFor someone else that also has this error, using a debugger, set a breakpoint in masonite\\utils\\structures.py in the load function after except Exception as e: and you can read out the exception message to see what module is missing\n" ]
[ 0 ]
[]
[]
[ "masonite", "python" ]
stackoverflow_0074559042_masonite_python.txt
Q: I was using Python and If statement won't write ( < ) and keep writing ( > ) whether they are true or not print("Welcome to Agurds. Before we begin can you tell me your name?") Name = input("name: ") print("Hello " + Name + " When were you born " + Name + "?") year = int(input("Born year:")) age = str(2022 - year) print("You must be " + age + " this year.") if age < str(18): print("You're too young to be here. Exiting world.") else: print("I see we have an adult here. Would you like to buy some of our products before hand?") Pens = input("How much do you have right now?") if Pens < str(100): print("You can only buy some of our products?") if Pens > str(100): print("You can buy most of our products") The result: Welcome to Agurds. Before we begin can you tell me your name? name: Hein Hello Hein When were you born Hein? Born year:2000 You must be 22 this year. I see we have an adult here. Would you like to buy some of our products before hand? How much do you have right now? 99 You can buy most of our products I was expecting it to give me the first line I wrote but it doesn't work. I'm just started python not too long ago so I don't know what I am doing wrong. A: When comparing two values to find the smallest, use int rather than str, such as using if age < 18 rather than if age < str(18). You problem was that it was comparing the string Pens rather than the int Pens print("Welcome to Agurds. Before we begin can you tell me your name?") Name = input("name: ") print("Hello " + Name + " When were you born " + Name + "?") year = int(input("Born year:")) age = 2022 - year print("You must be " + str(age) + " this year.") if age < 18: print("You're too young to be here. Exiting world.") else: print("I see we have an adult here. Would you like to buy some of our products before hand?") Pens = int(input("How much do you have right now?")) if Pens < 100: print("You can only buy some of our products?") if Pens > 100: print("You can buy most of our products") Hope this helps A: You are trying to compare strings. Saying "95" < "100" doesn't make much sense. What you could do, is convert the pens input to a int, and then compare it to 100: pens = int(input("How much do you have right now?")) if pens < 100: #your code Also, avoid using capitalizer names for variables, since most programming languages will detect that as an error
I was using Python and If statement won't write ( < ) and keep writing ( > ) whether they are true or not
print("Welcome to Agurds. Before we begin can you tell me your name?") Name = input("name: ") print("Hello " + Name + " When were you born " + Name + "?") year = int(input("Born year:")) age = str(2022 - year) print("You must be " + age + " this year.") if age < str(18): print("You're too young to be here. Exiting world.") else: print("I see we have an adult here. Would you like to buy some of our products before hand?") Pens = input("How much do you have right now?") if Pens < str(100): print("You can only buy some of our products?") if Pens > str(100): print("You can buy most of our products") The result: Welcome to Agurds. Before we begin can you tell me your name? name: Hein Hello Hein When were you born Hein? Born year:2000 You must be 22 this year. I see we have an adult here. Would you like to buy some of our products before hand? How much do you have right now? 99 You can buy most of our products I was expecting it to give me the first line I wrote but it doesn't work. I'm just started python not too long ago so I don't know what I am doing wrong.
[ "When comparing two values to find the smallest, use int rather than str, such as using if age < 18 rather than if age < str(18). You problem was that it was comparing the string Pens rather than the int Pens\nprint(\"Welcome to Agurds. Before we begin can you tell me your name?\")\nName = input(\"name: \")\nprint(\"Hello \" + Name + \" When were you born \" + Name + \"?\")\nyear = int(input(\"Born year:\"))\nage = 2022 - year\nprint(\"You must be \" + str(age) + \" this year.\")\nif age < 18:\n print(\"You're too young to be here. Exiting world.\")\nelse:\n print(\"I see we have an adult here. Would you like to buy some of our products before hand?\")\n Pens = int(input(\"How much do you have right now?\"))\n if Pens < 100:\n print(\"You can only buy some of our products?\")\n if Pens > 100:\n print(\"You can buy most of our products\")\n\nHope this helps\n", "You are trying to compare strings. Saying \"95\" < \"100\" doesn't make much sense. What you could do, is convert the pens input to a int, and then compare it to 100:\npens = int(input(\"How much do you have right now?\"))\nif pens < 100:\n #your code\n\nAlso, avoid using capitalizer names for variables, since most programming languages will detect that as an error\n" ]
[ 0, 0 ]
[]
[]
[ "function", "if_statement", "project", "python", "windows" ]
stackoverflow_0074557176_function_if_statement_project_python_windows.txt
Q: Plotly: Create a Scatter with categorical x-axis jitter and multi level axis I would like to make a graph with a multi-level x axis like in the following picture: import plotly.graph_objects as go fig = go.Figure() fig.add_trace( go.Scatter( x = [df['x'], df['x1']], y = df['y'], mode='markers' ) ) But also I would like to put jitter on the x-axis like in the next picture: So far I can make each graph independently using the next code: import plotly.express as px fig = px.strip(df, x=[df["x"], df['x1']], y="y", stripmode='overlay') Is it possible to combine the jitter and the multi-level axis in one plot? Here is a code to reproduce the dataset: import numpy as np import pandas as pd import random '''Create DataFrame''' price = np.append( np.random.normal(20, 5, size=(1, 50)), np.random.normal(40, 2, size=(1, 10)) ) quantity = np.append( np.random.randint(1, 5, size=(50)), np.random.randint(8, 12, size=(10)) ) firstLayerList = ['15 in', '16 in'] secondLayerList = ['1/2', '3/8'] vendorList = ['Vendor1','Vendor2','Vendor3'] data = { 'Width': [random.choice(firstLayerList) for i in range(len(price))], 'Length': [random.choice(secondLayerList) for i in range(len(price))], 'Vendor': [random.choice(vendorList) for i in range(len(price))], 'Quantity': quantity, 'Price': price } df = pd.DataFrame.from_dict(data) A: Firstly - thanks for the challenge! There aren't many challenging Plotly questions these days. The key elements to creating a scatter graph with jitter are: Using mode: 'box' - to create a box-plot, not a scatter plot. Setting 'boxpoints': 'all' - so all points are plotted. Using 'pointpos': 0 - to center the points on the x-axis. Removing (hiding!) the whisker boxes using: 'fillcolor': 'rgba(255,255,255,0)' 'line': {'color': 'rgba(255,255,255,0)'} DataFrame preparation: This code simply splits the main DataFrame into a frame for each vendor, thus allowing a trace to be created for each, with their own colour. df1 = df[df['Vendor'] == 'Vendor1'] df2 = df[df['Vendor'] == 'Vendor2'] df3 = df[df['Vendor'] == 'Vendor3'] Plotting code: The plotting code could use a for-loop if you like. However, I've intentionally kept it more verbose, so as to increase clarity. import plotly.io as pio layout = {'title': 'Categorical X-Axis, with Jitter'} traces = [] traces.append({'x': [df1['Width'], df1['Length']], 'y': df1['Price'], 'name': 'Vendor1', 'marker': {'color': 'green'}}) traces.append({'x': [df2['Width'], df2['Length']], 'y': df2['Price'], 'name': 'Vendor2', 'marker': {'color': 'blue'}}) traces.append({'x': [df3['Width'], df3['Length']], 'y': df3['Price'], 'name': 'Vendor3', 'marker': {'color': 'orange'}}) # Update (add) trace elements common to all traces. for t in traces: t.update({'type': 'box', 'boxpoints': 'all', 'fillcolor': 'rgba(255,255,255,0)', 'hoveron': 'points', 'hovertemplate': 'value=%{x}<br>Price=%{y}<extra></extra>', 'line': {'color': 'rgba(255,255,255,0)'}, 'pointpos': 0, 'showlegend': True}) pio.show({'data': traces, 'layout': layout}) Graph: The data behind this graph was generated using np.random.seed(73), against the dataset creation code posted in the question. Comments (TL;DR): The example code shown here uses the lower-level Plotly API, rather than a convenience wrapper such as graph_objects or express. The reason is that I (personally) feel it's helpful to users to show what is occurring 'under the hood', rather than masking the underlying code logic with a convenience wrapper. This way, when the user needs to modify a finer detail of the graph, they will have a better understanding of the lists and dicts which Plotly is constructing for the underlying graphing engine (orca). And this use-case is a prime example of this reasoning, as it’s edging Plotly past its (current) design point. A: An alternative straightforward solution might be using: plotly.express.strip with stripmode="overlay" (more info about parameters) Here I show you an example with the Iris data. Plotly version 4.4.1. import plotly.express as px df = px.data.iris() fig = px.strip(df, x="species", y="sepal_width", color="species", title="This is a stripplot!", stripmode = "overlay" # Select between "group" or "overlay" mode ) fig.show() This is the result (run the code snippet) <div> <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <div id="70e0d94a-4a4c-40fc-af77-95274959151b" class="plotly-graph-div" style="height:100%; width:100%;"></div> <script type="text/javascript"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("70e0d94a-4a4c-40fc-af77-95274959151b")) { Plotly.newPlot( '70e0d94a-4a4c-40fc-af77-95274959151b', [{"alignmentgroup": "True", "boxpoints": "all", "fillcolor": "rgba(255,255,255,0)", "hoverlabel": {"namelength": 0}, "hoveron": "points", "hovertemplate": "species=%{x}<br>sepal_width=%{y}", "legendgroup": "species=setosa", "line": {"color": "rgba(255,255,255,0)"}, "marker": {"color": "#636efa"}, "name": "species=setosa", "offsetgroup": "species=setosa", "orientation": "v", "pointpos": 0, "showlegend": true, "type": "box", "x": ["setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa", "setosa"], "x0": " ", "xaxis": "x", "y": [3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.1, 3.0, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3.0, 3.8, 3.2, 3.7, 3.3], "y0": " ", "yaxis": "y"}, {"alignmentgroup": "True", "boxpoints": "all", "fillcolor": "rgba(255,255,255,0)", "hoverlabel": {"namelength": 0}, "hoveron": "points", "hovertemplate": "species=%{x}<br>sepal_width=%{y}", "legendgroup": "species=versicolor", "line": {"color": "rgba(255,255,255,0)"}, "marker": {"color": "#EF553B"}, "name": "species=versicolor", "offsetgroup": "species=versicolor", "orientation": "v", "pointpos": 0, "showlegend": true, "type": "box", "x": ["versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor", "versicolor"], "x0": " ", "xaxis": "x", "y": [3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0, 2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8], "y0": " ", "yaxis": "y"}, {"alignmentgroup": "True", "boxpoints": "all", "fillcolor": "rgba(255,255,255,0)", "hoverlabel": {"namelength": 0}, "hoveron": "points", "hovertemplate": "species=%{x}<br>sepal_width=%{y}", "legendgroup": "species=virginica", "line": {"color": "rgba(255,255,255,0)"}, "marker": {"color": "#00cc96"}, "name": "species=virginica", "offsetgroup": "species=virginica", "orientation": "v", "pointpos": 0, "showlegend": true, "type": "box", "x": ["virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica", "virginica"], "x0": " ", "xaxis": "x", "y": [3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5, 3.0, 3.4, 3.0], "y0": " ", "yaxis": "y"}], {"boxmode": "overlay", "legend": {"tracegroupgap": 0}, "template": {"data": {"bar": [{"error_x": {"color": "#2a3f5f"}, "error_y": {"color": "#2a3f5f"}, "marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "bar"}], "barpolar": [{"marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "barpolar"}], "carpet": [{"aaxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "baxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "type": "carpet"}], "choropleth": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "choropleth"}], "contour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "contour"}], "contourcarpet": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "contourcarpet"}], "heatmap": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmap"}], "heatmapgl": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmapgl"}], "histogram": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "histogram"}], "histogram2d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2d"}], "histogram2dcontour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2dcontour"}], "mesh3d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "mesh3d"}], "parcoords": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "parcoords"}], "pie": [{"automargin": true, "type": "pie"}], "scatter": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter"}], "scatter3d": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter3d"}], "scattercarpet": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattercarpet"}], "scattergeo": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergeo"}], "scattergl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergl"}], "scattermapbox": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattermapbox"}], "scatterpolar": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolar"}], "scatterpolargl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolargl"}], "scatterternary": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterternary"}], "surface": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "surface"}], "table": [{"cells": {"fill": {"color": "#EBF0F8"}, "line": {"color": "white"}}, "header": {"fill": {"color": "#C8D4E3"}, "line": {"color": "white"}}, "type": "table"}]}, "layout": {"annotationdefaults": {"arrowcolor": "#2a3f5f", "arrowhead": 0, "arrowwidth": 1}, "coloraxis": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "colorscale": {"diverging": [[0, "#8e0152"], [0.1, "#c51b7d"], [0.2, "#de77ae"], [0.3, "#f1b6da"], [0.4, "#fde0ef"], [0.5, "#f7f7f7"], [0.6, "#e6f5d0"], [0.7, "#b8e186"], [0.8, "#7fbc41"], [0.9, "#4d9221"], [1, "#276419"]], "sequential": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "sequentialminus": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]]}, "colorway": ["#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52"], "font": {"color": "#2a3f5f"}, "geo": {"bgcolor": "white", "lakecolor": "white", "landcolor": "#E5ECF6", "showlakes": true, "showland": true, "subunitcolor": "white"}, "hoverlabel": {"align": "left"}, "hovermode": "closest", "mapbox": {"style": "light"}, "paper_bgcolor": "white", "plot_bgcolor": "#E5ECF6", "polar": {"angularaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "radialaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "scene": {"xaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "yaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "zaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}}, "shapedefaults": {"line": {"color": "#2a3f5f"}}, "ternary": {"aaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "baxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "caxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "title": {"x": 0.05}, "xaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "title": {"standoff": 15}, "zerolinecolor": "white", "zerolinewidth": 2}, "yaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "title": {"standoff": 15}, "zerolinecolor": "white", "zerolinewidth": 2}}}, "title": {"text": "This is a stripplot!"}, "xaxis": {"anchor": "y", "categoryarray": ["setosa", "versicolor", "virginica"], "categoryorder": "array", "domain": [0.0, 1.0], "title": {"text": "species"}}, "yaxis": {"anchor": "x", "domain": [0.0, 1.0], "title": {"text": "sepal_width"}}}, {"responsive": true} ) }; </script> </div> A: Some plotly.express functions provide a facet argument which allows you to create a plot that closely resembles the multi-level x-axis from your example, without calls to the low-level API. Starting wiht some sample data and imports: import plotly.express as px import pandas as pd import numpy as np # Create data df = pd.DataFrame(data={"y": np.random.uniform(low=0, high=45, size=100)}) df["x"] = [*["3/8"] * 25, *["1/2"] * 25, *["3/8"] * 25, *["1/2"] * 25] df["x1"] = [*["16 in"] * 50, *["15 in"] * 50] print(df.head().to_markdown()) y x x1 0 27.1279 3/8 16 in 1 13.8564 3/8 16 in 2 11.8026 3/8 16 in 3 25.3769 3/8 16 in 4 12.1194 3/8 16 in You can provide one of the columns from the dataframe to the facet_col argument: px.strip(df, x=["x", "x1"], y="y", stripmode='overlay', facet_col="x1") Which results in: If you like, you can further tweak the appearance of the subplot titles.
Plotly: Create a Scatter with categorical x-axis jitter and multi level axis
I would like to make a graph with a multi-level x axis like in the following picture: import plotly.graph_objects as go fig = go.Figure() fig.add_trace( go.Scatter( x = [df['x'], df['x1']], y = df['y'], mode='markers' ) ) But also I would like to put jitter on the x-axis like in the next picture: So far I can make each graph independently using the next code: import plotly.express as px fig = px.strip(df, x=[df["x"], df['x1']], y="y", stripmode='overlay') Is it possible to combine the jitter and the multi-level axis in one plot? Here is a code to reproduce the dataset: import numpy as np import pandas as pd import random '''Create DataFrame''' price = np.append( np.random.normal(20, 5, size=(1, 50)), np.random.normal(40, 2, size=(1, 10)) ) quantity = np.append( np.random.randint(1, 5, size=(50)), np.random.randint(8, 12, size=(10)) ) firstLayerList = ['15 in', '16 in'] secondLayerList = ['1/2', '3/8'] vendorList = ['Vendor1','Vendor2','Vendor3'] data = { 'Width': [random.choice(firstLayerList) for i in range(len(price))], 'Length': [random.choice(secondLayerList) for i in range(len(price))], 'Vendor': [random.choice(vendorList) for i in range(len(price))], 'Quantity': quantity, 'Price': price } df = pd.DataFrame.from_dict(data)
[ "Firstly - thanks for the challenge! There aren't many challenging Plotly questions these days.\nThe key elements to creating a scatter graph with jitter are:\n\nUsing mode: 'box' - to create a box-plot, not a scatter plot.\nSetting 'boxpoints': 'all' - so all points are plotted.\nUsing 'pointpos': 0 - to center the points on the x-axis.\nRemoving (hiding!) the whisker boxes using:\n\n'fillcolor': 'rgba(255,255,255,0)'\n'line': {'color': 'rgba(255,255,255,0)'}\n\n\n\nDataFrame preparation:\nThis code simply splits the main DataFrame into a frame for each vendor, thus allowing a trace to be created for each, with their own colour.\ndf1 = df[df['Vendor'] == 'Vendor1']\ndf2 = df[df['Vendor'] == 'Vendor2']\ndf3 = df[df['Vendor'] == 'Vendor3']\n\nPlotting code:\nThe plotting code could use a for-loop if you like. However, I've intentionally kept it more verbose, so as to increase clarity.\nimport plotly.io as pio\n\nlayout = {'title': 'Categorical X-Axis, with Jitter'}\ntraces = []\n\ntraces.append({'x': [df1['Width'], df1['Length']], 'y': df1['Price'], 'name': 'Vendor1', 'marker': {'color': 'green'}})\ntraces.append({'x': [df2['Width'], df2['Length']], 'y': df2['Price'], 'name': 'Vendor2', 'marker': {'color': 'blue'}})\ntraces.append({'x': [df3['Width'], df3['Length']], 'y': df3['Price'], 'name': 'Vendor3', 'marker': {'color': 'orange'}})\n\n# Update (add) trace elements common to all traces.\nfor t in traces:\n t.update({'type': 'box',\n 'boxpoints': 'all',\n 'fillcolor': 'rgba(255,255,255,0)',\n 'hoveron': 'points',\n 'hovertemplate': 'value=%{x}<br>Price=%{y}<extra></extra>',\n 'line': {'color': 'rgba(255,255,255,0)'},\n 'pointpos': 0,\n 'showlegend': True})\n\npio.show({'data': traces, 'layout': layout})\n\nGraph:\nThe data behind this graph was generated using np.random.seed(73), against the dataset creation code posted in the question.\n\nComments (TL;DR):\nThe example code shown here uses the lower-level Plotly API, rather than a convenience wrapper such as graph_objects or express. The reason is that I (personally) feel it's helpful to users to show what is occurring 'under the hood', rather than masking the underlying code logic with a convenience wrapper.\nThis way, when the user needs to modify a finer detail of the graph, they will have a better understanding of the lists and dicts which Plotly is constructing for the underlying graphing engine (orca).\nAnd this use-case is a prime example of this reasoning, as it’s edging Plotly past its (current) design point.\n", "An alternative straightforward solution might be using: plotly.express.strip with stripmode=\"overlay\" (more info about parameters)\nHere I show you an example with the Iris data. Plotly version 4.4.1.\nimport plotly.express as px\ndf = px.data.iris()\nfig = px.strip(df, \n x=\"species\", y=\"sepal_width\", color=\"species\", \n title=\"This is a stripplot!\", \n stripmode = \"overlay\" # Select between \"group\" or \"overlay\" mode\n)\nfig.show()\n\nThis is the result (run the code snippet)\n\n\n<div>\n \n <script type=\"text/javascript\">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n <script src=\"https://cdn.plot.ly/plotly-latest.min.js\"></script> \n <div id=\"70e0d94a-4a4c-40fc-af77-95274959151b\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>\n <script type=\"text/javascript\">\n \n window.PLOTLYENV=window.PLOTLYENV || {};\n \n if (document.getElementById(\"70e0d94a-4a4c-40fc-af77-95274959151b\")) {\n Plotly.newPlot(\n '70e0d94a-4a4c-40fc-af77-95274959151b',\n [{\"alignmentgroup\": \"True\", \"boxpoints\": \"all\", \"fillcolor\": \"rgba(255,255,255,0)\", \"hoverlabel\": {\"namelength\": 0}, \"hoveron\": \"points\", \"hovertemplate\": \"species=%{x}<br>sepal_width=%{y}\", \"legendgroup\": \"species=setosa\", \"line\": {\"color\": \"rgba(255,255,255,0)\"}, \"marker\": {\"color\": \"#636efa\"}, \"name\": \"species=setosa\", \"offsetgroup\": \"species=setosa\", \"orientation\": \"v\", \"pointpos\": 0, \"showlegend\": true, \"type\": \"box\", \"x\": [\"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\"], \"x0\": \" \", \"xaxis\": \"x\", \"y\": [3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.1, 3.0, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3.0, 3.8, 3.2, 3.7, 3.3], \"y0\": \" \", \"yaxis\": \"y\"}, {\"alignmentgroup\": \"True\", \"boxpoints\": \"all\", \"fillcolor\": \"rgba(255,255,255,0)\", \"hoverlabel\": {\"namelength\": 0}, \"hoveron\": \"points\", \"hovertemplate\": \"species=%{x}<br>sepal_width=%{y}\", \"legendgroup\": \"species=versicolor\", \"line\": {\"color\": \"rgba(255,255,255,0)\"}, \"marker\": {\"color\": \"#EF553B\"}, \"name\": \"species=versicolor\", \"offsetgroup\": \"species=versicolor\", \"orientation\": \"v\", \"pointpos\": 0, \"showlegend\": true, \"type\": \"box\", \"x\": [\"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\", \"versicolor\"], \"x0\": \" \", \"xaxis\": \"x\", \"y\": [3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0, 2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8], \"y0\": \" \", \"yaxis\": \"y\"}, {\"alignmentgroup\": \"True\", \"boxpoints\": \"all\", \"fillcolor\": \"rgba(255,255,255,0)\", \"hoverlabel\": {\"namelength\": 0}, \"hoveron\": \"points\", \"hovertemplate\": \"species=%{x}<br>sepal_width=%{y}\", \"legendgroup\": \"species=virginica\", \"line\": {\"color\": \"rgba(255,255,255,0)\"}, \"marker\": {\"color\": \"#00cc96\"}, \"name\": \"species=virginica\", \"offsetgroup\": \"species=virginica\", \"orientation\": \"v\", \"pointpos\": 0, \"showlegend\": true, \"type\": \"box\", \"x\": [\"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\", \"virginica\"], \"x0\": \" \", \"xaxis\": \"x\", \"y\": [3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5, 3.0, 3.4, 3.0], \"y0\": \" \", \"yaxis\": \"y\"}],\n {\"boxmode\": \"overlay\", \"legend\": {\"tracegroupgap\": 0}, \"template\": {\"data\": {\"bar\": [{\"error_x\": {\"color\": \"#2a3f5f\"}, \"error_y\": {\"color\": \"#2a3f5f\"}, \"marker\": {\"line\": {\"color\": \"#E5ECF6\", \"width\": 0.5}}, \"type\": \"bar\"}], \"barpolar\": [{\"marker\": {\"line\": {\"color\": \"#E5ECF6\", \"width\": 0.5}}, \"type\": \"barpolar\"}], \"carpet\": [{\"aaxis\": {\"endlinecolor\": \"#2a3f5f\", \"gridcolor\": \"white\", \"linecolor\": \"white\", \"minorgridcolor\": \"white\", \"startlinecolor\": \"#2a3f5f\"}, \"baxis\": {\"endlinecolor\": \"#2a3f5f\", \"gridcolor\": \"white\", \"linecolor\": \"white\", \"minorgridcolor\": \"white\", \"startlinecolor\": \"#2a3f5f\"}, \"type\": \"carpet\"}], \"choropleth\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"type\": \"choropleth\"}], \"contour\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"contour\"}], \"contourcarpet\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"type\": \"contourcarpet\"}], \"heatmap\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"heatmap\"}], \"heatmapgl\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"heatmapgl\"}], \"histogram\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"histogram\"}], \"histogram2d\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"histogram2d\"}], \"histogram2dcontour\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"histogram2dcontour\"}], \"mesh3d\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"type\": \"mesh3d\"}], \"parcoords\": [{\"line\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"parcoords\"}], \"pie\": [{\"automargin\": true, \"type\": \"pie\"}], \"scatter\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scatter\"}], \"scatter3d\": [{\"line\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scatter3d\"}], \"scattercarpet\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scattercarpet\"}], \"scattergeo\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scattergeo\"}], \"scattergl\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scattergl\"}], \"scattermapbox\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scattermapbox\"}], \"scatterpolar\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scatterpolar\"}], \"scatterpolargl\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scatterpolargl\"}], \"scatterternary\": [{\"marker\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"type\": \"scatterternary\"}], \"surface\": [{\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}, \"colorscale\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"type\": \"surface\"}], \"table\": [{\"cells\": {\"fill\": {\"color\": \"#EBF0F8\"}, \"line\": {\"color\": \"white\"}}, \"header\": {\"fill\": {\"color\": \"#C8D4E3\"}, \"line\": {\"color\": \"white\"}}, \"type\": \"table\"}]}, \"layout\": {\"annotationdefaults\": {\"arrowcolor\": \"#2a3f5f\", \"arrowhead\": 0, \"arrowwidth\": 1}, \"coloraxis\": {\"colorbar\": {\"outlinewidth\": 0, \"ticks\": \"\"}}, \"colorscale\": {\"diverging\": [[0, \"#8e0152\"], [0.1, \"#c51b7d\"], [0.2, \"#de77ae\"], [0.3, \"#f1b6da\"], [0.4, \"#fde0ef\"], [0.5, \"#f7f7f7\"], [0.6, \"#e6f5d0\"], [0.7, \"#b8e186\"], [0.8, \"#7fbc41\"], [0.9, \"#4d9221\"], [1, \"#276419\"]], \"sequential\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]], \"sequentialminus\": [[0.0, \"#0d0887\"], [0.1111111111111111, \"#46039f\"], [0.2222222222222222, \"#7201a8\"], [0.3333333333333333, \"#9c179e\"], [0.4444444444444444, \"#bd3786\"], [0.5555555555555556, \"#d8576b\"], [0.6666666666666666, \"#ed7953\"], [0.7777777777777778, \"#fb9f3a\"], [0.8888888888888888, \"#fdca26\"], [1.0, \"#f0f921\"]]}, \"colorway\": [\"#636efa\", \"#EF553B\", \"#00cc96\", \"#ab63fa\", \"#FFA15A\", \"#19d3f3\", \"#FF6692\", \"#B6E880\", \"#FF97FF\", \"#FECB52\"], \"font\": {\"color\": \"#2a3f5f\"}, \"geo\": {\"bgcolor\": \"white\", \"lakecolor\": \"white\", \"landcolor\": \"#E5ECF6\", \"showlakes\": true, \"showland\": true, \"subunitcolor\": \"white\"}, \"hoverlabel\": {\"align\": \"left\"}, \"hovermode\": \"closest\", \"mapbox\": {\"style\": \"light\"}, \"paper_bgcolor\": \"white\", \"plot_bgcolor\": \"#E5ECF6\", \"polar\": {\"angularaxis\": {\"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\"}, \"bgcolor\": \"#E5ECF6\", \"radialaxis\": {\"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\"}}, \"scene\": {\"xaxis\": {\"backgroundcolor\": \"#E5ECF6\", \"gridcolor\": \"white\", \"gridwidth\": 2, \"linecolor\": \"white\", \"showbackground\": true, \"ticks\": \"\", \"zerolinecolor\": \"white\"}, \"yaxis\": {\"backgroundcolor\": \"#E5ECF6\", \"gridcolor\": \"white\", \"gridwidth\": 2, \"linecolor\": \"white\", \"showbackground\": true, \"ticks\": \"\", \"zerolinecolor\": \"white\"}, \"zaxis\": {\"backgroundcolor\": \"#E5ECF6\", \"gridcolor\": \"white\", \"gridwidth\": 2, \"linecolor\": \"white\", \"showbackground\": true, \"ticks\": \"\", \"zerolinecolor\": \"white\"}}, \"shapedefaults\": {\"line\": {\"color\": \"#2a3f5f\"}}, \"ternary\": {\"aaxis\": {\"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\"}, \"baxis\": {\"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\"}, \"bgcolor\": \"#E5ECF6\", \"caxis\": {\"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\"}}, \"title\": {\"x\": 0.05}, \"xaxis\": {\"automargin\": true, \"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\", \"title\": {\"standoff\": 15}, \"zerolinecolor\": \"white\", \"zerolinewidth\": 2}, \"yaxis\": {\"automargin\": true, \"gridcolor\": \"white\", \"linecolor\": \"white\", \"ticks\": \"\", \"title\": {\"standoff\": 15}, \"zerolinecolor\": \"white\", \"zerolinewidth\": 2}}}, \"title\": {\"text\": \"This is a stripplot!\"}, \"xaxis\": {\"anchor\": \"y\", \"categoryarray\": [\"setosa\", \"versicolor\", \"virginica\"], \"categoryorder\": \"array\", \"domain\": [0.0, 1.0], \"title\": {\"text\": \"species\"}}, \"yaxis\": {\"anchor\": \"x\", \"domain\": [0.0, 1.0], \"title\": {\"text\": \"sepal_width\"}}},\n {\"responsive\": true}\n )\n };\n \n </script>\n </div>\n\n\n\n", "Some plotly.express functions provide a facet argument which allows you to create a plot that closely resembles the multi-level x-axis from your example, without calls to the low-level API.\nStarting wiht some sample data and imports:\nimport plotly.express as px\nimport pandas as pd\nimport numpy as np\n\n# Create data\ndf = pd.DataFrame(data={\"y\": np.random.uniform(low=0, high=45, size=100)})\ndf[\"x\"] = [*[\"3/8\"] * 25, *[\"1/2\"] * 25, *[\"3/8\"] * 25, *[\"1/2\"] * 25]\ndf[\"x1\"] = [*[\"16 in\"] * 50, *[\"15 in\"] * 50]\nprint(df.head().to_markdown())\n\n\n\n\n\n\ny\nx\nx1\n\n\n\n\n0\n27.1279\n3/8\n16 in\n\n\n1\n13.8564\n3/8\n16 in\n\n\n2\n11.8026\n3/8\n16 in\n\n\n3\n25.3769\n3/8\n16 in\n\n\n4\n12.1194\n3/8\n16 in\n\n\n\n\nYou can provide one of the columns from the dataframe to the facet_col argument:\npx.strip(df, x=[\"x\", \"x1\"], y=\"y\", stripmode='overlay', facet_col=\"x1\")\n\nWhich results in:\n\nIf you like, you can further tweak the appearance of the subplot titles.\n" ]
[ 14, 1, 0 ]
[]
[]
[ "graph", "jitter", "plotly", "python", "scatter_plot" ]
stackoverflow_0065044430_graph_jitter_plotly_python_scatter_plot.txt
Q: How to scrape only one price? I'm trying to scrape product prices from a website and both real price and the monthly payment quota value has exactly the same class, so I can't figure it out how to only get main price. and this is for the main price: "879.990" this is for the monthly payment quota: "39.990", this is the URL: https://listado.mercadolibre.cl/macbook#D[A:macbook] #THIS GETS ALL THE NAMES AND STORES IT IN A LIST prod = soup.find_all('h2', class_ ='ui-search-item__title shops__item-title') productos = list() count=0 for i in prod: if count < 33: productos.append(i.text) else: break count +=1 size= len(productos) +1 #print(size) #print(productos, len(productos)) print(productos) #THIS GETS ALL THE NAMES AND STORES IT IN A LIST pri = soup.find_all('span',class_ ="price-tag-fraction") precios = list() count=0 for i in pri: if count < 33: precios.append(i.text) else: break count +=1 #rint(precios) prices= [item.split(',')for item in precios] Here is the output A: You can filter out the other prices using CSS selectors # filsel = 'span.price-tag-fraction:not(span.ui-search-installments span):not(s.price-tag__disabled span)' emiSp_sel = 'span.ui-search-installments span' # monthly disab_sel = 's.price-tag__disabled span' # crossed out filsel = f'span.price-tag-fraction:not({emiSp_sel}):not({disab_sel})' pri = [p.get_text() for p in soup.select(filsel)] or using lambda with find pri = soup.find_all( lambda p: p.name == 'span' and 'price-tag-fraction' in p.get('class', '') and p.find_parent('span', {'class': 'ui-search-installments'}) is None and p.find_parent('s', {'class': 'price-tag__disabled'}) is None ) or even by combining lists comprehension with your current method pri = [ p for p in soup.find_all('span',class_ ="price-tag-fraction") if p.find_parent('span', {'class': 'ui-search-installments'}) is None and p.find_parent('s', {'class': 'price-tag__disabled'}) is None ]
How to scrape only one price?
I'm trying to scrape product prices from a website and both real price and the monthly payment quota value has exactly the same class, so I can't figure it out how to only get main price. and this is for the main price: "879.990" this is for the monthly payment quota: "39.990", this is the URL: https://listado.mercadolibre.cl/macbook#D[A:macbook] #THIS GETS ALL THE NAMES AND STORES IT IN A LIST prod = soup.find_all('h2', class_ ='ui-search-item__title shops__item-title') productos = list() count=0 for i in prod: if count < 33: productos.append(i.text) else: break count +=1 size= len(productos) +1 #print(size) #print(productos, len(productos)) print(productos) #THIS GETS ALL THE NAMES AND STORES IT IN A LIST pri = soup.find_all('span',class_ ="price-tag-fraction") precios = list() count=0 for i in pri: if count < 33: precios.append(i.text) else: break count +=1 #rint(precios) prices= [item.split(',')for item in precios] Here is the output
[ "You can filter out the other prices using CSS selectors\n# filsel = 'span.price-tag-fraction:not(span.ui-search-installments span):not(s.price-tag__disabled span)'\nemiSp_sel = 'span.ui-search-installments span' # monthly\ndisab_sel = 's.price-tag__disabled span' # crossed out\nfilsel = f'span.price-tag-fraction:not({emiSp_sel}):not({disab_sel})'\n\npri = [p.get_text() for p in soup.select(filsel)]\n\nor using lambda with find\npri = soup.find_all(\n lambda p: p.name == 'span' and 'price-tag-fraction' in p.get('class', '')\n and p.find_parent('span', {'class': 'ui-search-installments'}) is None\n and p.find_parent('s', {'class': 'price-tag__disabled'}) is None\n)\n\nor even by combining lists comprehension with your current method\npri = [\n p for p in soup.find_all('span',class_ =\"price-tag-fraction\") \n if p.find_parent('span', {'class': 'ui-search-installments'}) is None\n and p.find_parent('s', {'class': 'price-tag__disabled'}) is None\n]\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "jupyter_notebook", "python" ]
stackoverflow_0074540266_beautifulsoup_jupyter_notebook_python.txt
Q: discord.py based bot doesn't work after 2.0 update So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery import discord from keep_alive import keep_alive class MyClient(discord.Client): async def on_ready(self): print('bot is online now', self.user) async def on_message(self, message): word_list = ['ffs','gdsgds'] if message.author == self.user: return messageContent = message.content if len(messageContent) > 0: for word in word_list: if word in messageContent: await message.delete() await message.channel.send('Do not say that!') # keep_alive() client = discord.Client(intents=discord.Intents.default()) client.run('OTkxfsa9WC5G34') from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return 'dont forget uptime robot monitor' def run(): app.run(host='0.0.0.0',port=8000) def keep_alive(): t = Thread(target=run) t.start() I tried to fix it by my own by changing this line client = discord.Client(intents=discord.Intents.default()) It has to be some trivial syntax mistake, but I cannot locate it Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work import discord from keep_alive import keep_alive class MyClient(discord.Client): async def on_ready(self): print('bot is online now', self.user) async def on_message(self, message): word_list = ['fdsfds','fsa'] if message.author == self.user: return messageContent = message.content if len(messageContent) > 0: for word in word_list: if word in messageContent: await message.delete() await message.channel.send('Do not say that!') # keep_alive() intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents = intents) client.run('OTkxMDcxMTUx') A: If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents. intents = discord.Intents.default() intents.message_content = True Don't forget to enable it on your bot's developer portal as well. Also all of that keep alive & flask stuff hints that you're abusing an online host to run a bot on. This brings loads of issues along with it that you can't fix so you should really consider moving away from that. There's posts on a daily basis of people with problems caused by this.
discord.py based bot doesn't work after 2.0 update
So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery import discord from keep_alive import keep_alive class MyClient(discord.Client): async def on_ready(self): print('bot is online now', self.user) async def on_message(self, message): word_list = ['ffs','gdsgds'] if message.author == self.user: return messageContent = message.content if len(messageContent) > 0: for word in word_list: if word in messageContent: await message.delete() await message.channel.send('Do not say that!') # keep_alive() client = discord.Client(intents=discord.Intents.default()) client.run('OTkxfsa9WC5G34') from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return 'dont forget uptime robot monitor' def run(): app.run(host='0.0.0.0',port=8000) def keep_alive(): t = Thread(target=run) t.start() I tried to fix it by my own by changing this line client = discord.Client(intents=discord.Intents.default()) It has to be some trivial syntax mistake, but I cannot locate it Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work import discord from keep_alive import keep_alive class MyClient(discord.Client): async def on_ready(self): print('bot is online now', self.user) async def on_message(self, message): word_list = ['fdsfds','fsa'] if message.author == self.user: return messageContent = message.content if len(messageContent) > 0: for word in word_list: if word in messageContent: await message.delete() await message.channel.send('Do not say that!') # keep_alive() intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents = intents) client.run('OTkxMDcxMTUx')
[ "If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents.\nintents = discord.Intents.default()\nintents.message_content = True\n\nDon't forget to enable it on your bot's developer portal as well.\nAlso all of that keep alive & flask stuff hints that you're abusing an online host to run a bot on. This brings loads of issues along with it that you can't fix so you should really consider moving away from that. There's posts on a daily basis of people with problems caused by this.\n" ]
[ 2 ]
[ "Your code should be:\nimport discord\nfrom discord.ext import commands # you need to import this to be able to use commands and events\nfrom keep_alive import keep_alive\nclient = commands.Bot(intents=discord.Intents.default())\n\n@bot.event\nasync def on_ready(): # you don't need self in here\n print('bot is online now', client.user) # you can just use client.user\n\n@bot.event\nasync def on_message(message): # again, you do not need self\n word_list = ['ffs','gdsgds']\n if message.author == client.user: # you can use client.user here too\n return\n messageContent = message.content\n if len(messageContent) > 0:\n for word in word_list:\n if word in messageContent:\n await message.delete()\n await message.channel.send('Do not say that!')\n\nkeep_alive()\nclient.run('OTkxfsa9WC5G34') #if this is your real token/you have been using this token since you made the bot, you should definitely generate a new one\n\nTo help you, I added some comments to help show you what I have changed and why. As one of the comments in the code says, you should regenerate your bot token at the Discord Developer Portal.\nFor more info about migrating to 2.0, read the Discord.Py docs\n" ]
[ -2 ]
[ "discord.py", "python" ]
stackoverflow_0074557378_discord.py_python.txt
Q: Get the count of Text, Numeric/Float, Blank and Nan values for each column in a Dataframe and extract using a filter Assume the table below Index Col1 Col2 Col3 0 10.5 2.5 nan 1 s 2 2.9 3.2 a 3 #VAL nan 2 4 3 5.6 4 Now what I'm trying to get is a summary dataframe which will give me a count of different datatypes/conditions as mentioned above Index Col1 Col2 Col3 Integer/Float 3 3 2 Blank 1 0 1 Nan 0 1 1 Text 1 1 1 I come from Excel so in Excel conditioning it would be pretty much simple Integer/Float formula: I would use ISNUMBER and create an array of True and False values and sum the true ones Blank: I would simply use COUNTIF(Column, "") Text: Similar to ISNUMBER I would use ISTEXT above. I have tried searching this on Stack Overflow however the best I've gotten is pd.DataFrame(df["Col1"].apply(type).value_counts()) This does not however give me the exact output. I also wanted to check if it was possible to filter out the values basis the above condition and get the fitting cells. e.g. df[Col1==ISTEXT] A: Use custom funstion for count each type separately: def f(x): a = pd.to_numeric(x, errors='coerce').notna().sum() b = x.eq('').sum() c = x.isna().sum() d = len(x) - (a + b + c) return pd.Series([a,b,c,d], ['Integer/Float','Blank','Nan','Text']) df = df.apply(f) print (df) Col1 Col2 Col3 Integer/Float 3 3 2 Blank 1 0 1 Nan 0 1 1 Text 1 1 1
Get the count of Text, Numeric/Float, Blank and Nan values for each column in a Dataframe and extract using a filter
Assume the table below Index Col1 Col2 Col3 0 10.5 2.5 nan 1 s 2 2.9 3.2 a 3 #VAL nan 2 4 3 5.6 4 Now what I'm trying to get is a summary dataframe which will give me a count of different datatypes/conditions as mentioned above Index Col1 Col2 Col3 Integer/Float 3 3 2 Blank 1 0 1 Nan 0 1 1 Text 1 1 1 I come from Excel so in Excel conditioning it would be pretty much simple Integer/Float formula: I would use ISNUMBER and create an array of True and False values and sum the true ones Blank: I would simply use COUNTIF(Column, "") Text: Similar to ISNUMBER I would use ISTEXT above. I have tried searching this on Stack Overflow however the best I've gotten is pd.DataFrame(df["Col1"].apply(type).value_counts()) This does not however give me the exact output. I also wanted to check if it was possible to filter out the values basis the above condition and get the fitting cells. e.g. df[Col1==ISTEXT]
[ "Use custom funstion for count each type separately:\ndef f(x):\n a = pd.to_numeric(x, errors='coerce').notna().sum()\n b = x.eq('').sum()\n c = x.isna().sum()\n d = len(x) - (a + b + c)\n return pd.Series([a,b,c,d], ['Integer/Float','Blank','Nan','Text'])\n\ndf = df.apply(f)\nprint (df)\n Col1 Col2 Col3\nInteger/Float 3 3 2\nBlank 1 0 1\nNan 0 1 1\nText 1 1 1\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074559093_dataframe_pandas_python.txt
Q: Why does the last letter doesn't add up where it belongs? i am pretty new to coding in python and we have some programs to make for class. The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first part and then the last digit doesn't add up where it belongs. Could you explain me why? def decoupage(nombre:str)->(str,str): partie_entiere = '' partie_decimale = '' delimiteurs = [',','.'] compte = 0 for lettre in nombre: if lettre not in delimiteurs: if compte != 1: partie_entiere += lettre elif compte == 1: partie_decimale += lettre else: compte += 1 return partie_entiere, partie_decimale assert decoupage("12.5") == ('12', '5') assert decoupage("12,5") == ('12', '5') assert decoupage("0.5") == ('0', '5') assert decoupage("12") == ('12', '0') Tried to execute the code line by line and then i saw the problem, 12 finishes where it belongs "partie_entiere" then "partie_decimale" doesn't have 5 in it. A: Try this? def decoupage(word: str) -> tuple(str, str): entire_part = '' decimal_part = '' delimiters = [',','.'] after = False # let's use a boolean to check if we are before or after the delimiter for letter in word: if not after: # if we are before after = letter in delimiters # populate the boolean value if we meet the delimiter if letter not in delimiters: # if it's not one of the delimiters entire_part += letter else: decimal_part += letter if decimal_part == '': # finally we want to add something to the decimal if an int was passed decimal_part = '0' return entire_part, decimal_part assert decoupage("12.5") == ('12', '5') assert decoupage("12,5") == ('12', '5') assert decoupage("0.5") == ('0', '5') assert decoupage("12") == ('12', '0')
Why does the last letter doesn't add up where it belongs?
i am pretty new to coding in python and we have some programs to make for class. The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first part and then the last digit doesn't add up where it belongs. Could you explain me why? def decoupage(nombre:str)->(str,str): partie_entiere = '' partie_decimale = '' delimiteurs = [',','.'] compte = 0 for lettre in nombre: if lettre not in delimiteurs: if compte != 1: partie_entiere += lettre elif compte == 1: partie_decimale += lettre else: compte += 1 return partie_entiere, partie_decimale assert decoupage("12.5") == ('12', '5') assert decoupage("12,5") == ('12', '5') assert decoupage("0.5") == ('0', '5') assert decoupage("12") == ('12', '0') Tried to execute the code line by line and then i saw the problem, 12 finishes where it belongs "partie_entiere" then "partie_decimale" doesn't have 5 in it.
[ "Try this?\ndef decoupage(word: str) -> tuple(str, str):\n entire_part = ''\n decimal_part = ''\n delimiters = [',','.']\n\n after = False # let's use a boolean to check if we are before or after the delimiter\n for letter in word:\n if not after: # if we are before\n after = letter in delimiters # populate the boolean value if we meet the delimiter\n if letter not in delimiters: # if it's not one of the delimiters\n entire_part += letter\n else:\n decimal_part += letter\n\n if decimal_part == '': # finally we want to add something to the decimal if an int was passed\n decimal_part = '0'\n\n return entire_part, decimal_part\n\nassert decoupage(\"12.5\") == ('12', '5')\nassert decoupage(\"12,5\") == ('12', '5')\nassert decoupage(\"0.5\") == ('0', '5')\nassert decoupage(\"12\") == ('12', '0')\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074558957_python.txt
Q: Can anyone help me find out where I made a mistake? I am trying to figure out how to print a requested amount of prime numbers but I am having problems. I can't describe what I did so I'll just paste my code so far: requested_primes = 3 #just for simplicity, i am going to request an input for how many prime integers they #want printed found_primes = 0 examined_number = 2 #starting point for counting while found_primes != requested_primes: #self-evident i hope for i in range(2, examined_number): #trying to check if it's a prime number or not with this one. if examined_number % i == 0: #if it can be neatly divided, it's not a prime and the search has to go #on examined_number += 1 else: #if no neat divisions can occur then i got a prime number and i can print it before going back #and searching for another one, until found_primes == requested_primes print(examined_number, end=' ') examined_number += 1 found_primes += 1 Nothing comes up in the terminal. A: Your for loop never runs due to i having the same starting value as examined_number (both are 2). Try using for in in range(1, examined_number) and that should get your loop to execute - you can verify it is running by adding a few print statements A: There are 2 problems, both of which can potentially cause you to have infinite loop. First of all, you are starting with range(2, 2) - it has 0 elements, meaning your for loop will not do anything and you will stay in the while loop infintiely. Start from 3 and just assume 2 is prime. Fixing this will still not make the code work, because you are increasing examined_number and found_primes every time number does not divide evenly. Which means your found_primes very quickly goes past requested_primes and you will stay in the while loop forever. In order to fix that, you can use that fact that for loop supports else clause that only happens if the loop finished normally - so we break if a number has divided evenly. If we didn't break, we run the else clause. requested_primes = 10 #just for simplicity, i am going to request an input for how many prime integers they #want printed found_primes = 1 print(2, end=' ') examined_number = 3 #starting point for counting while found_primes != requested_primes: #self-evident i hope for i in range(2, examined_number): #trying to check if it's a prime number or not with this one. if examined_number % i == 0: #if it can be neatly divided, it's not a prime and the search has to go #on examined_number += 1 break else: #if no neat divisions can occur then i got a prime number and i can print it before going back #and searching for another one, until found_primes == requested_primes print(examined_number, end=' ') examined_number += 1 found_primes += 1
Can anyone help me find out where I made a mistake?
I am trying to figure out how to print a requested amount of prime numbers but I am having problems. I can't describe what I did so I'll just paste my code so far: requested_primes = 3 #just for simplicity, i am going to request an input for how many prime integers they #want printed found_primes = 0 examined_number = 2 #starting point for counting while found_primes != requested_primes: #self-evident i hope for i in range(2, examined_number): #trying to check if it's a prime number or not with this one. if examined_number % i == 0: #if it can be neatly divided, it's not a prime and the search has to go #on examined_number += 1 else: #if no neat divisions can occur then i got a prime number and i can print it before going back #and searching for another one, until found_primes == requested_primes print(examined_number, end=' ') examined_number += 1 found_primes += 1 Nothing comes up in the terminal.
[ "Your for loop never runs due to i having the same starting value as examined_number (both are 2).\nTry using for in in range(1, examined_number) and that should get your loop to execute - you can verify it is running by adding a few print statements\n", "There are 2 problems, both of which can potentially cause you to have infinite loop. First of all, you are starting with range(2, 2) - it has 0 elements, meaning your for loop will not do anything and you will stay in the while loop infintiely. Start from 3 and just assume 2 is prime.\nFixing this will still not make the code work, because you are increasing examined_number and found_primes every time number does not divide evenly. Which means your found_primes very quickly goes past requested_primes and you will stay in the while loop forever. In order to fix that, you can use that fact that for loop supports else clause that only happens if the loop finished normally - so we break if a number has divided evenly. If we didn't break, we run the else clause.\nrequested_primes = 10 #just for simplicity, i am going to request an input for how many prime integers they #want printed\nfound_primes = 1\nprint(2, end=' ')\nexamined_number = 3 #starting point for counting\n\nwhile found_primes != requested_primes: #self-evident i hope\n for i in range(2, examined_number): #trying to check if it's a prime number or not with this one.\n if examined_number % i == 0: #if it can be neatly divided, it's not a prime and the search has to go #on\n examined_number += 1\n break\n else: #if no neat divisions can occur then i got a prime number and i can print it before going back #and searching for another one, until found_primes == requested_primes\n print(examined_number, end=' ')\n examined_number += 1\n found_primes += 1\n\n" ]
[ 0, 0 ]
[]
[]
[ "loops", "primes", "python" ]
stackoverflow_0074559088_loops_primes_python.txt
Q: How do I change a variable's value with the command from a Tkinter button? The command I set for a Tkinter button was a function that changed the text of a label. Yet the text does not seem to change! The variable I attempted to change using the function "textChange()" is called "text", and the purpose of its value is to be the text of a label called "finalText". But, the text of the label "finalText" didn't change! #Imports from tkinter import * #Variables wn = Tk() text = 'Button Commands' #Change Text def textChange(): global variable text = 'Can do THIS!' finalText = Label(wn, text=text) finalText = Label(wn, text=text) finalText.place(x=0, y=0) #Button btn = Button(wn, command=(textChange())) btn.place(x=5, y=20) A: You actually create a new label and assign to a local variable finalText inside textChange(). So the global finalText is not changed. You need to use finalText.config(text=text) to update the text of the global finalText. Also command=(textChange()) will execute textChange() immediately without clicking the button. Use command=textChange instead. Below is the updated code: #Imports from tkinter import * #Variables wn = Tk() text = 'Button Commands' #Change Text def textChange(): text = 'Can do THIS!' # update the text of the global label finalText finalText.config(text=text) finalText = Label(wn, text=text) finalText.place(x=0, y=0) #Button btn = Button(wn, command=textChange) btn.place(x=5, y=20) wn.mainloop()
How do I change a variable's value with the command from a Tkinter button?
The command I set for a Tkinter button was a function that changed the text of a label. Yet the text does not seem to change! The variable I attempted to change using the function "textChange()" is called "text", and the purpose of its value is to be the text of a label called "finalText". But, the text of the label "finalText" didn't change! #Imports from tkinter import * #Variables wn = Tk() text = 'Button Commands' #Change Text def textChange(): global variable text = 'Can do THIS!' finalText = Label(wn, text=text) finalText = Label(wn, text=text) finalText.place(x=0, y=0) #Button btn = Button(wn, command=(textChange())) btn.place(x=5, y=20)
[ "You actually create a new label and assign to a local variable finalText inside textChange(). So the global finalText is not changed.\nYou need to use finalText.config(text=text) to update the text of the global finalText.\nAlso command=(textChange()) will execute textChange() immediately without clicking the button. Use command=textChange instead.\nBelow is the updated code:\n#Imports\nfrom tkinter import *\n\n#Variables\nwn = Tk()\ntext = 'Button Commands'\n\n#Change Text\ndef textChange():\n text = 'Can do THIS!'\n # update the text of the global label finalText\n finalText.config(text=text)\n\nfinalText = Label(wn, text=text)\nfinalText.place(x=0, y=0)\n\n#Button\nbtn = Button(wn, command=textChange)\nbtn.place(x=5, y=20)\n\nwn.mainloop()\n\n" ]
[ 1 ]
[]
[]
[ "button", "command", "label", "python", "tkinter" ]
stackoverflow_0074559149_button_command_label_python_tkinter.txt
Q: Extract very nested string-text between tags? I'm trying to make list of minerals+prices. I Succeed at making first step (it shows list of minerals from 1st page), but I can't reach for Price values. I've tried with some other methods I've found on StackOverflow (with siblings/parents tags etc.) but I didn't succeed... Also, can you later attach/add one list to another (name+price) if I use two 'for' loops? Below is a fragment I want to reach, it is between tags. Using find by 'font' wasn't successful for me... I don't really need "Price" text, but I do need "€580 / US$598 / ¥84010 / AUD$890". ` import requests from bs4 import BeautifulSoup URL = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'} page = requests.get(URL, headers=headers) print(page.content) soup = BeautifulSoup(page.content, 'html5lib') table = soup.find('a', attrs = {'name':'SearchTop'}) print(table.prettify()) for names in table.find_all('img', alt=True): print(names['alt']) print(soup.find_all('font')) <font face="Arial, Helvetica, sans-serif" size="-1"> <font color="#FF0000"> Price: </font> €580 / US$598 / ¥84010 / AUD$890 </font> ` A: Try this: import requests from bs4 import BeautifulSoup URL = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0" headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36", } soup = BeautifulSoup(requests.get(URL, headers=headers).text, "lxml") prices = [ p.getText(strip=True).split("Price:")[-1] for p in soup.select("table tr td font font") ] names = [n.getText(strip=True) for n in soup.select("table tr td font a")] # Filter the lists names[:] = [" ".join(n.split()) for n in names if not n.startswith("[")] prices[:] = [p for p in prices if p] # Print the results for name, price in zip(names, prices): print(f"{name}\n{price}") print("-" * 50) Output: NX51AH2: 'lepidolite' after Elbaite with Elbaite €580 / US$598 / ¥84010 / AUD$890 -------------------------------------------------- TH27AL9: 'Pearceite' with Calcite €220 / US$227 / ¥31860 / AUD$330 -------------------------------------------------- TFM69AN5: 'Stilbite' €450 / US$464 / ¥65180 / AUD$690 -------------------------------------------------- SM90CEX: Acanthite €90 / US$92 / ¥13030 / AUD$130 -------------------------------------------------- TMA97AN5: Acanthite €240 / US$247 / ¥34760 / AUD$370 -------------------------------------------------- TB90AE8: Acanthite €540 / US$557 / ¥78220 / AUD$830 -------------------------------------------------- TZ71AK9: Acanthite €580 / US$598 / ¥84010 / AUD$890 -------------------------------------------------- EC63G1: Acanthite €85 / US$87 / ¥12310 / AUD$130 -------------------------------------------------- MN56K9: Acanthite €155 / US$159 / ¥22450 / AUD$230 -------------------------------------------------- TF89AL3: Acanthite (Se-bearing) with Polybasite (Se-bearing) and Calcite €460 / US$474 / ¥66630 / AUD$700 -------------------------------------------------- TP66AJ8: Acanthite (Se-bearing) with Pyrite €1500 / US$1547 / ¥217290 / AUD$2310 -------------------------------------------------- TY86AN2: Acanthite after Polybasite €1600 / US$1651 / ¥231770 / AUD$2460 -------------------------------------------------- TA66AF6: Acanthite with Calcite €160 / US$165 / ¥23170 / AUD$240 -------------------------------------------------- JFD104AO2: Acanthite with Calcite €240 / US$247 / ¥34760 / AUD$370 -------------------------------------------------- TX36AL6: Acanthite with Calcite €1200 / US$1238 / ¥173830 / AUD$1850 -------------------------------------------------- TA48AH1: Acanthite with Chalcopyrite €290 / US$299 / ¥42000 / AUD$440 -------------------------------------------------- EF89L9: Acanthite with Pyrite and Calcite €480 / US$495 / ¥69530 / AUD$740 -------------------------------------------------- TX89AN0: Acanthite with Siderite and Proustite €4800 / US$4953 / ¥695320 / AUD$7400 -------------------------------------------------- EA56K0: Acanthite with Silver €150 / US$154 / ¥21720 / AUD$230 -------------------------------------------------- EC48K0: Acanthite with Silver €290 / US$299 / ¥42000 / AUD$440 -------------------------------------------------- 11AT12: Acanthite, Calcite €70 / US$72 / ¥10140 / AUD$100 -------------------------------------------------- 9EF89L9: Acanthite, Pyrite, Calcite €320 / US$330 / ¥46350 / AUD$490 -------------------------------------------------- SM75TDA: Adamite €75 / US$77 / ¥10860 / AUD$110 -------------------------------------------------- 2M14: Adamite €90 / US$92 / ¥13030 / AUD$130 -------------------------------------------------- 20MJX66: Adamite €140 / US$144 / ¥20280 / AUD$215 --------------------------------------------------
Extract very nested string-text between tags?
I'm trying to make list of minerals+prices. I Succeed at making first step (it shows list of minerals from 1st page), but I can't reach for Price values. I've tried with some other methods I've found on StackOverflow (with siblings/parents tags etc.) but I didn't succeed... Also, can you later attach/add one list to another (name+price) if I use two 'for' loops? Below is a fragment I want to reach, it is between tags. Using find by 'font' wasn't successful for me... I don't really need "Price" text, but I do need "€580 / US$598 / ¥84010 / AUD$890". ` import requests from bs4 import BeautifulSoup URL = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'} page = requests.get(URL, headers=headers) print(page.content) soup = BeautifulSoup(page.content, 'html5lib') table = soup.find('a', attrs = {'name':'SearchTop'}) print(table.prettify()) for names in table.find_all('img', alt=True): print(names['alt']) print(soup.find_all('font')) <font face="Arial, Helvetica, sans-serif" size="-1"> <font color="#FF0000"> Price: </font> €580 / US$598 / ¥84010 / AUD$890 </font> `
[ "Try this:\nimport requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36\",\n}\n\nsoup = BeautifulSoup(requests.get(URL, headers=headers).text, \"lxml\")\n\nprices = [\n p.getText(strip=True).split(\"Price:\")[-1] for p\n in soup.select(\"table tr td font font\")\n]\nnames = [n.getText(strip=True) for n in soup.select(\"table tr td font a\")]\n\n# Filter the lists\nnames[:] = [\" \".join(n.split()) for n in names if not n.startswith(\"[\")]\nprices[:] = [p for p in prices if p]\n\n# Print the results\nfor name, price in zip(names, prices):\n print(f\"{name}\\n{price}\")\n print(\"-\" * 50)\n\nOutput:\nNX51AH2: 'lepidolite' after Elbaite with Elbaite\n€580 / US$598 / ¥84010 / AUD$890\n--------------------------------------------------\nTH27AL9: 'Pearceite' with Calcite\n€220 / US$227 / ¥31860 / AUD$330\n--------------------------------------------------\nTFM69AN5: 'Stilbite'\n€450 / US$464 / ¥65180 / AUD$690\n--------------------------------------------------\nSM90CEX: Acanthite\n€90 / US$92 / ¥13030 / AUD$130\n--------------------------------------------------\nTMA97AN5: Acanthite\n€240 / US$247 / ¥34760 / AUD$370\n--------------------------------------------------\nTB90AE8: Acanthite\n€540 / US$557 / ¥78220 / AUD$830\n--------------------------------------------------\nTZ71AK9: Acanthite\n€580 / US$598 / ¥84010 / AUD$890\n--------------------------------------------------\nEC63G1: Acanthite\n€85 / US$87 / ¥12310 / AUD$130\n--------------------------------------------------\nMN56K9: Acanthite\n€155 / US$159 / ¥22450 / AUD$230\n--------------------------------------------------\nTF89AL3: Acanthite (Se-bearing) with Polybasite (Se-bearing) and Calcite\n€460 / US$474 / ¥66630 / AUD$700\n--------------------------------------------------\nTP66AJ8: Acanthite (Se-bearing) with Pyrite\n€1500 / US$1547 / ¥217290 / AUD$2310\n--------------------------------------------------\nTY86AN2: Acanthite after Polybasite\n€1600 / US$1651 / ¥231770 / AUD$2460\n--------------------------------------------------\nTA66AF6: Acanthite with Calcite\n€160 / US$165 / ¥23170 / AUD$240\n--------------------------------------------------\nJFD104AO2: Acanthite with Calcite\n€240 / US$247 / ¥34760 / AUD$370\n--------------------------------------------------\nTX36AL6: Acanthite with Calcite\n€1200 / US$1238 / ¥173830 / AUD$1850\n--------------------------------------------------\nTA48AH1: Acanthite with Chalcopyrite\n€290 / US$299 / ¥42000 / AUD$440\n--------------------------------------------------\nEF89L9: Acanthite with Pyrite and Calcite\n€480 / US$495 / ¥69530 / AUD$740\n--------------------------------------------------\nTX89AN0: Acanthite with Siderite and Proustite\n€4800 / US$4953 / ¥695320 / AUD$7400\n--------------------------------------------------\nEA56K0: Acanthite with Silver\n€150 / US$154 / ¥21720 / AUD$230\n--------------------------------------------------\nEC48K0: Acanthite with Silver\n€290 / US$299 / ¥42000 / AUD$440\n--------------------------------------------------\n11AT12: Acanthite, Calcite\n€70 / US$72 / ¥10140 / AUD$100\n--------------------------------------------------\n9EF89L9: Acanthite, Pyrite, Calcite\n€320 / US$330 / ¥46350 / AUD$490\n--------------------------------------------------\nSM75TDA: Adamite\n€75 / US$77 / ¥10860 / AUD$110\n--------------------------------------------------\n2M14: Adamite\n€90 / US$92 / ¥13030 / AUD$130\n--------------------------------------------------\n20MJX66: Adamite\n€140 / US$144 / ¥20280 / AUD$215\n--------------------------------------------------\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074559233_beautifulsoup_html_python_web_scraping.txt
Q: The same python binary in two different terminals sees a different environment I tried to run a jupyter notebook cell in vscode today and got "Running cells with 'Python 3.10.6 64-bit' requires ipykernel package". This is very strange, as my Jupiter laptop environment was still working yesterday. Also, I see all the python packages in their place. The only thing that has changed is that last night I updated the system packages through Pop!_Shop (Pop!_OS 22.04 LTS). Running python3.10 I noticed that the version of the GCC inside the vscode terminal is different from the one in the system terminal. How is this even possible when the which command shows that the path to the binary is the same? Then I checked gcc --version itself and to my surprise the same thing happened to it. from vscode terminal from system terminal sys.path in both terminals is the same, but one sees packages, for example requests, and the other does not. I am sure that the original problem with the jupyter cell is related to this, because ipykernel is also in the sys.path, which is somehow inaccessible to the vscode's terminal and maybe jupyter extension. For Jupyter I can switch to one of the venvs, where the problem disappears. But the magic with the binary in the terminals remains unclear. EDIT: The problem was solved by uninstalling the flatpak version of vscode and installing the fresh deb package from the official site. Now in vscode terminal I have the same compiler version as in the system terminal and the modules are found without problems, including ipykernel. A: Solution is to reinstall vscode with deb package from official website. See the edited part of the question.
The same python binary in two different terminals sees a different environment
I tried to run a jupyter notebook cell in vscode today and got "Running cells with 'Python 3.10.6 64-bit' requires ipykernel package". This is very strange, as my Jupiter laptop environment was still working yesterday. Also, I see all the python packages in their place. The only thing that has changed is that last night I updated the system packages through Pop!_Shop (Pop!_OS 22.04 LTS). Running python3.10 I noticed that the version of the GCC inside the vscode terminal is different from the one in the system terminal. How is this even possible when the which command shows that the path to the binary is the same? Then I checked gcc --version itself and to my surprise the same thing happened to it. from vscode terminal from system terminal sys.path in both terminals is the same, but one sees packages, for example requests, and the other does not. I am sure that the original problem with the jupyter cell is related to this, because ipykernel is also in the sys.path, which is somehow inaccessible to the vscode's terminal and maybe jupyter extension. For Jupyter I can switch to one of the venvs, where the problem disappears. But the magic with the binary in the terminals remains unclear. EDIT: The problem was solved by uninstalling the flatpak version of vscode and installing the fresh deb package from the official site. Now in vscode terminal I have the same compiler version as in the system terminal and the modules are found without problems, including ipykernel.
[ "Solution is to reinstall vscode with deb package from official website. See the edited part of the question.\n" ]
[ 1 ]
[]
[]
[ "gcc", "python", "visual_studio_code" ]
stackoverflow_0074545965_gcc_python_visual_studio_code.txt
Q: How to integrate a cursor in a QtWidgets app I am new to QtWidgets and trying to build an app in QtWidgets and Python (3.x). the end goal of the app is to show images and a superposed cursor (to be exact, a "plus" sign of 2cm) that can be moved along the image reacting to mouse events. I concentrate now first on this cursor. So far, I read examples on how to do it on matplotlib. however, i have trouble to understand how to integrate matplotlib on my code. Also, is matplotlib the easiest way to do it on this code. or there might be a better way to do it. any hint would be helpful thank you in advance. here is my desired output and the code of my app import sys from PySide2 import QtWidgets from vispy import scene from PySide2.QtCore import QMetaObject from PySide2.QtWidgets import * class SimpleItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) def boundingRect(self): penWidth = 1.0 return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth) def paint(self, painter, option, widget): rect = self.boundingRect() painter.drawRect(rect) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.groupBox = QGroupBox(self.centralwidget) self.groupBox.setObjectName("groupBox") self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) QMetaObject.connectSlotsByName(MainWindow) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # OpenGL drawing surface self.canvas = scene.SceneCanvas(keys='interactive') self.canvas.create_native() self.canvas.native.setParent(self) self.view = self.canvas.central_widget.add_view() self.view.bgcolor = '#ffffff' # set the canva to a white background scene2 = QGraphicsScene() item = SimpleItem() scene2.addItem(item) self.setWindowTitle('MyApp') def main(): import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui') app = QtWidgets.QApplication([]) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() edit: I added a class (here it is a rectangle just as an example) to illustrate my problem. i have trouble integrating that snippet of the code (with SimpleItem) to OpenGL canvas A: You can use the QApplication.setOverrideCursor method to assign a .png image file as your cursor when it appears inside of the Qt program. Here is an example that is mostly based on the code in your question. And below is a gif that demonstrates the example. And the last image is the image I used in the code as cursor.png Hope this helps import sys from PySide2.QtCore import * from PySide2.QtWidgets import * from PySide2.QtGui import * class SimpleItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) self._brush = QBrush(Qt.black) def boundingRect(self): penWidth = 1.0 return QRectF(-50 - penWidth / 2, -50 - penWidth / 2, 50 + penWidth, 50 + penWidth) def paint(self, painter, option, widget): rect = self.boundingRect() painter.drawRect(rect) painter.fillRect(rect, self._brush) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.resize(800, 600) self.scene = QGraphicsScene() self.canvas = scene.SceneCanvas(keys='interactive') self.view = QGraphicsView(self.scene) item = SimpleItem() self.scene.addItem(item) self.setCentralWidget(self.view) self.setWindowTitle('MyApp') def main(): import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui') app = QtWidgets.QApplication([]) app.setOverrideCursor(QCursor(QPixmap('cursor.png'))) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
How to integrate a cursor in a QtWidgets app
I am new to QtWidgets and trying to build an app in QtWidgets and Python (3.x). the end goal of the app is to show images and a superposed cursor (to be exact, a "plus" sign of 2cm) that can be moved along the image reacting to mouse events. I concentrate now first on this cursor. So far, I read examples on how to do it on matplotlib. however, i have trouble to understand how to integrate matplotlib on my code. Also, is matplotlib the easiest way to do it on this code. or there might be a better way to do it. any hint would be helpful thank you in advance. here is my desired output and the code of my app import sys from PySide2 import QtWidgets from vispy import scene from PySide2.QtCore import QMetaObject from PySide2.QtWidgets import * class SimpleItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) def boundingRect(self): penWidth = 1.0 return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth) def paint(self, painter, option, widget): rect = self.boundingRect() painter.drawRect(rect) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.groupBox = QGroupBox(self.centralwidget) self.groupBox.setObjectName("groupBox") self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) QMetaObject.connectSlotsByName(MainWindow) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # OpenGL drawing surface self.canvas = scene.SceneCanvas(keys='interactive') self.canvas.create_native() self.canvas.native.setParent(self) self.view = self.canvas.central_widget.add_view() self.view.bgcolor = '#ffffff' # set the canva to a white background scene2 = QGraphicsScene() item = SimpleItem() scene2.addItem(item) self.setWindowTitle('MyApp') def main(): import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui') app = QtWidgets.QApplication([]) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() edit: I added a class (here it is a rectangle just as an example) to illustrate my problem. i have trouble integrating that snippet of the code (with SimpleItem) to OpenGL canvas
[ "You can use the QApplication.setOverrideCursor method to assign a .png image file as your cursor when it appears inside of the Qt program.\nHere is an example that is mostly based on the code in your question. And below is a gif that demonstrates the example. And the last image is the image I used in the code as cursor.png\nHope this helps\nimport sys\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtGui import *\n\nclass SimpleItem(QtWidgets.QGraphicsItem):\n def __init__(self):\n QtWidgets.QGraphicsItem.__init__(self)\n self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)\n self._brush = QBrush(Qt.black)\n\n def boundingRect(self):\n penWidth = 1.0\n return QRectF(-50 - penWidth / 2, -50 - penWidth / 2,\n 50 + penWidth, 50 + penWidth)\n\n def paint(self, painter, option, widget):\n rect = self.boundingRect()\n painter.drawRect(rect)\n painter.fillRect(rect, self._brush)\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.resize(800, 600)\n self.scene = QGraphicsScene()\n self.canvas = scene.SceneCanvas(keys='interactive')\n self.view = QGraphicsView(self.scene)\n item = SimpleItem()\n self.scene.addItem(item)\n self.setCentralWidget(self.view)\n self.setWindowTitle('MyApp')\n\n\ndef main():\n import ctypes\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('my_gui')\n app = QtWidgets.QApplication([])\n app.setOverrideCursor(QCursor(QPixmap('cursor.png')))\n main_window = MainWindow()\n main_window.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n\n\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pyside2", "python", "qtwidgets" ]
stackoverflow_0074490415_matplotlib_pyside2_python_qtwidgets.txt
Q: TypeError: 'type' object is not subscriptable, error when creating an trading bot with python I am creating a trading bot. I have 2 files a settings.json file and a main.py file. my settings.json file : `{ "username": "51410030", "password": "s5p3GI1zY", "server": "Alpari-MT5-Demo", "mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe", "symbols": ["USDJPY.a"], "timeframe": "M30" } and my main.py file : import json import os import mt5_interface import strategy # Function to import settings from settings.json def get_project_settings(importFilepath): # Test the filepath to sure it exists if os.path.exists(importFilepath): # Open the file f = open(importFilepath, "r") # Get the information from file project_settings = json.load(f) # Close the file f.close() project_settings = list(project_settings) # Return project settings to program return project_settings else: return ImportError # Main function if __name__ == '__main__': # Set up the import filepath import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json" # Import project settings project_settings = get_project_settings(import_filepath) # Start MT5 mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"], project_settings["mt5Pathway"]) # Initialize symbols mt5_interface.initialize_symbols(project_settings["symbols"]) # Select symbol to run strategy on symbol_for_strategy = project_settings['symbols'][0] # Start strategy one on selected symbol strategy.strategy_one(symbol=symbol_for_strategy, timeframe=project_settings['timeframe'], pip_size=project_settings['pip_size']) my prblem is when i run my main.py file it gives me this error: Traceback (most recent call last): File "i:\Traiding Bot\code\main.py", line 32, in <module> mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"], TypeError: 'type' object is not subscriptable please help me. I couldn't find a solution please help me. A: There are a few issues with your code: You're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields. You're returning an ImportError, if you want to raise an error, use raise ImportError("Your error message"). Or if you want to catch the error, use a try: <your code> except: return None and then check if you're returning None or not.
TypeError: 'type' object is not subscriptable, error when creating an trading bot with python
I am creating a trading bot. I have 2 files a settings.json file and a main.py file. my settings.json file : `{ "username": "51410030", "password": "s5p3GI1zY", "server": "Alpari-MT5-Demo", "mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe", "symbols": ["USDJPY.a"], "timeframe": "M30" } and my main.py file : import json import os import mt5_interface import strategy # Function to import settings from settings.json def get_project_settings(importFilepath): # Test the filepath to sure it exists if os.path.exists(importFilepath): # Open the file f = open(importFilepath, "r") # Get the information from file project_settings = json.load(f) # Close the file f.close() project_settings = list(project_settings) # Return project settings to program return project_settings else: return ImportError # Main function if __name__ == '__main__': # Set up the import filepath import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json" # Import project settings project_settings = get_project_settings(import_filepath) # Start MT5 mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"], project_settings["mt5Pathway"]) # Initialize symbols mt5_interface.initialize_symbols(project_settings["symbols"]) # Select symbol to run strategy on symbol_for_strategy = project_settings['symbols'][0] # Start strategy one on selected symbol strategy.strategy_one(symbol=symbol_for_strategy, timeframe=project_settings['timeframe'], pip_size=project_settings['pip_size']) my prblem is when i run my main.py file it gives me this error: Traceback (most recent call last): File "i:\Traiding Bot\code\main.py", line 32, in <module> mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"], TypeError: 'type' object is not subscriptable please help me. I couldn't find a solution please help me.
[ "There are a few issues with your code:\n\nYou're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields.\n\nYou're returning an ImportError, if you want to raise an error, use raise ImportError(\"Your error message\"). Or if you want to catch the error, use a try: <your code> except: return None and then check if you're returning None or not.\n\n\n" ]
[ 0 ]
[]
[]
[ "json", "metatrader5", "python", "trading" ]
stackoverflow_0074559282_json_metatrader5_python_trading.txt
Q: VS Code not detecting package in conda environment I used conda install -c Quantopian zipline to install the zipline package in a new conda environment. I activated the conda environment from within VS Code and my settings.json reads as follows: { "python.pythonPath": "C:\\Anaconda3\\envs\\zipline\\python.exe" } The bottom bar in my VS Code shows that the 'zipline' conda environment is being used. However, the following import statement is throwing a ModuleNotFoundError. from zipline.examples import buyapple Error: Traceback (most recent call last): File "d:\Studies\nsedata\zipline_setup.py", line 1, in <module> from zipline.examples import buyapple ModuleNotFoundError: No module named 'zipline' When I am importing the same package from within VS Code terminal, there's no issue: (base) PS D:\Studies\nsedata> conda activate zipline (zipline) PS D:\Studies\nsedata> python Python 3.6.10 |Anaconda, Inc.| (default, May 7 2020, 19:46:08) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from zipline.examples import buyapple >>> What am I doing wrong here and what can be a possible fix? Will appreciate any help on this. A: As i can see you are using conda environment, you need to specify pythonPath of that specific conda environment instead of Base Conda path. In your case its 'zipline' so in Command Palette, search for your conda environment and select it as pythonPath. Refer below image: Yse the Python: Select Interpreter command from the Command Palette To activate your conda env Add the below settings to your settings.json: “terminal.integrated.shell.windows”:“C:\\Windows\\System32\\cmd.exe” “terminal.integrated.shellArgs.windows”: [“/K”, “C:\\<path-to-conda-installation>\\Scripts\\activate.bat C:\\<path-to-conda-installation> & conda activate <your-env-name>”] Restart your vscode once the above settings are in place. You can also try this amazing extension for vscode as a add on https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner A: After you install the package you'd better reload the VSCode. 'Ctrl+Left-click' or 'F12' on the 'zipline' can navigation to the file under the zipline package? Could you add these code in the python file? import sys print(sys.executable) print(sys.path) The outputs can show you which interpreter you are using and the locations where the interpreter looking for packages. A: Came to your answer having the same problem and in my case the conda environment was missing from the list of interpreters from the vscode command palette, specifically there was one with the wrong PATH, it had a <TOKEN> in the middle. My solution Open the command palette (Ctrl + Shift + P in linux) Type > Python select interpreter and press enter Paste the conda environment path, in my case /home/USER/miniconda3/envs/ldm That will automatically work, didn't have to restart vscode, but you may want to try with the command Developer: Restart extension host from the command palette as well if you have an older version of vscode.
VS Code not detecting package in conda environment
I used conda install -c Quantopian zipline to install the zipline package in a new conda environment. I activated the conda environment from within VS Code and my settings.json reads as follows: { "python.pythonPath": "C:\\Anaconda3\\envs\\zipline\\python.exe" } The bottom bar in my VS Code shows that the 'zipline' conda environment is being used. However, the following import statement is throwing a ModuleNotFoundError. from zipline.examples import buyapple Error: Traceback (most recent call last): File "d:\Studies\nsedata\zipline_setup.py", line 1, in <module> from zipline.examples import buyapple ModuleNotFoundError: No module named 'zipline' When I am importing the same package from within VS Code terminal, there's no issue: (base) PS D:\Studies\nsedata> conda activate zipline (zipline) PS D:\Studies\nsedata> python Python 3.6.10 |Anaconda, Inc.| (default, May 7 2020, 19:46:08) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from zipline.examples import buyapple >>> What am I doing wrong here and what can be a possible fix? Will appreciate any help on this.
[ "As i can see you are using conda environment, you need to specify pythonPath of that specific conda environment instead of Base Conda path.\nIn your case its 'zipline' so in Command Palette, search for your conda environment and select it as pythonPath. Refer below image:\nYse the Python: Select Interpreter command from the Command Palette\n\nTo activate your conda env\nAdd the below settings to your settings.json:\n“terminal.integrated.shell.windows”:“C:\\\\Windows\\\\System32\\\\cmd.exe”\n“terminal.integrated.shellArgs.windows”: [“/K”, “C:\\\\<path-to-conda-installation>\\\\Scripts\\\\activate.bat C:\\\\<path-to-conda-installation> & conda activate <your-env-name>”]\n\nRestart your vscode once the above settings are in place.\nYou can also try this amazing extension for vscode as a add on\nhttps://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner\n", "After you install the package you'd better reload the VSCode.\n'Ctrl+Left-click' or 'F12' on the 'zipline' can navigation to the file under the zipline package?\nCould you add these code in the python file?\nimport sys\nprint(sys.executable)\nprint(sys.path)\n\nThe outputs can show you which interpreter you are using and the locations where the interpreter looking for packages.\n", "Came to your answer having the same problem and in my case the conda environment was missing from the list of interpreters from the vscode command palette, specifically there was one with the wrong PATH, it had a <TOKEN> in the middle.\nMy solution\n\nOpen the command palette (Ctrl + Shift + P in linux)\nType > Python select interpreter and press enter\nPaste the conda environment path, in my case /home/USER/miniconda3/envs/ldm\n\nThat will automatically work, didn't have to restart vscode, but you may want to try with the command Developer: Restart extension host from the command palette as well if you have an older version of vscode.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "conda", "python", "visual_studio_code", "zipline" ]
stackoverflow_0063484377_conda_python_visual_studio_code_zipline.txt
Q: Quasi Random Number generation Scatter plot Require python code for Quasi random number generation scatter plot. Tried this method but getting name not found error as shown below [code](https://i.stack.imgur.com/Eg5og.png) [code](https://i.stack.imgur.com/2a6o8.png) [error](https://i.stack.imgur.com/j2O04.png) I tries to obtain quasi random number generator scatter plot. But got name not found error as shown below. I used Jupiter notebook I tried calling the function inside the main code still it's not displaying the output scatter plots. <!-- begin snippet: hide: false console: true babel: false --> # Connecting cython one cell in jupiter notebook %load_ext Cython # another cell %%cython import gsl from cpython.mem cimport PyMem_Malloc, PyMem_Free # Declare the few types and functions we need cdef extern from "gsl/gsl_qrng.h": ctypedef struct gsl_qrng # Declare the few types and functions we need ctypedef struct gsl_qrng_type gsl_qrng_type* gsl_qrng_sobol # Declare the few types and functions we need gsl_qrng* gsl_qrng_alloc(gsl_qrng_type* T, unsigned int d) void gsl_qrng_free(gsl_qrng* q) # Declare the few types and functions we need int gsl_qrng_get(const gsl_qrng * q, double x[]) # This is the wrapper class cdef class Sobol: cdef gsl_qrng* _q cdef unsigned _D cdef double *_v def __cinit__(self, D=1): """Create a `D` dimensional Sobol sequence.""" self._D = D # Declare the few types and functions we need # gsl_qrng_get() returns the next # value in one of its arguments self._v = <double *>PyMem_Malloc(D * sizeof(double)) if not self._v: raise MemoryError() # Actually allocate the QRNG generator self._q = gsl_qrng_alloc(gsl_qrng_sobol, D) if self._q is NULL: raise MemoryError() # getting values def get(self, int N=1): """The next `N` points in the sequence.""" points = [] for n in xrange(N): points.append(self.__next__()) return points # getting next values def __next__(self): """Iterate over the sequence.""" gsl_qrng_get(self._q, self._v) return [self._v[i] for i in xrange(self._D)] def __iter__(self): return self # Make sure we free all the memory we allocated def __dealloc__(self): if self._q is not NULL: gsl_qrng_free(self._q) PyMem_Free(self._v) # another cell s2 = Sobol(2) # Declare the few types and functions we need sobol_X, sobol_Y = zip(*s2.get(100)) # Declare the few types and functions we need sobol_X2 = (np.array(sobol_X) + np.random.uniform())%1 sobol_Y2 = (np.array(sobol_Y) + np.random.uniform())%1 X = np.random.uniform(size=(100*2)) # Declare the few types and functions we need f, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12,4)) ax1.scatter(X[:100], X[100:],) ax2.scatter(sobol_X, sobol_Y, color="red") ax3.scatter(sobol_X2, sobol_Y2, color="green") ax1.set_title("Random") ax2.set_title("quasi") ax3.set_title("quasi again") Error: --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_19752\3909363266.py in <module> ----> 1 s2 = Sobol(2) 2 3 sobol_X, sobol_Y = zip(*s2.get(100)) 4 5 sobol_X2 = (np. array(sobol_X) + np. random. uniform())%1 Name Error: name 'Sobol' is not defined Here I have used 3 cells to perform operations. One cell is to connect Cython. One cell is for cython logic and other cell is for python code were we call cython function. Can i know what is the error. Also do we need to import Gsl or is there any other way to find a scatter plot for quasi random number generation? A: I can't find any examples on this site of plotting the output of Scipy's Quasi Monte-Carlo generators, so here's one that replicates the first plot of Wikipedia's entry on the Sobol sequence: # import generators from SciPy from scipy.stats import qmc import matplotlib.pyplot as plt # create 2D Sobol sequence and draw 256 points qr = qmc.Sobol(2, scramble=False) XY = qr.random(256) # plot points fig, ax = plt.subplots() ax.scatter( XY[:,0], XY[:,1], facecolor='none', edgecolor=['C1'] * 10 + ['C0'] * 90 + ['C2'] * 154, linewidth=2, ) ax.margins(0.02) ax.set_aspect(1) which produces:
Quasi Random Number generation Scatter plot
Require python code for Quasi random number generation scatter plot. Tried this method but getting name not found error as shown below [code](https://i.stack.imgur.com/Eg5og.png) [code](https://i.stack.imgur.com/2a6o8.png) [error](https://i.stack.imgur.com/j2O04.png) I tries to obtain quasi random number generator scatter plot. But got name not found error as shown below. I used Jupiter notebook I tried calling the function inside the main code still it's not displaying the output scatter plots. <!-- begin snippet: hide: false console: true babel: false --> # Connecting cython one cell in jupiter notebook %load_ext Cython # another cell %%cython import gsl from cpython.mem cimport PyMem_Malloc, PyMem_Free # Declare the few types and functions we need cdef extern from "gsl/gsl_qrng.h": ctypedef struct gsl_qrng # Declare the few types and functions we need ctypedef struct gsl_qrng_type gsl_qrng_type* gsl_qrng_sobol # Declare the few types and functions we need gsl_qrng* gsl_qrng_alloc(gsl_qrng_type* T, unsigned int d) void gsl_qrng_free(gsl_qrng* q) # Declare the few types and functions we need int gsl_qrng_get(const gsl_qrng * q, double x[]) # This is the wrapper class cdef class Sobol: cdef gsl_qrng* _q cdef unsigned _D cdef double *_v def __cinit__(self, D=1): """Create a `D` dimensional Sobol sequence.""" self._D = D # Declare the few types and functions we need # gsl_qrng_get() returns the next # value in one of its arguments self._v = <double *>PyMem_Malloc(D * sizeof(double)) if not self._v: raise MemoryError() # Actually allocate the QRNG generator self._q = gsl_qrng_alloc(gsl_qrng_sobol, D) if self._q is NULL: raise MemoryError() # getting values def get(self, int N=1): """The next `N` points in the sequence.""" points = [] for n in xrange(N): points.append(self.__next__()) return points # getting next values def __next__(self): """Iterate over the sequence.""" gsl_qrng_get(self._q, self._v) return [self._v[i] for i in xrange(self._D)] def __iter__(self): return self # Make sure we free all the memory we allocated def __dealloc__(self): if self._q is not NULL: gsl_qrng_free(self._q) PyMem_Free(self._v) # another cell s2 = Sobol(2) # Declare the few types and functions we need sobol_X, sobol_Y = zip(*s2.get(100)) # Declare the few types and functions we need sobol_X2 = (np.array(sobol_X) + np.random.uniform())%1 sobol_Y2 = (np.array(sobol_Y) + np.random.uniform())%1 X = np.random.uniform(size=(100*2)) # Declare the few types and functions we need f, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12,4)) ax1.scatter(X[:100], X[100:],) ax2.scatter(sobol_X, sobol_Y, color="red") ax3.scatter(sobol_X2, sobol_Y2, color="green") ax1.set_title("Random") ax2.set_title("quasi") ax3.set_title("quasi again") Error: --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_19752\3909363266.py in <module> ----> 1 s2 = Sobol(2) 2 3 sobol_X, sobol_Y = zip(*s2.get(100)) 4 5 sobol_X2 = (np. array(sobol_X) + np. random. uniform())%1 Name Error: name 'Sobol' is not defined Here I have used 3 cells to perform operations. One cell is to connect Cython. One cell is for cython logic and other cell is for python code were we call cython function. Can i know what is the error. Also do we need to import Gsl or is there any other way to find a scatter plot for quasi random number generation?
[ "I can't find any examples on this site of plotting the output of Scipy's Quasi Monte-Carlo generators, so here's one that replicates the first plot of Wikipedia's entry on the Sobol sequence:\n# import generators from SciPy\nfrom scipy.stats import qmc\nimport matplotlib.pyplot as plt\n\n# create 2D Sobol sequence and draw 256 points\nqr = qmc.Sobol(2, scramble=False)\nXY = qr.random(256)\n\n# plot points\nfig, ax = plt.subplots()\nax.scatter(\n XY[:,0], XY[:,1],\n facecolor='none',\n edgecolor=['C1'] * 10 + ['C0'] * 90 + ['C2'] * 154,\n linewidth=2,\n)\nax.margins(0.02)\nax.set_aspect(1)\n\nwhich produces:\n\n" ]
[ 0 ]
[]
[]
[ "cython", "python", "random" ]
stackoverflow_0074554924_cython_python_random.txt
Q: How to compact a dataset with empty rows in Python? I have a data set formatted as follows: sha 0_x 1_x N_x Sha1 rm rm Sha2 rw rw Sha3 rw Sha4 tr In particular, the dataset currently contains about 2000 columns. I want to reduce the number of columns removing as many as possible the empty rows, as follows: sha 0_x 1_x Sha1 rm rm Sha2 rw rw Sha3 rw Sha4 tr I don't care about the names of the columns. A: Assuming empty cells are NaN, if not, first replace('', np.nan). You can stack and pivot: cols = df.columns[1:] # ['0_x', '1_x', 'N_x'] (df.set_index('sha') .stack() .reset_index() .assign(cols=lambda d: d.groupby('sha') .cumcount() .map(dict(enumerate(cols))) ) .pivot(index='sha', columns='cols', values=0) .reset_index() ) Other option, with apply: cols = list(df.columns[1:]) # ['0_x', '1_x', 'N_x'] (df.set_index('sha') .apply(lambda s: s.dropna().reset_index(drop=True), axis=1) .pipe(lambda d: d.set_axis(cols[:len(d.columns)], axis=1)) .reset_index() ) Output: cols sha 0_x 1_x 0 Sha1 rm rm 1 Sha2 rw rw 2 Sha3 rw NaN 3 Sha4 tr NaN A: Another possible solution: (df.set_index('sha') .replace(r'$', '_', regex=True) .replace(np.nan, '') .sum(numeric_only=False, axis=1) .str.split('_+', regex=True, expand=True) .replace('', np.nan) .dropna(how='all', axis=1) .pipe(lambda d: d.set_axis(d.columns.astype('str') + '_x', axis=1)) .reset_index()) Output: sha 0_x 1_x 0 Sha1 rm rm 1 Sha2 rw rw 2 Sha3 rw NaN 3 Sha4 tr NaN
How to compact a dataset with empty rows in Python?
I have a data set formatted as follows: sha 0_x 1_x N_x Sha1 rm rm Sha2 rw rw Sha3 rw Sha4 tr In particular, the dataset currently contains about 2000 columns. I want to reduce the number of columns removing as many as possible the empty rows, as follows: sha 0_x 1_x Sha1 rm rm Sha2 rw rw Sha3 rw Sha4 tr I don't care about the names of the columns.
[ "Assuming empty cells are NaN, if not, first replace('', np.nan).\nYou can stack and pivot:\ncols = df.columns[1:]\n# ['0_x', '1_x', 'N_x']\n\n(df.set_index('sha')\n .stack()\n .reset_index()\n .assign(cols=lambda d: d.groupby('sha')\n .cumcount()\n .map(dict(enumerate(cols)))\n )\n .pivot(index='sha', columns='cols', values=0)\n .reset_index()\n)\n\nOther option, with apply:\ncols = list(df.columns[1:])\n# ['0_x', '1_x', 'N_x']\n\n(df.set_index('sha')\n .apply(lambda s: s.dropna().reset_index(drop=True), axis=1)\n .pipe(lambda d: d.set_axis(cols[:len(d.columns)], axis=1))\n .reset_index()\n)\n\nOutput:\ncols sha 0_x 1_x\n0 Sha1 rm rm\n1 Sha2 rw rw\n2 Sha3 rw NaN\n3 Sha4 tr NaN\n\n", "Another possible solution:\n(df.set_index('sha')\n .replace(r'$', '_', regex=True)\n .replace(np.nan, '')\n .sum(numeric_only=False, axis=1)\n .str.split('_+', regex=True, expand=True)\n .replace('', np.nan)\n .dropna(how='all', axis=1)\n .pipe(lambda d: d.set_axis(d.columns.astype('str') + '_x', axis=1))\n .reset_index())\n\nOutput:\n sha 0_x 1_x\n0 Sha1 rm rm\n1 Sha2 rw rw\n2 Sha3 rw NaN\n3 Sha4 tr NaN\n\n" ]
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074558800_dataframe_pandas_python.txt
Q: Drawing Arabic Characters to bitmap i have been trying to print arabic characters using SPRT thermal printer with the python-escpos package, but i cant seem to find any solution at all, so i decided to draw the arabic characters to a bitmap and then print it. But that also doesn't work.. this is the code used for converting the text to bitmap: ` from PIL import Image, ImageDraw, ImageFont img = Image.new('L', (100, 10)) d = ImageDraw.Draw(img) a = 'محمد' d.text((1,1), f"{a}",255) img.save('pil_text.png') ` Result in Error: UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256) Also, i have tried to encode the string using utf-8 and 1256, but both didnt give me the correct characters: b'\xd9\x85\xd8\xad\xd9\x85\xd8\xaf' A: In this case you need to use a particular font. from PIL import Image, ImageFont, ImageDraw image = Image.new("RGB",[320,320]) draw = ImageDraw.Draw(image) a = 'محمد' font = ImageFont.truetype("arial-unicode-ms.ttf", 14) draw.text((50, 50), a, font=font) image.save("image.png")
Drawing Arabic Characters to bitmap
i have been trying to print arabic characters using SPRT thermal printer with the python-escpos package, but i cant seem to find any solution at all, so i decided to draw the arabic characters to a bitmap and then print it. But that also doesn't work.. this is the code used for converting the text to bitmap: ` from PIL import Image, ImageDraw, ImageFont img = Image.new('L', (100, 10)) d = ImageDraw.Draw(img) a = 'محمد' d.text((1,1), f"{a}",255) img.save('pil_text.png') ` Result in Error: UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256) Also, i have tried to encode the string using utf-8 and 1256, but both didnt give me the correct characters: b'\xd9\x85\xd8\xad\xd9\x85\xd8\xaf'
[ "In this case you need to use a particular font.\nfrom PIL import Image, ImageFont, ImageDraw\n\nimage = Image.new(\"RGB\",[320,320])\ndraw = ImageDraw.Draw(image)\na = 'محمد'\nfont = ImageFont.truetype(\"arial-unicode-ms.ttf\", 14)\ndraw.text((50, 50), a, font=font)\nimage.save(\"image.png\")\n\n" ]
[ 0 ]
[]
[]
[ "escpos", "python", "thermal_printer" ]
stackoverflow_0074559180_escpos_python_thermal_printer.txt
Q: How to share the x axis in reverse between two subplots in matplotlib? I want to show two different anatomical views of a subject, front and back, and I want the coordinates to be consistent between both while also showing them as you would naturally see them. This means that the X axis should increase to the right in the front view and to the left in the back view. I want the navigation actions (pan, zoom) to affect both views at the same time. For example, if I zoom on the left shoulder of the subject in the front view (which would be located on the right side of the image) I want the back view to also zoom on the left shoulder (which would be located on the left side of the image). Usually this is achieved by sharing the axis with something like the sharex and sharey parameters. However, as I said, I want the X axis (and only the X axis) in the second subplot to be reversed, and that option forces the limits on both subplots to go the same way. Is there any way to achieve this? A: Well, it does not look like there is a specific functionality already implemented for what I'm trying to achieve, so after a bit of tinkering this is the simplest that I was able to come up with. I am integrating this into a Qt application and I had already modified the navigation toolbar to hide some actions and change some shortcuts. What I have ended up doing is overriding the following methods from my custom navigation toolbar class: class CustomNavigationToolbar(NavigationToolbar): ... def release_zoom(self, event) -> None: zoom_axes = self._zoom_info.axes[0] other_axes = [a for a in self.canvas.figure.get_axes() if a != zoom_axes][0] super().release_zoom(event) other_axes.set_ylim(zoom_axes.get_ylim()) other_axes.set_xlim(reversed(zoom_axes.get_xlim())) self.canvas.draw_idle() def drag_pan(self, event) -> None: pan_axes = self._pan_info.axes[0] other_axes = [a for a in self.canvas.figure.get_axes() if a != pan_axes][0] super().drag_pan(event) other_axes.set_ylim(pan_axes.get_ylim()) other_axes.set_xlim(reversed(pan_axes.get_xlim())) self.canvas.draw_idle() For the zoom action the view is updated when the mouse button is release (the release_zoom method) so I get the other axes first and, after the call to super(), I update the X and Y limits based on the zoomed axes. Same thing for the pan action, but this is updated while the mouse is being dragged (the drag_pan method). Please note, this works for my use case because I'm guaranteed to only have two axes, but it wouldn't be difficult to adapt to more than two.
How to share the x axis in reverse between two subplots in matplotlib?
I want to show two different anatomical views of a subject, front and back, and I want the coordinates to be consistent between both while also showing them as you would naturally see them. This means that the X axis should increase to the right in the front view and to the left in the back view. I want the navigation actions (pan, zoom) to affect both views at the same time. For example, if I zoom on the left shoulder of the subject in the front view (which would be located on the right side of the image) I want the back view to also zoom on the left shoulder (which would be located on the left side of the image). Usually this is achieved by sharing the axis with something like the sharex and sharey parameters. However, as I said, I want the X axis (and only the X axis) in the second subplot to be reversed, and that option forces the limits on both subplots to go the same way. Is there any way to achieve this?
[ "Well, it does not look like there is a specific functionality already implemented for what I'm trying to achieve, so after a bit of tinkering this is the simplest that I was able to come up with.\nI am integrating this into a Qt application and I had already modified the navigation toolbar to hide some actions and change some shortcuts. What I have ended up doing is overriding the following methods from my custom navigation toolbar class:\nclass CustomNavigationToolbar(NavigationToolbar):\n ...\n\n def release_zoom(self, event) -> None:\n zoom_axes = self._zoom_info.axes[0]\n other_axes = [a for a in self.canvas.figure.get_axes() if a != zoom_axes][0]\n super().release_zoom(event)\n other_axes.set_ylim(zoom_axes.get_ylim())\n other_axes.set_xlim(reversed(zoom_axes.get_xlim()))\n self.canvas.draw_idle()\n\n def drag_pan(self, event) -> None:\n pan_axes = self._pan_info.axes[0]\n other_axes = [a for a in self.canvas.figure.get_axes() if a != pan_axes][0]\n super().drag_pan(event)\n other_axes.set_ylim(pan_axes.get_ylim())\n other_axes.set_xlim(reversed(pan_axes.get_xlim()))\n self.canvas.draw_idle()\n\nFor the zoom action the view is updated when the mouse button is release (the release_zoom method) so I get the other axes first and, after the call to super(), I update the X and Y limits based on the zoomed axes. Same thing for the pan action, but this is updated while the mouse is being dragged (the drag_pan method).\nPlease note, this works for my use case because I'm guaranteed to only have two axes, but it wouldn't be difficult to adapt to more than two.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074548808_matplotlib_python.txt
Q: Python Pandas Dataframe manipulation (Excel File) I'm fairly new to Python and I have a issue with dataframe manipulation using EXCEL: This is a snippet of the excel: I was able to drop the duplicates for datetime rows, and get a dataframe with only the datatime rows and another with only the descriptions; I was able to drop the last row as well: What I wanted to do is to 'shift' the column A with dates to column B for the row above. If both Dataframes were 1-1 its easy, but I have a row (in yellow) that does not have any datetime below. Anyone has any idea how to do it? To be something like this> df_cdms_labour = pd.read_excel(test_cdms, header=None, names=['start_date', 'end_date', 'price','percent', 'comment','rate', 'rate_comment','number_1','markup','markup_number']) df_cdms_labour.drop(df_cdms_labour.tail().index,inplace=True) df_cdms_labour def get_rate_text(df): return(df.loc[4,'start_date'] ) def get_rates(df): flt = df.loc[:,'start_date'].apply(lambda x: isinstance(x, datetime)) return(df[flt] .drop_duplicates() .reset_index(drop=True)) rates = get_rates(df_cdms_labour) A: Here is a proposition using standard pandas frame's functions : import pandas as pd import numpy as np def flag_delete(df): df.insert(0, "temp_col", df.groupby("Col_A")["Col_A"].transform("count")) df.loc[df.pop("temp_col").eq(1), df.columns!="Col_A"] = "DELETE" return df def format_dates(df): temp_df = df.select_dtypes('datetime64') df[temp_df.columns] = temp_df.apply(lambda x: x.dt.strftime('%d-%b-%Y')) return df df= ( pd.read_excel("BrunoA.xlsx", header=None, dtype=str) .assign(Col_A= lambda x: pd.Series(np.where(~x[0].str.contains("\d{4}-\d{2}-\d{2}", regex=True), x[0], np.NaN)).ffill(), Col_B= lambda x: np.where(x[0].str.contains("\d{4}-\d{2}-\d{2}", regex=True), x[0], np.NaN)) .drop(columns=0) .drop_duplicates() .apply(lambda _: pd.to_datetime(_, format='%Y-%m-%d', errors="ignore")) .pipe(format_dates) .pipe(flag_delete) .dropna() .rename(columns={"Col_A": -1, "Col_B": 0}) .sort_index(axis=1) .reset_index(drop=True) ) display(df) # Output :
Python Pandas Dataframe manipulation (Excel File)
I'm fairly new to Python and I have a issue with dataframe manipulation using EXCEL: This is a snippet of the excel: I was able to drop the duplicates for datetime rows, and get a dataframe with only the datatime rows and another with only the descriptions; I was able to drop the last row as well: What I wanted to do is to 'shift' the column A with dates to column B for the row above. If both Dataframes were 1-1 its easy, but I have a row (in yellow) that does not have any datetime below. Anyone has any idea how to do it? To be something like this> df_cdms_labour = pd.read_excel(test_cdms, header=None, names=['start_date', 'end_date', 'price','percent', 'comment','rate', 'rate_comment','number_1','markup','markup_number']) df_cdms_labour.drop(df_cdms_labour.tail().index,inplace=True) df_cdms_labour def get_rate_text(df): return(df.loc[4,'start_date'] ) def get_rates(df): flt = df.loc[:,'start_date'].apply(lambda x: isinstance(x, datetime)) return(df[flt] .drop_duplicates() .reset_index(drop=True)) rates = get_rates(df_cdms_labour)
[ "Here is a proposition using standard pandas frame's functions :\nimport pandas as pd\nimport numpy as np\n\ndef flag_delete(df):\n df.insert(0, \"temp_col\", df.groupby(\"Col_A\")[\"Col_A\"].transform(\"count\"))\n df.loc[df.pop(\"temp_col\").eq(1), df.columns!=\"Col_A\"] = \"DELETE\"\n return df\n\ndef format_dates(df):\n temp_df = df.select_dtypes('datetime64')\n df[temp_df.columns] = temp_df.apply(lambda x: x.dt.strftime('%d-%b-%Y'))\n return df\n\n\ndf= (\n pd.read_excel(\"BrunoA.xlsx\", header=None, dtype=str)\n .assign(Col_A= lambda x: pd.Series(np.where(~x[0].str.contains(\"\\d{4}-\\d{2}-\\d{2}\", regex=True), x[0], np.NaN)).ffill(),\n Col_B= lambda x: np.where(x[0].str.contains(\"\\d{4}-\\d{2}-\\d{2}\", regex=True), x[0], np.NaN))\n .drop(columns=0)\n .drop_duplicates()\n .apply(lambda _: pd.to_datetime(_, format='%Y-%m-%d', errors=\"ignore\"))\n .pipe(format_dates)\n .pipe(flag_delete)\n .dropna()\n .rename(columns={\"Col_A\": -1, \"Col_B\": 0})\n .sort_index(axis=1)\n .reset_index(drop=True)\n )\n\ndisplay(df)\n\n# Output :\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "excel", "pandas", "python" ]
stackoverflow_0074559111_dataframe_excel_pandas_python.txt
Q: Reading parquet file in pandas I am trying to read a parquet files to pandas data=pd.read_parquet('MyFiles.parquet', engine='pyarrow') but I am getting the following error ArrowInvalid: Casting from timestamp[us] to timestamp[ns] would result in out of bounds timestamp: 253402214400000000 If I change the engine type to fastparquet data=pd.read_parquet('MyFiles.parquet', engine='fastparquet') There is also this error AttributeError: 'numpy.ndarray' object has no attribute 'tz' A: Problem with the column which has timestamp in different timezone. You might need to download the parquet file first, and modify it before convert to pandas DataFrame. Some related issues: Parquet File datetime value mismatch
Reading parquet file in pandas
I am trying to read a parquet files to pandas data=pd.read_parquet('MyFiles.parquet', engine='pyarrow') but I am getting the following error ArrowInvalid: Casting from timestamp[us] to timestamp[ns] would result in out of bounds timestamp: 253402214400000000 If I change the engine type to fastparquet data=pd.read_parquet('MyFiles.parquet', engine='fastparquet') There is also this error AttributeError: 'numpy.ndarray' object has no attribute 'tz'
[ "Problem with the column which has timestamp in different timezone. You might need to download the parquet file first, and modify it before convert to pandas DataFrame.\nSome related issues: Parquet File datetime value mismatch\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "parquet", "python", "python_3.x" ]
stackoverflow_0072405974_dataframe_pandas_parquet_python_python_3.x.txt
Q: How to call methods in a different class Confused on OOP in Python3: main.py: import ma as m1 r = m1.ma1() r.doit() print(r.m1avar) print(r.m2var) r.m2do() ma.py: import mb as m2 class ma1(m2.mclass2): m1avar = 10 def doit(self): self.logout("doit!") def logout(self, a): print(a+" <--- this is correct") mb.py: class mclass2(): m2var = 5; m1avar = 5; def doit(self): super().logout("m2 do it") def m2do(self): super().logout("child class") Produces: doit! <--- this is correct 10 5 Traceback (most recent call last): File "/home/alex/Desktop/rrr/m1.py", line 8, in <module> r.m2do() File "/home/alex/Desktop/rrr/mb.py", line 11, in m2do super().logout("child class") AttributeError: 'super' object has no attribute 'logout' How do I get the lowest class (mclass2) to access methods in a higher class ma1 - specifically the .logout method. Thanks! A: Try this - mclass2 does not see it's parent class as super, just as itself. So it's self. that you need not super. class mclass2(): m2var = 5; m1avar = 5; def doit(self): super().logout("m2 do it") def m2do(self): self.logout("child class") A: The problem is that m2 doesnt inherit from m1. In other words, m2 doesn't even know that m1 exist. The only thing you can do to make it work is assign a m1 object at an instance of the m2 object. I don't think this is a good practice.
How to call methods in a different class
Confused on OOP in Python3: main.py: import ma as m1 r = m1.ma1() r.doit() print(r.m1avar) print(r.m2var) r.m2do() ma.py: import mb as m2 class ma1(m2.mclass2): m1avar = 10 def doit(self): self.logout("doit!") def logout(self, a): print(a+" <--- this is correct") mb.py: class mclass2(): m2var = 5; m1avar = 5; def doit(self): super().logout("m2 do it") def m2do(self): super().logout("child class") Produces: doit! <--- this is correct 10 5 Traceback (most recent call last): File "/home/alex/Desktop/rrr/m1.py", line 8, in <module> r.m2do() File "/home/alex/Desktop/rrr/mb.py", line 11, in m2do super().logout("child class") AttributeError: 'super' object has no attribute 'logout' How do I get the lowest class (mclass2) to access methods in a higher class ma1 - specifically the .logout method. Thanks!
[ "Try this - mclass2 does not see it's parent class as super, just as itself. So it's self. that you need not super.\nclass mclass2():\n \n m2var = 5;\n m1avar = 5;\n \n def doit(self):\n super().logout(\"m2 do it\")\n \n def m2do(self):\n self.logout(\"child class\")\n\n", "The problem is that m2 doesnt inherit from m1. In other words, m2 doesn't even know that m1 exist.\nThe only thing you can do to make it work is assign a m1 object at an instance of the m2 object. I don't think this is a good practice.\n" ]
[ 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074559113_oop_python.txt
Q: Discord.py command to play audio in a VC and command to leave VC using interactions/slash commands. NOT ctx or 'discord.ext commands' I am wanting to make my own personal/private bot join the voice channel I am in and play audio files. I have it able to join the VC but I can't figure out how to make the bot leave or play music/audio using slash commands/interactions. Everywhere I look it's just old & outdated examples. Even the discord.py github examples don't help and rely on using ctx and discord.ext commands. (same for what I can find here on stackoverflow). It's something that should be SO simple but is so obfuscated with garbage examples and outdated material. Nothing with what I am wanting to do. Not cogs/classes, no ctx., nothing to do with "self". Just interactions/slash commands. "app_commands" I also don't need to know how to use slash commands or how to work with them. I think I have that down. I am trying to use interaction.voice_client.play() to play audio but I just get the following error. AttributeError: 'Interaction' object has no attribute 'voice_client' I have spent all day trying to understand the discord.py documentation with no way of finding up to date examples that use slash commands/interactions. I am not even sure what to look for or where to even look in that mess of a documentation. Searching up the error just gives me no help with the search results being completely different errors, etc. Here's some code that I am using for the play command..I have nothing for the leave command: (From an example in the discord.py github examples directory but edited slightly to try and allow me to use slash commands instead of just sending "!play" in the chat.) @muise.tree.command() @app_commands.describe(url='Youtube URL') async def play(interaction: discord.Interaction, url: str): """Streams audio from a url""" player = await YTDLSource.from_url(url, loop=muise.loop, stream=True) #no idea if muise.loop will even work. used to be "self.bot.loop" But I am not in a cog or class. interaction.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None) embed = discord.Embed(title='Muise', colour=main_embed_color, timestamp=datetime.datetime.now(datetime.timezone.utc)) embed.add_field(name='Now Playing', value=f'{player.title}') embed.set_footer(text=Config["author"], icon_url='https://cdn.discordapp.com/attachments/1019374213037035530/1040294855315836998/Ori_the_cutie-1.png') await interaction.response.send_message(embed=embed) The expected outcome should be audio being played in the VC. My main issue is not having the proper knowledge of how to make this work..idk what to do, where to look. I am so tired and want this simple task to be over with. Any help would be very appreciated. Feel free to ask questions and I'll answer them to the best of my ability. A: Try doing guild = interaction.guild guild.voice_client.play instead of interaction.voice_client.play
Discord.py command to play audio in a VC and command to leave VC using interactions/slash commands. NOT ctx or 'discord.ext commands'
I am wanting to make my own personal/private bot join the voice channel I am in and play audio files. I have it able to join the VC but I can't figure out how to make the bot leave or play music/audio using slash commands/interactions. Everywhere I look it's just old & outdated examples. Even the discord.py github examples don't help and rely on using ctx and discord.ext commands. (same for what I can find here on stackoverflow). It's something that should be SO simple but is so obfuscated with garbage examples and outdated material. Nothing with what I am wanting to do. Not cogs/classes, no ctx., nothing to do with "self". Just interactions/slash commands. "app_commands" I also don't need to know how to use slash commands or how to work with them. I think I have that down. I am trying to use interaction.voice_client.play() to play audio but I just get the following error. AttributeError: 'Interaction' object has no attribute 'voice_client' I have spent all day trying to understand the discord.py documentation with no way of finding up to date examples that use slash commands/interactions. I am not even sure what to look for or where to even look in that mess of a documentation. Searching up the error just gives me no help with the search results being completely different errors, etc. Here's some code that I am using for the play command..I have nothing for the leave command: (From an example in the discord.py github examples directory but edited slightly to try and allow me to use slash commands instead of just sending "!play" in the chat.) @muise.tree.command() @app_commands.describe(url='Youtube URL') async def play(interaction: discord.Interaction, url: str): """Streams audio from a url""" player = await YTDLSource.from_url(url, loop=muise.loop, stream=True) #no idea if muise.loop will even work. used to be "self.bot.loop" But I am not in a cog or class. interaction.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None) embed = discord.Embed(title='Muise', colour=main_embed_color, timestamp=datetime.datetime.now(datetime.timezone.utc)) embed.add_field(name='Now Playing', value=f'{player.title}') embed.set_footer(text=Config["author"], icon_url='https://cdn.discordapp.com/attachments/1019374213037035530/1040294855315836998/Ori_the_cutie-1.png') await interaction.response.send_message(embed=embed) The expected outcome should be audio being played in the VC. My main issue is not having the proper knowledge of how to make this work..idk what to do, where to look. I am so tired and want this simple task to be over with. Any help would be very appreciated. Feel free to ask questions and I'll answer them to the best of my ability.
[ "Try doing\nguild = interaction.guild\nguild.voice_client.play\n\ninstead of\ninteraction.voice_client.play\n\n" ]
[ 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074553794_discord.py_python.txt
Q: How to write json data(nested array) to file in one line format with Python? I want to write json data to file, my expect as below, the nested array is very long { "test1": { "key1": [[0, 40], [2, 42], [4, 44], [6, 46], [8, 48], [10, 50], [12, 52],......], "key2": [[1, 41], [3, 43], [5, 45], [7, 47], [9, 49], [11, 51], [13, 53],......] }, "test2": { "key1": [[0, 52], [1, 53], [2, 54], [3, 55], [4, 56], [5, 57], [6, 58],......], "key2": [[26, 78], [27, 79], [28, 80], [29, 81], [30, 82], [31, 83],......] } } But when I use json.dump to write file, there are a lot of lines with open("test.json", 'w') as f: json.dump(result, f, ensure_ascii=False, indent=2) { "test1": { "key1": [ [ 0, 40 ], [ 2, 42 ], [ 4, 44 ], [ 6, 46 ], [ 8, 48 ], [ ... ... Is there any way can make these arraies in one line? A: with open("test.json", 'w') as f: f.write(str(result))
How to write json data(nested array) to file in one line format with Python?
I want to write json data to file, my expect as below, the nested array is very long { "test1": { "key1": [[0, 40], [2, 42], [4, 44], [6, 46], [8, 48], [10, 50], [12, 52],......], "key2": [[1, 41], [3, 43], [5, 45], [7, 47], [9, 49], [11, 51], [13, 53],......] }, "test2": { "key1": [[0, 52], [1, 53], [2, 54], [3, 55], [4, 56], [5, 57], [6, 58],......], "key2": [[26, 78], [27, 79], [28, 80], [29, 81], [30, 82], [31, 83],......] } } But when I use json.dump to write file, there are a lot of lines with open("test.json", 'w') as f: json.dump(result, f, ensure_ascii=False, indent=2) { "test1": { "key1": [ [ 0, 40 ], [ 2, 42 ], [ 4, 44 ], [ 6, 46 ], [ 8, 48 ], [ ... ... Is there any way can make these arraies in one line?
[ "with open(\"test.json\", 'w') as f:\n f.write(str(result))\n\n" ]
[ 0 ]
[]
[]
[ "file", "json", "python" ]
stackoverflow_0074559379_file_json_python.txt
Q: How can I access to the IP camera connected to a subnetwork of a router without port forwarding? I'm struggling with some kind of connection problem. Here's the problem that I wanted to resolve What I want to do is getting video streaming data from a IP camera (RTSP) The IP camera is attached to the router which has access to the internet I want to connect to this IP camera from remote computer. IP cam --- Router --- Internet --- My computer I know that I can do this by setting port forwarding option of the router. However, I cannot set the option because the router is not mine, which means I cannot access to the router's admininstration server (192.168.0.1) I'm trying to figure out this issue by connecting a small edge computer (e.g., raspberry pi) to the router's subnetwork and send streaming data to my computer through the Internet. IP cam --------- Router --- Internet --- My computer minicomputer --- It's certain that the minicomputer can access to my computer through ssh, so I think It's possible to use the minicom as a proxy. What is the best the way to get the IP camera's streaming in my circumstance? Please help. A: I think a good idea would be to use a VPN. Install a VPN-Server (openvpn, wireguard, etc...) on your minicomputer in the same network as your camera. Than connect to your vpn from your computer. Now you should be able to access the camera. I have a few ideas how to view the camera stream, depending how you would normaly access it. If it is a software to connect to the camera, install a desktop-environment on your minicomputer and connect to it via VNC (more or less a linux equivalent to rdp on windows) or RDP. Then open the software and view your stream. It could be a bit laggy because it has to be transmitted two times (camera -> minipc -> your pc) If you can access the stream via a url, you could setup a webserver (nginx or apache2) on your minicomputer and build a small html website, that displays the stream. This should be more perfomant than the first solution, but involves a bit more tinkering. If you should decide to use this solution, I should have an example HTML-Page somewhere. Just let me know and i will try to find it and share it. Depending on how you setup your VPN-Server maybe you can connect to your Camera directly via it's IP. To do that, your VPN-Server has to do some routing between the subnets. I know these are just some Ideas from the top of my head, but I hope I can help a bit. If you have more questions or I didn't explain it in a way it is understandable, feel free to ask again.
How can I access to the IP camera connected to a subnetwork of a router without port forwarding?
I'm struggling with some kind of connection problem. Here's the problem that I wanted to resolve What I want to do is getting video streaming data from a IP camera (RTSP) The IP camera is attached to the router which has access to the internet I want to connect to this IP camera from remote computer. IP cam --- Router --- Internet --- My computer I know that I can do this by setting port forwarding option of the router. However, I cannot set the option because the router is not mine, which means I cannot access to the router's admininstration server (192.168.0.1) I'm trying to figure out this issue by connecting a small edge computer (e.g., raspberry pi) to the router's subnetwork and send streaming data to my computer through the Internet. IP cam --------- Router --- Internet --- My computer minicomputer --- It's certain that the minicomputer can access to my computer through ssh, so I think It's possible to use the minicom as a proxy. What is the best the way to get the IP camera's streaming in my circumstance? Please help.
[ "I think a good idea would be to use a VPN. Install a VPN-Server (openvpn, wireguard, etc...) on your minicomputer in the same network as your camera. Than connect to your vpn from your computer. Now you should be able to access the camera.\nI have a few ideas how to view the camera stream, depending how you would normaly access it.\n\nIf it is a software to connect to the camera, install a desktop-environment on your minicomputer and connect to it via VNC (more or less a linux equivalent to rdp on windows) or RDP. Then open the software and view your stream. It could be a bit laggy because it has to be transmitted two times (camera -> minipc -> your pc)\n\nIf you can access the stream via a url, you could setup a webserver (nginx or apache2) on your minicomputer and build a small html website, that displays the stream. This should be more perfomant than the first solution, but involves a bit more tinkering. If you should decide to use this solution, I should have an example HTML-Page somewhere. Just let me know and i will try to find it and share it.\n\nDepending on how you setup your VPN-Server maybe you can connect to your Camera directly via it's IP. To do that, your VPN-Server has to do some routing between the subnets.\n\n\nI know these are just some Ideas from the top of my head, but I hope I can help a bit. If you have more questions or I didn't explain it in a way it is understandable, feel free to ask again.\n" ]
[ 0 ]
[]
[]
[ "connection", "python", "router", "streaming" ]
stackoverflow_0074558953_connection_python_router_streaming.txt
Q: Convert CSV Blank cell to SQL NULL in Python I'm trying to convert blank cells in a csv file to NULL and upload them in SQL Server table so it shows as NULL rather blank. below code works but they load NULL as a string. Can you please help me to modify the code so it loads NULL in SQL ? reader = csv.reader(f_in) # setup code writer = csv.writer(f_out) row = next(reader) # handle first line (with no replacements) writer.writerow(row) last_row = row # always save the last row of data that we've written variable = None for row in reader: # loop over the rest of the lines row = [x if x else "NULL" for x, y in zip(row, last_row)] # replace empty strings writer.writerow(row) last_row = row with open(outputFileName,'r') as fin: # `with` statement available in 2.5+ dr = csv.DictReader(fin) # comma is default delimiter to_db = [(i['SubFund'], i['Trader'], i['Prime Broker/Clearing Broker']) cur.executemany("INSERT INTO Citco_SPOS (" + "subfund, " + "trader, " + "prime_broker_clearing_broker, " + + "VALUES (?, ?, ?);", to_db) con.commit() A: This should work import pyodbc import csv cnxn = pyodbc.connect(connection string) cur = cnxn.cursor() query = "insert into yourtable values(?, ?)" with open('yourfile.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: for i in range(len(row)): if row[i] == '': row[i] = None cur.execute(query, row) cur.commit() A: I found a great way of doing this. Step 1: Create a function in DB as Below: CREATE FUNCTION dbo.ConvertBlankToNull(@tag nvarchar(100)) RETURNS varchar(100) WITH EXECUTE AS CALLER AS BEGIN Select @tag=IIF(@tag='',NULL,@tag) Return(@tag); END; GO Step 2: Refer below for Cursor.execute statement. cursor.execute("INSERT INTO dbo.NTable (CustomerID) Select dboconvertBlanktonull(?) ", row['Company.internalid'])
Convert CSV Blank cell to SQL NULL in Python
I'm trying to convert blank cells in a csv file to NULL and upload them in SQL Server table so it shows as NULL rather blank. below code works but they load NULL as a string. Can you please help me to modify the code so it loads NULL in SQL ? reader = csv.reader(f_in) # setup code writer = csv.writer(f_out) row = next(reader) # handle first line (with no replacements) writer.writerow(row) last_row = row # always save the last row of data that we've written variable = None for row in reader: # loop over the rest of the lines row = [x if x else "NULL" for x, y in zip(row, last_row)] # replace empty strings writer.writerow(row) last_row = row with open(outputFileName,'r') as fin: # `with` statement available in 2.5+ dr = csv.DictReader(fin) # comma is default delimiter to_db = [(i['SubFund'], i['Trader'], i['Prime Broker/Clearing Broker']) cur.executemany("INSERT INTO Citco_SPOS (" + "subfund, " + "trader, " + "prime_broker_clearing_broker, " + + "VALUES (?, ?, ?);", to_db) con.commit()
[ "This should work\nimport pyodbc\nimport csv\ncnxn = pyodbc.connect(connection string)\ncur = cnxn.cursor()\nquery = \"insert into yourtable values(?, ?)\"\nwith open('yourfile.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for i in range(len(row)):\n if row[i] == '':\n row[i] = None\n cur.execute(query, row) \n cur.commit()\n\n", "I found a great way of doing this.\nStep 1: Create a function in DB as Below:\nCREATE FUNCTION dbo.ConvertBlankToNull(@tag nvarchar(100))\nRETURNS varchar(100)\nWITH EXECUTE AS CALLER\nAS\nBEGIN\n\nSelect @tag=IIF(@tag='',NULL,@tag)\nReturn(@tag);\nEND;\nGO\n\nStep 2: Refer below for Cursor.execute statement.\ncursor.execute(\"INSERT INTO dbo.NTable (CustomerID) \nSelect dboconvertBlanktonull(?) \",\nrow['Company.internalid'])\n" ]
[ 4, 0 ]
[]
[]
[ "csv", "null", "python", "python_3.x", "sql_server" ]
stackoverflow_0041473612_csv_null_python_python_3.x_sql_server.txt
Q: pandas rolling apply function has slow performance The source code in question is import numpy as np dd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x)) df.rolling(window=period, min_periods=1).apply(dd) It takes an extremely long time to execute the above 2 lines of code. It is with latest pandas version(1.4.0). The dataframe has 3000 rows and 2000 columns only. Same code with previous pandas version(0.23.x) provides result much faster. I've tried with other suggessions and questions like Slow performance of pandas groupby/apply but are of not much help. period is a int variable with value 250. A: These are not a solution, at most workarounds for simple cases like the example function. But it confirms the suspicion that the processing speed of df.rolling.apply is anything but optimal. Using a much smaller dataset for obvious reasons import pandas as pd import numpy as np df = pd.DataFrame( np.random.rand(200,100) ) period = 10 res = [0,0] Running time with pandas v1.3.5 %%timeit -n1 -r1 dd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x)) res[0] = df.rolling(window=period, min_periods=1).apply(dd) # 1 loop, best of 1: 8.72 s per loop Against a numpy implementation from numpy.lib.stride_tricks import sliding_window_view as window %%timeit x = window(np.vstack([np.full((period-1,df.shape[1]), np.nan),df.to_numpy()]), period, axis=0) res[1] = np.nanmax(1.0 - x / np.fmax.accumulate(x, axis=-1), axis=-1) # 100 loops, best of 5: 3.39 ms per loop np.testing.assert_allclose(res[0], res[1]) 8.72*1000 / 3.39 = 2572.27 x speedup. Processing columns in chunks l = [] for arr in np.array_split(df.to_numpy(), 100, 1): x = window(np.vstack([np.full((period-1,arr.shape[1]), np.nan),arr]), period, axis=0) l.append(np.nanmax(1.0 - x / np.fmax.accumulate(x, axis=-1), axis=-1)) res[1] = np.hstack(l) # 1 loop, best of 5: 9.15 s per loop for df.shape (2000,2000) Using pandas numba engine We can get even faster with pandas support for numba jitted functions. Unfortunately numba v0.55.1 can't compile ufunc.accumulate. We have to write our own implementation of np.fmax.accumulate (no guarantees on my implementation). Please note that the first call is slower because the function needs to be compiled. def dd_numba(x): res = np.empty_like(x) res[0] = x[0] for i in range(1, len(res)): if res[i-1] > x[i] or np.isnan(x[i]): res[i] = res[i-1] else: res[i] = x[i] return np.nanmax(1.0 - x / res) df.rolling(window=period, min_periods=1).apply(dd_numba, engine='numba', raw=True) We can use the familiar pandas interface and it's ~1.16x faster than my chunked numpy approach for df.shape (2000,2000). A: Take a look at the parallel-pandas library. With its help, you can parallelize the apply method of a sliding window. Thanks Michael Szczesny for dd_numba function. I considered the dataframe of the size you need import pandas as pd import numpy as np from time import monotonic from parallel_pandas import ParallelPandas def dd_numba(x): res = np.empty_like(x) res[0] = x[0] for i in range(1, len(res)): if res[i - 1] > x[i] or np.isnan(x[i]): res[i] = res[i - 1] else: res[i] = x[i] return np.nanmax(1.0 - x / res) if __name__ == '__main__': # initialize parallel-pandas ParallelPandas.initialize(n_cpu=4, split_factor=1) df = pd.DataFrame(np.random.rand(3000, 2000)) period = 250 dd = lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x)) start = monotonic() res = df.rolling(window=period, min_periods=1).apply(dd) print(f'synchronous time took: {monotonic() - start:.1f} s.') start = monotonic() res = df.rolling(window=period, min_periods=1).apply(dd, raw=True) print(f'with raw=True time took: {monotonic() - start:.1f} s.') start = monotonic() res = df.rolling(window=period, min_periods=1).apply(dd_numba, raw=True, engine='numba') print(f'numba engine time took: {monotonic() - start:.1f} s.') start = monotonic() res = df.rolling(window=period, min_periods=1).p_apply(dd, raw=True) print(f'parallel with raw=True time took: {monotonic() - start:.1f} s.') start = monotonic() res = df.rolling(window=period, min_periods=1).p_apply(dd_numba, raw=True, engine='numba') print(f'parallel with raw=True and numba time took: {monotonic() - start:.1f} s.') Output: synchronous time took: 994.6 s. with raw=True time took: 48.6 s. numba engine time took: 9.8 s. parallel with raw=True time took: 13.5 s. parallel with raw=True and numba time took: 1.5 s. 994/1.5 ~ 662.6 x speedup.
pandas rolling apply function has slow performance
The source code in question is import numpy as np dd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x)) df.rolling(window=period, min_periods=1).apply(dd) It takes an extremely long time to execute the above 2 lines of code. It is with latest pandas version(1.4.0). The dataframe has 3000 rows and 2000 columns only. Same code with previous pandas version(0.23.x) provides result much faster. I've tried with other suggessions and questions like Slow performance of pandas groupby/apply but are of not much help. period is a int variable with value 250.
[ "These are not a solution, at most workarounds for simple cases like the example function. But it confirms the suspicion that the processing speed of df.rolling.apply is anything but optimal.\nUsing a much smaller dataset for obvious reasons\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(\n np.random.rand(200,100)\n)\nperiod = 10\nres = [0,0]\n\nRunning time with pandas v1.3.5\n%%timeit -n1 -r1\ndd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x))\nres[0] = df.rolling(window=period, min_periods=1).apply(dd)\n# 1 loop, best of 1: 8.72 s per loop\n\nAgainst a numpy implementation\nfrom numpy.lib.stride_tricks import sliding_window_view as window\n\n%%timeit\nx = window(np.vstack([np.full((period-1,df.shape[1]), np.nan),df.to_numpy()]), period, axis=0)\nres[1] = np.nanmax(1.0 - x / np.fmax.accumulate(x, axis=-1), axis=-1)\n# 100 loops, best of 5: 3.39 ms per loop\n\nnp.testing.assert_allclose(res[0], res[1])\n\n8.72*1000 / 3.39 = 2572.27 x speedup.\n\nProcessing columns in chunks\nl = []\nfor arr in np.array_split(df.to_numpy(), 100, 1):\n x = window(np.vstack([np.full((period-1,arr.shape[1]), np.nan),arr]), period, axis=0)\n l.append(np.nanmax(1.0 - x / np.fmax.accumulate(x, axis=-1), axis=-1))\nres[1] = np.hstack(l)\n# 1 loop, best of 5: 9.15 s per loop for df.shape (2000,2000)\n\n\nUsing pandas numba engine\nWe can get even faster with pandas support for numba jitted functions. Unfortunately numba v0.55.1 can't compile ufunc.accumulate. We have to write our own implementation of np.fmax.accumulate (no guarantees on my implementation). Please note that the first call is slower because the function needs to be compiled.\ndef dd_numba(x):\n res = np.empty_like(x)\n res[0] = x[0]\n for i in range(1, len(res)):\n if res[i-1] > x[i] or np.isnan(x[i]):\n res[i] = res[i-1]\n else:\n res[i] = x[i]\n return np.nanmax(1.0 - x / res)\n\ndf.rolling(window=period, min_periods=1).apply(dd_numba, engine='numba', raw=True)\n\nWe can use the familiar pandas interface and it's ~1.16x faster than my chunked numpy approach for df.shape (2000,2000).\n", "Take a look at the parallel-pandas library. With its help, you can parallelize the apply method of a sliding window. Thanks Michael Szczesny for dd_numba function. I considered the dataframe of the size you need\nimport pandas as pd\nimport numpy as np\nfrom time import monotonic\nfrom parallel_pandas import ParallelPandas\n\n\ndef dd_numba(x):\n res = np.empty_like(x)\n res[0] = x[0]\n for i in range(1, len(res)):\n if res[i - 1] > x[i] or np.isnan(x[i]):\n res[i] = res[i - 1]\n else:\n res[i] = x[i]\n return np.nanmax(1.0 - x / res)\n\n\nif __name__ == '__main__':\n # initialize parallel-pandas\n ParallelPandas.initialize(n_cpu=4, split_factor=1)\n df = pd.DataFrame(np.random.rand(3000, 2000))\n period = 250\n dd = lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x))\n\n start = monotonic()\n res = df.rolling(window=period, min_periods=1).apply(dd)\n print(f'synchronous time took: {monotonic() - start:.1f} s.')\n\n start = monotonic()\n res = df.rolling(window=period, min_periods=1).apply(dd, raw=True)\n print(f'with raw=True time took: {monotonic() - start:.1f} s.')\n\n start = monotonic()\n res = df.rolling(window=period, min_periods=1).apply(dd_numba, raw=True, engine='numba')\n print(f'numba engine time took: {monotonic() - start:.1f} s.')\n\n start = monotonic()\n res = df.rolling(window=period, min_periods=1).p_apply(dd, raw=True)\n print(f'parallel with raw=True time took: {monotonic() - start:.1f} s.')\n start = monotonic()\n res = df.rolling(window=period, min_periods=1).p_apply(dd_numba, raw=True, engine='numba')\n print(f'parallel with raw=True and numba time took: {monotonic() - start:.1f} s.')\n\n\nOutput:\nsynchronous time took: 994.6 s.\nwith raw=True time took: 48.6 s.\nnumba engine time took: 9.8 s.\nparallel with raw=True time took: 13.5 s.\nparallel with raw=True and numba time took: 1.5 s.\n\n994/1.5 ~ 662.6 x speedup.\n" ]
[ 0, 0 ]
[]
[]
[ "apply", "pandas", "pandas_rolling", "python" ]
stackoverflow_0071795937_apply_pandas_pandas_rolling_python.txt
Q: What is the most pythonic way to check if an object is a number? Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector. Checking if something is int, float, long, bool is annoying and doesn't cover user-defined objects that might act like numbers. But, checking for __mul__, for example, isn't good enough because the vector class I just described would define __mul__, but it wouldn't be the kind of number I want. A: Use Number from the numbers module to test isinstance(n, Number) (available since 2.6). >>> from numbers import Number ... from decimal import Decimal ... from fractions import Fraction ... for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']: ... print(f'{n!r:>14} {isinstance(n, Number)}') 2 True 2.0 True Decimal('2.0') True (2+0j) True Fraction(2, 1) True '2' False This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise. A: You want to check if some object acts like a number in certain circumstances If you're using Python 2.5 or older, the only real way is to check some of those "certain circumstances" and see. In 2.6 or better, you can use isinstance with numbers.Number -- an abstract base class (ABC) that exists exactly for this purpose (lots more ABCs exist in the collections module for various forms of collections/containers, again starting with 2.6; and, also only in those releases, you can easily add your own abstract base classes if you need to). Bach to 2.5 and earlier, "can be added to 0 and is not iterable" could be a good definition in some cases. But, you really need to ask yourself, what it is that you're asking that what you want to consider "a number" must definitely be able to do, and what it must absolutely be unable to do -- and check. This may also be needed in 2.6 or later, perhaps for the purpose of making your own registrations to add types you care about that haven't already be registered onto numbers.Numbers -- if you want to exclude some types that claim they're numbers but you just can't handle, that takes even more care, as ABCs have no unregister method [[for example you could make your own ABC WeirdNum and register there all such weird-for-you types, then first check for isinstance thereof to bail out before you proceed to checking for isinstance of the normal numbers.Number to continue successfully. BTW, if and when you need to check if x can or cannot do something, you generally have to try something like: try: 0 + x except TypeError: canadd=False else: canadd=True The presence of __add__ per se tells you nothing useful, since e.g all sequences have it for the purpose of concatenation with other sequences. This check is equivalent to the definition "a number is something such that a sequence of such things is a valid single argument to the builtin function sum", for example. Totally weird types (e.g. ones that raise the "wrong" exception when summed to 0, such as, say, a ZeroDivisionError or ValueError &c) will propagate exception, but that's OK, let the user know ASAP that such crazy types are just not acceptable in good company;-); but, a "vector" that's summable to a scalar (Python's standard library doesn't have one, but of course they're popular as third party extensions) would also give the wrong result here, so (e.g.) this check should come after the "not allowed to be iterable" one (e.g., check that iter(x) raises TypeError, or for the presence of special method __iter__ -- if you're in 2.5 or earlier and thus need your own checks). A brief glimpse at such complications may be sufficient to motivate you to rely instead on abstract base classes whenever feasible...;-). A: This is a good example where exceptions really shine. Just do what you would do with the numeric types and catch the TypeError from everything else. But obviously, this only checks if a operation works, not whether it makes sense! The only real solution for that is to never mix types and always know exactly what typeclass your values belong to. A: Multiply the object by zero. Any number times zero is zero. Any other result means that the object is not a number (including exceptions) def isNumber(x): try: return bool(0 == x*0) except: return False Using isNumber thusly will give the following output: class A: pass def foo(): return 1 for x in [1,1.4, A(), range(10), foo, foo()]: answer = isNumber(x) print('{answer} == isNumber({x})'.format(**locals())) Output: True == isNumber(1) True == isNumber(1.4) False == isNumber(<__main__.A instance at 0x7ff52c15d878>) False == isNumber([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) False == isNumber(<function foo at 0x7ff52c121488>) True == isNumber(1) There probably are some non-number objects in the world that define __mul__ to return zero when multiplied by zero but that is an extreme exception. This solution should cover all normal and sane code that you generate/encouter. numpy.array example: import numpy as np def isNumber(x): try: return bool(x*0 == 0) except: return False x = np.array([0,1]) answer = isNumber(x) print('{answer} == isNumber({x})'.format(**locals())) output: False == isNumber([0 1]) A: To rephrase your question, you are trying to determine whether something is a collection or a single value. Trying to compare whether something is a vector or a number is comparing apples to oranges - I can have a vector of strings or numbers, and I can have a single string or single number. You are interested in how many you have (1 or more), not what type you actually have. my solution for this problem is to check whether the input is a single value or a collection by checking the presence of __len__. For example: def do_mult(foo, a_vector): if hasattr(foo, '__len__'): return sum([a*b for a,b in zip(foo, a_vector)]) else: return [foo*b for b in a_vector] Or, for the duck-typing approach, you can try iterating on foo first: def do_mult(foo, a_vector): try: return sum([a*b for a,b in zip(foo, a_vector)]) except TypeError: return [foo*b for b in a_vector] Ultimately, it is easier to test whether something is vector-like than to test whether something is scalar-like. If you have values of different type (i.e. string, numeric, etc.) coming through, then the logic of your program may need some work - how did you end up trying to multiply a string by a numeric vector in the first place? A: To summarize / evaluate existing methods: Candidate | type | delnan | mat | shrewmouse | ant6n ------------------------------------------------------------------------- 0 | <type 'int'> | 1 | 1 | 1 | 1 0.0 | <type 'float'> | 1 | 1 | 1 | 1 0j | <type 'complex'> | 1 | 1 | 1 | 0 Decimal('0') | <class 'decimal.Decimal'> | 1 | 0 | 1 | 1 True | <type 'bool'> | 1 | 1 | 1 | 1 False | <type 'bool'> | 1 | 1 | 1 | 1 '' | <type 'str'> | 0 | 0 | 0 | 0 None | <type 'NoneType'> | 0 | 0 | 0 | 0 '0' | <type 'str'> | 0 | 0 | 0 | 1 '1' | <type 'str'> | 0 | 0 | 0 | 1 [] | <type 'list'> | 0 | 0 | 0 | 0 [1] | <type 'list'> | 0 | 0 | 0 | 0 [1, 2] | <type 'list'> | 0 | 0 | 0 | 0 (1,) | <type 'tuple'> | 0 | 0 | 0 | 0 (1, 2) | <type 'tuple'> | 0 | 0 | 0 | 0 (I came here by this question) Code #!/usr/bin/env python """Check if a variable is a number.""" import decimal def delnan_is_number(candidate): import numbers return isinstance(candidate, numbers.Number) def mat_is_number(candidate): return isinstance(candidate, (int, long, float, complex)) def shrewmouse_is_number(candidate): try: return 0 == candidate * 0 except: return False def ant6n_is_number(candidate): try: float(candidate) return True except: return False # Test candidates = (0, 0.0, 0j, decimal.Decimal(0), True, False, '', None, '0', '1', [], [1], [1, 2], (1, ), (1, 2)) methods = [delnan_is_number, mat_is_number, shrewmouse_is_number, ant6n_is_number] print("Candidate | type | delnan | mat | shrewmouse | ant6n") print("-------------------------------------------------------------------------") for candidate in candidates: results = [m(candidate) for m in methods] print("{:<12} | {:<25} | {:>6} | {:>3} | {:>10} | {:>5}" .format(repr(candidate), type(candidate), *results)) A: Probably it's better to just do it the other way around: You check if it's a vector. If it is, you do a dot product and in all other cases you attempt scalar multiplication. Checking for the vector is easy, since it should of your vector class type (or inherited from it). You could also just try first to do a dot-product, and if that fails (= it wasn't really a vector), then fall back to scalar multiplication. A: Just to add upon. Perhaps we can use a combination of isinstance and isdigit as follows to find whether a value is a number (int, float, etc) if isinstance(num1, int) or isinstance(num1 , float) or num1.isdigit(): A: can be implemented in a simple try exception block def check_if_number(str1): try: int(float(str1)) return 'number' except: return 'not a number' a = check_if_number('32322') print (a) # number A: For the hypothetical vector class: Suppose v is a vector, and we are multiplying it by x. If it makes sense to multiply each component of v by x, we probably meant that, so try that first. If not, maybe we can dot? Otherwise it's a type error. EDIT -- the below code doesn't work, because 2*[0]==[0,0] instead of raising a TypeError. I leave it because it was commented-upon. def __mul__( self, x ): try: return [ comp * x for comp in self ] except TypeError: return [ x * y for x, y in itertools.zip_longest( self, x, fillvalue = 0 ) A: I had a similar issue, when implementing a sort of vector class. One way to check for a number is to just convert to one, i.e. by using float(x) This should reject cases where x cannot be converted to a number; but may also reject other kinds of number-like structures that could be valid, for example complex numbers. A: If you want to call different methods depending on the argument type(s), look into multipledispatch. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector. from multipledispatch import dispatch class Vector(list): @dispatch(object) def __mul__(self, scalar): return Vector( x*scalar for x in self) @dispatch(list) def __mul__(self, other): return sum(x*y for x,y in zip(self, other)) >>> Vector([1,2,3]) * Vector([2,4,5]) # Vector time Vector is dot product 25 >>> Vector([1,2,3]) * 2 # Vector times scalar is scaling [2, 4, 6] Unfortunately, (to my knowledge) we can't write @dispatch(Vector) since we are still defining the type Vector, so that type name is not yet defined. Instead, I'm using the base type list, which allows you to even find the dot product of a Vector and a list. A: Short and simple way : obj = 12345 print(isinstance(obj,int)) Output : True If the object is a string, 'False' will be returned : obj = 'some string' print(isinstance(obj,int)) Output : False A: You have a data item, say rec_day that when written to a file will be a float. But during program processing it can be either float, int or str type (the str is used when initializing a new record and contains a dummy flag value). You can then check to see if you have a number with this type(rec_day) != str I've structured a python program this way and just put in 'maintenance patch' using this as a numeric check. Is it the Pythonic way? Most likely not since I used to program in COBOL. A: You can use numbers.Number to check if an object is a number. For numbers, Python 3 supports 3 types int, float and complex types so if checking the 3 types of values with numbers.Number as shown below: import numbers print(type(100), isinstance(100, numbers.Number)) print(type(100.23), isinstance(100.23, numbers.Number)) print(type(100 + 2j), isinstance(100 + 2j, numbers.Number)) All return True as shown below: <class 'int'> True <class 'float'> True <class 'complex'> True And, for numbers, Python 2 supperts 4 types int, long, float and complex types so if checking the 4 types of values with numbers.Number as shown below:: import numbers print(type(100), isinstance(100, numbers.Number)) print(type(10000000000000000000), isinstance(10000000000000000000, numbers.Number)) print(type(100.23), isinstance(100.23, numbers.Number)) print(type(100 + 2j), isinstance(100 + 2j, numbers.Number)) All return True as shown below: (<type 'int'>, True) (<type 'long'>, True) (<type 'float'>, True) (<type 'complex'>, True)
What is the most pythonic way to check if an object is a number?
Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector. Checking if something is int, float, long, bool is annoying and doesn't cover user-defined objects that might act like numbers. But, checking for __mul__, for example, isn't good enough because the vector class I just described would define __mul__, but it wouldn't be the kind of number I want.
[ "Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).\n>>> from numbers import Number\n... from decimal import Decimal\n... from fractions import Fraction\n... for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']:\n... print(f'{n!r:>14} {isinstance(n, Number)}')\n 2 True\n 2.0 True\n Decimal('2.0') True\n (2+0j) True\n Fraction(2, 1) True\n '2' False\n\nThis is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.\n", "You want to check if some object\n\nacts like a number in certain\n circumstances\n\nIf you're using Python 2.5 or older, the only real way is to check some of those \"certain circumstances\" and see.\nIn 2.6 or better, you can use isinstance with numbers.Number -- an abstract base class (ABC) that exists exactly for this purpose (lots more ABCs exist in the collections module for various forms of collections/containers, again starting with 2.6; and, also only in those releases, you can easily add your own abstract base classes if you need to).\nBach to 2.5 and earlier,\n\"can be added to 0 and is not iterable\" could be a good definition in some cases. But,\nyou really need to ask yourself, what it is that you're asking that what you want to consider \"a number\" must definitely be able to do, and what it must absolutely be unable to do -- and check.\nThis may also be needed in 2.6 or later, perhaps for the purpose of making your own registrations to add types you care about that haven't already be registered onto numbers.Numbers -- if you want to exclude some types that claim they're numbers but you just can't handle, that takes even more care, as ABCs have no unregister method [[for example you could make your own ABC WeirdNum and register there all such weird-for-you types, then first check for isinstance thereof to bail out before you proceed to checking for isinstance of the normal numbers.Number to continue successfully.\nBTW, if and when you need to check if x can or cannot do something, you generally have to try something like:\ntry: 0 + x\nexcept TypeError: canadd=False\nelse: canadd=True\n\nThe presence of __add__ per se tells you nothing useful, since e.g all sequences have it for the purpose of concatenation with other sequences. This check is equivalent to the definition \"a number is something such that a sequence of such things is a valid single argument to the builtin function sum\", for example. Totally weird types (e.g. ones that raise the \"wrong\" exception when summed to 0, such as, say, a ZeroDivisionError or ValueError &c) will propagate exception, but that's OK, let the user know ASAP that such crazy types are just not acceptable in good company;-); but, a \"vector\" that's summable to a scalar (Python's standard library doesn't have one, but of course they're popular as third party extensions) would also give the wrong result here, so (e.g.) this check should come after the \"not allowed to be iterable\" one (e.g., check that iter(x) raises TypeError, or for the presence of special method __iter__ -- if you're in 2.5 or earlier and thus need your own checks).\nA brief glimpse at such complications may be sufficient to motivate you to rely instead on abstract base classes whenever feasible...;-).\n", "This is a good example where exceptions really shine. Just do what you would do with the numeric types and catch the TypeError from everything else.\nBut obviously, this only checks if a operation works, not whether it makes sense! The only real solution for that is to never mix types and always know exactly what typeclass your values belong to.\n", "Multiply the object by zero. Any number times zero is zero. Any other result means that the object is not a number (including exceptions)\ndef isNumber(x):\n try:\n return bool(0 == x*0)\n except:\n return False\n\nUsing isNumber thusly will give the following output:\nclass A: pass \n\ndef foo(): return 1\n\nfor x in [1,1.4, A(), range(10), foo, foo()]:\n answer = isNumber(x)\n print('{answer} == isNumber({x})'.format(**locals()))\n\nOutput:\nTrue == isNumber(1)\nTrue == isNumber(1.4)\nFalse == isNumber(<__main__.A instance at 0x7ff52c15d878>)\nFalse == isNumber([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\nFalse == isNumber(<function foo at 0x7ff52c121488>)\nTrue == isNumber(1)\n\nThere probably are some non-number objects in the world that define __mul__ to return zero when multiplied by zero but that is an extreme exception. This solution should cover all normal and sane code that you generate/encouter.\nnumpy.array example:\nimport numpy as np\n\ndef isNumber(x):\n try:\n return bool(x*0 == 0)\n except:\n return False\n\nx = np.array([0,1])\n\nanswer = isNumber(x)\nprint('{answer} == isNumber({x})'.format(**locals()))\n\noutput:\nFalse == isNumber([0 1])\n\n", "To rephrase your question, you are trying to determine whether something is a collection or a single value. Trying to compare whether something is a vector or a number is comparing apples to oranges - I can have a vector of strings or numbers, and I can have a single string or single number. You are interested in how many you have (1 or more), not what type you actually have.\nmy solution for this problem is to check whether the input is a single value or a collection by checking the presence of __len__. For example:\ndef do_mult(foo, a_vector):\n if hasattr(foo, '__len__'):\n return sum([a*b for a,b in zip(foo, a_vector)])\n else:\n return [foo*b for b in a_vector]\n\nOr, for the duck-typing approach, you can try iterating on foo first:\ndef do_mult(foo, a_vector):\n try:\n return sum([a*b for a,b in zip(foo, a_vector)])\n except TypeError:\n return [foo*b for b in a_vector]\n\nUltimately, it is easier to test whether something is vector-like than to test whether something is scalar-like. If you have values of different type (i.e. string, numeric, etc.) coming through, then the logic of your program may need some work - how did you end up trying to multiply a string by a numeric vector in the first place?\n", "To summarize / evaluate existing methods:\nCandidate | type | delnan | mat | shrewmouse | ant6n\n-------------------------------------------------------------------------\n0 | <type 'int'> | 1 | 1 | 1 | 1\n0.0 | <type 'float'> | 1 | 1 | 1 | 1\n0j | <type 'complex'> | 1 | 1 | 1 | 0\nDecimal('0') | <class 'decimal.Decimal'> | 1 | 0 | 1 | 1\nTrue | <type 'bool'> | 1 | 1 | 1 | 1\nFalse | <type 'bool'> | 1 | 1 | 1 | 1\n'' | <type 'str'> | 0 | 0 | 0 | 0\nNone | <type 'NoneType'> | 0 | 0 | 0 | 0\n'0' | <type 'str'> | 0 | 0 | 0 | 1\n'1' | <type 'str'> | 0 | 0 | 0 | 1\n[] | <type 'list'> | 0 | 0 | 0 | 0\n[1] | <type 'list'> | 0 | 0 | 0 | 0\n[1, 2] | <type 'list'> | 0 | 0 | 0 | 0\n(1,) | <type 'tuple'> | 0 | 0 | 0 | 0\n(1, 2) | <type 'tuple'> | 0 | 0 | 0 | 0\n\n(I came here by this question)\nCode\n#!/usr/bin/env python\n\n\"\"\"Check if a variable is a number.\"\"\"\n\nimport decimal\n\n\ndef delnan_is_number(candidate):\n import numbers\n return isinstance(candidate, numbers.Number)\n\n\ndef mat_is_number(candidate):\n return isinstance(candidate, (int, long, float, complex))\n\n\ndef shrewmouse_is_number(candidate):\n try:\n return 0 == candidate * 0\n except:\n return False\n\n\ndef ant6n_is_number(candidate):\n try:\n float(candidate)\n return True\n except:\n return False\n\n# Test\ncandidates = (0, 0.0, 0j, decimal.Decimal(0),\n True, False, '', None, '0', '1', [], [1], [1, 2], (1, ), (1, 2))\n\nmethods = [delnan_is_number, mat_is_number, shrewmouse_is_number, ant6n_is_number]\n\nprint(\"Candidate | type | delnan | mat | shrewmouse | ant6n\")\nprint(\"-------------------------------------------------------------------------\")\nfor candidate in candidates:\n results = [m(candidate) for m in methods]\n print(\"{:<12} | {:<25} | {:>6} | {:>3} | {:>10} | {:>5}\"\n .format(repr(candidate), type(candidate), *results))\n\n", "Probably it's better to just do it the other way around: You check if it's a vector. If it is, you do a dot product and in all other cases you attempt scalar multiplication.\nChecking for the vector is easy, since it should of your vector class type (or inherited from it). You could also just try first to do a dot-product, and if that fails (= it wasn't really a vector), then fall back to scalar multiplication.\n", "Just to add upon.\nPerhaps we can use a combination of isinstance and isdigit as follows to find whether a value is a number (int, float, etc)\nif isinstance(num1, int) or isinstance(num1 , float) or num1.isdigit():\n", "can be implemented in a simple try exception block\ndef check_if_number(str1):\n try:\n int(float(str1))\n return 'number'\n except:\n return 'not a number'\n\na = check_if_number('32322')\nprint (a)\n# number\n\n", "For the hypothetical vector class:\nSuppose v is a vector, and we are multiplying it by x. If it makes sense to multiply each component of v by x, we probably meant that, so try that first. If not, maybe we can dot? Otherwise it's a type error.\nEDIT -- the below code doesn't work, because 2*[0]==[0,0] instead of raising a TypeError. I leave it because it was commented-upon.\ndef __mul__( self, x ):\n try:\n return [ comp * x for comp in self ]\n except TypeError:\n return [ x * y for x, y in itertools.zip_longest( self, x, fillvalue = 0 )\n\n", "I had a similar issue, when implementing a sort of vector class. One way to check for a number is to just convert to one, i.e. by using\nfloat(x)\n\nThis should reject cases where x cannot be converted to a number; but may also reject other kinds of number-like structures that could be valid, for example complex numbers.\n", "If you want to call different methods depending on the argument type(s), look into multipledispatch.\n\nFor example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector.\n\nfrom multipledispatch import dispatch\n\nclass Vector(list):\n\n @dispatch(object)\n def __mul__(self, scalar):\n return Vector( x*scalar for x in self)\n\n @dispatch(list)\n def __mul__(self, other):\n return sum(x*y for x,y in zip(self, other))\n\n\n>>> Vector([1,2,3]) * Vector([2,4,5]) # Vector time Vector is dot product\n25\n>>> Vector([1,2,3]) * 2 # Vector times scalar is scaling\n[2, 4, 6]\n\nUnfortunately, (to my knowledge) we can't write @dispatch(Vector) since we are still defining the type Vector, so that type name is not yet defined. Instead, I'm using the base type list, which allows you to even find the dot product of a Vector and a list.\n", "Short and simple way :\nobj = 12345\nprint(isinstance(obj,int))\n\nOutput :\nTrue\n\nIf the object is a string, 'False' will be returned :\nobj = 'some string'\nprint(isinstance(obj,int))\n\nOutput :\nFalse\n\n", "You have a data item, say rec_day that when written to a file will be a float. But during program processing it can be either float, int or str type (the str is used when initializing a new record and contains a dummy flag value).\nYou can then check to see if you have a number with this\n type(rec_day) != str \n\nI've structured a python program this way and just put in 'maintenance patch' using this as a numeric check. Is it the Pythonic way? Most likely not since I used to program in COBOL. \n", "You can use numbers.Number to check if an object is a number.\nFor numbers, Python 3 supports 3 types int, float and complex types so if checking the 3 types of values with numbers.Number as shown below:\nimport numbers\n\nprint(type(100), isinstance(100, numbers.Number))\nprint(type(100.23), isinstance(100.23, numbers.Number))\nprint(type(100 + 2j), isinstance(100 + 2j, numbers.Number))\n\nAll return True as shown below:\n<class 'int'> True\n<class 'float'> True\n<class 'complex'> True\n\nAnd, for numbers, Python 2 supperts 4 types int, long, float and complex types so if checking the 4 types of values with numbers.Number as shown below::\nimport numbers\n\nprint(type(100), isinstance(100, numbers.Number))\nprint(type(10000000000000000000), isinstance(10000000000000000000, numbers.Number))\nprint(type(100.23), isinstance(100.23, numbers.Number))\nprint(type(100 + 2j), isinstance(100 + 2j, numbers.Number))\n\nAll return True as shown below:\n(<type 'int'>, True)\n(<type 'long'>, True)\n(<type 'float'>, True)\n(<type 'complex'>, True)\n\n" ]
[ 160, 33, 17, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "You could use the isdigit() function.\n>>> x = \"01234\"\n>>> a.isdigit()\nTrue\n>>> y = \"1234abcd\"\n>>> y.isdigit()\nFalse\n\n" ]
[ -1 ]
[ "numbers", "python", "types" ]
stackoverflow_0003441358_numbers_python_types.txt
Q: RecursionError: maximum recursion depth exceeded in comparison I hope that this is not a duplicate, I apologise if so, but have done some googling and looking around stack overflow and not found anything as yet... MCVE I understand that if a function keeps calling itself, this can't keep happening indefinitely without a stack overflow, and so an error is raised after a certain limit. For example: def foo(): return foo() foo() This gives rise to the following error: RecursionError: maximum recursion depth exceeded However, if I write a function such as the following: def count(n): if n == 0: return 0 else: return count(n-1)+1 count(1000) I get a slightly different error: RecursionError: maximum recursion depth exceeded in comparison The question What is the "in comparison" referring to in the above error. I guess what I'm asking is what is difference between these two situations, that gives rise to two different errors. A: When a RecursionError is raised, the python interpreter may also offer you the context of the call that caused the error. This only serves for debugging, to give you a hint where in your code you should look in order to fix the problem. See for example this circular str-call setup that leads to a different message: >>> class A: ... def __str__(self): ... return str(self.parent) >>> a = A() >>> a.parent = a >>> str(a) RecursionError: maximum recursion depth exceeded while calling a Python object There is no documentation of this behaviour on the issue discussion where RecursionError was introduced, but you can just search the cpython code for occurences of Py_EnterRecursiveCall. Then you can see the actual contexts that will be returned depending on where the error is raised: Py_EnterRecursiveCall(" while encoding a JSON object") Py_EnterRecursiveCall(" while pickling an object") Py_EnterRecursiveCall(" in __instancecheck__") Py_EnterRecursiveCall(" in __subclasscheck__") Py_EnterRecursiveCall(" in comparison") Py_EnterRecursiveCall(" while getting the repr of an object") Py_EnterRecursiveCall(" while getting the str of an object") Py_EnterRecursiveCall(" while calling a Python object") Py_EnterRecursiveCall("while processing _as_parameter_") # sic # .. and some more that I might have missed A: I played around with it and found some interesting results. As we know: def foo(): foo() Gives rise to RecursionError: maximum recursion depth exceeded What I found was def bar(): if False: return 0 else: bar() def baz(): if True: baz() else: return 0 Both bar() and baz() give rise to RecursionError: maximum recursion depth exceeded And then def ding(): if 1 == 2: return 0 else: ding() def dong(): if 1 != 2: dong() else: return 0 Both ding() and dong() give rise to RecursionError: maximum recursion depth exceeded in comparison My intuition here is that python knows you are doing a comparison using the comparators =,!,<,> and that this comparison never reaches the 'base case' condition (within the limits of the maximum depth). So python is letting you know that your comparison never converges to meet the condition. This helpfulness starts to break down when you try def oops(): if 1 == 2: oops() else: oops() But in the end python can only be so helpful with error messages. A: A similar RecursionError issue occured in my code with following errors: File "C:\Users\xx\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\backends\_backend_tk.py", line 473, in flush_events self._master.update() . . . File "C:\Users\xxx\AppData\Local\Programs\Python\Python37-32\lib\abc.py", line 139, in __instancecheck__ return _abc_instancecheck(cls, instance) RecursionError: maximum recursion depth exceeded in comparison After removing the self.canvas.flush_events() line in my code below, the problem is resolved. def update(self, k=1, step = 1): if self.start.get() and not self.is_paused.get(): idx = [i for i in range(0,k,1)][-1] x_data.append(idx) y_data.append(np.sin(idx/5)) self.line.set_data(x_data, y_data) self.fig.gca().relim() self.fig.gca().autoscale_view() self.canvas.draw() #self.canvas.flush_events() k += step if k <= self.voltage_range.get(): self.after(100, self.update, k)
RecursionError: maximum recursion depth exceeded in comparison
I hope that this is not a duplicate, I apologise if so, but have done some googling and looking around stack overflow and not found anything as yet... MCVE I understand that if a function keeps calling itself, this can't keep happening indefinitely without a stack overflow, and so an error is raised after a certain limit. For example: def foo(): return foo() foo() This gives rise to the following error: RecursionError: maximum recursion depth exceeded However, if I write a function such as the following: def count(n): if n == 0: return 0 else: return count(n-1)+1 count(1000) I get a slightly different error: RecursionError: maximum recursion depth exceeded in comparison The question What is the "in comparison" referring to in the above error. I guess what I'm asking is what is difference between these two situations, that gives rise to two different errors.
[ "When a RecursionError is raised, the python interpreter may also offer you the context of the call that caused the error. This only serves for debugging, to give you a hint where in your code you should look in order to fix the problem.\nSee for example this circular str-call setup that leads to a different message:\n>>> class A:\n... def __str__(self):\n... return str(self.parent)\n>>> a = A()\n>>> a.parent = a\n>>> str(a)\nRecursionError: maximum recursion depth exceeded while calling a Python object\n\n\nThere is no documentation of this behaviour on the issue discussion where RecursionError was introduced, but you can just search the cpython code for occurences of Py_EnterRecursiveCall. Then you can see the actual contexts that will be returned depending on where the error is raised:\nPy_EnterRecursiveCall(\" while encoding a JSON object\")\nPy_EnterRecursiveCall(\" while pickling an object\")\nPy_EnterRecursiveCall(\" in __instancecheck__\")\nPy_EnterRecursiveCall(\" in __subclasscheck__\")\nPy_EnterRecursiveCall(\" in comparison\")\nPy_EnterRecursiveCall(\" while getting the repr of an object\")\nPy_EnterRecursiveCall(\" while getting the str of an object\")\nPy_EnterRecursiveCall(\" while calling a Python object\")\nPy_EnterRecursiveCall(\"while processing _as_parameter_\") # sic\n# .. and some more that I might have missed\n\n", "I played around with it and found some interesting results.\nAs we know:\ndef foo():\n foo()\n\nGives rise to \nRecursionError: maximum recursion depth exceeded\n\nWhat I found was\ndef bar():\n if False:\n return 0\n else:\n bar()\n\ndef baz():\n if True:\n baz()\n else:\n return 0\n\nBoth bar() and baz() give rise to \nRecursionError: maximum recursion depth exceeded\n\nAnd then \ndef ding():\n if 1 == 2:\n return 0\n else:\n ding()\n\ndef dong():\n if 1 != 2:\n dong()\n else:\n return 0\n\nBoth ding() and dong() give rise to \nRecursionError: maximum recursion depth exceeded in comparison\n\nMy intuition here is that python knows you are doing a comparison using the comparators =,!,<,> and that this comparison never reaches the 'base case' condition (within the limits of the maximum depth). So python is letting you know that your comparison never converges to meet the condition.\nThis helpfulness starts to break down when you try\ndef oops():\n if 1 == 2:\n oops()\n else:\n oops()\n\nBut in the end python can only be so helpful with error messages.\n", "A similar RecursionError issue occured in my code with following errors:\nFile \"C:\\Users\\xx\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\matplotlib\\backends\\_backend_tk.py\", line 473, in flush_events\nself._master.update()\n.\n.\n.\n\nFile \"C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\abc.py\", line 139, in __instancecheck__\nreturn _abc_instancecheck(cls, instance)\nRecursionError: maximum recursion depth exceeded in comparison\n\nAfter removing the self.canvas.flush_events() line in my code below, the problem is resolved.\ndef update(self, k=1, step = 1):\n\n if self.start.get() and not self.is_paused.get(): \n idx = [i for i in range(0,k,1)][-1]\n x_data.append(idx)\n y_data.append(np.sin(idx/5))\n self.line.set_data(x_data, y_data)\n self.fig.gca().relim()\n self.fig.gca().autoscale_view()\n self.canvas.draw()\n #self.canvas.flush_events()\n k += step\n \n if k <= self.voltage_range.get():\n \n self.after(100, self.update, k)\n\n" ]
[ 10, 7, 0 ]
[]
[]
[ "python", "python_3.x", "recursion" ]
stackoverflow_0052873067_python_python_3.x_recursion.txt
Q: create multiple list from a list taking every nth item using for loop in python test_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18'] my_result = {'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'], 'list_b': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'], 'list_c': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']} here is a example of test_list and my_result. i want to create multiple lists from a list taking every nth item using for loop in python. I tried but failed. Can anyone help me solving this probem? thanks in advance. A: You can use mod: list_a = [] list_b = [] list_c = [] for i in range(len(test_list)): if i % 3 == 0: list_a.append(test_list[i]) if i % 3 == 1: list_b.append(test_list[i]) if i % 3 == 2: list_c.append(test_list[i]) A: num_list = 3 out = dict(zip([f'list_{i}' for i in range(1, num_list+1)], [[test_list[j] for j in range(i, len(test_list), num_list)] for i in range(num_list)])) # {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'], # 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'], # 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']} A: you can do the following and generalize your code using a function def reorder_list(original_list, interval): return {f"list_{i+1}": original_list[i::interval] for i in range(interval)} reorder_list(test_list, 3) >>> {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'], 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'], 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']} A: try this: result={} for i in range (0,n): result[f"list_{i}"]=test_list[i::n]
create multiple list from a list taking every nth item using for loop in python
test_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18'] my_result = {'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'], 'list_b': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'], 'list_c': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']} here is a example of test_list and my_result. i want to create multiple lists from a list taking every nth item using for loop in python. I tried but failed. Can anyone help me solving this probem? thanks in advance.
[ "You can use mod:\nlist_a = []\nlist_b = []\nlist_c = []\n\n\nfor i in range(len(test_list)):\n if i % 3 == 0:\n list_a.append(test_list[i])\n if i % 3 == 1:\n list_b.append(test_list[i])\n if i % 3 == 2:\n list_c.append(test_list[i])\n\n", "num_list = 3\n\nout = dict(zip([f'list_{i}' for i in range(1, num_list+1)], [[test_list[j] for j in range(i, len(test_list), num_list)] for i in range(num_list)]))\n\n# {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],\n# 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],\n# 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}\n\n", "you can do the following and generalize your code using a function\ndef reorder_list(original_list, interval):\n return {f\"list_{i+1}\": original_list[i::interval] for i in range(interval)}\n\n\nreorder_list(test_list, 3) \n>>> {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],\n 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],\n 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}\n\n", "try this:\nresult={}\nfor i in range (0,n):\n result[f\"list_{i}\"]=test_list[i::n]\n\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "set" ]
stackoverflow_0074559692_dictionary_list_python_set.txt
Q: How to validate the enum values for python dataclass attributes I have a dataclass and enum values which are as below: @dataclass class my_class: id: str dataType: CheckTheseDataTypes class CheckTheseDataTypes(str,Enum): FIRST="int" SECOND="float" THIRD = "string" I want to check whenever this dataclass is called it should have the datatype values only from the given enum list. I wrote an external validator initially like the below: if datatype not in CheckTheseDataTypes.__members__: I am actually looking for something where I don't need this external validation. Any help is much appreciated. A: You can use the post_init() method to do that. from enum import Enum from dataclasses import dataclass class CheckTheseDataTypes(str, Enum): FIRST = "int" SECOND = "float" THIRD = "string" @dataclass class MyClass: id: str data_type: CheckTheseDataTypes def __post_init__(self): if self.data_type not in list(CheckTheseDataTypes): raise ValueError('data_type id not a valid value') data = MyClass(id='abc', data_type="wrong_type") A couple of side notes: By convention class should use the CamelCase naming style The order of things matters. Python reads code top to bottom, so by having the Enum under the @dataclass you will get a NameError: name 'CheckTheseDataTypes' is not defined Hope this helps :)
How to validate the enum values for python dataclass attributes
I have a dataclass and enum values which are as below: @dataclass class my_class: id: str dataType: CheckTheseDataTypes class CheckTheseDataTypes(str,Enum): FIRST="int" SECOND="float" THIRD = "string" I want to check whenever this dataclass is called it should have the datatype values only from the given enum list. I wrote an external validator initially like the below: if datatype not in CheckTheseDataTypes.__members__: I am actually looking for something where I don't need this external validation. Any help is much appreciated.
[ "You can use the post_init() method to do that.\nfrom enum import Enum\nfrom dataclasses import dataclass\n\n\nclass CheckTheseDataTypes(str, Enum):\n FIRST = \"int\"\n SECOND = \"float\"\n THIRD = \"string\"\n\n\n@dataclass\nclass MyClass:\n id: str\n data_type: CheckTheseDataTypes\n\n def __post_init__(self):\n if self.data_type not in list(CheckTheseDataTypes):\n raise ValueError('data_type id not a valid value')\n\n\ndata = MyClass(id='abc', data_type=\"wrong_type\")\n\nA couple of side notes:\n\nBy convention class should use the CamelCase naming style\nThe order of things matters. Python reads code top to bottom,\nso by having the Enum under the @dataclass you will get a NameError: name 'CheckTheseDataTypes' is not defined\n\nHope this helps :)\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074559603_python_python_3.x.txt
Q: Visualizing multiple all point clouds with .bin format as a video from Lidar - Open3d I generated several point clouds in .bin files through velodyne and would like to view the various point clouds as a video or animation. My files 000000.bin to 007480.bin are from a route with a LIDAR turned on until the end of the path and they are all in a directory called ../velodyne/ and I'm running a Deep learning model called OpenPCDet and it's time to run the demo.py with the following command: python demo.py --cfg_file cfgs/kitti_models/pointrcnn.yaml --ckpt ../OpenPCDet/stev_models/pointrcnn_7870.pth --data_path ../OpenPCDet/data/ kitti/training/velodyne/ enter image description here the result I have is that it opens an image through the Open3D visualizer but I have to keep clicking Q (quit) or ESC to close the window and the code read the next image. My goal is to run demo.py and it will read all the .bin files at once and do the detection with OpenPCDet model treined. https://github.com/open-mmlab/OpenPCDet/blob/master/tools/demo.py I've already installed everything you need, now I have to run it as if it were a video already detecting the objects I trained... A: You can modify the demo.py script to achive that. Mayavi is capable of saving the images as .png-s in a specific folders. Insert the following under the plot: #import import mayavi.mlab as mlab #The draw scene plot already in demo.py, just to show where to insert V.draw_scenes(points=data_dict['points'][:, 1:], ref_boxes=pred_dicts[0] ['pred_boxes'], ref_scores=pred_dicts[0]['pred_scores'], ref_labels=pred_dicts[0] ['pred_labels']) #Setting the view and distance, place this under mlab.view(180, 85) mlab.view(distance=40) #Stop showing, you don't have to use Q or ESC mlab.show(stop=True) #Path to save the image mlab.savefig('/home/OpenPCDet/data/prediction_results/' + str(i).zfill(6) + ".png") mlab.close(all=True) Since this is inserted in the loop of for idx, data_dict in enumerate(demo_dataset) it is going to iterate over all the bin-s you have. After this, you can connect the exported images into a video with another script. Like this: https://stackoverflow.com/a/44948030/16495145 Note, this works well if you are happy with the clouds to be "converted" to png-s.
Visualizing multiple all point clouds with .bin format as a video from Lidar - Open3d
I generated several point clouds in .bin files through velodyne and would like to view the various point clouds as a video or animation. My files 000000.bin to 007480.bin are from a route with a LIDAR turned on until the end of the path and they are all in a directory called ../velodyne/ and I'm running a Deep learning model called OpenPCDet and it's time to run the demo.py with the following command: python demo.py --cfg_file cfgs/kitti_models/pointrcnn.yaml --ckpt ../OpenPCDet/stev_models/pointrcnn_7870.pth --data_path ../OpenPCDet/data/ kitti/training/velodyne/ enter image description here the result I have is that it opens an image through the Open3D visualizer but I have to keep clicking Q (quit) or ESC to close the window and the code read the next image. My goal is to run demo.py and it will read all the .bin files at once and do the detection with OpenPCDet model treined. https://github.com/open-mmlab/OpenPCDet/blob/master/tools/demo.py I've already installed everything you need, now I have to run it as if it were a video already detecting the objects I trained...
[ "You can modify the demo.py script to achive that.\nMayavi is capable of saving the images as .png-s in a specific folders.\nInsert the following under the plot:\n#import\nimport mayavi.mlab as mlab\n\n#The draw scene plot already in demo.py, just to show where to insert\nV.draw_scenes(points=data_dict['points'][:, 1:], ref_boxes=pred_dicts[0] \n['pred_boxes'],\nref_scores=pred_dicts[0]['pred_scores'], ref_labels=pred_dicts[0] \n['pred_labels'])\n#Setting the view and distance, place this under\nmlab.view(180, 85)\nmlab.view(distance=40)\n#Stop showing, you don't have to use Q or ESC\nmlab.show(stop=True)\n#Path to save the image\nmlab.savefig('/home/OpenPCDet/data/prediction_results/' + \nstr(i).zfill(6) + \".png\")\nmlab.close(all=True)\n\nSince this is inserted in the loop of\nfor idx, data_dict in enumerate(demo_dataset) it is going to iterate over all the bin-s you have.\nAfter this, you can connect the exported images into a video with another script. Like this: https://stackoverflow.com/a/44948030/16495145\nNote, this works well if you are happy with the clouds to be \"converted\" to png-s.\n" ]
[ 0 ]
[]
[]
[ "lidar_data", "linux", "open3d", "python", "python_3.x" ]
stackoverflow_0074184928_lidar_data_linux_open3d_python_python_3.x.txt
Q: Switch rows and columns of a multindex dataframe created from nested dictionary I converted the following nested dictionary into a data frame: dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}}, 'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}} df = pd.DataFrame.from_dict({(i,j): dic[i][j] for i in dic.keys() for j in dic[i].keys() }) The data frame looks: Current Output How can I switch the columns Traffic and Sales into the rows? To get an output of this sort: Required Output A: Use collections.defaultdict: from collections import defaultdict d1 = defaultdict(dict) for k, v in dic.items(): for k1, v1 in v.items(): for k2, v2 in v1.items(): d1[(k, k2)].update({k1: v2}) df = pd.DataFrame(d1) print(df) US UK new repeat new repeat Traffic 1415 670 230 156 Sales 67068 105677 4568 10738 Your solution should be changed with DataFrame.stack and Series.unstack: df = pd.DataFrame.from_dict({(i,j): dic[i][j] for i in dic.keys() for j in dic[i].keys() }).stack().unstack(0) print(df) UK US new repeat new repeat Sales 4568 10738 67068 105677 Traffic 230 156 1415 670
Switch rows and columns of a multindex dataframe created from nested dictionary
I converted the following nested dictionary into a data frame: dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}}, 'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}} df = pd.DataFrame.from_dict({(i,j): dic[i][j] for i in dic.keys() for j in dic[i].keys() }) The data frame looks: Current Output How can I switch the columns Traffic and Sales into the rows? To get an output of this sort: Required Output
[ "Use collections.defaultdict:\nfrom collections import defaultdict\n\nd1 = defaultdict(dict)\n\nfor k, v in dic.items():\n for k1, v1 in v.items():\n for k2, v2 in v1.items():\n d1[(k, k2)].update({k1: v2})\n\ndf = pd.DataFrame(d1)\nprint(df)\n US UK \n new repeat new repeat\nTraffic 1415 670 230 156\nSales 67068 105677 4568 10738\n\nYour solution should be changed with DataFrame.stack and Series.unstack:\ndf = pd.DataFrame.from_dict({(i,j): dic[i][j]\n for i in dic.keys()\n for j in dic[i].keys()\n }).stack().unstack(0)\nprint(df)\n UK US \n new repeat new repeat\nSales 4568 10738 67068 105677\nTraffic 230 156 1415 670\n\n" ]
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074559739_pandas_python.txt
Q: I'm getting an Atribute Error in the following Question, can someone help me to figure out the problem import re phonenumregex=re.compile(r'ddd-ddd-dddd') mo=phonenumregex.search("My number is 415-555-4242") print("Phone Number found: " + mo.group()) #it gives me this error. AttributeError: 'NoneType' object has no attribute 'group' I gave the format as ddd-ddd-dddd in raw string. and was expecting to get the number 415-555-4242 in return A: Your regec should be correct, \d not d import re # phonenumregex=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') phonenumregex=re.compile(r'\d{3}-\d{3}-\d{4}') mo=phonenumregex.search("My number is 415-555-4242") print("Phone Number found: " + mo.group()) A: For regex \d is for digit so you can use '\d': For example: import re phonenumregex=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo=phonenumregex.search("My number is 415-555-4242") print("Phone Number found: " + mo.group()) Output: Phone Number found: 415-555-4242
I'm getting an Atribute Error in the following Question, can someone help me to figure out the problem
import re phonenumregex=re.compile(r'ddd-ddd-dddd') mo=phonenumregex.search("My number is 415-555-4242") print("Phone Number found: " + mo.group()) #it gives me this error. AttributeError: 'NoneType' object has no attribute 'group' I gave the format as ddd-ddd-dddd in raw string. and was expecting to get the number 415-555-4242 in return
[ "Your regec should be correct, \\d not d\nimport re\n# phonenumregex=re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\nphonenumregex=re.compile(r'\\d{3}-\\d{3}-\\d{4}')\nmo=phonenumregex.search(\"My number is 415-555-4242\")\nprint(\"Phone Number found: \" + mo.group())\n\n", "For regex \\d is for digit so you can use '\\d':\nFor example:\nimport re\nphonenumregex=re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\nmo=phonenumregex.search(\"My number is 415-555-4242\")\nprint(\"Phone Number found: \" + mo.group())\n\nOutput:\nPhone Number found: 415-555-4242\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074558031_python_python_re.txt
Q: Can I get a sub-DataFrame according to first letter in columns names? I want to get only columns whose names start with 'Q1' and those starting with 'Q3', I know that this is possible by doing: new_df=df[['Q1_1', 'Q1_2', 'Q1_3','Q3_1', 'Q3_2', 'Q3_3']] But since my real df is too large (more than 70 variables) I search a way to get the new_df by using only desired first letters in the columns titles. My example dataframe is: df=pd.DataFrame({ 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': [np.random.randint(1,100) for i in range(10)], 'Q2_2': np.random.random(10), 'Q2_3': np.random.randint(2, size=10), 'Q3_1': [np.random.randint(1,100) for i in range(10)], 'Q3_2': np.random.random(10), 'Q3_3': np.random.randint(2, size=10), 'Q4_1': [np.random.randint(1,100) for i in range(10)], 'Q4_2': np.random.random(10), 'Q4_3': np.random.randint(2, size=10) }) df has the following display: Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3 0 92 0.551722 1 36 0.063269 1 95 0.541573 1 91 0.521076 1 1 89 0.951076 1 82 0.853572 1 49 0.782290 1 98 0.232572 0 2 88 0.909953 1 19 0.544450 1 66 0.021061 1 51 0.951225 0 3 66 0.904642 1 17 0.727190 1 85 0.697792 0 35 0.412844 1 4 78 0.802783 1 23 0.634575 1 77 0.759861 0 55 0.460012 0 5 41 0.943271 1 63 0.460578 1 95 0.004986 1 89 0.970059 0 6 54 0.600558 0 18 0.031487 0 84 0.716314 0 84 0.636364 1 7 2 0.458006 0 95 0.029421 0 10 0.927356 1 27 0.031572 1 8 38 0.029658 1 30 0.125706 1 94 0.096702 1 32 0.241613 1 9 52 0.584300 1 85 0.026642 0 78 0.358952 0 70 0.696008 0 I want a simpler way to get the following sub-df: Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3 0 92 0.551722 1 95 0.541573 1 1 89 0.951076 1 49 0.782290 1 2 88 0.909953 1 66 0.021061 1 3 66 0.904642 1 85 0.697792 0 4 78 0.802783 1 77 0.759861 0 5 41 0.943271 1 95 0.004986 1 6 54 0.600558 0 84 0.716314 0 7 2 0.458006 0 10 0.927356 1 8 38 0.029658 1 94 0.096702 1 9 52 0.584300 1 78 0.358952 0 Please if you need more detail let me know in comments, Any help from your side will be highly appreciated. A: You can use pd.DataFrame.filter for this: df.filter(regex = r'Q1_\d|Q3_\d') Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3 0 5 0.631041 0 46 0.768563 0 1 32 0.594106 1 46 0.982396 1 2 78 0.703139 1 38 0.252107 0 3 98 0.353230 0 35 0.324079 0 4 77 0.913203 1 11 0.456287 0 5 62 0.565350 1 77 0.387365 0 6 38 0.975652 1 59 0.276421 1 7 97 0.505808 1 84 0.035756 0 8 15 0.525452 0 57 0.675310 1 9 94 0.545259 0 25 0.628030 0 A: You may use list comprehension to get the desired column headers like this: cols = [col for col in df.columns if col[:2] in ('Q1', 'Q3')] new_df = df[cols].copy()
Can I get a sub-DataFrame according to first letter in columns names?
I want to get only columns whose names start with 'Q1' and those starting with 'Q3', I know that this is possible by doing: new_df=df[['Q1_1', 'Q1_2', 'Q1_3','Q3_1', 'Q3_2', 'Q3_3']] But since my real df is too large (more than 70 variables) I search a way to get the new_df by using only desired first letters in the columns titles. My example dataframe is: df=pd.DataFrame({ 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': [np.random.randint(1,100) for i in range(10)], 'Q2_2': np.random.random(10), 'Q2_3': np.random.randint(2, size=10), 'Q3_1': [np.random.randint(1,100) for i in range(10)], 'Q3_2': np.random.random(10), 'Q3_3': np.random.randint(2, size=10), 'Q4_1': [np.random.randint(1,100) for i in range(10)], 'Q4_2': np.random.random(10), 'Q4_3': np.random.randint(2, size=10) }) df has the following display: Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3 0 92 0.551722 1 36 0.063269 1 95 0.541573 1 91 0.521076 1 1 89 0.951076 1 82 0.853572 1 49 0.782290 1 98 0.232572 0 2 88 0.909953 1 19 0.544450 1 66 0.021061 1 51 0.951225 0 3 66 0.904642 1 17 0.727190 1 85 0.697792 0 35 0.412844 1 4 78 0.802783 1 23 0.634575 1 77 0.759861 0 55 0.460012 0 5 41 0.943271 1 63 0.460578 1 95 0.004986 1 89 0.970059 0 6 54 0.600558 0 18 0.031487 0 84 0.716314 0 84 0.636364 1 7 2 0.458006 0 95 0.029421 0 10 0.927356 1 27 0.031572 1 8 38 0.029658 1 30 0.125706 1 94 0.096702 1 32 0.241613 1 9 52 0.584300 1 85 0.026642 0 78 0.358952 0 70 0.696008 0 I want a simpler way to get the following sub-df: Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3 0 92 0.551722 1 95 0.541573 1 1 89 0.951076 1 49 0.782290 1 2 88 0.909953 1 66 0.021061 1 3 66 0.904642 1 85 0.697792 0 4 78 0.802783 1 77 0.759861 0 5 41 0.943271 1 95 0.004986 1 6 54 0.600558 0 84 0.716314 0 7 2 0.458006 0 10 0.927356 1 8 38 0.029658 1 94 0.096702 1 9 52 0.584300 1 78 0.358952 0 Please if you need more detail let me know in comments, Any help from your side will be highly appreciated.
[ "You can use pd.DataFrame.filter for this:\ndf.filter(regex = r'Q1_\\d|Q3_\\d')\n\n Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3\n0 5 0.631041 0 46 0.768563 0\n1 32 0.594106 1 46 0.982396 1\n2 78 0.703139 1 38 0.252107 0\n3 98 0.353230 0 35 0.324079 0\n4 77 0.913203 1 11 0.456287 0\n5 62 0.565350 1 77 0.387365 0\n6 38 0.975652 1 59 0.276421 1\n7 97 0.505808 1 84 0.035756 0\n8 15 0.525452 0 57 0.675310 1\n9 94 0.545259 0 25 0.628030 0\n\n", "You may use list comprehension to get the desired column headers like this:\ncols = [col for col in df.columns if col[:2] in ('Q1', 'Q3')]\nnew_df = df[cols].copy()\n\n" ]
[ 4, 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074559691_dataframe_pandas_python.txt
Q: Show another image while showing one image in loop in opencv python I am trying to show an image, named "Result", And if a person clicks on the image then, it should show another image, named "Result image", but after clicking, the image Result which has to be live input from webcam freezes. Can anyone help me with this ? Here is my code : import cv2 cap = cv2.VideoCapture(0) def showImage(event,x,y,flags,param): if event == 1: cv2.imshow('Result Image', img) cv2.namedWindow('Result') cv2.setMouseCallback('Result', showImage) while True: _, img = cap.read() cv2.imshow('Result', img) cv2.waitKey(1) I have tried to set the waitKey(1) if the image is clicked in the if event == 1 statement A: This code worked for me: import cv2 def showImage(event,x,y,flags,param): if event == 1: cv2.imshow('Result Image', img) cv2.namedWindow('Result') cv2.setMouseCallback('Result', showImage) cv2.namedWindow('Result Image') cap = cv2.VideoCapture(0) while True: _, img = cap.read() cv2.imshow('Result', img) if cv2.waitKey(1) != -1: break cv2.destroyAllWindows()
Show another image while showing one image in loop in opencv python
I am trying to show an image, named "Result", And if a person clicks on the image then, it should show another image, named "Result image", but after clicking, the image Result which has to be live input from webcam freezes. Can anyone help me with this ? Here is my code : import cv2 cap = cv2.VideoCapture(0) def showImage(event,x,y,flags,param): if event == 1: cv2.imshow('Result Image', img) cv2.namedWindow('Result') cv2.setMouseCallback('Result', showImage) while True: _, img = cap.read() cv2.imshow('Result', img) cv2.waitKey(1) I have tried to set the waitKey(1) if the image is clicked in the if event == 1 statement
[ "This code worked for me:\nimport cv2\n\ndef showImage(event,x,y,flags,param):\n if event == 1:\n\n cv2.imshow('Result Image', img)\n\ncv2.namedWindow('Result')\ncv2.setMouseCallback('Result', showImage)\ncv2.namedWindow('Result Image')\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n _, img = cap.read()\n\n cv2.imshow('Result', img)\n\n if cv2.waitKey(1) != -1: break\n\ncv2.destroyAllWindows()\n\n" ]
[ 0 ]
[]
[]
[ "cv2", "python" ]
stackoverflow_0074547237_cv2_python.txt
Q: Can't generate Python docstring with autoDocstring extension in VS Code when multiline string in the function body To generate documentation with Python Sphinx I have to use a specific docstring format. VS Code extension autoDocstring is capable to generate this specific format, but if the function contains multiline string then it doesn't work. Example in this case works: def func(param1, param2, param3): # docstring nicely generated """_summary_ :param param1: _description_ :type param1: _type_ :param param2: _description_ :type param2: _type_ :param param3: _description_ :type param3: _type_ :return: _description_ :rtype: _type_ """ random_variable = 42 string_variable = "not a multiline string" return string_variable But in this case can't generate auto docstring: def func(param1, param2, param3): # doesn't work """""" random_variable = 42 string_variable = """ a multiline string """ return string_variable Anyone know a trick, or something to make it work? I use a lot of multiline SQL strings in my functions and if I have to extract these strings just to make it work I need a lot of refactoring. A: Keyboard shortcut: ctrl+shift+2 or cmd+shift+2 for mac A: I figured out the solution and I post it here, maybe will help somebody. Actually the solution is pretty straightforward. I changed the triple apostrophes to triple single quotes in the function/class/whatever string variable and now autoDocstring's parser doesn't get confused. Example: def func(param1, param2, param3): # autoDocstring works """_summary_ :param param1: _description_ :type param1: _type_ :param param2: _description_ :type param2: _type_ :param param3: _description_ :type param3: _type_ :return: _description_ :rtype: _type_ """ random_variable = 42 string_variable = ''' a multiline string ''' return string_variable
Can't generate Python docstring with autoDocstring extension in VS Code when multiline string in the function body
To generate documentation with Python Sphinx I have to use a specific docstring format. VS Code extension autoDocstring is capable to generate this specific format, but if the function contains multiline string then it doesn't work. Example in this case works: def func(param1, param2, param3): # docstring nicely generated """_summary_ :param param1: _description_ :type param1: _type_ :param param2: _description_ :type param2: _type_ :param param3: _description_ :type param3: _type_ :return: _description_ :rtype: _type_ """ random_variable = 42 string_variable = "not a multiline string" return string_variable But in this case can't generate auto docstring: def func(param1, param2, param3): # doesn't work """""" random_variable = 42 string_variable = """ a multiline string """ return string_variable Anyone know a trick, or something to make it work? I use a lot of multiline SQL strings in my functions and if I have to extract these strings just to make it work I need a lot of refactoring.
[ "Keyboard shortcut: ctrl+shift+2 or cmd+shift+2 for mac\n", "I figured out the solution and I post it here, maybe will help somebody.\nActually the solution is pretty straightforward.\nI changed the triple apostrophes to triple single quotes in the function/class/whatever string variable and now autoDocstring's parser doesn't get confused.\nExample:\ndef func(param1, param2, param3):\n # autoDocstring works\n \"\"\"_summary_\n\n :param param1: _description_\n :type param1: _type_\n :param param2: _description_\n :type param2: _type_\n :param param3: _description_\n :type param3: _type_\n :return: _description_\n :rtype: _type_\n \"\"\"\n\n random_variable = 42\n string_variable = '''\n a \n multiline\n string\n '''\n\n return string_variable\n\n" ]
[ 0, 0 ]
[]
[]
[ "docstring", "python", "visual_studio_code" ]
stackoverflow_0071211181_docstring_python_visual_studio_code.txt
Q: Cythonize Package & Tox Testing I am developing a pypi-package (*.py-files), which is being tested via tox. Since compiling the package might yield some performance improvements, I'd like to cythonize it, and also verify using tox that the package is compiled. For this purpose, I have made the following adjustments: setup.py additions: import pathlib from setuptools import setup from Cython.Build import cythonize setup( install_requires=[ "Cython>=0.29.21" #<-- new ], ext_modules=cythonize("mypackage_name/*.py"), #<-- new ) pyproject.toml created: [build-system] requires = ["setuptools", "wheel", "Cython>=0.29.21"] build-backend = "setuptools.build_meta" And added the following to my existing tox.ini: [tox] envlist = py{310, 311} isolated_build = true ;<-- new [testenv] deps = -rrequirements.txt commands = python -m pytest tests -s In order to test if this is working, I've added the following to a python file in my package: def compiled() -> bool: import Cython return Cython.compiled I have created a test (pytest/tox) to see if the package has been cythonized. Here, I just call the above function. The result is always that it is not compiled. A minimal reproducible example can be found here: https://github.com/CodingTil/Minimal-Example-Cythonize-Package-Tox I have mainly used the following resources: https://levelup.gitconnected.com/how-to-deploy-a-cython-package-to-pypi-8217a6581f09 https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html https://packaging-guide.openastronomy.org/en/latest/extensions.html A: I activated a virtualenv created by tox and ran the code manually: $ . Minimal-Example-Cythonize-Package-Tox/.tox/py310/bin/activate $ python Python 3.10.8 (main, Oct 25 2022, 01:00:56) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from mypackage_name import code >>> code <module 'mypackage_name.code' from 'Minimal-Example-Cythonize-Package-Tox/.tox/py310/lib/python3.10/site-packages/mypackage_name/code.cpython-310-x86_64-linux-gnu.so'> >>> code.compiled() False It seems compiled() returns False even when imported from a cythonized module. I don't know why.
Cythonize Package & Tox Testing
I am developing a pypi-package (*.py-files), which is being tested via tox. Since compiling the package might yield some performance improvements, I'd like to cythonize it, and also verify using tox that the package is compiled. For this purpose, I have made the following adjustments: setup.py additions: import pathlib from setuptools import setup from Cython.Build import cythonize setup( install_requires=[ "Cython>=0.29.21" #<-- new ], ext_modules=cythonize("mypackage_name/*.py"), #<-- new ) pyproject.toml created: [build-system] requires = ["setuptools", "wheel", "Cython>=0.29.21"] build-backend = "setuptools.build_meta" And added the following to my existing tox.ini: [tox] envlist = py{310, 311} isolated_build = true ;<-- new [testenv] deps = -rrequirements.txt commands = python -m pytest tests -s In order to test if this is working, I've added the following to a python file in my package: def compiled() -> bool: import Cython return Cython.compiled I have created a test (pytest/tox) to see if the package has been cythonized. Here, I just call the above function. The result is always that it is not compiled. A minimal reproducible example can be found here: https://github.com/CodingTil/Minimal-Example-Cythonize-Package-Tox I have mainly used the following resources: https://levelup.gitconnected.com/how-to-deploy-a-cython-package-to-pypi-8217a6581f09 https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html https://packaging-guide.openastronomy.org/en/latest/extensions.html
[ "I activated a virtualenv created by tox and ran the code manually:\n$ . Minimal-Example-Cythonize-Package-Tox/.tox/py310/bin/activate\n$ python\nPython 3.10.8 (main, Oct 25 2022, 01:00:56) [GCC 10.2.1 20210110] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from mypackage_name import code\n>>> code\n<module 'mypackage_name.code' from 'Minimal-Example-Cythonize-Package-Tox/.tox/py310/lib/python3.10/site-packages/mypackage_name/code.cpython-310-x86_64-linux-gnu.so'>\n\n>>> code.compiled()\nFalse\n\nIt seems compiled() returns False even when imported from a cythonized module. I don't know why.\n" ]
[ 0 ]
[]
[]
[ "cythonize", "pip", "python", "tox" ]
stackoverflow_0074558388_cythonize_pip_python_tox.txt
Q: Install mysqlclient for Django Python on Mac OS X Sierra I have already installed Python 2.7.13 Django 1.11 MySQL 5.7.17 I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue: Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/ A: I needed the following to build / install mysqlclient brew install mysql-client # mysql-client is not on the `PATH` by default export PATH="/usr/local/opt/mysql-client/bin:$PATH" # openssl is not on the link path by default export LIBRARY_PATH="$LIBRARY_PATH:/usr/local/opt/openssl/lib/" Then I could pip wheel mysqlclient / pip install mysqlclient successfully A: I have encountered this problem too,below is my step: 1.brew install mysql-connector-c 2.pip install mysqlclient and then encountered this error,i have Traced the source code,but solved this one then the other error occured. so i changed the way to install mysqlclient,just : 1.brew install mysql 2.pip install mysqlclient this worked for me,no any errors occured. A: Install mysql-client instead of mysql if you don't plan to have mysql in your computer brew install mysql-client echo 'export PATH="/usr/local/opt/mysql-client/bin:$PATH"' >> ~/.bash_profile source ~/.bash_profile pip install mysqlclient export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include" A: brew install/upgrade/reinstall mysql brew install mysql-client export PATH="/usr/local/opt/openssl/bin:$PATH" export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include" pip install mysqlclient works perfectly A: For Mac: first download Xcode from App Store and MySqlWorkbench from https://dev.mysql.com/downloads/workbench/ Run the following commands in terminal, $ brew install mysql $ export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS $ xcode-select --install $ pip install mysqlclient A: Install mysql using brew and add it to the path: $ brew install mysql $ export PATH=/usr/local/mysql/bin:$PATH $ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib $ pip install mysqlclient A: This worked for me today, after using brew install mysql to install the MySQL server using Homebrew: MYSQLCLIENT_CFLAGS=`pkg-config mysqlclient --cflags` \ MYSQLCLIENT_LDFLAGS=`pkg-config mysqlclient --libs` \ pip install mysqlclient A: For my mac os, I need not to specify the path because brew do that for you. I just did below commands, brew install mysql brew install mysql-client pip3 install mysqlclient Everything is perfect & fine. A: MAC M1 run xcode-select --install then run pip install mysqlclient
Install mysqlclient for Django Python on Mac OS X Sierra
I have already installed Python 2.7.13 Django 1.11 MySQL 5.7.17 I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue: Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/
[ "I needed the following to build / install mysqlclient\nbrew install mysql-client\n# mysql-client is not on the `PATH` by default\nexport PATH=\"/usr/local/opt/mysql-client/bin:$PATH\"\n# openssl is not on the link path by default\nexport LIBRARY_PATH=\"$LIBRARY_PATH:/usr/local/opt/openssl/lib/\"\n\nThen I could pip wheel mysqlclient / pip install mysqlclient successfully\n", "I have encountered this problem too,below is my step:\n1.brew install mysql-connector-c\n2.pip install mysqlclient\nand then encountered this error,i have Traced the source code,but solved this one then the other error occured.\nso i changed the way to install mysqlclient,just :\n1.brew install mysql\n2.pip install mysqlclient\nthis worked for me,no any errors occured.\n", "Install mysql-client instead of mysql if you don't plan to have mysql in your computer\nbrew install mysql-client\necho 'export PATH=\"/usr/local/opt/mysql-client/bin:$PATH\"' >> ~/.bash_profile\nsource ~/.bash_profile\npip install mysqlclient\nexport LDFLAGS=\"-L/usr/local/opt/openssl/lib\"\nexport CPPFLAGS=\"-I/usr/local/opt/openssl/include\"\n", "brew install/upgrade/reinstall mysql\nbrew install mysql-client\nexport PATH=\"/usr/local/opt/openssl/bin:$PATH\"\nexport LDFLAGS=\"-L/usr/local/opt/openssl/lib\"\nexport CPPFLAGS=\"-I/usr/local/opt/openssl/include\"\npip install mysqlclient\nworks perfectly\n\n", "For Mac:\nfirst download Xcode from App Store and MySqlWorkbench from https://dev.mysql.com/downloads/workbench/\nRun the following commands in terminal,\n$ brew install mysql\n\n$ export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS\n\n$ xcode-select --install\n\n$ pip install mysqlclient\n\n", "Install mysql using brew and add it to the path:\n$ brew install mysql\n\n$ export PATH=/usr/local/mysql/bin:$PATH\n\n$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib\n\n$ pip install mysqlclient\n\n", "This worked for me today, after using brew install mysql to install the MySQL server using Homebrew:\nMYSQLCLIENT_CFLAGS=`pkg-config mysqlclient --cflags` \\\n MYSQLCLIENT_LDFLAGS=`pkg-config mysqlclient --libs` \\\n pip install mysqlclient\n\n", "For my mac os,\nI need not to specify the path because brew do that for you.\nI just did below commands,\nbrew install mysql\nbrew install mysql-client\npip3 install mysqlclient\n\nEverything is perfect & fine.\n", "MAC M1 run\nxcode-select --install \n\nthen run\npip install mysqlclient\n\n" ]
[ 53, 24, 15, 13, 7, 3, 2, 0, 0 ]
[]
[]
[ "django", "macos", "mysql", "python" ]
stackoverflow_0043612243_django_macos_mysql_python.txt
Q: imaplib.error: b'LOGIN failed' when trying to login using imaplib I got that error, credentials is ok and was working in the morning. Reset password did not change, logging into OWA works fine, login using imaplib fails with "LOGIN failed" after 1 minute or so! def get_otp(): # sleeping for 20 seconds time.sleep(20) # username for mail id user = '***********' # password for email id password = '********' # hostname for webmail.recogx.ai hostname = 'mail.office365.com' print("entered hostname ") def get_body(msg): # id=f message is present in more than one part if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) print("bodyyyyyy") # entering hostname to enter into session # time.sleep(10) mail = imaplib.IMAP4_SSL(hostname) time.sleep(5) print("logged ") # logging in page print("mail login",mail.login(user, password)) mail.login(user, password) print("logged in") # selecting inbox mail.select('INBOX') # searching unseen messages result, data = mail.search(None, 'UNSEEN') # finding total mail numbers mail_ids = data[0] id_list = mail_ids.split() latest = id_list[-1] print("opt next") # fetching data from latest email result, data = mail.fetch(latest, '(RFC822)') ror = email.message_from_bytes(data[0][1]) body = get_body(ror) # converting text body from byte to string body = body.decode("utf-8") time.sleep(3) otp = re.search(r'\d{7}', body).group() Unable to read the OTP. A: Microsoft has disabled basic authentication in Office 365: https://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437 However, there might be a method to authenticate using oauth2. I'm personally working on a solution that might be using: Office 365 IMAP authentication via OAuth2 and python MSAL library
imaplib.error: b'LOGIN failed' when trying to login using imaplib
I got that error, credentials is ok and was working in the morning. Reset password did not change, logging into OWA works fine, login using imaplib fails with "LOGIN failed" after 1 minute or so! def get_otp(): # sleeping for 20 seconds time.sleep(20) # username for mail id user = '***********' # password for email id password = '********' # hostname for webmail.recogx.ai hostname = 'mail.office365.com' print("entered hostname ") def get_body(msg): # id=f message is present in more than one part if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) print("bodyyyyyy") # entering hostname to enter into session # time.sleep(10) mail = imaplib.IMAP4_SSL(hostname) time.sleep(5) print("logged ") # logging in page print("mail login",mail.login(user, password)) mail.login(user, password) print("logged in") # selecting inbox mail.select('INBOX') # searching unseen messages result, data = mail.search(None, 'UNSEEN') # finding total mail numbers mail_ids = data[0] id_list = mail_ids.split() latest = id_list[-1] print("opt next") # fetching data from latest email result, data = mail.fetch(latest, '(RFC822)') ror = email.message_from_bytes(data[0][1]) body = get_body(ror) # converting text body from byte to string body = body.decode("utf-8") time.sleep(3) otp = re.search(r'\d{7}', body).group() Unable to read the OTP.
[ "Microsoft has disabled basic authentication in Office 365:\nhttps://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437\nHowever, there might be a method to authenticate using oauth2.\nI'm personally working on a solution that might be using:\nOffice 365 IMAP authentication via OAuth2 and python MSAL library\n" ]
[ 0 ]
[]
[]
[ "gmail_imap", "imap", "python" ]
stackoverflow_0074023368_gmail_imap_imap_python.txt
Q: These two strings are supposed to be the same length but when printed they do not appear that way a="|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |" b="|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|" both of these strings should be 98 characters, but when printing with a monospaced font (in my terminal) it shows b as being longer terminal output when printing length of each string followed by string This shouldn't be an issue but I'm trying to draw a box around some text and this glitch causes the table to be misaligned. Is it possible that the font is not properly monospaced? I am using VS Code for the Web. Thank you kindly for your time. A: I was guessing that one of the chars in a is strange. We can see this if we print them: In [4]: for i, char in enumerate(a): ...: print((i, char)) ...: (0, '|') (1, ':') (2, 'w') (3, 'a') (4, 't') (5, 'c') (6, 'h') (7, ':') (8, '️') (9, ' ') (10, ':') (11, 'm') (12, 'o') (13, 'b') (14, 'i') (15, 'l') (16, 'e') (17, ' ') (18, 'p') (19, 'h') (20, 'o') (21, 'n') (22, 'e') (23, ':') (24, ' ') (25, ':') (26, 'm') (27, 'o') (28, 'b') (29, 'i') (30, 'l') (31, 'e') (32, ' ') (33, 'p') (34, 'h') (35, 'o') (36, 'n') (37, 'e') (38, ' ') (39, 'w') (40, 'i') (41, 't') (42, 'h') (43, ' ') (44, 'a') (45, 'r') (46, 'r') (47, 'o') (48, 'w') (49, ':') (50, ' ') (51, ':') (52, 'l') (53, 'a') (54, 'p') (55, 't') (56, 'o') (57, 'p') (58, ':') (59, ' ') (60, ':') (61, 'k') (62, 'e') (63, 'y') (64, 'b') (65, 'o') (66, 'a') (67, 'r') (68, 'd') (69, ':') (70, ' ') (71, ':') (72, 'd') (73, 'e') (74, 's') (75, 'k') (76, 't') (77, 'o') (78, 'p') (79, ' ') (80, 'c') (81, 'o') (82, 'm') (83, 'p') (84, 'u') (85, 't') (86, 'e') (87, 'r') (88, ':') (89, ' ') (90, ' ') (91, ' ') (92, ' ') (93, ' ') (94, ' ') (95, ' ') (96, ' ') (97, '|') So we can see that at index 8 there is some kind of "zero width" character. We can inspect the char to find its codepoint: In [5]: ord(a[8]) Out[5]: 65039 This appears to be Unicode "VARIATION SELECTOR-16": https://www.fileformat.info/info/unicode/char/fe0f/index.htm Some kind of modifying character that has no printable representation of its own. A: try to add one profit to a or copy this and try... a="|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |" b="|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|"
These two strings are supposed to be the same length but when printed they do not appear that way
a="|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |" b="|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|" both of these strings should be 98 characters, but when printing with a monospaced font (in my terminal) it shows b as being longer terminal output when printing length of each string followed by string This shouldn't be an issue but I'm trying to draw a box around some text and this glitch causes the table to be misaligned. Is it possible that the font is not properly monospaced? I am using VS Code for the Web. Thank you kindly for your time.
[ "I was guessing that one of the chars in a is strange. We can see this if we print them:\nIn [4]: for i, char in enumerate(a):\n ...: print((i, char))\n ...:\n(0, '|')\n(1, ':')\n(2, 'w')\n(3, 'a')\n(4, 't')\n(5, 'c')\n(6, 'h')\n(7, ':')\n(8, '️')\n(9, ' ')\n(10, ':')\n(11, 'm')\n(12, 'o')\n(13, 'b')\n(14, 'i')\n(15, 'l')\n(16, 'e')\n(17, ' ')\n(18, 'p')\n(19, 'h')\n(20, 'o')\n(21, 'n')\n(22, 'e')\n(23, ':')\n(24, ' ')\n(25, ':')\n(26, 'm')\n(27, 'o')\n(28, 'b')\n(29, 'i')\n(30, 'l')\n(31, 'e')\n(32, ' ')\n(33, 'p')\n(34, 'h')\n(35, 'o')\n(36, 'n')\n(37, 'e')\n(38, ' ')\n(39, 'w')\n(40, 'i')\n(41, 't')\n(42, 'h')\n(43, ' ')\n(44, 'a')\n(45, 'r')\n(46, 'r')\n(47, 'o')\n(48, 'w')\n(49, ':')\n(50, ' ')\n(51, ':')\n(52, 'l')\n(53, 'a')\n(54, 'p')\n(55, 't')\n(56, 'o')\n(57, 'p')\n(58, ':')\n(59, ' ')\n(60, ':')\n(61, 'k')\n(62, 'e')\n(63, 'y')\n(64, 'b')\n(65, 'o')\n(66, 'a')\n(67, 'r')\n(68, 'd')\n(69, ':')\n(70, ' ')\n(71, ':')\n(72, 'd')\n(73, 'e')\n(74, 's')\n(75, 'k')\n(76, 't')\n(77, 'o')\n(78, 'p')\n(79, ' ')\n(80, 'c')\n(81, 'o')\n(82, 'm')\n(83, 'p')\n(84, 'u')\n(85, 't')\n(86, 'e')\n(87, 'r')\n(88, ':')\n(89, ' ')\n(90, ' ')\n(91, ' ')\n(92, ' ')\n(93, ' ')\n(94, ' ')\n(95, ' ')\n(96, ' ')\n(97, '|')\n\nSo we can see that at index 8 there is some kind of \"zero width\" character.\nWe can inspect the char to find its codepoint:\nIn [5]: ord(a[8])\nOut[5]: 65039\n\nThis appears to be Unicode \"VARIATION SELECTOR-16\": https://www.fileformat.info/info/unicode/char/fe0f/index.htm\nSome kind of modifying character that has no printable representation of its own.\n", "try to add one profit to a or copy this and try...\na=\"|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |\"\nb=\"|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|\"\n\n" ]
[ 1, 0 ]
[]
[]
[ "ascii_art", "python", "visual_studio_code" ]
stackoverflow_0074559938_ascii_art_python_visual_studio_code.txt
Q: How to read a file which in CSV format, but different extension? I have a dataset which has a good dataframe structure starting from row 3. For the first rows, unfortunately separators are diverse, and there is a few information to be included in my dataframe. The files are in CSV strcture mostly, but they have extensions like WOC, WOL, WPL, and so on. The WOC file first rows look like: Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 Header of the ollowing values should be like: A, B, C, D, E 45,34,22,26,0 78,74,82,11,0 Here is my attempt: df44 = pd.DataFrame() # creates empty dataframe for f in glob.glob('file_path_to_single_file'): with open(f, 'rb') as file: encodings = chardet.detect(file.read())["encoding"] a = pd.read_csv(f,sep='\s+|;|,', engine='python', encoding=encodings,header=None,names=['A','B', 'C', 'D', 'E'], skiprows=2) df44 = df44.append(a) What would be the best way to read such a file so that I can also extract height, weight, age and city? My expected output is: A, B, C, D, E, City, Height, Weight, Age 45,34,22,26,0,NewYork, 144, 35, 5 78,74,82,11,0,NewYork, 144, 35, 5 A: Base on additional info from your comments above I think you can start build your solution with following: `# I created a file 'data.woc' with data as stream from your question:` import pandas as pd from io import StringIO import re stack_data = '''Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0''' # read heading rows, I arbitrally chose 5 rows to read with open('data.woc', 'r') as f: heading_rows = [next(f) for _ in range(5)] city = re.findall(pattern = ' \w+ ', string = heading_rows[0])[0].strip() numbers_list = [re.findall(pattern='\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0] height, weight, age = [int(numbers_lst[i]) for i in range(3)] df = pd.read_csv('data.woc', sep='\s+|;|,', skiprows=2,comment='cm', index_col=None, names=list('ABCDE')) df.dropna(inplace=True)
How to read a file which in CSV format, but different extension?
I have a dataset which has a good dataframe structure starting from row 3. For the first rows, unfortunately separators are diverse, and there is a few information to be included in my dataframe. The files are in CSV strcture mostly, but they have extensions like WOC, WOL, WPL, and so on. The WOC file first rows look like: Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 Header of the ollowing values should be like: A, B, C, D, E 45,34,22,26,0 78,74,82,11,0 Here is my attempt: df44 = pd.DataFrame() # creates empty dataframe for f in glob.glob('file_path_to_single_file'): with open(f, 'rb') as file: encodings = chardet.detect(file.read())["encoding"] a = pd.read_csv(f,sep='\s+|;|,', engine='python', encoding=encodings,header=None,names=['A','B', 'C', 'D', 'E'], skiprows=2) df44 = df44.append(a) What would be the best way to read such a file so that I can also extract height, weight, age and city? My expected output is: A, B, C, D, E, City, Height, Weight, Age 45,34,22,26,0,NewYork, 144, 35, 5 78,74,82,11,0,NewYork, 144, 35, 5
[ "Base on additional info from your comments above I think you can start build your solution with following:\n`# I created a file 'data.woc' with data as stream from your question:`\nimport pandas as pd\nfrom io import StringIO\nimport re\nstack_data = '''Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n\n144 cm/35 Kg/5 YearsOld\n\n\n\n\n\n\n45,34,22,26,0\n78,74,82,11,0'''\n\n# read heading rows, I arbitrally chose 5 rows to read\n\nwith open('data.woc', 'r') as f:\n heading_rows = [next(f) for _ in range(5)]\n\ncity = re.findall(pattern = ' \\w+ ', string = heading_rows[0])[0].strip()\n\nnumbers_list = [re.findall(pattern='\\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0]\n\nheight, weight, age = [int(numbers_lst[i]) for i in range(3)]\n \ndf = pd.read_csv('data.woc', sep='\\s+|;|,', skiprows=2,comment='cm', index_col=None, names=list('ABCDE'))\n \ndf.dropna(inplace=True)\n\n" ]
[ 1 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074558525_csv_pandas_python.txt
Q: for loop: applying a, b in two lists I am trying to modify the following script so that my legends are changed to that list in speeds. How can I do this without changing the iterator list? x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator: plt.plot(x, a*x, label=f'{a}rpm') plt.legend(loc='best') Modified script: x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator and b in speeds: plt.plot(x, a*x, label=f'{b}rpm') plt.legend(loc='best') plt.show() Desired Outcome: legends are changed to that in speeds list ie, 1rpm -> 100rpm 2rpm -> 300rpm 3prm -> 500rpm A: and is a logical operator, not a general connective as in English. Combine the lists first with zip and then iterate: >>> x = [1,2,3] >>> y = [4,5,6] >>> for a, b in zip(x, y): print(a, b) ... 1 4 2 5 3 6 A: Not so sure, what's the usage of [*range(100, 300, 500)] >>> [100] From your question if I understand correctly what you want is: speeds = [*range(100, 700, 200)] >>> [100, 300, 500] Now both iterator and speed have a length of 3, so you can rewrite your plotting routine using zip for a, b in zip(iterator, speeds): plt.plot(x, a*x, label=f'{b}rpm') plt.legend(loc='best') plt.show() Hope this helps, cheers!
for loop: applying a, b in two lists
I am trying to modify the following script so that my legends are changed to that list in speeds. How can I do this without changing the iterator list? x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator: plt.plot(x, a*x, label=f'{a}rpm') plt.legend(loc='best') Modified script: x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator and b in speeds: plt.plot(x, a*x, label=f'{b}rpm') plt.legend(loc='best') plt.show() Desired Outcome: legends are changed to that in speeds list ie, 1rpm -> 100rpm 2rpm -> 300rpm 3prm -> 500rpm
[ "and is a logical operator, not a general connective as in English.\nCombine the lists first with zip and then iterate:\n>>> x = [1,2,3]\n>>> y = [4,5,6]\n>>> for a, b in zip(x, y): print(a, b)\n...\n1 4\n2 5\n3 6\n\n", "Not so sure, what's the usage of\n[*range(100, 300, 500)]\n>>> [100]\n\nFrom your question if I understand correctly what you want is:\nspeeds = [*range(100, 700, 200)]\n>>> [100, 300, 500]\n\nNow both iterator and speed have a length of 3, so you can rewrite your plotting routine using zip\nfor a, b in zip(iterator, speeds):\n plt.plot(x, a*x, label=f'{b}rpm')\nplt.legend(loc='best') \nplt.show() \n\nHope this helps, cheers!\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074559896_python.txt
Q: is this the right way to apply softmax? self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(in_features = 32*8*8, out_features = 26), nn.ReLU(), nn.Linear(in_features = 26, out_features = output_shape), nn.Softmax(dim=1) ) and my loss fn is loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(params = model_0.parameters(), lr = 0.07) Is that the right way to use softmax? output_shape is equal to num of class (this is multi class classification) If my implementation isn't wrong, then why do all of my data in 1 batch output the same class (even each data has very similar output probability) A: No, CrossEntropyLoss doesn't require Softmax as it already includes it (or actually LogSoftmax): https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?highlight=crossentropy#torch.nn.CrossEntropyLoss.
is this the right way to apply softmax?
self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(in_features = 32*8*8, out_features = 26), nn.ReLU(), nn.Linear(in_features = 26, out_features = output_shape), nn.Softmax(dim=1) ) and my loss fn is loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(params = model_0.parameters(), lr = 0.07) Is that the right way to use softmax? output_shape is equal to num of class (this is multi class classification) If my implementation isn't wrong, then why do all of my data in 1 batch output the same class (even each data has very similar output probability)
[ "No, CrossEntropyLoss doesn't require Softmax as it already includes it (or actually LogSoftmax): https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?highlight=crossentropy#torch.nn.CrossEntropyLoss.\n" ]
[ 0 ]
[]
[]
[ "activation_function", "deep_learning", "python", "pytorch" ]
stackoverflow_0074554945_activation_function_deep_learning_python_pytorch.txt
Q: Pandas Apply transformation to multiple columns but do not discard other columns? I have a table of an "Id" column and multiple integer columns that I want to convert to categorical variables. Therefore, I want to apply this transformation only to those multiple integer columns, but leave the ID column unchanged. All the other methods involve dropping the ID column. How do I do this without dropping the ID column? This is the current code i have: df= df.loc[:, df.columns != 'Id'].apply(lambda x: x.astype('category')) Sample dataframe: {'Id': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, 'Foundation': {0: 2, 1: 1, 2: 2, 3: 0, 4: 2}, 'GarageFinish': {0: 1, 1: 1, 2: 1, 3: 2, 4: 1}, 'LandSlope': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'LotConfig': {0: 4, 1: 2, 2: 4, 3: 0, 4: 2}, 'GarageQual': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'GarageCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'LandContour': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'Utilities': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'GarageType': {0: 1, 1: 1, 2: 1, 3: 5, 4: 1}, 'LotShape': {0: 3, 1: 3, 2: 0, 3: 0, 4: 0}, 'Alley': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'Street': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'PoolQC': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'Fence': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'MiscFeature': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'MSZoning': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'SaleType': {0: 8, 1: 8, 2: 8, 3: 8, 4: 8}, 'PavedDrive': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'FireplaceQu': {0: 5, 1: 4, 2: 4, 3: 2, 4: 4}, 'Condition1': {0: 2, 1: 1, 2: 2, 3: 2, 4: 2}, 'Functional': {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}, 'BsmtQual': {0: 2, 1: 2, 2: 2, 3: 3, 4: 2}, 'BsmtCond': {0: 3, 1: 3, 2: 3, 3: 1, 4: 3}, 'BsmtExposure': {0: 3, 1: 1, 2: 2, 3: 3, 4: 0}, 'BsmtFinType1': {0: 2, 1: 0, 2: 2, 3: 0, 4: 2}, 'ExterQual': {0: 2, 1: 3, 2: 2, 3: 3, 4: 2}, 'BsmtFinType2': {0: 5, 1: 5, 2: 5, 3: 5, 4: 5}, 'MasVnrType': {0: 1, 1: 2, 2: 1, 3: 2, 4: 1}, 'Exterior2nd': {0: 13, 1: 8, 2: 13, 3: 15, 4: 13}, 'Heating': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'Neighborhood': {0: 5, 1: 24, 2: 5, 3: 6, 4: 15}, 'SaleCondition': {0: 4, 1: 4, 2: 4, 3: 0, 4: 4}, 'Electrical': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'Exterior1st': {0: 12, 1: 8, 2: 12, 3: 13, 4: 12}, 'RoofMatl': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'RoofStyle': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'HouseStyle': {0: 5, 1: 2, 2: 5, 3: 5, 4: 5}, 'BldgType': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'Condition2': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'KitchenQual': {0: 2, 1: 3, 2: 2, 3: 2, 4: 2}, 'ExterCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'CentralAir': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'HeatingQC': {0: 0, 1: 0, 2: 0, 3: 2, 4: 0}} A: One way to do this is by isolating the Id column and then joining the converted columns: df = df[['Id']].join( df.loc[:, df.columns != 'Id'].astype('category') ) A: Another way is to try: df = df.groupby('Id').transform(lambda x: pd.Categorical(x)).reset_index(names = 'id') A: I think the easier way would be to use astype directly, and provide a generated dictionary. cast_df = df.astype({col: 'category' for col in df if col != 'Id'}) It's probably more performant than the other solutions too.
Pandas Apply transformation to multiple columns but do not discard other columns?
I have a table of an "Id" column and multiple integer columns that I want to convert to categorical variables. Therefore, I want to apply this transformation only to those multiple integer columns, but leave the ID column unchanged. All the other methods involve dropping the ID column. How do I do this without dropping the ID column? This is the current code i have: df= df.loc[:, df.columns != 'Id'].apply(lambda x: x.astype('category')) Sample dataframe: {'Id': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, 'Foundation': {0: 2, 1: 1, 2: 2, 3: 0, 4: 2}, 'GarageFinish': {0: 1, 1: 1, 2: 1, 3: 2, 4: 1}, 'LandSlope': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'LotConfig': {0: 4, 1: 2, 2: 4, 3: 0, 4: 2}, 'GarageQual': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'GarageCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'LandContour': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'Utilities': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'GarageType': {0: 1, 1: 1, 2: 1, 3: 5, 4: 1}, 'LotShape': {0: 3, 1: 3, 2: 0, 3: 0, 4: 0}, 'Alley': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'Street': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'PoolQC': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'Fence': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'MiscFeature': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'MSZoning': {0: 3, 1: 3, 2: 3, 3: 3, 4: 3}, 'SaleType': {0: 8, 1: 8, 2: 8, 3: 8, 4: 8}, 'PavedDrive': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'FireplaceQu': {0: 5, 1: 4, 2: 4, 3: 2, 4: 4}, 'Condition1': {0: 2, 1: 1, 2: 2, 3: 2, 4: 2}, 'Functional': {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}, 'BsmtQual': {0: 2, 1: 2, 2: 2, 3: 3, 4: 2}, 'BsmtCond': {0: 3, 1: 3, 2: 3, 3: 1, 4: 3}, 'BsmtExposure': {0: 3, 1: 1, 2: 2, 3: 3, 4: 0}, 'BsmtFinType1': {0: 2, 1: 0, 2: 2, 3: 0, 4: 2}, 'ExterQual': {0: 2, 1: 3, 2: 2, 3: 3, 4: 2}, 'BsmtFinType2': {0: 5, 1: 5, 2: 5, 3: 5, 4: 5}, 'MasVnrType': {0: 1, 1: 2, 2: 1, 3: 2, 4: 1}, 'Exterior2nd': {0: 13, 1: 8, 2: 13, 3: 15, 4: 13}, 'Heating': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'Neighborhood': {0: 5, 1: 24, 2: 5, 3: 6, 4: 15}, 'SaleCondition': {0: 4, 1: 4, 2: 4, 3: 0, 4: 4}, 'Electrical': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'Exterior1st': {0: 12, 1: 8, 2: 12, 3: 13, 4: 12}, 'RoofMatl': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'RoofStyle': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'HouseStyle': {0: 5, 1: 2, 2: 5, 3: 5, 4: 5}, 'BldgType': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'Condition2': {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}, 'KitchenQual': {0: 2, 1: 3, 2: 2, 3: 2, 4: 2}, 'ExterCond': {0: 4, 1: 4, 2: 4, 3: 4, 4: 4}, 'CentralAir': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'HeatingQC': {0: 0, 1: 0, 2: 0, 3: 2, 4: 0}}
[ "One way to do this is by isolating the Id column and then joining the converted columns:\ndf = df[['Id']].join(\n df.loc[:, df.columns != 'Id'].astype('category')\n)\n\n", "Another way is to try:\ndf = df.groupby('Id').transform(lambda x: pd.Categorical(x)).reset_index(names = 'id')\n\n", "I think the easier way would be to use astype directly, and provide a generated dictionary.\ncast_df = df.astype({col: 'category' for col in df if col != 'Id'})\n\nIt's probably more performant than the other solutions too.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074330370_dataframe_pandas_python.txt
Q: Improving Weighted Moving Average Performance I have been playing around with a pandas data frame with 414,000 rows. Built into pandas is an exponential moving average computed by: series.ewm(span=period).mean() The above executes in < 0.3 seconds. I am however in search of trying to use a weighted moving average (which has a linear linear weighting of each element). I came across the following function: def WMA(self, s, period): return s.rolling(period).apply(lambda x: (np.arange(period)+1*x).sum()/(np.arange(period)+1).sum(), raw=True) The above function took 27 seconds to execute. I noticed the arange function could be cached and produced the following: def WMA(self, s, period): weights = np.arange(period)+1 weights_sum = weights.sum() return s.rolling(period).apply(lambda x: (weights*x).sum()/weights_sum, raw=True) The above function took 11 seconds, which is a noticeable improvement. What I'm trying to figure out is if there is some way I can further optimize this (ideally replace the apply function) but genuinely am not sure how to go about it. Any ideas would be appreciated! A: You can use the np sliding window function docs, then it looks like this: import numpy as np import pandas as pd d1 = pd.DataFrame(np.random.randint(0, 10, size=(500_000))) # x=500_000 p = 50 w = np.arange(p)+1 w_s = w.sum() ########## for comparison purpose ########## # 1.47 s ± 12.5 ms per loop (mean ± std. dev. of 7 runs, 2 loops each) r = d1.rolling(p).apply(lambda x: (w*x).sum()/w_s, raw=True) # 62.1 ms ± 4.57 ms per loop (mean ± std. dev. of 7 runs, 2 loops each) swv = np.lib.stride_tricks.sliding_window_view(d1.values.flatten(), window_shape=p) sw = (swv*w).sum(axis=1) / w_s ########## for comparison purpose ########## np.array_equal(r.iloc[p - 1:].values.flatten(), sw) # True So, an overall speedup of ~23.67x. However, you need to adjust the shape to your desired shape afterwards. Since sw starts at 0 with a shape of x-p. Whereas r starts at p, with a shape of x and the first p values -> nan. A: Skeletor above was right on the money and I adapted it slightly to handle the issues with nan # THIS USES LOWER LEVEL NUMPY TO GREATLY SPEED IT UP! def WMA(self, s, period): w = np.arange(period)+1 w_s = w.sum() swv = sliding_window_view(s.values.flatten(), window_shape=period) sw = (swv * w).sum(axis=1) / w_s # Need to now return it as a normal series sw = np.concatenate((np.full(period - 1, np.nan), sw)) return pd.Series(sw) dropped it from 11 seconds down to 1.5 seconds which is much better! A: Take a look at the parallel-pandas library. With its help, you can parallelize the apply method of a sliding window. Just two extra lines of code if you count library imports) import pandas as pd import numpy as np from time import monotonic from parallel_pandas import ParallelPandas def WMA(s, period): weights = np.arange(period) + 1 weights_sum = weights.sum() return s.rolling(period).apply(lambda x: (weights * x).sum() / weights_sum, raw=True) def parallel_wma(s, period): weights = np.arange(period) + 1 weights_sum = weights.sum() # p_apply is parallel apply method return s.rolling(period).p_apply(lambda x: (weights * x).sum() / weights_sum, raw=True) if __name__ == '__main__': # initialize parallel-pandas ParallelPandas.initialize(n_cpu=16, disable_pr_bar=True) #create series of length 500 000 s = pd.Series(np.random.randint(0, 5, size=500_000)) period = 50 start = monotonic() res = WMA(s, period) print(f'synchronous wma time took: {monotonic() - start:.2f} s.') start = monotonic() res2 = parallel_wma(s, period) print(f'parallel wma time took: {monotonic() - start:.2f} s.') Output: synchronous wma time took: 1.16 s. parallel wma time took: 0.22 s. Total speedup: 1.16/0.22 ~ 5.3 and close to the performance on numpy arrays that demonstrated Skeletor
Improving Weighted Moving Average Performance
I have been playing around with a pandas data frame with 414,000 rows. Built into pandas is an exponential moving average computed by: series.ewm(span=period).mean() The above executes in < 0.3 seconds. I am however in search of trying to use a weighted moving average (which has a linear linear weighting of each element). I came across the following function: def WMA(self, s, period): return s.rolling(period).apply(lambda x: (np.arange(period)+1*x).sum()/(np.arange(period)+1).sum(), raw=True) The above function took 27 seconds to execute. I noticed the arange function could be cached and produced the following: def WMA(self, s, period): weights = np.arange(period)+1 weights_sum = weights.sum() return s.rolling(period).apply(lambda x: (weights*x).sum()/weights_sum, raw=True) The above function took 11 seconds, which is a noticeable improvement. What I'm trying to figure out is if there is some way I can further optimize this (ideally replace the apply function) but genuinely am not sure how to go about it. Any ideas would be appreciated!
[ "You can use the np sliding window function docs, then it looks like this:\nimport numpy as np\nimport pandas as pd\n\nd1 = pd.DataFrame(np.random.randint(0, 10, size=(500_000))) # x=500_000\n\np = 50\nw = np.arange(p)+1\nw_s = w.sum()\n\n########## for comparison purpose ##########\n# 1.47 s ± 12.5 ms per loop (mean ± std. dev. of 7 runs, 2 loops each)\nr = d1.rolling(p).apply(lambda x: (w*x).sum()/w_s, raw=True)\n\n# 62.1 ms ± 4.57 ms per loop (mean ± std. dev. of 7 runs, 2 loops each)\nswv = np.lib.stride_tricks.sliding_window_view(d1.values.flatten(), window_shape=p)\nsw = (swv*w).sum(axis=1) / w_s\n\n########## for comparison purpose ##########\nnp.array_equal(r.iloc[p - 1:].values.flatten(), sw) # True\n\nSo, an overall speedup of ~23.67x. However, you need to adjust the shape to your desired shape afterwards. Since sw starts at 0 with a shape of x-p. Whereas r starts at p, with a shape of x and the first p values -> nan.\n", "Skeletor above was right on the money and I adapted it slightly to handle the issues with nan\n # THIS USES LOWER LEVEL NUMPY TO GREATLY SPEED IT UP!\n def WMA(self, s, period):\n w = np.arange(period)+1\n w_s = w.sum() \n swv = sliding_window_view(s.values.flatten(), window_shape=period)\n sw = (swv * w).sum(axis=1) / w_s\n\n # Need to now return it as a normal series\n sw = np.concatenate((np.full(period - 1, np.nan), sw))\n return pd.Series(sw)\n\ndropped it from 11 seconds down to 1.5 seconds which is much better!\n", "Take a look at the parallel-pandas library. With its help, you can parallelize the apply method of a sliding window.\nJust two extra lines of code if you count library imports)\nimport pandas as pd\nimport numpy as np\nfrom time import monotonic\nfrom parallel_pandas import ParallelPandas\n\n\ndef WMA(s, period):\n weights = np.arange(period) + 1\n weights_sum = weights.sum()\n return s.rolling(period).apply(lambda x: (weights * x).sum() / weights_sum, raw=True)\n\n\ndef parallel_wma(s, period):\n weights = np.arange(period) + 1\n weights_sum = weights.sum()\n # p_apply is parallel apply method\n return s.rolling(period).p_apply(lambda x: (weights * x).sum() / weights_sum, raw=True)\n\n\nif __name__ == '__main__':\n # initialize parallel-pandas\n ParallelPandas.initialize(n_cpu=16, disable_pr_bar=True)\n \n #create series of length 500 000\n s = pd.Series(np.random.randint(0, 5, size=500_000))\n period = 50\n\n start = monotonic()\n res = WMA(s, period)\n print(f'synchronous wma time took: {monotonic() - start:.2f} s.')\n\n start = monotonic()\n res2 = parallel_wma(s, period)\n print(f'parallel wma time took: {monotonic() - start:.2f} s.')\n\nOutput:\n synchronous wma time took: 1.16 s.\n parallel wma time took: 0.22 s.\n\n\nTotal speedup: 1.16/0.22 ~ 5.3 and close to the performance on numpy arrays that demonstrated Skeletor\n" ]
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074518386_dataframe_pandas_python.txt
Q: Using Usb Camera with Opencv Python I am developing a neural network with python opencv. It works when I turn on the laptop's own camera. When I plug in an external usb camera, I don't get any response. Independent of the program, only if I write opencv camera opening codes, it hangs. The program does not close, it seems to be running, but nothing happens. Why could it be? Opening usb camera for opencv python My Source Code: img_height = 128 img_width = 128 model = tf.keras.models.load_model("modelson.h5") camera_id = 1 camera_width = 1920 camera_height = 1080 camera_frame_rate = 30 camera_fourcc = cv2.VideoWriter_fourcc(*"MJPG") auto_percent = 0.2 auto_threshold = 127 auto_blur = 5 norm_alpha = 0 norm_beta = 255 A: The device index is just a number to determine which camera. Usually one camera will be connected (as in my case my camera id is 0). You can choose a second camera by changing camera id : 1 to camera id : 0 or camera id : 2. Camera id can be changed to index 0 - 9. hope this can help you
Using Usb Camera with Opencv Python
I am developing a neural network with python opencv. It works when I turn on the laptop's own camera. When I plug in an external usb camera, I don't get any response. Independent of the program, only if I write opencv camera opening codes, it hangs. The program does not close, it seems to be running, but nothing happens. Why could it be? Opening usb camera for opencv python My Source Code: img_height = 128 img_width = 128 model = tf.keras.models.load_model("modelson.h5") camera_id = 1 camera_width = 1920 camera_height = 1080 camera_frame_rate = 30 camera_fourcc = cv2.VideoWriter_fourcc(*"MJPG") auto_percent = 0.2 auto_threshold = 127 auto_blur = 5 norm_alpha = 0 norm_beta = 255
[ " The device index is just a number to determine which camera. Usually one camera will be connected (as in my case my camera id is 0). You can choose a second camera by changing camera id : 1 to camera id : 0 or camera id : 2. Camera id can be changed to index 0 - 9.\nhope this can help you\n" ]
[ 0 ]
[]
[]
[ "opencv", "python", "python_3.x" ]
stackoverflow_0074543478_opencv_python_python_3.x.txt
Q: groupby in pandas with custom function over a subset of rows in each group I have a pandas DataFrame of the following format: Input: X [OTHER_COLUMNS] version branch v0 overall 2475.0 -1 . v1 overall 2475.0 -1 . A 1712.5 1 . B 257.5 2 . C 392.5 2 D 112.5 3 v2 overall 2475.0 -1 A 2341.5 1 B 95.0 2 C 38.5 2 v3 overall 2475.0 -1 A 2000.0 1 B 475.0 2 v4 overall 2475.0 -1 A 2341.5 1 B 133.5 1 where (version, branch) is a MultiIndex. PROBLEM DESCRIPTION: I want to groupby version and set the values in the column X with branch overall to the sum of the values in the column X for the remaining branches (having the same version), weighted by the values in the column N. For groups (i.e. versions) which have only one branch (named overall), I want X to be set to 1. EXAMPLE: For version v2, the value in the cell with column X and branch overall should be (2341.5 * 1 + 95.0 * 2 + 38.5 * 2) / 2475.0 = 1.05393939394, and in pseudo-code: (A_N * A_X + B_N * B_X) / overall_N. Note: For a given version, the value in column N and branch overall will always be equal to the sum of the values in column N for the other branch'es. IDEA AND QUESTION: I think I have to do the following: df.loc[pd.IndexSlice[:, 'overall'], 'X'] = df.groupby('version').apply(...) where df is the DataFrame and where ... is to be replaced by a custom function. I am looking for help in constructing such a function. Expected output: N X version branch v0 overall 2475.0 1 v1 overall 2475.0 1.35353535354 A 1712.5 1 B 257.5 2 C 392.5 2 D 112.5 3 v2 overall 2475.0 1.05393939394 A 2341.5 1 B 95.0 2 C 38.5 2 v3 overall 2475.0 1.19191919192 A 2000.0 1 B 475.0 2 v4 overall 2475.0 1 A 2341.5 1 B 133.5 1 Explaination of expected output: (1712.5 * 1 + 257.5 * 2 + 392.5 * 2 + 112.5 * 3) / 2475.0 = 1.35353535354 (2341.5 * 1 + 95.0 * 2 + 38.5 * 2) / 2475.0 = 1.05393939394 (2000.0 * 1 + 475.0 * 2) / 2475.0 = 1.19191919192 (2341.5 * 1 + 133.5 * 1) / 2475.0 = 1 CODE TO CREATE DATAFRAME: import numpy as np import pandas as pd df = pd.DataFrame( data=np.array( [ [2475.0, 2475.0, 1712.5, 257.5, 392.5, 112.5, 2475.0, 2341.5, 95.0, 38.5, 2475.0, 2000.0, 475.0, 2475.0, 2341.5, 133.5], [-1, -1, 1, 2, 2, 3, -1, 1, 2, 2, -1, 1, 2, -1, 1, 1] ] ).T, index=pd.MultiIndex.from_tuples( tuples=[ ('v0', 'overall'), ('v1', 'overall'), ('v1', 'A'), ('v1', 'B'), ('v1', 'C'), ('v1', 'D'), ('v2', 'overall'), ('v2', 'A'), ('v2', 'B'), ('v2', 'C'), ('v3', 'overall'), ('v3', 'A'), ('v3', 'B'), ('v4', 'overall'), ('v4', 'A'), ('v4', 'B'), ], names=['version', 'branch'], ), columns=['N', 'X'], ) print (df) N X version branch v0 overall 2475.0 -1.0 v1 overall 2475.0 -1.0 A 1712.5 1.0 B 257.5 2.0 C 392.5 2.0 D 112.5 3.0 v2 overall 2475.0 -1.0 A 2341.5 1.0 B 95.0 2.0 C 38.5 2.0 v3 overall 2475.0 -1.0 A 2000.0 1.0 B 475.0 2.0 v4 overall 2475.0 -1.0 A 2341.5 1.0 B 133.5 1.0 A: Use: #select overalls only overall = df['N'].xs('overall', level=1) #select all rows without overalls df1 = df.drop('overall', level=1) #multiple and aggregate sum, divide overalls s = df1['N'].mul(df1['X']).groupby(level=0).sum().div(overall) #create MultiIndex and assign back df.loc[pd.IndexSlice[:, 'overall'], 'X'] = pd.concat({'overall':s}).swaplevel(0,1) print (df) N X version branch v1 overall 2475.0 1.353535 A 1712.5 1.000000 B 257.5 2.000000 C 392.5 2.000000 D 112.5 3.000000 v2 overall 2475.0 1.053939 A 2341.5 1.000000 B 95.0 2.000000 C 38.5 2.000000 v3 overall 2475.0 1.191919 A 2000.0 1.000000 B 475.0 2.000000 v4 overall 2475.0 1.000000 A 2341.5 1.000000 B 133.5 1.000000
groupby in pandas with custom function over a subset of rows in each group
I have a pandas DataFrame of the following format: Input: X [OTHER_COLUMNS] version branch v0 overall 2475.0 -1 . v1 overall 2475.0 -1 . A 1712.5 1 . B 257.5 2 . C 392.5 2 D 112.5 3 v2 overall 2475.0 -1 A 2341.5 1 B 95.0 2 C 38.5 2 v3 overall 2475.0 -1 A 2000.0 1 B 475.0 2 v4 overall 2475.0 -1 A 2341.5 1 B 133.5 1 where (version, branch) is a MultiIndex. PROBLEM DESCRIPTION: I want to groupby version and set the values in the column X with branch overall to the sum of the values in the column X for the remaining branches (having the same version), weighted by the values in the column N. For groups (i.e. versions) which have only one branch (named overall), I want X to be set to 1. EXAMPLE: For version v2, the value in the cell with column X and branch overall should be (2341.5 * 1 + 95.0 * 2 + 38.5 * 2) / 2475.0 = 1.05393939394, and in pseudo-code: (A_N * A_X + B_N * B_X) / overall_N. Note: For a given version, the value in column N and branch overall will always be equal to the sum of the values in column N for the other branch'es. IDEA AND QUESTION: I think I have to do the following: df.loc[pd.IndexSlice[:, 'overall'], 'X'] = df.groupby('version').apply(...) where df is the DataFrame and where ... is to be replaced by a custom function. I am looking for help in constructing such a function. Expected output: N X version branch v0 overall 2475.0 1 v1 overall 2475.0 1.35353535354 A 1712.5 1 B 257.5 2 C 392.5 2 D 112.5 3 v2 overall 2475.0 1.05393939394 A 2341.5 1 B 95.0 2 C 38.5 2 v3 overall 2475.0 1.19191919192 A 2000.0 1 B 475.0 2 v4 overall 2475.0 1 A 2341.5 1 B 133.5 1 Explaination of expected output: (1712.5 * 1 + 257.5 * 2 + 392.5 * 2 + 112.5 * 3) / 2475.0 = 1.35353535354 (2341.5 * 1 + 95.0 * 2 + 38.5 * 2) / 2475.0 = 1.05393939394 (2000.0 * 1 + 475.0 * 2) / 2475.0 = 1.19191919192 (2341.5 * 1 + 133.5 * 1) / 2475.0 = 1 CODE TO CREATE DATAFRAME: import numpy as np import pandas as pd df = pd.DataFrame( data=np.array( [ [2475.0, 2475.0, 1712.5, 257.5, 392.5, 112.5, 2475.0, 2341.5, 95.0, 38.5, 2475.0, 2000.0, 475.0, 2475.0, 2341.5, 133.5], [-1, -1, 1, 2, 2, 3, -1, 1, 2, 2, -1, 1, 2, -1, 1, 1] ] ).T, index=pd.MultiIndex.from_tuples( tuples=[ ('v0', 'overall'), ('v1', 'overall'), ('v1', 'A'), ('v1', 'B'), ('v1', 'C'), ('v1', 'D'), ('v2', 'overall'), ('v2', 'A'), ('v2', 'B'), ('v2', 'C'), ('v3', 'overall'), ('v3', 'A'), ('v3', 'B'), ('v4', 'overall'), ('v4', 'A'), ('v4', 'B'), ], names=['version', 'branch'], ), columns=['N', 'X'], ) print (df) N X version branch v0 overall 2475.0 -1.0 v1 overall 2475.0 -1.0 A 1712.5 1.0 B 257.5 2.0 C 392.5 2.0 D 112.5 3.0 v2 overall 2475.0 -1.0 A 2341.5 1.0 B 95.0 2.0 C 38.5 2.0 v3 overall 2475.0 -1.0 A 2000.0 1.0 B 475.0 2.0 v4 overall 2475.0 -1.0 A 2341.5 1.0 B 133.5 1.0
[ "Use:\n#select overalls only\noverall = df['N'].xs('overall', level=1)\n#select all rows without overalls\ndf1 = df.drop('overall', level=1)\n\n#multiple and aggregate sum, divide overalls \ns = df1['N'].mul(df1['X']).groupby(level=0).sum().div(overall)\n\n#create MultiIndex and assign back\ndf.loc[pd.IndexSlice[:, 'overall'], 'X'] = pd.concat({'overall':s}).swaplevel(0,1)\n\n\nprint (df)\n N X\nversion branch \nv1 overall 2475.0 1.353535\n A 1712.5 1.000000\n B 257.5 2.000000\n C 392.5 2.000000\n D 112.5 3.000000\nv2 overall 2475.0 1.053939\n A 2341.5 1.000000\n B 95.0 2.000000\n C 38.5 2.000000\nv3 overall 2475.0 1.191919\n A 2000.0 1.000000\n B 475.0 2.000000\nv4 overall 2475.0 1.000000\n A 2341.5 1.000000\n B 133.5 1.000000\n\n" ]
[ 1 ]
[]
[]
[ "aggregate", "group_by", "pandas", "python" ]
stackoverflow_0074560070_aggregate_group_by_pandas_python.txt
Q: How to truncate the time on a datetime object? What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string. A: I think this is what you're looking for... >>> import datetime >>> dt = datetime.datetime.now() >>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy >>> dt datetime.datetime(2011, 3, 29, 0, 0) But if you really don't care about the time aspect of things, then you should really only be passing around date objects... >>> d_truncated = datetime.date(dt.year, dt.month, dt.day) >>> d_truncated datetime.date(2011, 3, 29) A: Use a date not a datetime if you dont care about the time. >>> now = datetime.now() >>> now.date() datetime.date(2011, 3, 29) You can update a datetime like this: >>> now.replace(minute=0, hour=0, second=0, microsecond=0) datetime.datetime(2011, 3, 29, 0, 0) A: Four years later: another way, avoiding replace I know the accepted answer from four years ago works, but this seems a tad lighter than using replace: dt = datetime.date.today() dt = datetime.datetime(dt.year, dt.month, dt.day) Notes When you create a datetime object without passing time properties to the constructor, you get midnight. As others have noted, this assumes you want a datetime object for later use with timedeltas. You can, of course, substitute this for the first line: dt = datetime.datetime.now() A: You cannot truncate a datetime object because it is immutable. However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo: newdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0) A: To get a midnight corresponding to a given datetime object, you could use datetime.combine() method: >>> from datetime import datetime, time >>> dt = datetime.utcnow() >>> dt.date() datetime.date(2015, 2, 3) >>> datetime.combine(dt, time.min) datetime.datetime(2015, 2, 3, 0, 0) The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support. tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone? A: See more at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html It's now 2019, I think the most efficient way to do it is: df['truncate_date'] = df['timestamp'].dt.floor('d') A: You could use pandas for that (although it could be overhead for that task). You could use round, floor and ceil like for usual numbers and any pandas frequency from offset-aliases: import pandas as pd import datetime as dt now = dt.datetime.now() pd_now = pd.Timestamp(now) freq = '1d' pd_round = pd_now.round(freq) dt_round = pd_round.to_pydatetime() print(now) print(dt_round) """ 2018-06-15 09:33:44.102292 2018-06-15 00:00:00 """ A: There is a great library used to manipulate dates: Delorean import datetime from delorean import Delorean now = datetime.datetime.now() d = Delorean(now, timezone='US/Pacific') >>> now datetime.datetime(2015, 3, 26, 19, 46, 40, 525703) >>> d.truncate('second') Delorean(datetime=2015-03-26 19:46:40-07:00, timezone='US/Pacific') >>> d.truncate('minute') Delorean(datetime=2015-03-26 19:46:00-07:00, timezone='US/Pacific') >>> d.truncate('hour') Delorean(datetime=2015-03-26 19:00:00-07:00, timezone='US/Pacific') >>> d.truncate('day') Delorean(datetime=2015-03-26 00:00:00-07:00, timezone='US/Pacific') >>> d.truncate('month') Delorean(datetime=2015-03-01 00:00:00-07:00, timezone='US/Pacific') >>> d.truncate('year') Delorean(datetime=2015-01-01 00:00:00-07:00, timezone='US/Pacific') and if you want to get datetime value back: >>> d.truncate('year').datetime datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>) A: You can use datetime.strftime to extract the day, the month, the year... Example : from datetime import datetime d = datetime.today() # Retrieves the day and the year print d.strftime("%d-%Y") Output (for today): 29-2011 If you just want to retrieve the day, you can use day attribute like : from datetime import datetime d = datetime.today() # Retrieves the day print d.day Ouput (for today): 29 A: If you are dealing with a Series of type DateTime there is a more efficient way to truncate them, specially when the Series object has a lot of rows. You can use the floor function For example, if you want to truncate it to hours: Generate a range of dates times = pd.Series(pd.date_range(start='1/1/2018 04:00:00', end='1/1/2018 22:00:00', freq='s')) We can check it comparing the running time between the replace and the floor functions. %timeit times.apply(lambda x : x.replace(minute=0, second=0, microsecond=0)) >>> 341 ms ± 18.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit times.dt.floor('h') >>>>2.26 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) A: >>> import datetime >>> dt = datetime.datetime.now() >>> datetime.datetime.date(dt) datetime.date(2019, 4, 2) A: Here is yet another way which fits in one line but is not particularly elegant: dt = datetime.datetime.fromordinal(datetime.date.today().toordinal()) A: There is a module datetime_truncate which handlers this for you. It just calls datetime.replace. A: 6 years later... I found this post and I liked more the numpy aproach: import numpy as np dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]') truncated_dates = dates_array.astype('datetime64[D]') cheers A: You can just use datetime.date.today() It's light and returns exactly what you want. A: If you want to truncate to an arbitrary timedelta: from datetime import datetime, timedelta truncate = lambda t, d: t + (datetime.min - t) % - d # 2022-05-04 15:54:19.979349 now = datetime.now() # truncates to the last 15 secondes print(truncate(now, timedelta(seconds=15))) # truncates to the last minute print(truncate(now, timedelta(minutes=1))) # truncates to the last 2 hours print(truncate(now, timedelta(hours=2))) # ... """ 2022-05-04 15:54:15 2022-05-04 15:54:00 2022-05-04 14:00:00 """ PS: This is for python3 A: You could do it by specifying isoformat >>> import datetime >>> datetime.datetime.now().isoformat(timespec='seconds', sep=' ') 2022-11-24 12:42:05 The documentation offers more details about the isoformat() usage. https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat
How to truncate the time on a datetime object?
What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string.
[ "I think this is what you're looking for...\n>>> import datetime\n>>> dt = datetime.datetime.now()\n>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy\n>>> dt\ndatetime.datetime(2011, 3, 29, 0, 0)\n\nBut if you really don't care about the time aspect of things, then you should really only be passing around date objects...\n>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)\n>>> d_truncated\ndatetime.date(2011, 3, 29)\n\n", "Use a date not a datetime if you dont care about the time.\n>>> now = datetime.now()\n>>> now.date()\ndatetime.date(2011, 3, 29)\n\nYou can update a datetime like this:\n>>> now.replace(minute=0, hour=0, second=0, microsecond=0)\ndatetime.datetime(2011, 3, 29, 0, 0)\n\n", "Four years later: another way, avoiding replace\nI know the accepted answer from four years ago works, but this seems a tad lighter than using replace:\ndt = datetime.date.today()\ndt = datetime.datetime(dt.year, dt.month, dt.day)\n\nNotes\n\nWhen you create a datetime object without passing time properties to the constructor, you get midnight.\nAs others have noted, this assumes you want a datetime object for later use with timedeltas. \nYou can, of course, substitute this for the first line: dt = datetime.datetime.now()\n\n", "You cannot truncate a datetime object because it is immutable.\nHowever, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo:\nnewdatetime = now.replace(hour=0, minute=0, second=0, microsecond=0)\n\n", "To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:\n>>> from datetime import datetime, time\n>>> dt = datetime.utcnow()\n>>> dt.date()\ndatetime.date(2015, 2, 3)\n>>> datetime.combine(dt, time.min)\ndatetime.datetime(2015, 2, 3, 0, 0)\n\nThe advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.\ntzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?\n", "See more at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html\nIt's now 2019, I think the most efficient way to do it is:\ndf['truncate_date'] = df['timestamp'].dt.floor('d')\n\n", "You could use pandas for that (although it could be overhead for that task). You could use round, floor and ceil like for usual numbers and any pandas frequency from offset-aliases:\nimport pandas as pd\nimport datetime as dt\n\nnow = dt.datetime.now()\npd_now = pd.Timestamp(now)\n\nfreq = '1d'\npd_round = pd_now.round(freq)\ndt_round = pd_round.to_pydatetime()\n\nprint(now)\nprint(dt_round)\n\n\"\"\"\n2018-06-15 09:33:44.102292\n2018-06-15 00:00:00\n\"\"\"\n\n", "There is a great library used to manipulate dates: Delorean\nimport datetime\nfrom delorean import Delorean\nnow = datetime.datetime.now()\nd = Delorean(now, timezone='US/Pacific')\n\n>>> now \ndatetime.datetime(2015, 3, 26, 19, 46, 40, 525703)\n\n>>> d.truncate('second')\nDelorean(datetime=2015-03-26 19:46:40-07:00, timezone='US/Pacific')\n\n>>> d.truncate('minute')\nDelorean(datetime=2015-03-26 19:46:00-07:00, timezone='US/Pacific')\n\n>>> d.truncate('hour')\nDelorean(datetime=2015-03-26 19:00:00-07:00, timezone='US/Pacific')\n\n>>> d.truncate('day')\nDelorean(datetime=2015-03-26 00:00:00-07:00, timezone='US/Pacific')\n\n>>> d.truncate('month')\nDelorean(datetime=2015-03-01 00:00:00-07:00, timezone='US/Pacific')\n\n>>> d.truncate('year')\nDelorean(datetime=2015-01-01 00:00:00-07:00, timezone='US/Pacific')\n\nand if you want to get datetime value back:\n>>> d.truncate('year').datetime\ndatetime.datetime(2015, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)\n\n", "You can use datetime.strftime to extract the day, the month, the year...\nExample :\nfrom datetime import datetime\nd = datetime.today()\n\n# Retrieves the day and the year\nprint d.strftime(\"%d-%Y\")\n\nOutput (for today):\n29-2011\n\nIf you just want to retrieve the day, you can use day attribute like :\nfrom datetime import datetime\nd = datetime.today()\n\n# Retrieves the day\nprint d.day\n\nOuput (for today):\n29\n\n", "If you are dealing with a Series of type DateTime there is a more efficient way to truncate them, specially when the Series object has a lot of rows. \nYou can use the floor function \nFor example, if you want to truncate it to hours: \nGenerate a range of dates\ntimes = pd.Series(pd.date_range(start='1/1/2018 04:00:00', end='1/1/2018 22:00:00', freq='s'))\n\nWe can check it comparing the running time between the replace and the floor functions.\n%timeit times.apply(lambda x : x.replace(minute=0, second=0, microsecond=0))\n>>> 341 ms ± 18.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit times.dt.floor('h')\n>>>>2.26 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n", ">>> import datetime\n>>> dt = datetime.datetime.now()\n>>> datetime.datetime.date(dt)\ndatetime.date(2019, 4, 2)\n\n", "Here is yet another way which fits in one line but is not particularly elegant:\ndt = datetime.datetime.fromordinal(datetime.date.today().toordinal())\n\n", "There is a module datetime_truncate which handlers this for you. It just calls datetime.replace.\n", "6 years later... I found this post and I liked more the numpy aproach:\nimport numpy as np\ndates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')\ntruncated_dates = dates_array.astype('datetime64[D]')\n\ncheers\n", "You can just use\ndatetime.date.today()\n\nIt's light and returns exactly what you want.\n", "If you want to truncate to an arbitrary timedelta:\nfrom datetime import datetime, timedelta\ntruncate = lambda t, d: t + (datetime.min - t) % - d\n# 2022-05-04 15:54:19.979349\nnow = datetime.now()\n\n# truncates to the last 15 secondes\nprint(truncate(now, timedelta(seconds=15)))\n# truncates to the last minute\nprint(truncate(now, timedelta(minutes=1)))\n# truncates to the last 2 hours\nprint(truncate(now, timedelta(hours=2)))\n# ...\n\n\"\"\"\n2022-05-04 15:54:15\n2022-05-04 15:54:00\n2022-05-04 14:00:00\n\"\"\"\n\nPS: This is for python3\n", "You could do it by specifying isoformat\n>>> import datetime\n>>> datetime.datetime.now().isoformat(timespec='seconds', sep=' ')\n2022-11-24 12:42:05\n\nThe documentation offers more details about the isoformat() usage.\nhttps://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat\n" ]
[ 498, 96, 48, 24, 24, 12, 10, 4, 3, 3, 3, 2, 1, 1, 1, 1, 0 ]
[ "What does truncate mean?\nYou have full control over the formatting by using the strftime() method and using an appropriate format string.\nhttp://docs.python.org/library/datetime.html#strftime-strptime-behavior\n" ]
[ -3 ]
[ "datetime", "python" ]
stackoverflow_0005476065_datetime_python.txt
Q: python Remembering the list for another use suppose we have a main.py file and a_file.py that has a list like this : main.py from a_file import * while true: example = input("Enter Something : ") a_list.append(example) if example == 'showlist': print(a_list) a_file.py a_list = [] so as you can see the main.py file has a input that whatever you type in it gets stored in the a_list list in a_file.py when you first want to run the main.py it will ask some input in a loop and whatever you type gets appended to the a_list in the a_file.py Here is the problem... i want whatever you type in the input get stored in the list permanently because when you close the python script and run it again , the list will be empty so i want that everything that gets stored in the list permanently be in the list so good luck helping me.. Thanks for reading my problem A: instead of putting the data in a list try using file handling methods to save your input in a permanent file like: file = open("FILE PATH\\FILE NAME.txt", "w") while True: example = input("Enter Something : ") file.write(example) if example == 'showlist': for line in file: print(line) and by the way......try putting the if condition before adding the data to the file and making the adding in the else statement so that when you type "showlist" in the input you don't find it in the file. but the code above is just what you wanted, Hope that helps you. A: You need to save the list to a separate file and every time you start the program, you first have to read from that file and fill the list with all entries that are saved in the file. There are multiple ways to do this. One would be to write the entries of a list to a text file, as long as the list will contain only strings, not arbitrary objects. You could do it like this: import os # For convenience I have moved the list to the same file # It's not necessary though a_list = [] savefile = 'data.txt' # Repopulate the list with the entries in the file if it exists if os.path.exists(savefile): with open(savefile, 'r') as f: a_list = [line.rstrip('\n') for line in f.readlines()] while True: example = input("Enter Something : ") # It would be a good idea to introduce a break condition # This is just a suggestion on how to do it if example == 'stop loop': break a_list.append(example) # Check if file already exists if not os.path.exists(savefile): # If it doesn't exist, create it with open(savefile, 'w') as f: f.write(example + '\n') else: # If it exists, append to it with open(savefile, 'a') as f: f.write(example + '\n') if example == 'showlist': print(a_list) Another way would be to serialize the list using pickle. Here, we store the whole list at once when the program terminates, so here you definitely need a break condition. On program start, we load the list from the pickle file. import os import pickle a_list = [] savefile = 'data.pickle' if os.path.exists(savefile): with open(savefile, 'rb') as f: a_list = pickle.load(f) while True: example = input("Enter Something : ") if example == 'stop loop': with open(savefile, 'wb') as f: pickle.dump(a_list, f) break a_list.append(example) if example == 'showlist': print(a_list)
python Remembering the list for another use
suppose we have a main.py file and a_file.py that has a list like this : main.py from a_file import * while true: example = input("Enter Something : ") a_list.append(example) if example == 'showlist': print(a_list) a_file.py a_list = [] so as you can see the main.py file has a input that whatever you type in it gets stored in the a_list list in a_file.py when you first want to run the main.py it will ask some input in a loop and whatever you type gets appended to the a_list in the a_file.py Here is the problem... i want whatever you type in the input get stored in the list permanently because when you close the python script and run it again , the list will be empty so i want that everything that gets stored in the list permanently be in the list so good luck helping me.. Thanks for reading my problem
[ "instead of putting the data in a list try using file handling methods to save your input in a permanent file like:\nfile = open(\"FILE PATH\\\\FILE NAME.txt\", \"w\")\nwhile True:\n example = input(\"Enter Something : \")\n\n file.write(example)\n\n if example == 'showlist':\n\n for line in file:\n print(line)\n\nand by the way......try putting the if condition before adding the data to the file and making the adding in the else statement so that when you type \"showlist\" in the input you don't find it in the file.\nbut the code above is just what you wanted,\nHope that helps you.\n", "You need to save the list to a separate file and every time you start the program, you first have to read from that file and fill the list with all entries that are saved in the file.\nThere are multiple ways to do this. One would be to write the entries of a list to a text file, as long as the list will contain only strings, not arbitrary objects. You could do it like this:\nimport os\n# For convenience I have moved the list to the same file\n# It's not necessary though\na_list = []\n\nsavefile = 'data.txt'\n\n# Repopulate the list with the entries in the file if it exists\nif os.path.exists(savefile):\n with open(savefile, 'r') as f:\n a_list = [line.rstrip('\\n') for line in f.readlines()]\n\nwhile True:\n example = input(\"Enter Something : \")\n \n # It would be a good idea to introduce a break condition\n # This is just a suggestion on how to do it\n if example == 'stop loop':\n break\n\n a_list.append(example)\n \n # Check if file already exists\n if not os.path.exists(savefile):\n # If it doesn't exist, create it\n with open(savefile, 'w') as f:\n f.write(example + '\\n')\n else:\n # If it exists, append to it\n with open(savefile, 'a') as f:\n f.write(example + '\\n')\n\n if example == 'showlist':\n print(a_list)\n\nAnother way would be to serialize the list using pickle. Here, we store the whole list at once when the program terminates, so here you definitely need a break condition. On program start, we load the list from the pickle file.\nimport os\nimport pickle\n\na_list = []\n\nsavefile = 'data.pickle'\n\nif os.path.exists(savefile):\n with open(savefile, 'rb') as f:\n a_list = pickle.load(f)\n\nwhile True:\n example = input(\"Enter Something : \")\n\n if example == 'stop loop':\n with open(savefile, 'wb') as f:\n pickle.dump(a_list, f)\n break\n\n a_list.append(example)\n\n if example == 'showlist':\n print(a_list)\n\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074559770_list_python.txt
Q: Flatten nested dictionaries, compressing keys Suppose you have a dictionary like: {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} How would you go about flattening that into something like: {'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]} A: Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. import collections def flatten(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) >>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10} For Python >= 3.3, change the import to from collections.abc import MutableMapping to avoid a deprecation warning and change collections.MutableMapping to just MutableMapping. A: Or if you are already using pandas, You can do it with json_normalize() like so: import pandas as pd d = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} df = pd.json_normalize(d, sep='_') print(df.to_dict(orient='records')[0]) Output: {'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]} A: There are two big considerations that the original poster needs to consider: Are there keyspace clobbering issues? For example, {'a_b':{'c':1}, 'a':{'b_c':2}} would result in {'a_b_c':???}. The below solution evades the problem by returning an iterable of pairs. If performance is an issue, does the key-reducer function (which I hereby refer to as 'join') require access to the entire key-path, or can it just do O(1) work at every node in the tree? If you want to be able to say joinedKey = '_'.join(*keys), that will cost you O(N^2) running time. However if you're willing to say nextKey = previousKey+'_'+thisKey, that gets you O(N) time. The solution below lets you do both (since you could merely concatenate all the keys, then postprocess them). (Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or anything equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key a then a_1 then a_1_i..., and then calculating a then a_1 then a_1_ii..., but really you shouldn't have to calculate a_1 again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on {1:{1:{1:{1:...(N times)...{1:SOME_LARGE_DICTIONARY_OF_SIZE_N}...}}}}) Below is a function I wrote flattenDict(d, join=..., lift=...) which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one). from collections import Mapping from itertools import chain from operator import add _FLAG_FIRST = object() def flattenDict(d, join=add, lift=lambda x:(x,)): results = [] def visit(subdict, results, partialKey): for k,v in subdict.items(): newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k)) if isinstance(v,Mapping): visit(v, results, newKey) else: results.append((newKey,v)) visit(d, results, _FLAG_FIRST) return results To better understand what's going on, below is a diagram for those unfamiliar with reduce(left), otherwise known as "fold left". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here, J is our join function. We preprocess each kn with lift(k). [k0,k1,...,kN].foldleft(J) / \ ... kN / J(k0,J(k1,J(k2,k3))) / \ / \ J(J(k0,k1),k2) k3 / \ / \ J(k0,k1) k2 / \ / \ k0 k1 This is in fact the same as functools.reduce, but where our function does this to all key-paths of the tree. >>> reduce(lambda a,b:(a,b), range(5)) ((((0, 1), 2), 3), 4) Demonstration (which I'd otherwise put in docstring): >>> testData = { 'a':1, 'b':2, 'c':{ 'aa':11, 'bb':22, 'cc':{ 'aaa':111 } } } from pprint import pprint as pp >>> pp(dict( flattenDict(testData) )) {('a',): 1, ('b',): 2, ('c', 'aa'): 11, ('c', 'bb'): 22, ('c', 'cc', 'aaa'): 111} >>> pp(dict( flattenDict(testData, join=lambda a,b:a+'_'+b, lift=lambda x:x) )) {'a': 1, 'b': 2, 'c_aa': 11, 'c_bb': 22, 'c_cc_aaa': 111} >>> pp(dict( (v,k) for k,v in flattenDict(testData, lift=hash, join=lambda a,b:hash((a,b))) )) {1: 12416037344, 2: 12544037731, 11: 5470935132935744593, 22: 4885734186131977315, 111: 3461911260025554326} Performance: from functools import reduce def makeEvilDict(n): return reduce(lambda acc,x:{x:acc}, [{i:0 for i in range(n)}]+range(n)) import timeit def time(runnable): t0 = timeit.default_timer() _ = runnable() t1 = timeit.default_timer() print('took {:.2f} seconds'.format(t1-t0)) >>> pp(makeEvilDict(8)) {7: {6: {5: {4: {3: {2: {1: {0: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}}}}}}}}} import sys sys.setrecursionlimit(1000000) forget = lambda a,b:'' >>> time(lambda: dict(flattenDict(makeEvilDict(10000), join=forget)) ) took 0.10 seconds >>> time(lambda: dict(flattenDict(makeEvilDict(100000), join=forget)) ) [1] 12569 segmentation fault python ... sigh, don't think that one is my fault... [unimportant historical note due to moderation issues] Regarding the alleged duplicate of Flatten a dictionary of dictionaries (2 levels deep) of lists That question's solution can be implemented in terms of this one by doing sorted( sum(flatten(...),[]) ). The reverse is not possible: while it is true that the values of flatten(...) can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.) A: If you're using pandas there is a function hidden in pandas.io.json._normalize1 called nested_to_record which does this exactly. from pandas.io.json._normalize import nested_to_record flat = nested_to_record(my_dict, sep='_') 1 In pandas versions 0.24.x and older use pandas.io.json.normalize (without the _) A: Here is a kind of a "functional", "one-liner" implementation. It is recursive, and based on a conditional expression and a dict comprehension. def flatten_dict(dd, separator='_', prefix=''): return { prefix + separator + k if prefix else k : v for kk, vv in dd.items() for k, v in flatten_dict(vv, separator, kk).items() } if isinstance(dd, dict) else { prefix : dd } Test: In [2]: flatten_dict({'abc':123, 'hgf':{'gh':432, 'yu':433}, 'gfd':902, 'xzxzxz':{"432":{'0b0b0b':231}, "43234":1321}}, '.') Out[2]: {'abc': 123, 'gfd': 902, 'hgf.gh': 432, 'hgf.yu': 433, 'xzxzxz.432.0b0b0b': 231, 'xzxzxz.43234': 1321} A: Not exactly what the OP asked, but lots of folks are coming here looking for ways to flatten real-world nested JSON data which can have nested key-value json objects and arrays and json objects inside the arrays and so on. JSON doesn't include tuples, so we don't have to fret over those. I found an implementation of the list-inclusion comment by @roneo to the answer posted by @Imran : https://github.com/ScriptSmith/socialreaper/blob/master/socialreaper/tools.py#L8 import collections def flatten(dictionary, parent_key=False, separator='.'): """ Turn a nested dictionary into a flattened dictionary :param dictionary: The dictionary to flatten :param parent_key: The string to prepend to dictionary's keys :param separator: The string used to separate flattened keys :return: A flattened dictionary """ items = [] for key, value in dictionary.items(): new_key = str(parent_key) + separator + key if parent_key else key if isinstance(value, collections.MutableMapping): items.extend(flatten(value, new_key, separator).items()) elif isinstance(value, list): for k, v in enumerate(value): items.extend(flatten({str(k): v}, new_key).items()) else: items.append((new_key, value)) return dict(items) Test it: flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3] }) >> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3} Annd that does the job I need done: I throw any complicated json at this and it flattens it out for me. All credits to https://github.com/ScriptSmith . A: Code: test = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} def parse_dict(init, lkey=''): ret = {} for rkey,val in init.items(): key = lkey+rkey if isinstance(val, dict): ret.update(parse_dict(val, key+'_')) else: ret[key] = val return ret print(parse_dict(test,'')) Results: $ python test.py {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10} I am using python3.2, update for your version of python. A: This is not restricted to dictionaries, but every mapping type that implements .items(). Further ist faster as it avoides an if condition. Nevertheless credits go to Imran: def flatten(d, parent_key=''): items = [] for k, v in d.items(): try: items.extend(flatten(v, '%s%s_' % (parent_key, k)).items()) except AttributeError: items.append(('%s%s' % (parent_key, k), v)) return dict(items) A: If you are a fan of pythonic oneliners: my_dict={'a': 1,'c': {'a': 2,'b': {'x': 5,'y' : 10}},'d': [1, 2, 3]} list(pd.json_normalize(my_dict).T.to_dict().values())[0] returns: {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd': [1, 2, 3]} You can leave the [0] from the end, if you have a list of dictionaries and not just a single dictionary. A: How about a functional and performant solution in Python3.5? from functools import reduce def _reducer(items, key, val, pref): if isinstance(val, dict): return {**items, **flatten(val, pref + key)} else: return {**items, pref + key: val} def flatten(d, pref=''): return(reduce( lambda new_d, kv: _reducer(new_d, *kv, pref), d.items(), {} )) This is even more performant: def flatten(d, pref=''): return(reduce( lambda new_d, kv: \ isinstance(kv[1], dict) and \ {**new_d, **flatten(kv[1], pref + kv[0])} or \ {**new_d, pref + kv[0]: kv[1]}, d.items(), {} )) In use: my_obj = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y': 10}}, 'd': [1, 2, 3]} print(flatten(my_obj)) # {'d': [1, 2, 3], 'cby': 10, 'cbx': 5, 'ca': 2, 'a': 1} A: My Python 3.3 Solution using generators: def flattenit(pyobj, keystring=''): if type(pyobj) is dict: if (type(pyobj) is dict): keystring = keystring + "_" if keystring else keystring for k in pyobj: yield from flattenit(pyobj[k], keystring + k) elif (type(pyobj) is list): for lelm in pyobj: yield from flatten(lelm, keystring) else: yield keystring, pyobj my_obj = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y': 10}}, 'd': [1, 2, 3]} #your flattened dictionary object flattened={k:v for k,v in flattenit(my_obj)} print(flattened) # result: {'c_b_y': 10, 'd': [1, 2, 3], 'c_a': 2, 'a': 1, 'c_b_x': 5} A: Utilizing recursion, keeping it simple and human readable: def flatten_dict(dictionary, accumulator=None, parent_key=None, separator="."): if accumulator is None: accumulator = {} for k, v in dictionary.items(): k = f"{parent_key}{separator}{k}" if parent_key else k if isinstance(v, dict): flatten_dict(dictionary=v, accumulator=accumulator, parent_key=k) continue accumulator[k] = v return accumulator Call is simple: new_dict = flatten_dict(dictionary) or new_dict = flatten_dict(dictionary, separator="_") if we want to change the default separator. A little breakdown: When the function is first called, it is called only passing the dictionary we want to flatten. The accumulator parameter is here to support recursion, which we see later. So, we instantiate accumulator to an empty dictionary where we will put all of the nested values from the original dictionary. if accumulator is None: accumulator = {} As we iterate over the dictionary's values, we construct a key for every value. The parent_key argument will be None for the first call, while for every nested dictionary, it will contain the key pointing to it, so we prepend that key. k = f"{parent_key}{separator}{k}" if parent_key else k In case the value v the key k is pointing to is a dictionary, the function calls itself, passing the nested dictionary, the accumulator (which is passed by reference, so all changes done to it are done on the same instance) and the key k so that we can construct the concatenated key. Notice the continue statement. We want to skip the next line, outside of the if block, so that the nested dictionary doesn't end up in the accumulator under key k. if isinstance(v, dict): flatten_dict(dict=v, accumulator=accumulator, parent_key=k) continue So, what do we do in case the value v is not a dictionary? Just put it unchanged inside the accumulator. accumulator[k] = v Once we're done we just return the accumulator, leaving the original dictionary argument untouched. NOTE This will work only with dictionaries that have strings as keys. It will work with hashable objects implementing the __repr__ method, but will yield unwanted results. A: Simple function to flatten nested dictionaries. For Python 3, replace .iteritems() with .items() def flatten_dict(init_dict): res_dict = {} if type(init_dict) is not dict: return res_dict for k, v in init_dict.iteritems(): if type(v) == dict: res_dict.update(flatten_dict(v)) else: res_dict[k] = v return res_dict The idea/requirement was: Get flat dictionaries with no keeping parent keys. Example of usage: dd = {'a': 3, 'b': {'c': 4, 'd': 5}, 'e': {'f': {'g': 1, 'h': 2} }, 'i': 9, } flatten_dict(dd) >> {'a': 3, 'c': 4, 'd': 5, 'g': 1, 'h': 2, 'i': 9} Keeping parent keys is simple as well. A: I was thinking of a subclass of UserDict to automagically flat the keys. class FlatDict(UserDict): def __init__(self, *args, separator='.', **kwargs): self.separator = separator super().__init__(*args, **kwargs) def __setitem__(self, key, value): if isinstance(value, dict): for k1, v1 in FlatDict(value, separator=self.separator).items(): super().__setitem__(f"{key}{self.separator}{k1}", v1) else: super().__setitem__(key, value) ‌ The advantages it that keys can be added on the fly, or using standard dict instanciation, without surprise: ‌ >>> fd = FlatDict( ... { ... 'person': { ... 'sexe': 'male', ... 'name': { ... 'first': 'jacques', ... 'last': 'dupond' ... } ... } ... } ... ) >>> fd {'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond'} >>> fd['person'] = {'name': {'nickname': 'Bob'}} >>> fd {'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob'} >>> fd['person.name'] = {'civility': 'Dr'} >>> fd {'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob', 'person.name.civility': 'Dr'} A: Using generators: def flat_dic_helper(prepand,d): if len(prepand) > 0: prepand = prepand + "_" for k in d: i = d[k] if isinstance(i, dict): r = flat_dic_helper(prepand + k,i) for j in r: yield j else: yield (prepand + k,i) def flat_dic(d): return dict(flat_dic_helper("",d)) d = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} print(flat_dic(d)) >> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10} A: This is similar to both imran's and ralu's answer. It does not use a generator, but instead employs recursion with a closure: def flatten_dict(d, separator='_'): final = {} def _flatten_dict(obj, parent_keys=[]): for k, v in obj.iteritems(): if isinstance(v, dict): _flatten_dict(v, parent_keys + [k]) else: key = separator.join(parent_keys + [k]) final[key] = v _flatten_dict(d) return final >>> print flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10} A: The answers above work really well. Just thought I'd add the unflatten function that I wrote: def unflatten(d): ud = {} for k, v in d.items(): context = ud for sub_key in k.split('_')[:-1]: if sub_key not in context: context[sub_key] = {} context = context[sub_key] context[k.split('_')[-1]] = v return ud Note: This doesn't account for '_' already present in keys, much like the flatten counterparts. A: Davoud's solution is very nice but doesn't give satisfactory results when the nested dict also contains lists of dicts, but his code be adapted for that case: def flatten_dict(d): items = [] for k, v in d.items(): try: if (type(v)==type([])): for l in v: items.extend(flatten_dict(l).items()) else: items.extend(flatten_dict(v).items()) except AttributeError: items.append((k, v)) return dict(items) A: def flatten(unflattened_dict, separator='_'): flattened_dict = {} for k, v in unflattened_dict.items(): if isinstance(v, dict): sub_flattened_dict = flatten(v, separator) for k2, v2 in sub_flattened_dict.items(): flattened_dict[k + separator + k2] = v2 else: flattened_dict[k] = v return flattened_dict A: I actually wrote a package called cherrypicker recently to deal with this exact sort of thing since I had to do it so often! I think the following code would give you exactly what you're after: from cherrypicker import CherryPicker dct = { 'a': 1, 'c': { 'a': 2, 'b': { 'x': 5, 'y' : 10 } }, 'd': [1, 2, 3] } picker = CherryPicker(dct) picker.flatten().get() You can install the package with: pip install cherrypicker ...and there's more docs and guidance at https://cherrypicker.readthedocs.io. Other methods may be faster, but the priority of this package is to make such tasks easy. If you do have a large list of objects to flatten though, you can also tell CherryPicker to use parallel processing to speed things up. A: here's a solution using a stack. No recursion. def flatten_nested_dict(nested): stack = list(nested.items()) ans = {} while stack: key, val = stack.pop() if isinstance(val, dict): for sub_key, sub_val in val.items(): stack.append((f"{key}_{sub_key}", sub_val)) else: ans[key] = val return ans A: Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator. def flatten_json(json): if type(json) == dict: for k, v in list(json.items()): if type(v) == dict: flatten_json(v) json.pop(k) for k2, v2 in v.items(): json[k+"."+k2] = v2 Example: d = {'a': {'b': 'c'}} flatten_json(d) print(d) unflatten_json(d) print(d) Output: {'a.b': 'c'} {'a': {'b': 'c'}} I published this code here along with the matching unflatten_json function. A: If you want to flat nested dictionary and want all unique keys list then here is the solution: def flat_dict_return_unique_key(data, unique_keys=set()): if isinstance(data, dict): [unique_keys.add(i) for i in data.keys()] for each_v in data.values(): if isinstance(each_v, dict): flat_dict_return_unique_key(each_v, unique_keys) return list(set(unique_keys)) A: I always prefer access dict objects via .items(), so for flattening dicts I use the following recursive generator flat_items(d). If you like to have dict again, simply wrap it like this: flat = dict(flat_items(d)) def flat_items(d, key_separator='.'): """ Flattens the dictionary containing other dictionaries like here: https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys >>> example = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} >>> flat = dict(flat_items(example, key_separator='_')) >>> assert flat['c_b_y'] == 10 """ for k, v in d.items(): if type(v) is dict: for k1, v1 in flat_items(v, key_separator=key_separator): yield key_separator.join((k, k1)), v1 else: yield k, v A: def flatten_nested_dict(_dict, _str=''): ''' recursive function to flatten a nested dictionary json ''' ret_dict = {} for k, v in _dict.items(): if isinstance(v, dict): ret_dict.update(flatten_nested_dict(v, _str = '_'.join([_str, k]).strip('_'))) elif isinstance(v, list): for index, item in enumerate(v): if isinstance(item, dict): ret_dict.update(flatten_nested_dict(item, _str= '_'.join([_str, k, str(index)]).strip('_'))) else: ret_dict['_'.join([_str, k, str(index)]).strip('_')] = item else: ret_dict['_'.join([_str, k]).strip('_')] = v return ret_dict A: Using dict.popitem() in straightforward nested-list-like recursion: def flatten(d): if d == {}: return d else: k,v = d.popitem() if (dict != type(v)): return {k:v, **flatten(d)} else: flat_kv = flatten(v) for k1 in list(flat_kv.keys()): flat_kv[k + '_' + k1] = flat_kv[k1] del flat_kv[k1] return {**flat_kv, **flatten(d)} A: If you do not mind recursive functions, here is a solution. I have also taken the liberty to include an exclusion-parameter in case there are one or more values you wish to maintain. Code: def flatten_dict(dictionary, exclude = [], delimiter ='_'): flat_dict = dict() for key, value in dictionary.items(): if isinstance(value, dict) and key not in exclude: flatten_value_dict = flatten_dict(value, exclude, delimiter) for k, v in flatten_value_dict.items(): flat_dict[f"{key}{delimiter}{k}"] = v else: flat_dict[key] = value return flat_dict Usage: d = {'a':1, 'b':[1, 2], 'c':3, 'd':{'a':4, 'b':{'a':7, 'b':8}, 'c':6}, 'e':{'a':1,'b':2}} flat_d = flatten_dict(dictionary=d, exclude=['e'], delimiter='.') print(flat_d) Output: {'a': 1, 'b': [1, 2], 'c': 3, 'd.a': 4, 'd.b.a': 7, 'd.b.b': 8, 'd.c': 6, 'e': {'a': 1, 'b': 2}} A: Variation of this Flatten nested dictionaries, compressing keys with max_level and custom reducer. def flatten(d, max_level=None, reducer='tuple'): if reducer == 'tuple': reducer_seed = tuple() reducer_func = lambda x, y: (*x, y) else: raise ValueError(f'Unknown reducer: {reducer}') def impl(d, pref, level): return reduce( lambda new_d, kv: (max_level is None or level < max_level) and isinstance(kv[1], dict) and {**new_d, **impl(kv[1], reducer_func(pref, kv[0]), level + 1)} or {**new_d, reducer_func(pref, kv[0]): kv[1]}, d.items(), {} ) return impl(d, reducer_seed, 0) A: I tried some of the solutions on this page - though not all - but those I tried failed to handle the nested list of dict. Consider a dict like this: d = { 'owner': { 'name': {'first_name': 'Steven', 'last_name': 'Smith'}, 'lottery_nums': [1, 2, 3, 'four', '11', None], 'address': {}, 'tuple': (1, 2, 'three'), 'tuple_with_dict': (1, 2, 'three', {'is_valid': False}), 'set': {1, 2, 3, 4, 'five'}, 'children': [ {'name': {'first_name': 'Jessica', 'last_name': 'Smith', }, 'children': [] }, {'name': {'first_name': 'George', 'last_name': 'Smith'}, 'children': [] } ] } } Here's my makeshift solution: def flatten_dict(input_node: dict, key_: str = '', output_dict: dict = {}): if isinstance(input_node, dict): for key, val in input_node.items(): new_key = f"{key_}.{key}" if key_ else f"{key}" flatten_dict(val, new_key, output_dict) elif isinstance(input_node, list): for idx, item in enumerate(input_node): flatten_dict(item, f"{key_}.{idx}", output_dict) else: output_dict[key_] = input_node return output_dict which produces: { owner.name.first_name: Steven, owner.name.last_name: Smith, owner.lottery_nums.0: 1, owner.lottery_nums.1: 2, owner.lottery_nums.2: 3, owner.lottery_nums.3: four, owner.lottery_nums.4: 11, owner.lottery_nums.5: None, owner.tuple: (1, 2, 'three'), owner.tuple_with_dict: (1, 2, 'three', {'is_valid': False}), owner.set: {1, 2, 3, 4, 'five'}, owner.children.0.name.first_name: Jessica, owner.children.0.name.last_name: Smith, owner.children.1.name.first_name: George, owner.children.1.name.last_name: Smith, } A makeshift solution and it's not perfect. NOTE: it doesn't keep empty dicts such as the address: {} k/v pair. it won't flatten dicts in nested tuples - though it would be easy to add using the fact that python tuples act similar to lists. A: You can use recursion in order to flatten your dictionary. import collections def flatten( nested_dict, seperator='.', name=None, ): flatten_dict = {} if not nested_dict: return flatten_dict if isinstance( nested_dict, collections.abc.MutableMapping, ): for key, value in nested_dict.items(): if name is not None: flatten_dict.update( flatten( nested_dict=value, seperator=seperator, name=f'{name}{seperator}{key}', ), ) else: flatten_dict.update( flatten( nested_dict=value, seperator=seperator, name=key, ), ) else: flatten_dict[name] = nested_dict return flatten_dict if __name__ == '__main__': nested_dict = { 1: 'a', 2: { 3: 'c', 4: { 5: 'e', }, 6: [1, 2, 3, 4, 5, ], }, } print( flatten( nested_dict=nested_dict, ), ) Output: { "1":"a", "2.3":"c", "2.4.5":"e", "2.6":[1, 2, 3, 4, 5] } A: Using flatdict library: dic={'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} import flatdict f = flatdict.FlatDict(dic,delimiter='_') print(f) #output {'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]} A: def flatten(dictionary, prefix = '', separator = '_'): out_dict = {} if type(dictionary) != dict: out_dict[prefix] = dictionary return out_dict elif dictionary is None: return None for k in dictionary.keys(): if prefix: prefix_n = prefix + f'{separator}{k}' else: prefix_n = k out_dict.update(flatten_new(dictionary[k], prefix_n)) return out_dict Output: {'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}
Flatten nested dictionaries, compressing keys
Suppose you have a dictionary like: {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} How would you go about flattening that into something like: {'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}
[ "Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.\nimport collections\n\ndef flatten(d, parent_key='', sep='_'):\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, collections.MutableMapping):\n items.extend(flatten(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}\n\nFor Python >= 3.3, change the import to from collections.abc import MutableMapping to avoid a deprecation warning and change collections.MutableMapping to just MutableMapping.\n", "Or if you are already using pandas, You can do it with json_normalize() like so:\nimport pandas as pd\n\nd = {'a': 1,\n 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}},\n 'd': [1, 2, 3]}\n\ndf = pd.json_normalize(d, sep='_')\n\nprint(df.to_dict(orient='records')[0])\n\nOutput:\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}\n\n", "There are two big considerations that the original poster needs to consider:\n\nAre there keyspace clobbering issues? For example, {'a_b':{'c':1}, 'a':{'b_c':2}} would result in {'a_b_c':???}. The below solution evades the problem by returning an iterable of pairs.\nIf performance is an issue, does the key-reducer function (which I hereby refer to as 'join') require access to the entire key-path, or can it just do O(1) work at every node in the tree? If you want to be able to say joinedKey = '_'.join(*keys), that will cost you O(N^2) running time. However if you're willing to say nextKey = previousKey+'_'+thisKey, that gets you O(N) time. The solution below lets you do both (since you could merely concatenate all the keys, then postprocess them).\n\n(Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or anything equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key a then a_1 then a_1_i..., and then calculating a then a_1 then a_1_ii..., but really you shouldn't have to calculate a_1 again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on {1:{1:{1:{1:...(N times)...{1:SOME_LARGE_DICTIONARY_OF_SIZE_N}...}}}})\nBelow is a function I wrote flattenDict(d, join=..., lift=...) which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one).\nfrom collections import Mapping\nfrom itertools import chain\nfrom operator import add\n\n_FLAG_FIRST = object()\n\ndef flattenDict(d, join=add, lift=lambda x:(x,)):\n results = []\n def visit(subdict, results, partialKey):\n for k,v in subdict.items():\n newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k))\n if isinstance(v,Mapping):\n visit(v, results, newKey)\n else:\n results.append((newKey,v))\n visit(d, results, _FLAG_FIRST)\n return results\n\nTo better understand what's going on, below is a diagram for those unfamiliar with reduce(left), otherwise known as \"fold left\". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here, J is our join function. We preprocess each kn with lift(k).\n [k0,k1,...,kN].foldleft(J)\n / \\\n ... kN\n /\n J(k0,J(k1,J(k2,k3)))\n / \\\n / \\\n J(J(k0,k1),k2) k3\n / \\\n / \\\n J(k0,k1) k2\n / \\\n / \\\n k0 k1\n\nThis is in fact the same as functools.reduce, but where our function does this to all key-paths of the tree.\n>>> reduce(lambda a,b:(a,b), range(5))\n((((0, 1), 2), 3), 4)\n\nDemonstration (which I'd otherwise put in docstring):\n>>> testData = {\n 'a':1,\n 'b':2,\n 'c':{\n 'aa':11,\n 'bb':22,\n 'cc':{\n 'aaa':111\n }\n }\n }\nfrom pprint import pprint as pp\n\n>>> pp(dict( flattenDict(testData) ))\n{('a',): 1,\n ('b',): 2,\n ('c', 'aa'): 11,\n ('c', 'bb'): 22,\n ('c', 'cc', 'aaa'): 111}\n\n>>> pp(dict( flattenDict(testData, join=lambda a,b:a+'_'+b, lift=lambda x:x) ))\n{'a': 1, 'b': 2, 'c_aa': 11, 'c_bb': 22, 'c_cc_aaa': 111} \n\n>>> pp(dict( (v,k) for k,v in flattenDict(testData, lift=hash, join=lambda a,b:hash((a,b))) ))\n{1: 12416037344,\n 2: 12544037731,\n 11: 5470935132935744593,\n 22: 4885734186131977315,\n 111: 3461911260025554326}\n\n\nPerformance:\nfrom functools import reduce\ndef makeEvilDict(n):\n return reduce(lambda acc,x:{x:acc}, [{i:0 for i in range(n)}]+range(n))\n\nimport timeit\ndef time(runnable):\n t0 = timeit.default_timer()\n _ = runnable()\n t1 = timeit.default_timer()\n print('took {:.2f} seconds'.format(t1-t0))\n\n>>> pp(makeEvilDict(8))\n{7: {6: {5: {4: {3: {2: {1: {0: {0: 0,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0}}}}}}}}}\n\nimport sys\nsys.setrecursionlimit(1000000)\n\nforget = lambda a,b:''\n\n>>> time(lambda: dict(flattenDict(makeEvilDict(10000), join=forget)) )\ntook 0.10 seconds\n>>> time(lambda: dict(flattenDict(makeEvilDict(100000), join=forget)) )\n[1] 12569 segmentation fault python\n\n... sigh, don't think that one is my fault...\n\n[unimportant historical note due to moderation issues]\nRegarding the alleged duplicate of Flatten a dictionary of dictionaries (2 levels deep) of lists\nThat question's solution can be implemented in terms of this one by doing sorted( sum(flatten(...),[]) ). The reverse is not possible: while it is true that the values of flatten(...) can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.)\n", "If you're using pandas there is a function hidden in pandas.io.json._normalize1 called nested_to_record which does this exactly.\nfrom pandas.io.json._normalize import nested_to_record \n\nflat = nested_to_record(my_dict, sep='_')\n\n\n1 In pandas versions 0.24.x and older use pandas.io.json.normalize (without the _)\n", "Here is a kind of a \"functional\", \"one-liner\" implementation. It is recursive, and based on a conditional expression and a dict comprehension.\ndef flatten_dict(dd, separator='_', prefix=''):\n return { prefix + separator + k if prefix else k : v\n for kk, vv in dd.items()\n for k, v in flatten_dict(vv, separator, kk).items()\n } if isinstance(dd, dict) else { prefix : dd }\n\nTest:\nIn [2]: flatten_dict({'abc':123, 'hgf':{'gh':432, 'yu':433}, 'gfd':902, 'xzxzxz':{\"432\":{'0b0b0b':231}, \"43234\":1321}}, '.')\nOut[2]: \n{'abc': 123,\n 'gfd': 902,\n 'hgf.gh': 432,\n 'hgf.yu': 433,\n 'xzxzxz.432.0b0b0b': 231,\n 'xzxzxz.43234': 1321}\n\n", "Not exactly what the OP asked, but lots of folks are coming here looking for ways to flatten real-world nested JSON data which can have nested key-value json objects and arrays and json objects inside the arrays and so on. JSON doesn't include tuples, so we don't have to fret over those.\nI found an implementation of the list-inclusion comment by @roneo to the answer posted by @Imran :\nhttps://github.com/ScriptSmith/socialreaper/blob/master/socialreaper/tools.py#L8\nimport collections\ndef flatten(dictionary, parent_key=False, separator='.'):\n \"\"\"\n Turn a nested dictionary into a flattened dictionary\n :param dictionary: The dictionary to flatten\n :param parent_key: The string to prepend to dictionary's keys\n :param separator: The string used to separate flattened keys\n :return: A flattened dictionary\n \"\"\"\n\n items = []\n for key, value in dictionary.items():\n new_key = str(parent_key) + separator + key if parent_key else key\n if isinstance(value, collections.MutableMapping):\n items.extend(flatten(value, new_key, separator).items())\n elif isinstance(value, list):\n for k, v in enumerate(value):\n items.extend(flatten({str(k): v}, new_key).items())\n else:\n items.append((new_key, value))\n return dict(items)\n\nTest it:\nflatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3] })\n\n>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3}\n\nAnnd that does the job I need done: I throw any complicated json at this and it flattens it out for me.\nAll credits to https://github.com/ScriptSmith .\n", "Code:\ntest = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}\n\ndef parse_dict(init, lkey=''):\n ret = {}\n for rkey,val in init.items():\n key = lkey+rkey\n if isinstance(val, dict):\n ret.update(parse_dict(val, key+'_'))\n else:\n ret[key] = val\n return ret\n\nprint(parse_dict(test,''))\n\nResults:\n$ python test.py\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}\n\nI am using python3.2, update for your version of python.\n", "This is not restricted to dictionaries, but every mapping type that implements .items(). Further ist faster as it avoides an if condition. Nevertheless credits go to Imran:\ndef flatten(d, parent_key=''):\n items = []\n for k, v in d.items():\n try:\n items.extend(flatten(v, '%s%s_' % (parent_key, k)).items())\n except AttributeError:\n items.append(('%s%s' % (parent_key, k), v))\n return dict(items)\n\n", "If you are a fan of pythonic oneliners:\nmy_dict={'a': 1,'c': {'a': 2,'b': {'x': 5,'y' : 10}},'d': [1, 2, 3]}\n\nlist(pd.json_normalize(my_dict).T.to_dict().values())[0]\n\nreturns:\n{'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd': [1, 2, 3]}\n\nYou can leave the [0] from the end, if you have a list of dictionaries and not just a single dictionary.\n", "How about a functional and performant solution in Python3.5?\nfrom functools import reduce\n\n\ndef _reducer(items, key, val, pref):\n if isinstance(val, dict):\n return {**items, **flatten(val, pref + key)}\n else:\n return {**items, pref + key: val}\n\ndef flatten(d, pref=''):\n return(reduce(\n lambda new_d, kv: _reducer(new_d, *kv, pref), \n d.items(), \n {}\n ))\n\nThis is even more performant:\ndef flatten(d, pref=''):\n return(reduce(\n lambda new_d, kv: \\\n isinstance(kv[1], dict) and \\\n {**new_d, **flatten(kv[1], pref + kv[0])} or \\\n {**new_d, pref + kv[0]: kv[1]}, \n d.items(), \n {}\n ))\n\nIn use:\nmy_obj = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y': 10}}, 'd': [1, 2, 3]}\n\nprint(flatten(my_obj)) \n# {'d': [1, 2, 3], 'cby': 10, 'cbx': 5, 'ca': 2, 'a': 1}\n\n", "My Python 3.3 Solution using generators:\ndef flattenit(pyobj, keystring=''):\n if type(pyobj) is dict:\n if (type(pyobj) is dict):\n keystring = keystring + \"_\" if keystring else keystring\n for k in pyobj:\n yield from flattenit(pyobj[k], keystring + k)\n elif (type(pyobj) is list):\n for lelm in pyobj:\n yield from flatten(lelm, keystring)\n else:\n yield keystring, pyobj\n\nmy_obj = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y': 10}}, 'd': [1, 2, 3]}\n\n#your flattened dictionary object\nflattened={k:v for k,v in flattenit(my_obj)}\nprint(flattened)\n\n# result: {'c_b_y': 10, 'd': [1, 2, 3], 'c_a': 2, 'a': 1, 'c_b_x': 5}\n\n", "Utilizing recursion, keeping it simple and human readable:\ndef flatten_dict(dictionary, accumulator=None, parent_key=None, separator=\".\"):\n if accumulator is None:\n accumulator = {}\n\n for k, v in dictionary.items():\n k = f\"{parent_key}{separator}{k}\" if parent_key else k\n if isinstance(v, dict):\n flatten_dict(dictionary=v, accumulator=accumulator, parent_key=k)\n continue\n\n accumulator[k] = v\n\n return accumulator\n\nCall is simple:\nnew_dict = flatten_dict(dictionary)\n\nor\nnew_dict = flatten_dict(dictionary, separator=\"_\")\n\nif we want to change the default separator.\nA little breakdown:\nWhen the function is first called, it is called only passing the dictionary we want to flatten. The accumulator parameter is here to support recursion, which we see later. So, we instantiate accumulator to an empty dictionary where we will put all of the nested values from the original dictionary.\nif accumulator is None:\n accumulator = {}\n\nAs we iterate over the dictionary's values, we construct a key for every value. The parent_key argument will be None for the first call, while for every nested dictionary, it will contain the key pointing to it, so we prepend that key.\nk = f\"{parent_key}{separator}{k}\" if parent_key else k\n\nIn case the value v the key k is pointing to is a dictionary, the function calls itself, passing the nested dictionary, the accumulator (which is passed by reference, so all changes done to it are done on the same instance) and the key k so that we can construct the concatenated key. Notice the continue statement. We want to skip the next line, outside of the if block, so that the nested dictionary doesn't end up in the accumulator under key k.\nif isinstance(v, dict):\n flatten_dict(dict=v, accumulator=accumulator, parent_key=k)\n continue\n\nSo, what do we do in case the value v is not a dictionary? Just put it unchanged inside the accumulator.\naccumulator[k] = v\n\nOnce we're done we just return the accumulator, leaving the original dictionary argument untouched.\nNOTE\nThis will work only with dictionaries that have strings as keys. It will work with hashable objects implementing the __repr__ method, but will yield unwanted results.\n", "Simple function to flatten nested dictionaries. For Python 3, replace .iteritems() with .items()\ndef flatten_dict(init_dict):\n res_dict = {}\n if type(init_dict) is not dict:\n return res_dict\n\n for k, v in init_dict.iteritems():\n if type(v) == dict:\n res_dict.update(flatten_dict(v))\n else:\n res_dict[k] = v\n\n return res_dict\n\nThe idea/requirement was:\nGet flat dictionaries with no keeping parent keys.\nExample of usage:\ndd = {'a': 3, \n 'b': {'c': 4, 'd': 5}, \n 'e': {'f': \n {'g': 1, 'h': 2}\n }, \n 'i': 9,\n }\n\nflatten_dict(dd)\n\n>> {'a': 3, 'c': 4, 'd': 5, 'g': 1, 'h': 2, 'i': 9}\n\nKeeping parent keys is simple as well.\n", "I was thinking of a subclass of UserDict to automagically flat the keys.\nclass FlatDict(UserDict):\n def __init__(self, *args, separator='.', **kwargs):\n self.separator = separator\n super().__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n if isinstance(value, dict):\n for k1, v1 in FlatDict(value, separator=self.separator).items():\n super().__setitem__(f\"{key}{self.separator}{k1}\", v1)\n else:\n super().__setitem__(key, value)\n\n‌\nThe advantages it that keys can be added on the fly, or using standard dict instanciation, without surprise:\n‌\n>>> fd = FlatDict(\n... {\n... 'person': {\n... 'sexe': 'male', \n... 'name': {\n... 'first': 'jacques',\n... 'last': 'dupond'\n... }\n... }\n... }\n... )\n>>> fd\n{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond'}\n>>> fd['person'] = {'name': {'nickname': 'Bob'}}\n>>> fd\n{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob'}\n>>> fd['person.name'] = {'civility': 'Dr'}\n>>> fd\n{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob', 'person.name.civility': 'Dr'}\n\n", "Using generators:\ndef flat_dic_helper(prepand,d):\n if len(prepand) > 0:\n prepand = prepand + \"_\"\n for k in d:\n i = d[k]\n if isinstance(i, dict):\n r = flat_dic_helper(prepand + k,i)\n for j in r:\n yield j\n else:\n yield (prepand + k,i)\n\ndef flat_dic(d):\n return dict(flat_dic_helper(\"\",d))\n\nd = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}\nprint(flat_dic(d))\n\n\n>> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}\n\n", "This is similar to both imran's and ralu's answer. It does not use a generator, but instead employs recursion with a closure:\ndef flatten_dict(d, separator='_'):\n final = {}\n def _flatten_dict(obj, parent_keys=[]):\n for k, v in obj.iteritems():\n if isinstance(v, dict):\n _flatten_dict(v, parent_keys + [k])\n else:\n key = separator.join(parent_keys + [k])\n final[key] = v\n _flatten_dict(d)\n return final\n\n>>> print flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}\n\n", "The answers above work really well. Just thought I'd add the unflatten function that I wrote:\ndef unflatten(d):\n ud = {}\n for k, v in d.items():\n context = ud\n for sub_key in k.split('_')[:-1]:\n if sub_key not in context:\n context[sub_key] = {}\n context = context[sub_key]\n context[k.split('_')[-1]] = v\n return ud\n\nNote: This doesn't account for '_' already present in keys, much like the flatten counterparts.\n", "Davoud's solution is very nice but doesn't give satisfactory results when the nested dict also contains lists of dicts, but his code be adapted for that case:\ndef flatten_dict(d):\n items = []\n for k, v in d.items():\n try:\n if (type(v)==type([])): \n for l in v: items.extend(flatten_dict(l).items())\n else: \n items.extend(flatten_dict(v).items())\n except AttributeError:\n items.append((k, v))\n return dict(items)\n\n", "def flatten(unflattened_dict, separator='_'):\n flattened_dict = {}\n\n for k, v in unflattened_dict.items():\n if isinstance(v, dict):\n sub_flattened_dict = flatten(v, separator)\n for k2, v2 in sub_flattened_dict.items():\n flattened_dict[k + separator + k2] = v2\n else:\n flattened_dict[k] = v\n\n return flattened_dict\n\n", "I actually wrote a package called cherrypicker recently to deal with this exact sort of thing since I had to do it so often!\nI think the following code would give you exactly what you're after:\nfrom cherrypicker import CherryPicker\n\ndct = {\n 'a': 1,\n 'c': {\n 'a': 2,\n 'b': {\n 'x': 5,\n 'y' : 10\n }\n },\n 'd': [1, 2, 3]\n}\n\npicker = CherryPicker(dct)\npicker.flatten().get()\n\nYou can install the package with:\npip install cherrypicker\n\n...and there's more docs and guidance at https://cherrypicker.readthedocs.io.\nOther methods may be faster, but the priority of this package is to make such tasks easy. If you do have a large list of objects to flatten though, you can also tell CherryPicker to use parallel processing to speed things up.\n", "here's a solution using a stack. No recursion.\ndef flatten_nested_dict(nested):\n stack = list(nested.items())\n ans = {}\n while stack:\n key, val = stack.pop()\n if isinstance(val, dict):\n for sub_key, sub_val in val.items():\n stack.append((f\"{key}_{sub_key}\", sub_val))\n else:\n ans[key] = val\n return ans\n\n", "Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator.\ndef flatten_json(json):\n if type(json) == dict:\n for k, v in list(json.items()):\n if type(v) == dict:\n flatten_json(v)\n json.pop(k)\n for k2, v2 in v.items():\n json[k+\".\"+k2] = v2\n\nExample:\nd = {'a': {'b': 'c'}} \nflatten_json(d)\nprint(d)\nunflatten_json(d)\nprint(d)\n\nOutput:\n{'a.b': 'c'}\n{'a': {'b': 'c'}}\n\nI published this code here along with the matching unflatten_json function.\n", "If you want to flat nested dictionary and want all unique keys list then here is the solution:\ndef flat_dict_return_unique_key(data, unique_keys=set()):\n if isinstance(data, dict):\n [unique_keys.add(i) for i in data.keys()]\n for each_v in data.values():\n if isinstance(each_v, dict):\n flat_dict_return_unique_key(each_v, unique_keys)\n return list(set(unique_keys))\n\n", "I always prefer access dict objects via .items(), so for flattening dicts I use the following recursive generator flat_items(d). If you like to have dict again, simply wrap it like this: flat = dict(flat_items(d))\ndef flat_items(d, key_separator='.'):\n \"\"\"\n Flattens the dictionary containing other dictionaries like here: https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys\n\n >>> example = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}\n >>> flat = dict(flat_items(example, key_separator='_'))\n >>> assert flat['c_b_y'] == 10\n \"\"\"\n for k, v in d.items():\n if type(v) is dict:\n for k1, v1 in flat_items(v, key_separator=key_separator):\n yield key_separator.join((k, k1)), v1\n else:\n yield k, v\n\n", "def flatten_nested_dict(_dict, _str=''):\n '''\n recursive function to flatten a nested dictionary json\n '''\n ret_dict = {}\n for k, v in _dict.items():\n if isinstance(v, dict):\n ret_dict.update(flatten_nested_dict(v, _str = '_'.join([_str, k]).strip('_')))\n elif isinstance(v, list):\n for index, item in enumerate(v):\n if isinstance(item, dict):\n ret_dict.update(flatten_nested_dict(item, _str= '_'.join([_str, k, str(index)]).strip('_')))\n else:\n ret_dict['_'.join([_str, k, str(index)]).strip('_')] = item\n else:\n ret_dict['_'.join([_str, k]).strip('_')] = v\n return ret_dict\n\n", "Using dict.popitem() in straightforward nested-list-like recursion:\ndef flatten(d):\n if d == {}:\n return d\n else:\n k,v = d.popitem()\n if (dict != type(v)):\n return {k:v, **flatten(d)}\n else:\n flat_kv = flatten(v)\n for k1 in list(flat_kv.keys()):\n flat_kv[k + '_' + k1] = flat_kv[k1]\n del flat_kv[k1]\n return {**flat_kv, **flatten(d)}\n\n", "If you do not mind recursive functions, here is a solution. I have also taken the liberty to include an exclusion-parameter in case there are one or more values you wish to maintain.\nCode:\ndef flatten_dict(dictionary, exclude = [], delimiter ='_'):\n flat_dict = dict()\n for key, value in dictionary.items():\n if isinstance(value, dict) and key not in exclude:\n flatten_value_dict = flatten_dict(value, exclude, delimiter)\n for k, v in flatten_value_dict.items():\n flat_dict[f\"{key}{delimiter}{k}\"] = v\n else:\n flat_dict[key] = value\n return flat_dict\n\nUsage:\nd = {'a':1, 'b':[1, 2], 'c':3, 'd':{'a':4, 'b':{'a':7, 'b':8}, 'c':6}, 'e':{'a':1,'b':2}}\nflat_d = flatten_dict(dictionary=d, exclude=['e'], delimiter='.')\nprint(flat_d)\n\nOutput:\n{'a': 1, 'b': [1, 2], 'c': 3, 'd.a': 4, 'd.b.a': 7, 'd.b.b': 8, 'd.c': 6, 'e': {'a': 1, 'b': 2}}\n\n", "Variation of this Flatten nested dictionaries, compressing keys with max_level and custom reducer.\n def flatten(d, max_level=None, reducer='tuple'):\n if reducer == 'tuple':\n reducer_seed = tuple()\n reducer_func = lambda x, y: (*x, y)\n else:\n raise ValueError(f'Unknown reducer: {reducer}')\n\n def impl(d, pref, level):\n return reduce(\n lambda new_d, kv:\n (max_level is None or level < max_level)\n and isinstance(kv[1], dict)\n and {**new_d, **impl(kv[1], reducer_func(pref, kv[0]), level + 1)}\n or {**new_d, reducer_func(pref, kv[0]): kv[1]},\n d.items(),\n {}\n )\n\n return impl(d, reducer_seed, 0)\n\n", "I tried some of the solutions on this page - though not all - but those I tried failed to handle the nested list of dict. \nConsider a dict like this:\nd = {\n 'owner': {\n 'name': {'first_name': 'Steven', 'last_name': 'Smith'},\n 'lottery_nums': [1, 2, 3, 'four', '11', None],\n 'address': {},\n 'tuple': (1, 2, 'three'),\n 'tuple_with_dict': (1, 2, 'three', {'is_valid': False}),\n 'set': {1, 2, 3, 4, 'five'},\n 'children': [\n {'name': {'first_name': 'Jessica',\n 'last_name': 'Smith', },\n 'children': []\n },\n {'name': {'first_name': 'George',\n 'last_name': 'Smith'},\n 'children': []\n }\n ]\n }\n }\n\nHere's my makeshift solution:\ndef flatten_dict(input_node: dict, key_: str = '', output_dict: dict = {}):\n if isinstance(input_node, dict):\n for key, val in input_node.items():\n new_key = f\"{key_}.{key}\" if key_ else f\"{key}\"\n flatten_dict(val, new_key, output_dict)\n elif isinstance(input_node, list):\n for idx, item in enumerate(input_node):\n flatten_dict(item, f\"{key_}.{idx}\", output_dict)\n else:\n output_dict[key_] = input_node\n return output_dict\n\nwhich produces:\n{\n owner.name.first_name: Steven,\n owner.name.last_name: Smith,\n owner.lottery_nums.0: 1,\n owner.lottery_nums.1: 2,\n owner.lottery_nums.2: 3,\n owner.lottery_nums.3: four,\n owner.lottery_nums.4: 11,\n owner.lottery_nums.5: None,\n owner.tuple: (1, 2, 'three'),\n owner.tuple_with_dict: (1, 2, 'three', {'is_valid': False}),\n owner.set: {1, 2, 3, 4, 'five'},\n owner.children.0.name.first_name: Jessica,\n owner.children.0.name.last_name: Smith,\n owner.children.1.name.first_name: George,\n owner.children.1.name.last_name: Smith,\n}\n\nA makeshift solution and it's not perfect.\nNOTE: \n\nit doesn't keep empty dicts such as the address: {} k/v pair.\nit won't flatten dicts in nested tuples - though it would be easy to add using the fact that python tuples act similar to lists.\n\n", "You can use recursion in order to flatten your dictionary.\nimport collections\n\n\ndef flatten(\n nested_dict,\n seperator='.',\n name=None,\n):\n flatten_dict = {}\n\n if not nested_dict:\n return flatten_dict\n\n if isinstance(\n nested_dict,\n collections.abc.MutableMapping,\n ):\n for key, value in nested_dict.items():\n if name is not None:\n flatten_dict.update(\n flatten(\n nested_dict=value,\n seperator=seperator,\n name=f'{name}{seperator}{key}',\n ),\n )\n else:\n flatten_dict.update(\n flatten(\n nested_dict=value,\n seperator=seperator,\n name=key,\n ),\n )\n else:\n flatten_dict[name] = nested_dict\n\n return flatten_dict\n\n\nif __name__ == '__main__':\n nested_dict = {\n 1: 'a',\n 2: {\n 3: 'c',\n 4: {\n 5: 'e',\n },\n 6: [1, 2, 3, 4, 5, ],\n },\n }\n\n print(\n flatten(\n nested_dict=nested_dict,\n ),\n )\n\nOutput:\n{\n \"1\":\"a\",\n \"2.3\":\"c\",\n \"2.4.5\":\"e\",\n \"2.6\":[1, 2, 3, 4, 5]\n}\n\n", "Using flatdict library:\ndic={'a': 1,\n 'c': {'a': 2,\n 'b': {'x': 5,\n 'y' : 10}},\n 'd': [1, 2, 3]}\n\nimport flatdict\nf = flatdict.FlatDict(dic,delimiter='_')\nprint(f)\n#output\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}\n\n", "def flatten(dictionary, prefix = '', separator = '_'):\n out_dict = {}\n if type(dictionary) != dict:\n out_dict[prefix] = dictionary\n return out_dict\n elif dictionary is None:\n return None\n for k in dictionary.keys():\n if prefix:\n prefix_n = prefix + f'{separator}{k}'\n else:\n prefix_n = k\n out_dict.update(flatten_new(dictionary[k], prefix_n))\n return out_dict\n\nOutput:\n{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}\n\n" ]
[ 312, 182, 80, 50, 36, 30, 16, 8, 8, 7, 6, 6, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006027558_dictionary_python.txt
Q: Values replacement in python pandas I need to replace each cell containing values like number1(number2) with number2 (the value inside the parenthesis). For example: 56(3) -> 3, 33(5) -> 5 These values can appear in different columns. The problem is that with pandas function df.replace(to_replace=..., value=...) i cannot use as value something that depends on the string matched. I was trying something like: df.replace(to_replace='[0-9]+([0-9]+)', value=lambda x: int(x.split("(")[1].strip(")")), regex=True) But the lambda function doesn't work. Suggestions? A: Have you tried df.apply instead? A caveat is that using apply on a dataFrame sends the entire row as input to the lambda function, so you will have to do something like this: for col in df.columns: df[col] = df[col].apply(<insert lambda function here>)
Values replacement in python pandas
I need to replace each cell containing values like number1(number2) with number2 (the value inside the parenthesis). For example: 56(3) -> 3, 33(5) -> 5 These values can appear in different columns. The problem is that with pandas function df.replace(to_replace=..., value=...) i cannot use as value something that depends on the string matched. I was trying something like: df.replace(to_replace='[0-9]+([0-9]+)', value=lambda x: int(x.split("(")[1].strip(")")), regex=True) But the lambda function doesn't work. Suggestions?
[ "Have you tried df.apply instead?\nA caveat is that using apply on a dataFrame sends the entire row as input to the lambda function, so you will have to do something like this:\nfor col in df.columns:\n df[col] = df[col].apply(<insert lambda function here>)\n\n" ]
[ 0 ]
[]
[]
[ "lambda", "pandas", "python", "regex", "replace" ]
stackoverflow_0074560157_lambda_pandas_python_regex_replace.txt
Q: Connecting with Blob Container in one specific notebook in DataBricks I work under one cluster in DataBricks which has mounted blob container. I'd like to keep that one container for the whole cluster, but mount another already created cluster for one specific notebook (or repo, that would be awesome) to load data from there. How can I make it? Example: Repo 1 - blob 1: notebooks blob 1 Repo 2 - blob 1 (or blob if its possible) notebook (notebooks) blob2 A: You can use the following procedure load the data into storage account. I reproduce same in my environment with two repro's Repro 1: Container name: input Mount_point:/mnt/hffj Repro 2: Container name: output Mount_point:/mnt/output As per above scenario you can do in this way: First of all read the data frame df1 = spark.read.format("csv").option("header", "true").load("/mnt/hffj") Then, write it into repro 2 mount path /mnt/output. Data is stored in that mount location df1.coalesce(1).write.format('csv').mode("overwrite").save("/mnt/output")
Connecting with Blob Container in one specific notebook in DataBricks
I work under one cluster in DataBricks which has mounted blob container. I'd like to keep that one container for the whole cluster, but mount another already created cluster for one specific notebook (or repo, that would be awesome) to load data from there. How can I make it? Example: Repo 1 - blob 1: notebooks blob 1 Repo 2 - blob 1 (or blob if its possible) notebook (notebooks) blob2
[ "You can use the following procedure load the data into storage account.\nI reproduce same in my environment with two repro's\nRepro 1:\nContainer name: input Mount_point:/mnt/hffj\n\nRepro 2:\nContainer name: output Mount_point:/mnt/output\n\nAs per above scenario you can do in this way:\nFirst of all read the data frame\ndf1 = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"/mnt/hffj\")\n\nThen, write it into repro 2 mount path /mnt/output. Data is stored in that mount location\ndf1.coalesce(1).write.format('csv').mode(\"overwrite\").save(\"/mnt/output\")\n\n\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_blob_storage", "azure_databricks", "databricks", "python" ]
stackoverflow_0074557236_azure_azure_blob_storage_azure_databricks_databricks_python.txt
Q: python requests vs bash curl for session cookies I have a bash script that logs in to a website and fetches the json data from a URL and does other stuffs after that. I am trying to re-write the script using python but I am stuck at the log in part itself. Below is a function from the bash script that I wrote, to login to the site and fetch the status get_status() { curl -s ''"$url"'/target/app1/login' -c cookiejar curl -s ''"$url"'/target/app1/login' -X POST -c cookiejar --data 'username='"$username"'&password='"$password"'' cookie=$(grep JSESSIONID cookiejar | awk '{print $6"="$7}') status=$(curl -s ''"$url"'/target/app1/status' -H 'Cookie: '"$cookie"'' } The first curl gets a sample cookie to post to the login page in the second curl The second curl logs in using the username and password provided The third curl fetches the actual data using the 'JSESSIONID' cookie I am trying to do the same using requests in python as below session = requests.Session() session.get(url + "/target/app1/login") print(session.cookies) response = session.post(url + "/target/app1/login", data=data) print(response.cookies) In the above code the data variable holds the username and password string. When I print the response.cookies I do not get the JSESSIONID cookie that I can use to authenticate future reqests to fetch data. Note: When I print the response it returns 200 I am new to python, any help would be appreciated. Thanks A: To anyone having same issue hope this would help. I was able to get this working with the below code. session = requests.session() session.get(url + "/target/app1/login") login = session.post(url + "/target/app1/login", data) data = session.get(url)
python requests vs bash curl for session cookies
I have a bash script that logs in to a website and fetches the json data from a URL and does other stuffs after that. I am trying to re-write the script using python but I am stuck at the log in part itself. Below is a function from the bash script that I wrote, to login to the site and fetch the status get_status() { curl -s ''"$url"'/target/app1/login' -c cookiejar curl -s ''"$url"'/target/app1/login' -X POST -c cookiejar --data 'username='"$username"'&password='"$password"'' cookie=$(grep JSESSIONID cookiejar | awk '{print $6"="$7}') status=$(curl -s ''"$url"'/target/app1/status' -H 'Cookie: '"$cookie"'' } The first curl gets a sample cookie to post to the login page in the second curl The second curl logs in using the username and password provided The third curl fetches the actual data using the 'JSESSIONID' cookie I am trying to do the same using requests in python as below session = requests.Session() session.get(url + "/target/app1/login") print(session.cookies) response = session.post(url + "/target/app1/login", data=data) print(response.cookies) In the above code the data variable holds the username and password string. When I print the response.cookies I do not get the JSESSIONID cookie that I can use to authenticate future reqests to fetch data. Note: When I print the response it returns 200 I am new to python, any help would be appreciated. Thanks
[ "To anyone having same issue hope this would help.\nI was able to get this working with the below code.\nsession = requests.session()\nsession.get(url + \"/target/app1/login\")\nlogin = session.post(url + \"/target/app1/login\", data)\ndata = session.get(url)\n\n" ]
[ 0 ]
[]
[]
[ "bash", "cookies", "curl", "python", "python_requests" ]
stackoverflow_0073232869_bash_cookies_curl_python_python_requests.txt
Q: Optimizing a funcation using Scipy to estimate fitting parameters I am trying to optimize a function by finding its minimum value using Scipy. The code must find the values of the variables g and tau that will give the minimum value of MSE. However, These values must be arrays not scalars. Below is the code import numpy as np import numpy as np import pandas as pd import math import scipy.optimize as spo ## Insert the hihest numner of Prony Parameters for optimization.. N_Prony = 5 #########Intial_guess of g_i and tau_i################ #### Define Array for the guessing ######## Prony_0 = np.ones(N_Prony*2) ## Five for the relaxtion time (taui) and five for g_i # Initial guess of g_i and Tau_i gini = 4 Taui = 0.8 Prony_0[0:N_Prony] = Prony_0[0:N_Prony]*gini Prony_0[N_Prony:2*N_Prony] = Prony_0[N_Prony:2*N_Prony]*Taui g = Prony_0[0:N_Prony] ## The first part of the array is g tau = Prony_0[N_Prony:2*N_Prony] # The second part of the array is Tau df1 = pd.read_excel(r'C:\Users\Mahmoud Khadijeh\Desktop\DSR Application\Testdata_Einf.xlsx') ## Read the data from Excel file w = df1.iloc[:,1] ## Read the frequency from the Excel file E_INF = df1.iloc[4,2]; NU = df1.iloc[0,5] ## Read E_INF & Poission's Ratio from the EXCEL FILE G_INF = (E_INF)/2*(1+NU) # Calculate G_INF from G0 = G_INF/(1-sum(g)) # Calculate G0 from G_INF TANW_MEAS = (df1.iloc[:,3])/(df1.iloc[:,2]) # Degree of Viscoelasticity list1 = [] # This list is to store G' from the loop in an array {For each Frequnecy} list2 = [] # This list is to store G'' from the loop in an array {For each Frequnecy} ## Calculation.. for K in range(len(w)): #Second part of Equation 5 --> G' for L in range(N_Prony): GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony) list1.append(GPrime_1) print(list1[0]) df1["G'"] = list1 df1["E'"] = np.dot(2*(1+NU),list1) #Convert G' to E' and add it to the table print('df1 = ', df1) for J in range(len(w)): #Second part of Equation 5 --> G' for i in range(N_Prony): GPrime_2 = G0*((g[i]*((tau[i]))*w[J])/(1+((tau[i]**2))*w[J]**2)*N_Prony) list2.append(GPrime_2) print(list2[0]) df1["G''"] = list2 df1["E''"] = np.dot(2*(1+NU),list2) #Convert G'' to E'' and add it to the table #### Initial Guess array x0 = np.array([g, tau]) def objective(SE): global new_df g = SE[0] # Variable 1 that we have to optimize tau = SE[1] # Variable 2 that we have to optimize print('g::', g) print('tau::', tau) new_df = pd.DataFrame() new_df["E'_meas"] = df1.iloc[:,2] new_df["E''_meas"] =df1.iloc[:,3] #list1 = new_df["E'_meas"] #list2 = new_df["E''_meas"] new_df["E'_cal"] = list1 # Where list1 is E' new_df["E''_cal"] = list2 # Where list2 is E'' new_df["Tan(d)_meas"] = TANW_MEAS new_df["Tan(d)_cal"] = new_df["E''_meas"]/new_df["E'_meas"] MSE = np.square(np.subtract(new_df["E'_meas"],new_df["E'_cal"])).mean() #minimize = (((new_df["E'_meas"] - new_df["E'_cal"])**2)/np.std(new_df["E'_meas"])) + \ # (((new_df["E''_meas"] - new_df["E''_cal"])**2)/np.std(new_df["E''_meas"])) + \ # (((new_df["Tan(d)_meas"] - new_df["Tan(d)_cal"])**2)/np.std(new_df["Tan(d)_cal"])) return MSE sol = spo.minimize(objective, x0, method='SLSQP', options={'disp': True}) print(sol) However, the code is not changing the initial guess values.. For example: the output of the above code is: Optimization terminated successfully (Exit mode 0) Current function value: 3714530.31378857 Iterations: 1 Function evaluations: 11 Gradient evaluations: 1 fun: 3714530.31378857 jac: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) message: 'Optimization terminated successfully' nfev: 11 nit: 1 njev: 1 status: 0 success: True x: array([4. , 4. , 4. , 4. , 4. , 0.8, 0.8, 0.8, 0.8, 0.8]) so g = [4,4,4,4,4] and tau = [0.8,0.8,0.8,0.8,0.8] Any help! Note I used two for-loops in the code to calculate the following equations: For-loops A: Im not seeing how you are using the input of your objective function SE. You convert that into g and tau, but those are not used either. Your objective function returns an output that is simply based on some values in a panda array, which stay the same every time. Your optimisation parameters simply have no impact on the objective value, so therefore they do not change from their initial value. If you change the return value to be simply g + tau the output will be different from the initial values (note that I could not run this code myself, since I do not have your excel sheet): def objective(SE): global new_df g = SE[0] # Variable 1 that we have to optimize tau = SE[1] # Variable 2 that we have to optimize print('g::', g) print('tau::', tau) new_df = pd.DataFrame() new_df["E'_meas"] = df1.iloc[:,2] new_df["E''_meas"] =df1.iloc[:,3] #list1 = new_df["E'_meas"] #list2 = new_df["E''_meas"] new_df["E'_cal"] = list1 # Where list1 is E' new_df["E''_cal"] = list2 # Where list2 is E'' new_df["Tan(d)_meas"] = TANW_MEAS new_df["Tan(d)_cal"] = new_df["E''_meas"]/new_df["E'_meas"] MSE = np.square(np.subtract(new_df["E'_meas"],new_df["E'_cal"])).mean() #minimize = (((new_df["E'_meas"] - new_df["E'_cal"])**2)/np.std(new_df["E'_meas"])) + \ # (((new_df["E''_meas"] - new_df["E''_cal"])**2)/np.std(new_df["E''_meas"])) + \ # (((new_df["Tan(d)_meas"] - new_df["Tan(d)_cal"])**2)/np.std(new_df["Tan(d)_cal"])) return g + tau A: When I implemented the for-loops inside the function, like the following code: def objective(SE): global new_df g = SE[0] # Variable 1 that we have to optimize tau = SE[1] # Variable 2 that we have to optimize list1 = [] # This list is to store G' from the loop in an array {For each Frequnecy} list2 = [] # This list is to store G'' from the loop in an array {For each Frequnecy} ## Calculation.. for K in range(len(w)): #Second part of Equation 5 --> G' for L in range(N_Prony): GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony) list1.append(GPrime_1) print(list1[0]) df1["G'"] = list1 df1["E'"] = np.dot(2*(1+NU),list1) #Convert G' to E' and add it to the table print('df1 = ', df1) for J in range(len(w)): #Second part of Equation 5 --> G' for i in range(N_Prony): GPrime_2 = G0*((g[i]*((tau[i]))*w[J])/(1+((tau[i]**2))*w[J]**2)*N_Prony) list2.append(GPrime_2) print(list2[0]) df1["G''"] = list2 df1["E''"] = np.dot(2*(1+NU),list2) #Convert G'' to E'' and add it to the table new_df = pd.DataFrame() new_df["E'_meas"] = df1.iloc[:,2] new_df["E''_meas"] =df1.iloc[:,3] #list1 = new_df["E'_meas"] #list2 = new_df["E''_meas"] new_df["E'_cal"] = list1 # Where list1 is E' new_df["E''_cal"] = list2 # Where list2 is E'' new_df["Tan(d)_meas"] = TANW_MEAS new_df["Tan(d)_cal"] = new_df["E''_meas"]/new_df["E'_meas"] MSE = np.square(np.subtract(new_df["E'_meas"],new_df["E'_cal"])).mean() #minimize = (((new_df["E'_meas"] - new_df["E'_cal"])**2)/np.std(new_df["E'_meas"])) + \ # (((new_df["E''_meas"] - new_df["E''_cal"])**2)/np.std(new_df["E''_meas"])) + \ # (((new_df["Tan(d)_meas"] - new_df["Tan(d)_cal"])**2)/np.std(new_df["Tan(d)_cal"])) return MSE sol = spo.minimize(objective, x0, method='SLSQP', options={'disp': True}) print(sol) I got the following error: GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony) IndexError: invalid index to scalar variable. However, I did not get such error when I implemented the for-loops outside the functionn. Do you know why?
Optimizing a funcation using Scipy to estimate fitting parameters
I am trying to optimize a function by finding its minimum value using Scipy. The code must find the values of the variables g and tau that will give the minimum value of MSE. However, These values must be arrays not scalars. Below is the code import numpy as np import numpy as np import pandas as pd import math import scipy.optimize as spo ## Insert the hihest numner of Prony Parameters for optimization.. N_Prony = 5 #########Intial_guess of g_i and tau_i################ #### Define Array for the guessing ######## Prony_0 = np.ones(N_Prony*2) ## Five for the relaxtion time (taui) and five for g_i # Initial guess of g_i and Tau_i gini = 4 Taui = 0.8 Prony_0[0:N_Prony] = Prony_0[0:N_Prony]*gini Prony_0[N_Prony:2*N_Prony] = Prony_0[N_Prony:2*N_Prony]*Taui g = Prony_0[0:N_Prony] ## The first part of the array is g tau = Prony_0[N_Prony:2*N_Prony] # The second part of the array is Tau df1 = pd.read_excel(r'C:\Users\Mahmoud Khadijeh\Desktop\DSR Application\Testdata_Einf.xlsx') ## Read the data from Excel file w = df1.iloc[:,1] ## Read the frequency from the Excel file E_INF = df1.iloc[4,2]; NU = df1.iloc[0,5] ## Read E_INF & Poission's Ratio from the EXCEL FILE G_INF = (E_INF)/2*(1+NU) # Calculate G_INF from G0 = G_INF/(1-sum(g)) # Calculate G0 from G_INF TANW_MEAS = (df1.iloc[:,3])/(df1.iloc[:,2]) # Degree of Viscoelasticity list1 = [] # This list is to store G' from the loop in an array {For each Frequnecy} list2 = [] # This list is to store G'' from the loop in an array {For each Frequnecy} ## Calculation.. for K in range(len(w)): #Second part of Equation 5 --> G' for L in range(N_Prony): GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony) list1.append(GPrime_1) print(list1[0]) df1["G'"] = list1 df1["E'"] = np.dot(2*(1+NU),list1) #Convert G' to E' and add it to the table print('df1 = ', df1) for J in range(len(w)): #Second part of Equation 5 --> G' for i in range(N_Prony): GPrime_2 = G0*((g[i]*((tau[i]))*w[J])/(1+((tau[i]**2))*w[J]**2)*N_Prony) list2.append(GPrime_2) print(list2[0]) df1["G''"] = list2 df1["E''"] = np.dot(2*(1+NU),list2) #Convert G'' to E'' and add it to the table #### Initial Guess array x0 = np.array([g, tau]) def objective(SE): global new_df g = SE[0] # Variable 1 that we have to optimize tau = SE[1] # Variable 2 that we have to optimize print('g::', g) print('tau::', tau) new_df = pd.DataFrame() new_df["E'_meas"] = df1.iloc[:,2] new_df["E''_meas"] =df1.iloc[:,3] #list1 = new_df["E'_meas"] #list2 = new_df["E''_meas"] new_df["E'_cal"] = list1 # Where list1 is E' new_df["E''_cal"] = list2 # Where list2 is E'' new_df["Tan(d)_meas"] = TANW_MEAS new_df["Tan(d)_cal"] = new_df["E''_meas"]/new_df["E'_meas"] MSE = np.square(np.subtract(new_df["E'_meas"],new_df["E'_cal"])).mean() #minimize = (((new_df["E'_meas"] - new_df["E'_cal"])**2)/np.std(new_df["E'_meas"])) + \ # (((new_df["E''_meas"] - new_df["E''_cal"])**2)/np.std(new_df["E''_meas"])) + \ # (((new_df["Tan(d)_meas"] - new_df["Tan(d)_cal"])**2)/np.std(new_df["Tan(d)_cal"])) return MSE sol = spo.minimize(objective, x0, method='SLSQP', options={'disp': True}) print(sol) However, the code is not changing the initial guess values.. For example: the output of the above code is: Optimization terminated successfully (Exit mode 0) Current function value: 3714530.31378857 Iterations: 1 Function evaluations: 11 Gradient evaluations: 1 fun: 3714530.31378857 jac: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) message: 'Optimization terminated successfully' nfev: 11 nit: 1 njev: 1 status: 0 success: True x: array([4. , 4. , 4. , 4. , 4. , 0.8, 0.8, 0.8, 0.8, 0.8]) so g = [4,4,4,4,4] and tau = [0.8,0.8,0.8,0.8,0.8] Any help! Note I used two for-loops in the code to calculate the following equations: For-loops
[ "Im not seeing how you are using the input of your objective function SE. You convert that into g and tau, but those are not used either. Your objective function returns an output that is simply based on some values in a panda array, which stay the same every time. Your optimisation parameters simply have no impact on the objective value, so therefore they do not change from their initial value.\nIf you change the return value to be simply g + tau the output will be different from the initial values (note that I could not run this code myself, since I do not have your excel sheet):\ndef objective(SE):\n global new_df\n g = SE[0] # Variable 1 that we have to optimize\n tau = SE[1] # Variable 2 that we have to optimize\n print('g::', g)\n print('tau::', tau)\n new_df = pd.DataFrame()\n new_df[\"E'_meas\"] = df1.iloc[:,2]\n new_df[\"E''_meas\"] =df1.iloc[:,3]\n #list1 = new_df[\"E'_meas\"] \n #list2 = new_df[\"E''_meas\"] \n new_df[\"E'_cal\"] = list1 # Where list1 is E'\n new_df[\"E''_cal\"] = list2 # Where list2 is E''\n new_df[\"Tan(d)_meas\"] = TANW_MEAS\n new_df[\"Tan(d)_cal\"] = new_df[\"E''_meas\"]/new_df[\"E'_meas\"]\n \n \n MSE = np.square(np.subtract(new_df[\"E'_meas\"],new_df[\"E'_cal\"])).mean()\n \n #minimize = (((new_df[\"E'_meas\"] - new_df[\"E'_cal\"])**2)/np.std(new_df[\"E'_meas\"])) + \\\n # (((new_df[\"E''_meas\"] - new_df[\"E''_cal\"])**2)/np.std(new_df[\"E''_meas\"])) + \\\n # (((new_df[\"Tan(d)_meas\"] - new_df[\"Tan(d)_cal\"])**2)/np.std(new_df[\"Tan(d)_cal\"])) \n\n return g + tau\n\n", "When I implemented the for-loops inside the function, like the following code:\ndef objective(SE):\n global new_df\n g = SE[0] # Variable 1 that we have to optimize\n tau = SE[1] # Variable 2 that we have to optimize\n\n list1 = [] # This list is to store G' from the loop in an array {For each Frequnecy}\n list2 = [] # This list is to store G'' from the loop in an array {For each Frequnecy} \n\n ## Calculation.. \n\n for K in range(len(w)): \n #Second part of Equation 5 --> G'\n for L in range(N_Prony):\n GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony)\n list1.append(GPrime_1)\n print(list1[0])\n\n\n df1[\"G'\"] = list1 \n df1[\"E'\"] = np.dot(2*(1+NU),list1) #Convert G' to E' and add it to the table \n print('df1 = ', df1)\n\n\n\n for J in range(len(w)): \n #Second part of Equation 5 --> G'\n for i in range(N_Prony):\n GPrime_2 = G0*((g[i]*((tau[i]))*w[J])/(1+((tau[i]**2))*w[J]**2)*N_Prony) \n list2.append(GPrime_2)\n print(list2[0])\n\n\n df1[\"G''\"] = list2 \n df1[\"E''\"] = np.dot(2*(1+NU),list2) #Convert G'' to E'' and add it to the table \n\n\n\n\n new_df = pd.DataFrame()\n new_df[\"E'_meas\"] = df1.iloc[:,2]\n new_df[\"E''_meas\"] =df1.iloc[:,3]\n #list1 = new_df[\"E'_meas\"] \n #list2 = new_df[\"E''_meas\"] \n new_df[\"E'_cal\"] = list1 # Where list1 is E'\n new_df[\"E''_cal\"] = list2 # Where list2 is E''\n new_df[\"Tan(d)_meas\"] = TANW_MEAS\n new_df[\"Tan(d)_cal\"] = new_df[\"E''_meas\"]/new_df[\"E'_meas\"]\n \n \n MSE = np.square(np.subtract(new_df[\"E'_meas\"],new_df[\"E'_cal\"])).mean()\n \n #minimize = (((new_df[\"E'_meas\"] - new_df[\"E'_cal\"])**2)/np.std(new_df[\"E'_meas\"])) + \\\n # (((new_df[\"E''_meas\"] - new_df[\"E''_cal\"])**2)/np.std(new_df[\"E''_meas\"])) + \\\n # (((new_df[\"Tan(d)_meas\"] - new_df[\"Tan(d)_cal\"])**2)/np.std(new_df[\"Tan(d)_cal\"])) \n\n return MSE\n\nsol = spo.minimize(objective, x0, method='SLSQP', options={'disp': True})\n\nprint(sol)\n\nI got the following error:\n GPrime_1 = G_INF + G0*((g[L]*((tau[L])**2)*(w[K])**2)/(1+((tau[L]**2))*w[K]**2)*N_Prony)\n\nIndexError: invalid index to scalar variable.\n\nHowever, I did not get such error when I implemented the for-loops outside the functionn.\nDo you know why?\n" ]
[ 0, 0 ]
[]
[]
[ "function_fitting", "minimization", "optimization", "python", "scipy" ]
stackoverflow_0074558712_function_fitting_minimization_optimization_python_scipy.txt
Q: Extract time from a column in given The time column in my dataframe df looks like Date_UTC 1998-05-02T00:00:00 1998-05-02T00:01:00 1998-05-02T00:02:00 1998-05-02T00:03:00 1998-05-02T00:04:00 1998-05-02T00:05:00 1998-05-02T00:06:00 1998-05-02T00:07:00 1998-05-02T00:08:00 1998-05-02T00:09:00 1998-05-02T00:10:00 I want to extract time values from it. Please help. A: you can use: df['time']=pd.to_datetime(df['Date_UTC']).dt.time #if you want to only dates df['Date_UTC']=pd.to_datetime(['Date_UTC']).dt.date```
Extract time from a column in given
The time column in my dataframe df looks like Date_UTC 1998-05-02T00:00:00 1998-05-02T00:01:00 1998-05-02T00:02:00 1998-05-02T00:03:00 1998-05-02T00:04:00 1998-05-02T00:05:00 1998-05-02T00:06:00 1998-05-02T00:07:00 1998-05-02T00:08:00 1998-05-02T00:09:00 1998-05-02T00:10:00 I want to extract time values from it. Please help.
[ "you can use:\ndf['time']=pd.to_datetime(df['Date_UTC']).dt.time\n\n#if you want to only dates\ndf['Date_UTC']=pd.to_datetime(['Date_UTC']).dt.date```\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "numpy", "pandas", "python" ]
stackoverflow_0074560292_jupyter_notebook_numpy_pandas_python.txt
Q: Why is my code returning the address of the variable instead of the value? I am finding it difficult to understand why my code is returning my memory address. I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly. import random class Card: def __init__(self, suit, value): self.suit = suit #['H','D','C','S'] self.value = value #['A',2,3,4,5,6,7,8,9,10,'J','Q','K'] class Deck: def __init__(self): self.cards =[] def __repr__(self): return f'Card("{self.card}")' def build(self): for x in['H','D','C','S']: for y in range(1,14): self.cards.append(Card(x,y)) if(y==1): self.cards.append(Card(x,'A')) elif(y==11): self.cards.append(Card(x,'J')) elif(y==12): self.cards.append(Card(x,'Q')) elif(y==13): self.cards.append(Card(x,'K')) def shuffle(self): for i in range(len(self.cards)-1,0,-1): r = random.randint(0,i) self.cards[i], self.cards[r]= self.cards[r], self.cards[i] def deal(self): card = self.cards.pop() print(repr(card)) d = Deck() d.build() d.shuffle() d.deal() <__main__.Card object at 0x7f836e0ed070> Above is the Code and the output that I am getting, any help would be really appreciated. A: it seems that you have forgotten to define the __repr__ method for the Card class. Should be something like: def __repr__(self): return f"Card({self.value})" whereas for the Deck I would define it as: def __repr__(self): return f'Deck("{self.cards}")' the resulting output will be Card(<some-number>). A: Your Class Card needs the __repr__ function, as python tries to print an Instance of the Type Card, not the deck: class Card: def __init__(self, suit, value): self.suit = suit # ['H','D','C','S'] self.value = value # ['A',2,3,4,5,6,7,8,9,10,'J','Q','K'] def __repr__(self): return f'{self.suit}-{self.value}'
Why is my code returning the address of the variable instead of the value?
I am finding it difficult to understand why my code is returning my memory address. I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly. import random class Card: def __init__(self, suit, value): self.suit = suit #['H','D','C','S'] self.value = value #['A',2,3,4,5,6,7,8,9,10,'J','Q','K'] class Deck: def __init__(self): self.cards =[] def __repr__(self): return f'Card("{self.card}")' def build(self): for x in['H','D','C','S']: for y in range(1,14): self.cards.append(Card(x,y)) if(y==1): self.cards.append(Card(x,'A')) elif(y==11): self.cards.append(Card(x,'J')) elif(y==12): self.cards.append(Card(x,'Q')) elif(y==13): self.cards.append(Card(x,'K')) def shuffle(self): for i in range(len(self.cards)-1,0,-1): r = random.randint(0,i) self.cards[i], self.cards[r]= self.cards[r], self.cards[i] def deal(self): card = self.cards.pop() print(repr(card)) d = Deck() d.build() d.shuffle() d.deal() <__main__.Card object at 0x7f836e0ed070> Above is the Code and the output that I am getting, any help would be really appreciated.
[ "it seems that you have forgotten to define the __repr__ method for the Card class. Should be something like:\n def __repr__(self):\n return f\"Card({self.value})\"\n\nwhereas for the Deck I would define it as:\n def __repr__(self):\n return f'Deck(\"{self.cards}\")'\n\nthe resulting output will be Card(<some-number>).\n", "Your Class Card needs the __repr__ function, as python tries to print an Instance of the Type Card, not the deck:\nclass Card:\ndef __init__(self, suit, value):\n self.suit = suit # ['H','D','C','S']\n self.value = value # ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']\ndef __repr__(self):\n return f'{self.suit}-{self.value}'\n\n" ]
[ 3, 3 ]
[]
[]
[ "output", "python", "python_3.x" ]
stackoverflow_0074560234_output_python_python_3.x.txt
Q: Why do I have to use parantheses in (x > 0) & (x < 2) to avoid "The truth value of an array with more than one element is ambiguous"? Having: import numpy as np x = np.ndarray([0,1,2]) This doesn't work: x > 0 & x < 2 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() This works: (x > 0) & (x < 2) Out[32]: array([False, True, False]) So maybe the reason is operator precedence. But all of these work as well: ((x > 0) & x) < 2 Out[33]: array([ True, True, True]) (x > (0 & x)) < 2 Out[34]: array([ True, True, True]) x > ((0 & x) < 2) Out[35]: array([False, False, True]) x > (0 & (x < 2)) Out[36]: array([False, True, True]) Then why does the original expression not work, if any order of operator execution would work? Is it because choosing one of them is ambiguous? But then the exception message is misleading? A: It seems that x > 0 & x < 2 is more like (x > (0 & x)) and ((0 & x) < 2), and the error is raised for the operation and. I believe it's caused by that & will be calculated before comparison, and python has a syntactic sugar to translate x > y < z into (x > y) and (y < z).
Why do I have to use parantheses in (x > 0) & (x < 2) to avoid "The truth value of an array with more than one element is ambiguous"?
Having: import numpy as np x = np.ndarray([0,1,2]) This doesn't work: x > 0 & x < 2 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() This works: (x > 0) & (x < 2) Out[32]: array([False, True, False]) So maybe the reason is operator precedence. But all of these work as well: ((x > 0) & x) < 2 Out[33]: array([ True, True, True]) (x > (0 & x)) < 2 Out[34]: array([ True, True, True]) x > ((0 & x) < 2) Out[35]: array([False, False, True]) x > (0 & (x < 2)) Out[36]: array([False, True, True]) Then why does the original expression not work, if any order of operator execution would work? Is it because choosing one of them is ambiguous? But then the exception message is misleading?
[ "It seems that x > 0 & x < 2 is more like (x > (0 & x)) and ((0 & x) < 2), and the error is raised for the operation and.\nI believe it's caused by that & will be calculated before comparison, and python has a syntactic sugar to translate x > y < z into (x > y) and (y < z).\n" ]
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074560194_numpy_python.txt
Q: How to get the return value from a thread? The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target? from threading import Thread def foo(bar): print('hello {}'.format(bar)) return 'foo' thread = Thread(target=foo, args=('world!',)) thread.start() return_value = thread.join() The "one obvious way to do it", shown above, doesn't work: thread.join() returned None. A: One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example: def foo(bar, result, index): print 'hello {0}'.format(bar) result[index] = "foo" from threading import Thread threads = [None] * 10 results = [None] * 10 for i in range(len(threads)): threads[i] = Thread(target=foo, args=('world!', results, i)) threads[i].start() # do some other stuff for i in range(len(threads)): threads[i].join() print " ".join(results) # what sound does a metasyntactic locomotive make? If you really want join() to return the return value of the called function, you can do this with a Thread subclass like the following: from threading import Thread def foo(bar): print 'hello {0}'.format(bar) return "foo" class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): Thread.__init__(self, group, target, name, args, kwargs, Verbose) self._return = None def run(self): if self._Thread__target is not None: self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs) def join(self): Thread.join(self) return self._return twrv = ThreadWithReturnValue(target=foo, args=('world!',)) twrv.start() print twrv.join() # prints foo That gets a little hairy because of some name mangling, and it accesses "private" data structures that are specific to Thread implementation... but it works. For Python 3: class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): Thread.__init__(self, group, target, name, args, kwargs) self._return = None def run(self): if self._target is not None: self._return = self._target(*self._args, **self._kwargs) def join(self, *args): Thread.join(self, *args) return self._return A: FWIW, the multiprocessing module has a nice interface for this using the Pool class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool class as a drop-in replacement. def foo(bar, baz): print 'hello {0}'.format(bar) return 'foo' + baz from multiprocessing.pool import ThreadPool pool = ThreadPool(processes=1) async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo # do some other stuff in the main process return_val = async_result.get() # get the return value from your function. A: In Python 3.2+, stdlib concurrent.futures module provides a higher level API to threading, including passing return values or exceptions from a worker thread back to the main thread: import concurrent.futures def foo(bar): print('hello {}'.format(bar)) return 'foo' with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(foo, 'world!') return_value = future.result() print(return_value) A: Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good way to transmit information between threads is the built-in Queue.Queue class, as it offers thread safety. I created the following decorator to make it act in a similar fashion to the threadpool: def threaded(f, daemon=False): import Queue def wrapped_f(q, *args, **kwargs): '''this function calls the decorated function and puts the result in a queue''' ret = f(*args, **kwargs) q.put(ret) def wrap(*args, **kwargs): '''this is the function returned from the decorator. It fires off wrapped_f in a new thread and returns the thread object with the result queue attached''' q = Queue.Queue() t = threading.Thread(target=wrapped_f, args=(q,)+args, kwargs=kwargs) t.daemon = daemon t.start() t.result_queue = q return t return wrap Then you just use it as: @threaded def long_task(x): import time x = x + 5 time.sleep(5) return x # does not block, returns Thread object y = long_task(10) print y # this blocks, waiting for the result result = y.result_queue.get() print result The decorated function creates a new thread each time it's called and returns a Thread object that contains the queue that will receive the result. UPDATE It's been quite a while since I posted this answer, but it still gets views so I thought I would update it to reflect the way I do this in newer versions of Python: Python 3.2 added in the concurrent.futures module which provides a high-level interface for parallel tasks. It provides ThreadPoolExecutor and ProcessPoolExecutor, so you can use a thread or process pool with the same api. One benefit of this api is that submitting a task to an Executor returns a Future object, which will complete with the return value of the callable you submit. This makes attaching a queue object unnecessary, which simplifies the decorator quite a bit: _DEFAULT_POOL = ThreadPoolExecutor() def threadpool(f, executor=None): @wraps(f) def wrap(*args, **kwargs): return (executor or _DEFAULT_POOL).submit(f, *args, **kwargs) return wrap This will use a default module threadpool executor if one is not passed in. The usage is very similar to before: @threadpool def long_task(x): import time x = x + 5 time.sleep(5) return x # does not block, returns Future object y = long_task(10) print y # this blocks, waiting for the result result = y.result() print result If you're using Python 3.4+, one really nice feature of using this method (and Future objects in general) is that the returned future can be wrapped to turn it into an asyncio.Future with asyncio.wrap_future. This makes it work easily with coroutines: result = await asyncio.wrap_future(long_task(10)) If you don't need access to the underlying concurrent.Future object, you can include the wrap in the decorator: _DEFAULT_POOL = ThreadPoolExecutor() def threadpool(f, executor=None): @wraps(f) def wrap(*args, **kwargs): return asyncio.wrap_future((executor or _DEFAULT_POOL).submit(f, *args, **kwargs)) return wrap Then, whenever you need to push cpu intensive or blocking code off the event loop thread, you can put it in a decorated function: @threadpool def some_long_calculation(): ... # this will suspend while the function is executed on a threadpool result = await some_long_calculation() A: Another solution that doesn't require changing your existing code: import Queue # Python 2.x #from queue import Queue # Python 3.x from threading import Thread def foo(bar): print 'hello {0}'.format(bar) # Python 2.x #print('hello {0}'.format(bar)) # Python 3.x return 'foo' que = Queue.Queue() # Python 2.x #que = Queue() # Python 3.x t = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!')) t.start() t.join() result = que.get() print result # Python 2.x #print(result) # Python 3.x It can be also easily adjusted to a multi-threaded environment: import Queue # Python 2.x #from queue import Queue # Python 3.x from threading import Thread def foo(bar): print 'hello {0}'.format(bar) # Python 2.x #print('hello {0}'.format(bar)) # Python 3.x return 'foo' que = Queue.Queue() # Python 2.x #que = Queue() # Python 3.x threads_list = list() t = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!')) t.start() threads_list.append(t) # Add more threads here ... threads_list.append(t2) ... threads_list.append(t3) ... # Join all the threads for t in threads_list: t.join() # Check thread's return value while not que.empty(): result = que.get() print result # Python 2.x #print(result) # Python 3.x A: Most answers I've found are long and require being familiar with other modules or advanced python features, and will be rather confusing to someone unless they're already familiar with everything the answer talks about. Working code for a simplified approach: import threading class ThreadWithResult(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None): def function(): self.result = target(*args, **kwargs) super().__init__(group=group, target=function, name=name, daemon=daemon) Example code: import time, random def function_to_thread(n): count = 0 while count < 3: print(f'still running thread {n}') count +=1 time.sleep(3) result = random.random() print(f'Return value of thread {n} should be: {result}') return result def main(): thread1 = ThreadWithResult(target=function_to_thread, args=(1,)) thread2 = ThreadWithResult(target=function_to_thread, args=(2,)) thread1.start() thread2.start() thread1.join() thread2.join() print(thread1.result) print(thread2.result) main() Explanation: I wanted to simplify things significantly, so I created a ThreadWithResult class and had it inherit from threading.Thread. The nested function function in __init__ calls the threaded function we want to save the value of, and saves the result of that nested function as the instance attribute self.result after the thread finishes executing. Creating an instance of this is identical to creating an instance of threading.Thread. Pass in the function you want to run on a new thread to the target argument and any arguments that your function might need to the args argument and any keyword arguments to the kwargs argument. e.g. my_thread = ThreadWithResult(target=my_function, args=(arg1, arg2, arg3)) I think this is significantly easier to understand than the vast majority of answers, and this approach requires no extra imports! I included the time and random module to simulate the behavior of a thread, but they're not required to achieve the functionality asked in the original question. I know I'm answering this looong after the question was asked, but I hope this can help more people in the future! EDIT: I created the save-thread-result PyPI package to allow you to access the same code above and reuse it across projects (GitHub code is here). The PyPI package fully extends the threading.Thread class, so you can set any attributes you would set on threading.thread on the ThreadWithResult class as well! The original answer above goes over the main idea behind this subclass, but for more information, see the more detailed explanation (from the module docstring) here. Quick usage example: pip3 install -U save-thread-result # MacOS/Linux pip install -U save-thread-result # Windows python3 # MacOS/Linux python # Windows from save_thread_result import ThreadWithResult # As of Release 0.0.3, you can also specify values for #`group`, `name`, and `daemon` if you want to set those # values manually. thread = ThreadWithResult( target = my_function, args = (my_function_arg1, my_function_arg2, ...) kwargs = {my_function_kwarg1: kwarg1_value, my_function_kwarg2: kwarg2_value, ...} ) thread.start() thread.join() if getattr(thread, 'result', None): print(thread.result) else: # thread.result attribute not set - something caused # the thread to terminate BEFORE the thread finished # executing the function passed in through the # `target` argument print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!') # seeing help about the class and information about the threading.Thread super class methods and attributes available: help(ThreadWithResult) A: Parris / kindall's answer join/return answer ported to Python 3: from threading import Thread def foo(bar): print('hello {0}'.format(bar)) return "foo" class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon) self._return = None def run(self): if self._target is not None: self._return = self._target(*self._args, **self._kwargs) def join(self): Thread.join(self) return self._return twrv = ThreadWithReturnValue(target=foo, args=('world!',)) twrv.start() print(twrv.join()) # prints foo Note, the Thread class is implemented differently in Python 3. A: I stole kindall's answer and cleaned it up just a little bit. The key part is adding *args and **kwargs to join() in order to handle the timeout class threadWithReturn(Thread): def __init__(self, *args, **kwargs): super(threadWithReturn, self).__init__(*args, **kwargs) self._return = None def run(self): if self._Thread__target is not None: self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs) def join(self, *args, **kwargs): super(threadWithReturn, self).join(*args, **kwargs) return self._return UPDATED ANSWER BELOW This is my most popularly upvoted answer, so I decided to update with code that will run on both py2 and py3. Additionally, I see many answers to this question that show a lack of comprehension regarding Thread.join(). Some completely fail to handle the timeout arg. But there is also a corner-case that you should be aware of regarding instances when you have (1) a target function that can return None and (2) you also pass the timeout arg to join(). Please see "TEST 4" to understand this corner case. ThreadWithReturn class that works with py2 and py3: import sys from threading import Thread from builtins import super # https://stackoverflow.com/a/30159479 _thread_target_key, _thread_args_key, _thread_kwargs_key = ( ('_target', '_args', '_kwargs') if sys.version_info >= (3, 0) else ('_Thread__target', '_Thread__args', '_Thread__kwargs') ) class ThreadWithReturn(Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._return = None def run(self): target = getattr(self, _thread_target_key) if target is not None: self._return = target( *getattr(self, _thread_args_key), **getattr(self, _thread_kwargs_key) ) def join(self, *args, **kwargs): super().join(*args, **kwargs) return self._return Some sample tests are shown below: import time, random # TEST TARGET FUNCTION def giveMe(arg, seconds=None): if not seconds is None: time.sleep(seconds) return arg # TEST 1 my_thread = ThreadWithReturn(target=giveMe, args=('stringy',)) my_thread.start() returned = my_thread.join() # (returned == 'stringy') # TEST 2 my_thread = ThreadWithReturn(target=giveMe, args=(None,)) my_thread.start() returned = my_thread.join() # (returned is None) # TEST 3 my_thread = ThreadWithReturn(target=giveMe, args=('stringy',), kwargs={'seconds': 5}) my_thread.start() returned = my_thread.join(timeout=2) # (returned is None) # because join() timed out before giveMe() finished # TEST 4 my_thread = ThreadWithReturn(target=giveMe, args=(None,), kwargs={'seconds': 5}) my_thread.start() returned = my_thread.join(timeout=random.randint(1, 10)) Can you identify the corner-case that we may possibly encounter with TEST 4? The problem is that we expect giveMe() to return None (see TEST 2), but we also expect join() to return None if it times out. returned is None means either: (1) that's what giveMe() returned, or (2) join() timed out This example is trivial since we know that giveMe() will always return None. But in real-world instance (where the target may legitimately return None or something else) we'd want to explicitly check for what happened. Below is how to address this corner-case: # TEST 4 my_thread = ThreadWithReturn(target=giveMe, args=(None,), kwargs={'seconds': 5}) my_thread.start() returned = my_thread.join(timeout=random.randint(1, 10)) if my_thread.isAlive(): # returned is None because join() timed out # this also means that giveMe() is still running in the background pass # handle this based on your app's logic else: # join() is finished, and so is giveMe() # BUT we could also be in a race condition, so we need to update returned, just in case returned = my_thread.join() A: Using Queue : import threading, queue def calc_square(num, out_queue1): l = [] for x in num: l.append(x*x) out_queue1.put(l) arr = [1,2,3,4,5,6,7,8,9,10] out_queue1=queue.Queue() t1=threading.Thread(target=calc_square, args=(arr,out_queue1)) t1.start() t1.join() print (out_queue1.get()) A: My solution to the problem is to wrap the function and thread in a class. Does not require using pools,queues, or c type variable passing. It is also non blocking. You check status instead. See example of how to use it at end of code. import threading class ThreadWorker(): ''' The basic idea is given a function create an object. The object can then run the function in a thread. It provides a wrapper to start it,check its status,and get data out the function. ''' def __init__(self,func): self.thread = None self.data = None self.func = self.save_data(func) def save_data(self,func): '''modify function to save its returned data''' def new_func(*args, **kwargs): self.data=func(*args, **kwargs) return new_func def start(self,params): self.data = None if self.thread is not None: if self.thread.isAlive(): return 'running' #could raise exception here #unless thread exists and is alive start or restart it self.thread = threading.Thread(target=self.func,args=params) self.thread.start() return 'started' def status(self): if self.thread is None: return 'not_started' else: if self.thread.isAlive(): return 'running' else: return 'finished' def get_results(self): if self.thread is None: return 'not_started' #could return exception else: if self.thread.isAlive(): return 'running' else: return self.data def add(x,y): return x +y add_worker = ThreadWorker(add) print add_worker.start((1,2,)) print add_worker.status() print add_worker.get_results() A: Taking into consideration @iman comment on @JakeBiesinger answer I have recomposed it to have various number of threads: from multiprocessing.pool import ThreadPool def foo(bar, baz): print 'hello {0}'.format(bar) return 'foo' + baz numOfThreads = 3 results = [] pool = ThreadPool(numOfThreads) for i in range(0, numOfThreads): results.append(pool.apply_async(foo, ('world', 'foo'))) # tuple of args for foo) # do some other stuff in the main process # ... # ... results = [r.get() for r in results] print results pool.close() pool.join() A: I'm using this wrapper, which comfortably turns any function for running in a Thread - taking care of its return value or exception. It doesn't add Queue overhead. def threading_func(f): """Decorator for running a function in a thread and handling its return value or exception""" def start(*args, **kw): def run(): try: th.ret = f(*args, **kw) except: th.exc = sys.exc_info() def get(timeout=None): th.join(timeout) if th.exc: raise th.exc[0], th.exc[1], th.exc[2] # py2 ##raise th.exc[1] #py3 return th.ret th = threading.Thread(None, run) th.exc = None th.get = get th.start() return th return start Usage Examples def f(x): return 2.5 * x th = threading_func(f)(4) print("still running?:", th.is_alive()) print("result:", th.get(timeout=1.0)) @threading_func def th_mul(a, b): return a * b th = th_mul("text", 2.5) try: print(th.get()) except TypeError: print("exception thrown ok.") Notes on threading module Comfortable return value & exception handling of a threaded function is a frequent "Pythonic" need and should indeed already be offered by the threading module - possibly directly in the standard Thread class. ThreadPool has way too much overhead for simple tasks - 3 managing threads, lots of bureaucracy. Unfortunately Thread's layout was copied from Java originally - which you see e.g. from the still useless 1st (!) constructor parameter group. A: Based of what kindall mentioned, here's the more generic solution that works with Python3. import threading class ThreadWithReturnValue(threading.Thread): def __init__(self, *init_args, **init_kwargs): threading.Thread.__init__(self, *init_args, **init_kwargs) self._return = None def run(self): self._return = self._target(*self._args, **self._kwargs) def join(self): threading.Thread.join(self) return self._return Usage th = ThreadWithReturnValue(target=requests.get, args=('http://www.google.com',)) th.start() response = th.join() response.status_code # => 200 A: join always return None, i think you should subclass Thread to handle return codes and so. A: You can define a mutable above the scope of the threaded function, and add the result to that. (I also modified the code to be python3 compatible) returns = {} def foo(bar): print('hello {0}'.format(bar)) returns[bar] = 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() t.join() print(returns) This returns {'world!': 'foo'} If you use the function input as the key to your results dict, every unique input is guaranteed to give an entry in the results A: Define your target to 1) take an argument q 2) replace any statements return foo with q.put(foo); return so a function def func(a): ans = a * a return ans would become def func(a, q): ans = a * a q.put(ans) return and then you would proceed as such from Queue import Queue from threading import Thread ans_q = Queue() arg_tups = [(i, ans_q) for i in xrange(10)] threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups] _ = [t.start() for t in threads] _ = [t.join() for t in threads] results = [q.get() for _ in xrange(len(threads))] And you can use function decorators/wrappers to make it so you can use your existing functions as target without modifying them, but follow this basic scheme. A: GuySoft's idea is great, but I think the object does not necessarily have to inherit from Thread and start() could be removed from interface: from threading import Thread import queue class ThreadWithReturnValue(object): def __init__(self, target=None, args=(), **kwargs): self._que = queue.Queue() self._t = Thread(target=lambda q,arg1,kwargs1: q.put(target(*arg1, **kwargs1)) , args=(self._que, args, kwargs), ) self._t.start() def join(self): self._t.join() return self._que.get() def foo(bar): print('hello {0}'.format(bar)) return "foo" twrv = ThreadWithReturnValue(target=foo, args=('world!',)) print(twrv.join()) # prints foo A: This is a pretty old question, but I wanted to share a simple solution that has worked for me and helped my dev process. The methodology behind this answer is the fact that the "new" target function, inner is assigning the result of the original function (passed through the __init__ function) to the result instance attribute of the wrapper through something called closure. This allows the wrapper class to hold onto the return value for callers to access at anytime. NOTE: This method doesn't need to use any mangled methods or private methods of the threading.Thread class, although yield functions have not been considered (OP did not mention yield functions). Enjoy! from threading import Thread as _Thread class ThreadWrapper: def __init__(self, target, *args, **kwargs): self.result = None self._target = self._build_threaded_fn(target) self.thread = _Thread( target=self._target, *args, **kwargs ) def _build_threaded_fn(self, func): def inner(*args, **kwargs): self.result = func(*args, **kwargs) return inner Additionally, you can run pytest (assuming you have it installed) with the following code to demonstrate the results: import time from commons import ThreadWrapper def test(): def target(): time.sleep(1) return 'Hello' wrapper = ThreadWrapper(target=target) wrapper.thread.start() r = wrapper.result assert r is None time.sleep(2) r = wrapper.result assert r == 'Hello' A: As mentioned multiprocessing pool is much slower than basic threading. Using queues as proposeded in some answers here is a very effective alternative. I have use it with dictionaries in order to be able run a lot of small threads and recuperate multiple answers by combining them with dictionaries: #!/usr/bin/env python3 import threading # use Queue for python2 import queue import random LETTERS = 'abcdefghijklmnopqrstuvwxyz' LETTERS = [ x for x in LETTERS ] NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def randoms(k, q): result = dict() result['letter'] = random.choice(LETTERS) result['number'] = random.choice(NUMBERS) q.put({k: result}) threads = list() q = queue.Queue() results = dict() for name in ('alpha', 'oscar', 'yankee',): threads.append( threading.Thread(target=randoms, args=(name, q)) ) threads[-1].start() _ = [ t.join() for t in threads ] while not q.empty(): results.update(q.get()) print(results) A: Here is the version that I created of @Kindall's answer. This version makes it so that all you have to do is input your command with arguments to create the new thread. This was made with Python 3.8: from threading import Thread from typing import Any def test(plug, plug2, plug3): print(f"hello {plug}") print(f'I am the second plug : {plug2}') print(plug3) return 'I am the return Value!' def test2(msg): return f'I am from the second test: {msg}' def test3(): print('hello world') def NewThread(com, Returning: bool, *arguments) -> Any: """ Will create a new thread for a function/command. :param com: Command to be Executed :param arguments: Arguments to be sent to Command :param Returning: True/False Will this command need to return anything """ class NewThreadWorker(Thread): def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *, daemon = None): Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon) self._return = None def run(self): if self._target is not None: self._return = self._target(*self._args, **self._kwargs) def join(self): Thread.join(self) return self._return ntw = NewThreadWorker(target = com, args = (*arguments,)) ntw.start() if Returning: return ntw.join() if __name__ == "__main__": print(NewThread(test, True, 'hi', 'test', test2('hi'))) NewThread(test3, True) A: One usual solution is to wrap your function foo with a decorator like result = queue.Queue() def task_wrapper(*args): result.put(target(*args)) Then the whole code may looks like that result = queue.Queue() def task_wrapper(*args): result.put(target(*args)) threads = [threading.Thread(target=task_wrapper, args=args) for args in args_list] for t in threads: t.start() while(True): if(len(threading.enumerate()) < max_num): break for t in threads: t.join() return result Note One important issue is that the return values may be unorderred. (In fact, the return value is not necessarily saved to the queue, since you can choose arbitrary thread-safe data structure ) A: Kindall's answer in Python3 class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None): Thread.__init__(self, group, target, name, args, kwargs, daemon) self._return = None def run(self): try: if self._target: self._return = self._target(*self._args, **self._kwargs) finally: del self._target, self._args, self._kwargs def join(self,timeout=None): Thread.join(self,timeout) return self._return A: You can use pool.apply_async() of ThreadPool() to return the value from test() as shown below: from multiprocessing.pool import ThreadPool def test(num1, num2): return num1 + num2 pool = ThreadPool(processes=1) # Here result = pool.apply_async(test, (2, 3)) # Here print(result.get()) # 5 And, you can also use submit() of concurrent.futures.ThreadPoolExecutor() to return the value from test() as shown below: from concurrent.futures import ThreadPoolExecutor def test(num1, num2): return num1 + num2 with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(test, 2, 3) # Here print(future.result()) # 5 And, instead of return, you can use the array result as shown below: from threading import Thread def test(num1, num2, r): r[0] = num1 + num2 # Instead of "return" result = [None] # Here thread = Thread(target=test, args=(2, 3, result)) thread.start() thread.join() print(result[0]) # 5 And instead of return, you can also use the queue result as shown below: from threading import Thread import queue def test(num1, num2, q): q.put(num1 + num2) # Instead of "return" queue = queue.Queue() # Here thread = Thread(target=test, args=(2, 3, queue)) thread.start() thread.join() print(queue.get()) # '5' A: The shortest and simplest way I've found to do this is to take advantage of Python classes and their dynamic properties. You can retrieve the current thread from within the context of your spawned thread using threading.current_thread(), and assign the return value to a property. import threading def some_target_function(): # Your code here. threading.current_thread().return_value = "Some return value." your_thread = threading.Thread(target=some_target_function) your_thread.start() your_thread.join() return_value = your_thread.return_value print(return_value)
How to get the return value from a thread?
The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target? from threading import Thread def foo(bar): print('hello {}'.format(bar)) return 'foo' thread = Thread(target=foo, args=('world!',)) thread.start() return_value = thread.join() The "one obvious way to do it", shown above, doesn't work: thread.join() returned None.
[ "One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example:\ndef foo(bar, result, index):\n print 'hello {0}'.format(bar)\n result[index] = \"foo\"\n\nfrom threading import Thread\n\nthreads = [None] * 10\nresults = [None] * 10\n\nfor i in range(len(threads)):\n threads[i] = Thread(target=foo, args=('world!', results, i))\n threads[i].start()\n\n# do some other stuff\n\nfor i in range(len(threads)):\n threads[i].join()\n\nprint \" \".join(results) # what sound does a metasyntactic locomotive make?\n\nIf you really want join() to return the return value of the called function, you can do this with a Thread subclass like the following:\nfrom threading import Thread\n\ndef foo(bar):\n print 'hello {0}'.format(bar)\n return \"foo\"\n\nclass ThreadWithReturnValue(Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs={}, Verbose=None):\n Thread.__init__(self, group, target, name, args, kwargs, Verbose)\n self._return = None\n def run(self):\n if self._Thread__target is not None:\n self._return = self._Thread__target(*self._Thread__args,\n **self._Thread__kwargs)\n def join(self):\n Thread.join(self)\n return self._return\n\ntwrv = ThreadWithReturnValue(target=foo, args=('world!',))\n\ntwrv.start()\nprint twrv.join() # prints foo\n\nThat gets a little hairy because of some name mangling, and it accesses \"private\" data structures that are specific to Thread implementation... but it works.\nFor Python 3:\nclass ThreadWithReturnValue(Thread):\n \n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs={}, Verbose=None):\n Thread.__init__(self, group, target, name, args, kwargs)\n self._return = None\n\n def run(self):\n if self._target is not None:\n self._return = self._target(*self._args,\n **self._kwargs)\n def join(self, *args):\n Thread.join(self, *args)\n return self._return\n\n", "FWIW, the multiprocessing module has a nice interface for this using the Pool class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool class as a drop-in replacement.\ndef foo(bar, baz):\n print 'hello {0}'.format(bar)\n return 'foo' + baz\n\nfrom multiprocessing.pool import ThreadPool\npool = ThreadPool(processes=1)\n\nasync_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo\n\n# do some other stuff in the main process\n\nreturn_val = async_result.get() # get the return value from your function.\n\n", "In Python 3.2+, stdlib concurrent.futures module provides a higher level API to threading, including passing return values or exceptions from a worker thread back to the main thread:\nimport concurrent.futures\n\ndef foo(bar):\n print('hello {}'.format(bar))\n return 'foo'\n\nwith concurrent.futures.ThreadPoolExecutor() as executor:\n future = executor.submit(foo, 'world!')\n return_value = future.result()\n print(return_value)\n\n", "Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good way to transmit information between threads is the built-in Queue.Queue class, as it offers thread safety.\nI created the following decorator to make it act in a similar fashion to the threadpool:\ndef threaded(f, daemon=False):\n import Queue\n\n def wrapped_f(q, *args, **kwargs):\n '''this function calls the decorated function and puts the \n result in a queue'''\n ret = f(*args, **kwargs)\n q.put(ret)\n\n def wrap(*args, **kwargs):\n '''this is the function returned from the decorator. It fires off\n wrapped_f in a new thread and returns the thread object with\n the result queue attached'''\n\n q = Queue.Queue()\n\n t = threading.Thread(target=wrapped_f, args=(q,)+args, kwargs=kwargs)\n t.daemon = daemon\n t.start()\n t.result_queue = q \n return t\n\n return wrap\n\nThen you just use it as:\n@threaded\ndef long_task(x):\n import time\n x = x + 5\n time.sleep(5)\n return x\n\n# does not block, returns Thread object\ny = long_task(10)\nprint y\n\n# this blocks, waiting for the result\nresult = y.result_queue.get()\nprint result\n\nThe decorated function creates a new thread each time it's called and returns a Thread object that contains the queue that will receive the result.\nUPDATE\nIt's been quite a while since I posted this answer, but it still gets views so I thought I would update it to reflect the way I do this in newer versions of Python:\nPython 3.2 added in the concurrent.futures module which provides a high-level interface for parallel tasks. It provides ThreadPoolExecutor and ProcessPoolExecutor, so you can use a thread or process pool with the same api.\nOne benefit of this api is that submitting a task to an Executor returns a Future object, which will complete with the return value of the callable you submit.\nThis makes attaching a queue object unnecessary, which simplifies the decorator quite a bit:\n_DEFAULT_POOL = ThreadPoolExecutor()\n\ndef threadpool(f, executor=None):\n @wraps(f)\n def wrap(*args, **kwargs):\n return (executor or _DEFAULT_POOL).submit(f, *args, **kwargs)\n\n return wrap\n\nThis will use a default module threadpool executor if one is not passed in.\nThe usage is very similar to before:\n@threadpool\ndef long_task(x):\n import time\n x = x + 5\n time.sleep(5)\n return x\n\n# does not block, returns Future object\ny = long_task(10)\nprint y\n\n# this blocks, waiting for the result\nresult = y.result()\nprint result\n\nIf you're using Python 3.4+, one really nice feature of using this method (and Future objects in general) is that the returned future can be wrapped to turn it into an asyncio.Future with asyncio.wrap_future. This makes it work easily with coroutines:\nresult = await asyncio.wrap_future(long_task(10))\n\nIf you don't need access to the underlying concurrent.Future object, you can include the wrap in the decorator:\n_DEFAULT_POOL = ThreadPoolExecutor()\n\ndef threadpool(f, executor=None):\n @wraps(f)\n def wrap(*args, **kwargs):\n return asyncio.wrap_future((executor or _DEFAULT_POOL).submit(f, *args, **kwargs))\n\n return wrap\n\nThen, whenever you need to push cpu intensive or blocking code off the event loop thread, you can put it in a decorated function:\n@threadpool\ndef some_long_calculation():\n ...\n\n# this will suspend while the function is executed on a threadpool\nresult = await some_long_calculation()\n\n", "Another solution that doesn't require changing your existing code:\nimport Queue # Python 2.x\n#from queue import Queue # Python 3.x\n\nfrom threading import Thread\n\ndef foo(bar):\n print 'hello {0}'.format(bar) # Python 2.x\n #print('hello {0}'.format(bar)) # Python 3.x\n return 'foo'\n\nque = Queue.Queue() # Python 2.x\n#que = Queue() # Python 3.x\n\nt = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!'))\nt.start()\nt.join()\nresult = que.get()\nprint result # Python 2.x\n#print(result) # Python 3.x\n\nIt can be also easily adjusted to a multi-threaded environment:\nimport Queue # Python 2.x\n#from queue import Queue # Python 3.x\nfrom threading import Thread\n\ndef foo(bar):\n print 'hello {0}'.format(bar) # Python 2.x\n #print('hello {0}'.format(bar)) # Python 3.x\n return 'foo'\n\nque = Queue.Queue() # Python 2.x\n#que = Queue() # Python 3.x\n\nthreads_list = list()\n\nt = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!'))\nt.start()\nthreads_list.append(t)\n\n# Add more threads here\n...\nthreads_list.append(t2)\n...\nthreads_list.append(t3)\n...\n\n# Join all the threads\nfor t in threads_list:\n t.join()\n\n# Check thread's return value\nwhile not que.empty():\n result = que.get()\n print result # Python 2.x\n #print(result) # Python 3.x\n\n", "Most answers I've found are long and require being familiar with other modules or advanced python features, and will be rather confusing to someone unless they're already familiar with everything the answer talks about.\nWorking code for a simplified approach:\nimport threading\n\nclass ThreadWithResult(threading.Thread):\n def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):\n def function():\n self.result = target(*args, **kwargs)\n super().__init__(group=group, target=function, name=name, daemon=daemon)\n\n\nExample code:\nimport time, random\n\n\ndef function_to_thread(n):\n count = 0\n while count < 3:\n print(f'still running thread {n}')\n count +=1\n time.sleep(3)\n result = random.random()\n print(f'Return value of thread {n} should be: {result}')\n return result\n\n\ndef main():\n thread1 = ThreadWithResult(target=function_to_thread, args=(1,))\n thread2 = ThreadWithResult(target=function_to_thread, args=(2,))\n thread1.start()\n thread2.start()\n thread1.join()\n thread2.join()\n print(thread1.result)\n print(thread2.result)\n\nmain()\n\nExplanation:\nI wanted to simplify things significantly, so I created a ThreadWithResult class and had it inherit from threading.Thread. The nested function function in __init__ calls the threaded function we want to save the value of, and saves the result of that nested function as the instance attribute self.result after the thread finishes executing.\nCreating an instance of this is identical to creating an instance of threading.Thread. Pass in the function you want to run on a new thread to the target argument and any arguments that your function might need to the args argument and any keyword arguments to the kwargs argument.\ne.g.\nmy_thread = ThreadWithResult(target=my_function, args=(arg1, arg2, arg3))\n\nI think this is significantly easier to understand than the vast majority of answers, and this approach requires no extra imports! I included the time and random module to simulate the behavior of a thread, but they're not required to achieve the functionality asked in the original question.\nI know I'm answering this looong after the question was asked, but I hope this can help more people in the future!\n\nEDIT: I created the save-thread-result PyPI package to allow you to access the same code above and reuse it across projects (GitHub code is here). The PyPI package fully extends the threading.Thread class, so you can set any attributes you would set on threading.thread on the ThreadWithResult class as well!\nThe original answer above goes over the main idea behind this subclass, but for more information, see the more detailed explanation (from the module docstring) here.\nQuick usage example:\npip3 install -U save-thread-result # MacOS/Linux\npip install -U save-thread-result # Windows\n\npython3 # MacOS/Linux\npython # Windows\n\nfrom save_thread_result import ThreadWithResult\n\n# As of Release 0.0.3, you can also specify values for\n#`group`, `name`, and `daemon` if you want to set those\n# values manually.\nthread = ThreadWithResult(\n target = my_function,\n args = (my_function_arg1, my_function_arg2, ...)\n kwargs = {my_function_kwarg1: kwarg1_value, my_function_kwarg2: kwarg2_value, ...}\n)\n\nthread.start()\nthread.join()\nif getattr(thread, 'result', None):\n print(thread.result)\nelse:\n # thread.result attribute not set - something caused\n # the thread to terminate BEFORE the thread finished\n # executing the function passed in through the\n # `target` argument\n print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!')\n\n# seeing help about the class and information about the threading.Thread super class methods and attributes available:\nhelp(ThreadWithResult)\n\n", "Parris / kindall's answer join/return answer ported to Python 3:\nfrom threading import Thread\n\ndef foo(bar):\n print('hello {0}'.format(bar))\n return \"foo\"\n\nclass ThreadWithReturnValue(Thread):\n def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):\n Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)\n\n self._return = None\n\n def run(self):\n if self._target is not None:\n self._return = self._target(*self._args, **self._kwargs)\n\n def join(self):\n Thread.join(self)\n return self._return\n\n\ntwrv = ThreadWithReturnValue(target=foo, args=('world!',))\n\ntwrv.start()\nprint(twrv.join()) # prints foo\n\nNote, the Thread class is implemented differently in Python 3.\n", "I stole kindall's answer and cleaned it up just a little bit.\nThe key part is adding *args and **kwargs to join() in order to handle the timeout\nclass threadWithReturn(Thread):\n def __init__(self, *args, **kwargs):\n super(threadWithReturn, self).__init__(*args, **kwargs)\n \n self._return = None\n \n def run(self):\n if self._Thread__target is not None:\n self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)\n \n def join(self, *args, **kwargs):\n super(threadWithReturn, self).join(*args, **kwargs)\n \n return self._return\n\nUPDATED ANSWER BELOW\nThis is my most popularly upvoted answer, so I decided to update with code that will run on both py2 and py3.\nAdditionally, I see many answers to this question that show a lack of comprehension regarding Thread.join(). Some completely fail to handle the timeout arg. But there is also a corner-case that you should be aware of regarding instances when you have (1) a target function that can return None and (2) you also pass the timeout arg to join(). Please see \"TEST 4\" to understand this corner case.\nThreadWithReturn class that works with py2 and py3:\nimport sys\nfrom threading import Thread\nfrom builtins import super # https://stackoverflow.com/a/30159479\n\n_thread_target_key, _thread_args_key, _thread_kwargs_key = (\n ('_target', '_args', '_kwargs')\n if sys.version_info >= (3, 0) else\n ('_Thread__target', '_Thread__args', '_Thread__kwargs')\n)\n\nclass ThreadWithReturn(Thread):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._return = None\n \n def run(self):\n target = getattr(self, _thread_target_key)\n if target is not None:\n self._return = target(\n *getattr(self, _thread_args_key),\n **getattr(self, _thread_kwargs_key)\n )\n \n def join(self, *args, **kwargs):\n super().join(*args, **kwargs)\n return self._return\n\nSome sample tests are shown below:\nimport time, random\n\n# TEST TARGET FUNCTION\ndef giveMe(arg, seconds=None):\n if not seconds is None:\n time.sleep(seconds)\n return arg\n\n# TEST 1\nmy_thread = ThreadWithReturn(target=giveMe, args=('stringy',))\nmy_thread.start()\nreturned = my_thread.join()\n# (returned == 'stringy')\n\n# TEST 2\nmy_thread = ThreadWithReturn(target=giveMe, args=(None,))\nmy_thread.start()\nreturned = my_thread.join()\n# (returned is None)\n\n# TEST 3\nmy_thread = ThreadWithReturn(target=giveMe, args=('stringy',), kwargs={'seconds': 5})\nmy_thread.start()\nreturned = my_thread.join(timeout=2)\n# (returned is None) # because join() timed out before giveMe() finished\n\n# TEST 4\nmy_thread = ThreadWithReturn(target=giveMe, args=(None,), kwargs={'seconds': 5})\nmy_thread.start()\nreturned = my_thread.join(timeout=random.randint(1, 10))\n\nCan you identify the corner-case that we may possibly encounter with TEST 4?\nThe problem is that we expect giveMe() to return None (see TEST 2), but we also expect join() to return None if it times out.\nreturned is None means either:\n(1) that's what giveMe() returned, or\n(2) join() timed out\nThis example is trivial since we know that giveMe() will always return None. But in real-world instance (where the target may legitimately return None or something else) we'd want to explicitly check for what happened.\nBelow is how to address this corner-case:\n# TEST 4\nmy_thread = ThreadWithReturn(target=giveMe, args=(None,), kwargs={'seconds': 5})\nmy_thread.start()\nreturned = my_thread.join(timeout=random.randint(1, 10))\n\nif my_thread.isAlive():\n # returned is None because join() timed out\n # this also means that giveMe() is still running in the background\n pass\n # handle this based on your app's logic\nelse:\n # join() is finished, and so is giveMe()\n # BUT we could also be in a race condition, so we need to update returned, just in case\n returned = my_thread.join()\n\n", "Using Queue :\nimport threading, queue\n\ndef calc_square(num, out_queue1):\n l = []\n for x in num:\n l.append(x*x)\n out_queue1.put(l)\n\n\narr = [1,2,3,4,5,6,7,8,9,10]\nout_queue1=queue.Queue()\nt1=threading.Thread(target=calc_square, args=(arr,out_queue1))\nt1.start()\nt1.join()\nprint (out_queue1.get())\n\n", "My solution to the problem is to wrap the function and thread in a class. Does not require using pools,queues, or c type variable passing. It is also non blocking. You check status instead. See example of how to use it at end of code.\nimport threading\n\nclass ThreadWorker():\n '''\n The basic idea is given a function create an object.\n The object can then run the function in a thread.\n It provides a wrapper to start it,check its status,and get data out the function.\n '''\n def __init__(self,func):\n self.thread = None\n self.data = None\n self.func = self.save_data(func)\n\n def save_data(self,func):\n '''modify function to save its returned data'''\n def new_func(*args, **kwargs):\n self.data=func(*args, **kwargs)\n\n return new_func\n\n def start(self,params):\n self.data = None\n if self.thread is not None:\n if self.thread.isAlive():\n return 'running' #could raise exception here\n\n #unless thread exists and is alive start or restart it\n self.thread = threading.Thread(target=self.func,args=params)\n self.thread.start()\n return 'started'\n\n def status(self):\n if self.thread is None:\n return 'not_started'\n else:\n if self.thread.isAlive():\n return 'running'\n else:\n return 'finished'\n\n def get_results(self):\n if self.thread is None:\n return 'not_started' #could return exception\n else:\n if self.thread.isAlive():\n return 'running'\n else:\n return self.data\n\ndef add(x,y):\n return x +y\n\nadd_worker = ThreadWorker(add)\nprint add_worker.start((1,2,))\nprint add_worker.status()\nprint add_worker.get_results()\n\n", "Taking into consideration @iman comment on @JakeBiesinger answer I have recomposed it to have various number of threads:\nfrom multiprocessing.pool import ThreadPool\n\ndef foo(bar, baz):\n print 'hello {0}'.format(bar)\n return 'foo' + baz\n\nnumOfThreads = 3 \nresults = []\n\npool = ThreadPool(numOfThreads)\n\nfor i in range(0, numOfThreads):\n results.append(pool.apply_async(foo, ('world', 'foo'))) # tuple of args for foo)\n\n# do some other stuff in the main process\n# ...\n# ...\n\nresults = [r.get() for r in results]\nprint results\n\npool.close()\npool.join()\n\n", "I'm using this wrapper, which comfortably turns any function for running in a Thread - taking care of its return value or exception. It doesn't add Queue overhead. \ndef threading_func(f):\n \"\"\"Decorator for running a function in a thread and handling its return\n value or exception\"\"\"\n def start(*args, **kw):\n def run():\n try:\n th.ret = f(*args, **kw)\n except:\n th.exc = sys.exc_info()\n def get(timeout=None):\n th.join(timeout)\n if th.exc:\n raise th.exc[0], th.exc[1], th.exc[2] # py2\n ##raise th.exc[1] #py3 \n return th.ret\n th = threading.Thread(None, run)\n th.exc = None\n th.get = get\n th.start()\n return th\n return start\n\nUsage Examples\ndef f(x):\n return 2.5 * x\nth = threading_func(f)(4)\nprint(\"still running?:\", th.is_alive())\nprint(\"result:\", th.get(timeout=1.0))\n\n@threading_func\ndef th_mul(a, b):\n return a * b\nth = th_mul(\"text\", 2.5)\n\ntry:\n print(th.get())\nexcept TypeError:\n print(\"exception thrown ok.\")\n\nNotes on threading module\nComfortable return value & exception handling of a threaded function is a frequent \"Pythonic\" need and should indeed already be offered by the threading module - possibly directly in the standard Thread class. ThreadPool has way too much overhead for simple tasks - 3 managing threads, lots of bureaucracy. Unfortunately Thread's layout was copied from Java originally - which you see e.g. from the still useless 1st (!) constructor parameter group.\n", "Based of what kindall mentioned, here's the more generic solution that works with Python3.\nimport threading\n\nclass ThreadWithReturnValue(threading.Thread):\n def __init__(self, *init_args, **init_kwargs):\n threading.Thread.__init__(self, *init_args, **init_kwargs)\n self._return = None\n def run(self):\n self._return = self._target(*self._args, **self._kwargs)\n def join(self):\n threading.Thread.join(self)\n return self._return\n\nUsage\n th = ThreadWithReturnValue(target=requests.get, args=('http://www.google.com',))\n th.start()\n response = th.join()\n response.status_code # => 200\n\n", "join always return None, i think you should subclass Thread to handle return codes and so.\n", "You can define a mutable above the scope of the threaded function, and add the result to that. (I also modified the code to be python3 compatible)\nreturns = {}\ndef foo(bar):\n print('hello {0}'.format(bar))\n returns[bar] = 'foo'\n\nfrom threading import Thread\nt = Thread(target=foo, args=('world!',))\nt.start()\nt.join()\nprint(returns)\n\nThis returns {'world!': 'foo'}\nIf you use the function input as the key to your results dict, every unique input is guaranteed to give an entry in the results \n", "Define your target to\n1) take an argument q\n2) replace any statements return foo with q.put(foo); return\nso a function\ndef func(a):\n ans = a * a\n return ans\n\nwould become\ndef func(a, q):\n ans = a * a\n q.put(ans)\n return\n\nand then you would proceed as such\nfrom Queue import Queue\nfrom threading import Thread\n\nans_q = Queue()\narg_tups = [(i, ans_q) for i in xrange(10)]\n\nthreads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]\n_ = [t.start() for t in threads]\n_ = [t.join() for t in threads]\nresults = [q.get() for _ in xrange(len(threads))]\n\nAnd you can use function decorators/wrappers to make it so you can use your existing functions as target without modifying them, but follow this basic scheme.\n", "GuySoft's idea is great, but I think the object does not necessarily have to inherit from Thread and start() could be removed from interface:\nfrom threading import Thread\nimport queue\nclass ThreadWithReturnValue(object):\n def __init__(self, target=None, args=(), **kwargs):\n self._que = queue.Queue()\n self._t = Thread(target=lambda q,arg1,kwargs1: q.put(target(*arg1, **kwargs1)) ,\n args=(self._que, args, kwargs), )\n self._t.start()\n\n def join(self):\n self._t.join()\n return self._que.get()\n\n\ndef foo(bar):\n print('hello {0}'.format(bar))\n return \"foo\"\n\ntwrv = ThreadWithReturnValue(target=foo, args=('world!',))\n\nprint(twrv.join()) # prints foo\n\n", "This is a pretty old question, but I wanted to share a simple solution that has worked for me and helped my dev process.\nThe methodology behind this answer is the fact that the \"new\" target function, inner is assigning the result of the original function (passed through the __init__ function) to the result instance attribute of the wrapper through something called closure.\nThis allows the wrapper class to hold onto the return value for callers to access at anytime.\nNOTE: This method doesn't need to use any mangled methods or private methods of the threading.Thread class, although yield functions have not been considered (OP did not mention yield functions).\nEnjoy!\nfrom threading import Thread as _Thread\n\n\nclass ThreadWrapper:\n def __init__(self, target, *args, **kwargs):\n self.result = None\n self._target = self._build_threaded_fn(target)\n self.thread = _Thread(\n target=self._target,\n *args,\n **kwargs\n )\n\n def _build_threaded_fn(self, func):\n def inner(*args, **kwargs):\n self.result = func(*args, **kwargs)\n return inner\n\n\nAdditionally, you can run pytest (assuming you have it installed) with the following code to demonstrate the results:\nimport time\nfrom commons import ThreadWrapper\n\n\ndef test():\n\n def target():\n time.sleep(1)\n return 'Hello'\n\n wrapper = ThreadWrapper(target=target)\n wrapper.thread.start()\n\n r = wrapper.result\n assert r is None\n\n time.sleep(2)\n\n r = wrapper.result\n assert r == 'Hello'\n\n", "As mentioned multiprocessing pool is much slower than basic threading. Using queues as proposeded in some answers here is a very effective alternative. I have use it with dictionaries in order to be able run a lot of small threads and recuperate multiple answers by combining them with dictionaries:\n#!/usr/bin/env python3\n\nimport threading\n# use Queue for python2\nimport queue\nimport random\n\nLETTERS = 'abcdefghijklmnopqrstuvwxyz'\nLETTERS = [ x for x in LETTERS ]\n\nNUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ndef randoms(k, q):\n result = dict()\n result['letter'] = random.choice(LETTERS)\n result['number'] = random.choice(NUMBERS)\n q.put({k: result})\n\nthreads = list()\nq = queue.Queue()\nresults = dict()\n\nfor name in ('alpha', 'oscar', 'yankee',):\n threads.append( threading.Thread(target=randoms, args=(name, q)) )\n threads[-1].start()\n_ = [ t.join() for t in threads ]\nwhile not q.empty():\n results.update(q.get())\n\nprint(results)\n\n", "Here is the version that I created of @Kindall's answer.\nThis version makes it so that all you have to do is input your command with arguments to create the new thread.\nThis was made with Python 3.8:\nfrom threading import Thread\nfrom typing import Any\n\ndef test(plug, plug2, plug3):\n print(f\"hello {plug}\")\n print(f'I am the second plug : {plug2}')\n print(plug3)\n return 'I am the return Value!'\n\ndef test2(msg):\n return f'I am from the second test: {msg}'\n\ndef test3():\n print('hello world')\n\ndef NewThread(com, Returning: bool, *arguments) -> Any:\n \"\"\"\n Will create a new thread for a function/command.\n\n :param com: Command to be Executed\n :param arguments: Arguments to be sent to Command\n :param Returning: True/False Will this command need to return anything\n \"\"\"\n class NewThreadWorker(Thread):\n def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *,\n daemon = None):\n Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon)\n \n self._return = None\n \n def run(self):\n if self._target is not None:\n self._return = self._target(*self._args, **self._kwargs)\n \n def join(self):\n Thread.join(self)\n return self._return\n \n ntw = NewThreadWorker(target = com, args = (*arguments,))\n ntw.start()\n if Returning:\n return ntw.join()\n\nif __name__ == \"__main__\":\n print(NewThread(test, True, 'hi', 'test', test2('hi')))\n NewThread(test3, True)\n\n", "One usual solution is to wrap your function foo with a decorator like\nresult = queue.Queue()\n\ndef task_wrapper(*args):\n result.put(target(*args))\n\nThen the whole code may looks like that\nresult = queue.Queue()\n\ndef task_wrapper(*args):\n result.put(target(*args))\n\nthreads = [threading.Thread(target=task_wrapper, args=args) for args in args_list]\n\nfor t in threads:\n t.start()\n while(True):\n if(len(threading.enumerate()) < max_num):\n break\nfor t in threads:\n t.join()\nreturn result\n\nNote\nOne important issue is that the return values may be unorderred.\n(In fact, the return value is not necessarily saved to the queue, since you can choose arbitrary thread-safe data structure )\n", "Kindall's answer in Python3\nclass ThreadWithReturnValue(Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs={}, *, daemon=None):\n Thread.__init__(self, group, target, name, args, kwargs, daemon)\n self._return = None \n\n def run(self):\n try:\n if self._target:\n self._return = self._target(*self._args, **self._kwargs)\n finally:\n del self._target, self._args, self._kwargs \n\n def join(self,timeout=None):\n Thread.join(self,timeout)\n return self._return\n\n", "You can use pool.apply_async() of ThreadPool() to return the value from test() as shown below:\nfrom multiprocessing.pool import ThreadPool\n\ndef test(num1, num2):\n return num1 + num2\n\npool = ThreadPool(processes=1) # Here\nresult = pool.apply_async(test, (2, 3)) # Here\nprint(result.get()) # 5\n\nAnd, you can also use submit() of concurrent.futures.ThreadPoolExecutor() to return the value from test() as shown below:\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef test(num1, num2):\n return num1 + num2\n\nwith ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(test, 2, 3) # Here\nprint(future.result()) # 5\n\nAnd, instead of return, you can use the array result as shown below:\nfrom threading import Thread\n\ndef test(num1, num2, r):\n r[0] = num1 + num2 # Instead of \"return\"\n\nresult = [None] # Here\n\nthread = Thread(target=test, args=(2, 3, result))\nthread.start()\nthread.join()\nprint(result[0]) # 5\n\nAnd instead of return, you can also use the queue result as shown below:\nfrom threading import Thread\nimport queue\n\ndef test(num1, num2, q):\n q.put(num1 + num2) # Instead of \"return\" \n\nqueue = queue.Queue() # Here\n\nthread = Thread(target=test, args=(2, 3, queue))\nthread.start()\nthread.join()\nprint(queue.get()) # '5'\n\n", "The shortest and simplest way I've found to do this is to take advantage of Python classes and their dynamic properties. You can retrieve the current thread from within the context of your spawned thread using threading.current_thread(), and assign the return value to a property.\nimport threading\n\ndef some_target_function():\n # Your code here.\n threading.current_thread().return_value = \"Some return value.\"\n\nyour_thread = threading.Thread(target=some_target_function)\nyour_thread.start()\nyour_thread.join()\n\nreturn_value = your_thread.return_value\nprint(return_value)\n\n" ]
[ 409, 334, 260, 107, 92, 47, 34, 29, 26, 8, 7, 6, 6, 5, 4, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[ "I know this thread is old.... but I faced the same problem... If you are willing to use thread.join()\nimport threading\n\nclass test:\n\n def __init__(self):\n self.msg=\"\"\n\n def hello(self,bar):\n print('hello {}'.format(bar))\n self.msg=\"foo\"\n\n\n def main(self):\n thread = threading.Thread(target=self.hello, args=('world!',))\n thread.start()\n thread.join()\n print(self.msg)\n\ng=test()\ng.main()\n\n", "Best way... Define a global variable, then change the variable in the threaded function. Nothing to pass in or retrieve back\nfrom threading import Thread\n\n# global var\nradom_global_var = 5\n\ndef function():\n global random_global_var\n random_global_var += 1\n\ndomath = Thread(target=function)\ndomath.start()\ndomath.join()\nprint(random_global_var)\n\n# result: 6\n\n" ]
[ -2, -3 ]
[ "multithreading", "python", "return_value" ]
stackoverflow_0006893968_multithreading_python_return_value.txt
Q: Python strftime days without ZERO Why doesn't the codes from this page work?: http://strftime.org/. I want to output date and months without leading zeroes, like 'm/d/yyyy' e.g.: '4/5/1992' YES '04/05/1992' NO from datetime import datetime, timedelta, date yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y') print(yest) ValueError Traceback (most recent call last) <ipython-input-35-7c70a0a7eee5> in <module> 1 from datetime import datetime, timedelta, date ----> 2 yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y') 3 print(yest) ValueError: Invalid format string A: That %-m option does state that the format is platform specific, so mileage may vary. You can simply use f-strings in Python 3. yest = datetime.now() - timedelta(21) yest = f'{yest.month}/{yest.day}/{yest.year}' >>> yest '10/9/2019' In the case of your dataframe explained in the comments: df = pd.DataFrame({ 'fecha_vencimiento': [ '12/25/2009', '01/05/2010', '04/13/2011', '']}) df['fecha_vencimiento'] = pd.to_datetime( df['fecha_vencimiento'], format='%m/%d/%Y', errors='coerce').apply( lambda x: f'{x.month}/{x.day}/{x.year}' if pd.notnull(x) else '') A: The %-d would give you the day without the leading 0 and %-m the month, but this format only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %#d, %#m.
Python strftime days without ZERO
Why doesn't the codes from this page work?: http://strftime.org/. I want to output date and months without leading zeroes, like 'm/d/yyyy' e.g.: '4/5/1992' YES '04/05/1992' NO from datetime import datetime, timedelta, date yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y') print(yest) ValueError Traceback (most recent call last) <ipython-input-35-7c70a0a7eee5> in <module> 1 from datetime import datetime, timedelta, date ----> 2 yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y') 3 print(yest) ValueError: Invalid format string
[ "That %-m option does state that the format is platform specific, so mileage may vary.\nYou can simply use f-strings in Python 3.\nyest = datetime.now() - timedelta(21)\nyest = f'{yest.month}/{yest.day}/{yest.year}'\n>>> yest\n'10/9/2019'\n\nIn the case of your dataframe explained in the comments:\ndf = pd.DataFrame({\n 'fecha_vencimiento': [\n '12/25/2009', '01/05/2010', '04/13/2011', '']})\n\ndf['fecha_vencimiento'] = pd.to_datetime(\n df['fecha_vencimiento'], format='%m/%d/%Y', errors='coerce').apply(\n lambda x: f'{x.month}/{x.day}/{x.year}' \n if pd.notnull(x) else '')\n\n", "The %-d would give you the day without the leading 0 and %-m the month, but this format only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %#d, %#m.\n" ]
[ 2, 1 ]
[]
[]
[ "date", "python", "string" ]
stackoverflow_0058634685_date_python_string.txt
Q: How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON? I need to convert the ‘content’ column from a string dictionary to a dictionary in python. After that I will use the following line of code: df[‘content’].apply(pd.Series). To have the dictionary values as a column name and the dictionary value in a cell. I can’t do this now because there are missing values in the dictionary string. How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary? [I'm working on the 'content' column that I want to convert to the correct format first, I tried with the eval() function, but it doesn't work, because there are missing values. This is json data. My goal is to have the content column data for the keys in the column titles and the values in the cells](https://i.stack.imgur.com/1CsIl.png) A: you can use json.loads in lambda function. if row value is nan, pass, if not, apply json.loads: : import json import numpy as np df['content']=df['content'].apply(lambda x: json.loads(x) if pd.notna(x) else np.nan) now you can use pd.Series. v1 = df['Content'].apply(pd.Series) df = df.drop(['Content'],axis=1).join(v1) if you have missing values in string dictionaries: def check_json(x): import ast import json if pd.isna(x): return np.nan else: try: return json.loads(x) except: try: mask=x.replace('{','').replace('}','') #missing dictionary mask=mask.split(",") for i in range(0,len(mask)): if not len(mask[i].partition(":")[-1]) > 0: print(mask[i]) mask[i]=mask[i] + '"None"' # ---> you can replace None with what do you want return json.loads(str({','.join(mask)}).replace("\'", "")) except: try: x=x.replace("\'", "\"") mask=x.replace('{','').replace('}',"") #missing dictionary mask=mask.split(",") for i in range(0,len(mask)): if not len(mask[i].partition(":")[-1]) > 0: print(mask[i]) mask[i]=mask[i] + '"None"' # ---> you can replace None with what do you want b=str({','.join(mask)}).replace("\'", "") return ast.literal_eval(b) except: print("Could not parse json object. Returning nan") return np.nan df['content']=df['content'].apply(lambda x: check_json(x)) v1 = df['Content'].apply(pd.Series) df = df.drop(['Content'],axis=1).join(v1)
How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON?
I need to convert the ‘content’ column from a string dictionary to a dictionary in python. After that I will use the following line of code: df[‘content’].apply(pd.Series). To have the dictionary values as a column name and the dictionary value in a cell. I can’t do this now because there are missing values in the dictionary string. How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary? [I'm working on the 'content' column that I want to convert to the correct format first, I tried with the eval() function, but it doesn't work, because there are missing values. This is json data. My goal is to have the content column data for the keys in the column titles and the values in the cells](https://i.stack.imgur.com/1CsIl.png)
[ "you can use json.loads in lambda function. if row value is nan, pass, if not, apply json.loads:\n:\nimport json\nimport numpy as np\ndf['content']=df['content'].apply(lambda x: json.loads(x) if pd.notna(x) else np.nan)\n\n\nnow you can use pd.Series.\nv1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n\nif you have missing values in string dictionaries:\ndef check_json(x):\n import ast\n import json\n if pd.isna(x):\n return np.nan\n else:\n try:\n return json.loads(x)\n except:\n try:\n mask=x.replace('{','').replace('}','') #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n return json.loads(str({','.join(mask)}).replace(\"\\'\", \"\"))\n except:\n try:\n x=x.replace(\"\\'\", \"\\\"\")\n mask=x.replace('{','').replace('}',\"\") #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n b=str({','.join(mask)}).replace(\"\\'\", \"\")\n return ast.literal_eval(b)\n except:\n print(\"Could not parse json object. Returning nan\")\n return np.nan\n\ndf['content']=df['content'].apply(lambda x: check_json(x))\n\nv1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n\n" ]
[ 0 ]
[ "I cannot see what the missing values look like in your screenshot, but i tested the following code and got what seems to be a good result. The simple explanation in to use str.replace() to fix the null values before parsing the string to dict.\nimport pandas as pd\nimport numpy as np\nimport json\n\n## setting up an example dataframe. note that row2 has a null value\njson_example = [\n '{\"row1_key1\":\"row1_value1\",\"row1_key2\":\"row1_value2\"}',\n '{\"row2_key1\":\"row2_value1\",\"row2_key2\": null}'\n ]\n\ndf= pd.DataFrame()\n\ndf['Content'] = json_example\n\n## using string replace on the string representation of the json to clean it up\n\ndf['Content'].apply(lambda x: x.replace('null','\"0\"'))\n\n## using lambda x to first load the string into a dict, then applying pd.Series()\n\ndf['Content'].apply(lambda x: pd.Series(json.loads(x)))\n\nOutput\n" ]
[ -1 ]
[ "dictionary", "eval", "json", "pandas", "python" ]
stackoverflow_0074559959_dictionary_eval_json_pandas_python.txt
Q: Adjusting Values in one dataframe using balance from another dataframe in Python I have two tables: Table A Employee ID Date Data Used 1 01-01-2020 2 1 02-01-2020 5 1 03-01-2020 6 1 04-01-2020 4 2 05-01-2020 1 2 06-01-2020 2 2 07-01-2020 2 Table B Employee ID Date Data Balance 1 01-01-2020 6 1 02-01-2020 9 1 03-01-2020 5 1 04-01-2020 3 2 05-01-2020 7 2 06-01-2020 8 2 07-01-2020 1 What I am trying to do is that Table A checks in Table B how much data balance is available for an employee on a particular Date in Table A. Then create a new column in Table A say, "Adjusted" wherever enough balance is available in Table B for the adjustment, then update the column "Data Used" to 0 and update the balance in Table B so that remaining balance is available for next row in Table A. Working Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes Employee ID Date Data Balance New Balance 1 01-01-2020 6 4 1 02-01-2020 9 8 1 03-01-2020 5 7 1 04-01-2020 3 6 1 07-01-2020 7 14 1 06-01-2020 8 1 07-01-2020 1 Final Output Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes Thanks in advance :) Final Output Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes A: You essentially want to index the dataframes using two columns. df = df.set_index(["Employee ID","Date"]) on both dataframes should achieve this. You can now loop through one dataframe and match their indices. To take it further, you can join both dataframes with new_df = df1.join(df2,on=["Employee ID","Date"]) and now you have one dataframe to work with.
Adjusting Values in one dataframe using balance from another dataframe in Python
I have two tables: Table A Employee ID Date Data Used 1 01-01-2020 2 1 02-01-2020 5 1 03-01-2020 6 1 04-01-2020 4 2 05-01-2020 1 2 06-01-2020 2 2 07-01-2020 2 Table B Employee ID Date Data Balance 1 01-01-2020 6 1 02-01-2020 9 1 03-01-2020 5 1 04-01-2020 3 2 05-01-2020 7 2 06-01-2020 8 2 07-01-2020 1 What I am trying to do is that Table A checks in Table B how much data balance is available for an employee on a particular Date in Table A. Then create a new column in Table A say, "Adjusted" wherever enough balance is available in Table B for the adjustment, then update the column "Data Used" to 0 and update the balance in Table B so that remaining balance is available for next row in Table A. Working Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes Employee ID Date Data Balance New Balance 1 01-01-2020 6 4 1 02-01-2020 9 8 1 03-01-2020 5 7 1 04-01-2020 3 6 1 07-01-2020 7 14 1 06-01-2020 8 1 07-01-2020 1 Final Output Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes Thanks in advance :) Final Output Employee ID Date Data Used Adjusted 1 01-01-2020 0 yes 1 02-01-2020 0 yes 1 03-01-2020 0 yes 1 04-01-2020 0 yes 2 05-01-2020 1 no 2 06-01-2020 2 no 2 07-01-2020 2 yes
[ "You essentially want to index the dataframes using two columns.\ndf = df.set_index([\"Employee ID\",\"Date\"]) on both dataframes should achieve this. You can now loop through one dataframe and match their indices.\nTo take it further, you can join both dataframes with new_df = df1.join(df2,on=[\"Employee ID\",\"Date\"]) and now you have one dataframe to work with.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074560258_python.txt
Q: Using pandas how can i find a string from every row in a excel A in another excel B(from all columns) and if it matches, return column from B I have two excel. Excel A and Excel B. Excel A has 2 columns. Excel B has 5 columns I want to find value each from Column2 in A in All 5 columns of Excel B(it may not be exact match, its just may just contain that vaule) Example Excel A Column A1 Column A2 405 121h 496 156b 456 325v ExcelB Column B1 Column B2 Column B3 Column B4 Column B5 121h*12 Cell 2 Cell1 abc def Cell 3 156b456 Cell2 efg ijk Expecting Output Column A1 Column A2 ColumnB4 405 121h abc 496 156b efg 456 325v A: Assuming ExcelA and ExcelB are DataFrames. You can melt and use str.extract with a pattern made from ExcelA to use as a key for the merge: import re to_merge = ['Column B4'] # use here all columns to merge tmp = ExcelB.melt(to_merge) pattern = '|'.join(map(re.escape, ExcelA['Column A2'])) # '121h|156b|325v' out = ExcelA.merge(tmp[to_merge], how='left', left_on='Column A2', right_on=tmp['value'].str.extract(f'({pattern})', expand=False)) Output: Column A1 Column A2 Column B4 0 405 121h abc 1 496 156b efg 2 456 325v NaN
Using pandas how can i find a string from every row in a excel A in another excel B(from all columns) and if it matches, return column from B
I have two excel. Excel A and Excel B. Excel A has 2 columns. Excel B has 5 columns I want to find value each from Column2 in A in All 5 columns of Excel B(it may not be exact match, its just may just contain that vaule) Example Excel A Column A1 Column A2 405 121h 496 156b 456 325v ExcelB Column B1 Column B2 Column B3 Column B4 Column B5 121h*12 Cell 2 Cell1 abc def Cell 3 156b456 Cell2 efg ijk Expecting Output Column A1 Column A2 ColumnB4 405 121h abc 496 156b efg 456 325v
[ "Assuming ExcelA and ExcelB are DataFrames.\nYou can melt and use str.extract with a pattern made from ExcelA to use as a key for the merge:\nimport re\n\nto_merge = ['Column B4'] # use here all columns to merge\n\ntmp = ExcelB.melt(to_merge)\npattern = '|'.join(map(re.escape, ExcelA['Column A2']))\n# '121h|156b|325v'\n\nout = ExcelA.merge(tmp[to_merge], how='left', left_on='Column A2',\n right_on=tmp['value'].str.extract(f'({pattern})',\n expand=False))\n\nOutput:\n Column A1 Column A2 Column B4\n0 405 121h abc\n1 496 156b efg\n2 456 325v NaN\n\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074559194_pandas_python.txt
Q: python calculator indentation error (cant seem to get the program working) I just started python yesterday so I was trying to make this python code to make a calculator that adds, multiplies, divides, and subtracts. When I started testing the code just wasn't working even though I did similar things and to me, the code looked right this is the code: op =input("which operation would you like to use (type m for multiply d for divide s for subtract a for addition): ") first_number =float(input("please enter your first number: ")) second_number =float(input("please enter your second number: ")) if op.upper()=="m" or op.lower()=="m": print("multiply") elif op.upper()=="d" or op.lower()=="d": print("divide") elif op.upper()=="s" or op.lower()=="s": print("subtract") elif op.upper()=="a" or op.lower()=="a": print("addition") else:print("the operation you entered is not available") I was expecting it to take input and based on this it would know what operation I wanted to make but this is the error I got: elif op.upper()=="d" or op.lower()=="d": ^ IndentationError: unindent does not match any outer indentation level A: This should resolve the indentation error. op =input("which operation would you like to use (type m for multiply d for divide s for subtract a for addition): ") first_number =float(input("please enter your first number: ")) second_number =float(input("please enter your second number: ")) if op.upper()=="m" or op.lower()=="m": print("multiply") elif op.upper()=="d" or op.lower()=="d": print("divide") elif op.upper()=="s" or op.lower()=="s": print("subtract") elif op.upper()=="a" or op.lower()=="a": print("addition") else: print("the operation you entered is not available")
python calculator indentation error (cant seem to get the program working)
I just started python yesterday so I was trying to make this python code to make a calculator that adds, multiplies, divides, and subtracts. When I started testing the code just wasn't working even though I did similar things and to me, the code looked right this is the code: op =input("which operation would you like to use (type m for multiply d for divide s for subtract a for addition): ") first_number =float(input("please enter your first number: ")) second_number =float(input("please enter your second number: ")) if op.upper()=="m" or op.lower()=="m": print("multiply") elif op.upper()=="d" or op.lower()=="d": print("divide") elif op.upper()=="s" or op.lower()=="s": print("subtract") elif op.upper()=="a" or op.lower()=="a": print("addition") else:print("the operation you entered is not available") I was expecting it to take input and based on this it would know what operation I wanted to make but this is the error I got: elif op.upper()=="d" or op.lower()=="d": ^ IndentationError: unindent does not match any outer indentation level
[ "This should resolve the indentation error.\nop =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n\n" ]
[ 0 ]
[ "It should look like this:\nop =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower()==\"m\":\n print(\"multiply\")\nelif op.upper()==\"d\" or op.lower()==\"d\":\n print(\"divide\")\nelif op.upper()==\"s\" or op.lower()==\"s\":\n print(\"subtract\")\nelif op.upper()==\"a\" or op.lower()==\"a\":\n print(\"addition\")\nelse:\n print(\"the operation you entered is not available\")\n\n" ]
[ -1 ]
[ "calculator", "indentation", "python" ]
stackoverflow_0074560435_calculator_indentation_python.txt
Q: accessing python dict values with line-breaking (PEP-8) I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode) example: class GoFirstSpider(): def __init__(self, flight_search_request): self.name = 'goFirst' -> self.date = flight_search_request["FlightSearchRequest"]["FlightDetails"]["DepartureDate"] I've tried: self.date = flight_search_request["FlightSearchRequest"]\ ["FlightDetails"]["DepartureDate"] and got: whitespace before '[' Thanks. A: You can use \ to break lines. class GoFirstSpider(): def __init__(self, flight_search_request): self.name = 'goFirst' self.date = flight_search_request["FlightSearchRequest"] \ ["FlightDetails"]["DepartureDate"] A: You can use \ to break multiple lines as stated in the PEP 8 style guide: The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Backslashes may still be appropriate at times. For example, long, multiple with-statements could not use implicit continuation before Python 3.10, so backslashes were acceptable for that case In your case: class GoFirstSpider(): def __init__(self, flight_search_request): self.name = 'goFirst' self.date = flight_search_request["FlightSearchRequest"] \ ["FlightDetails"]["DepartureDate"]
accessing python dict values with line-breaking (PEP-8)
I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode) example: class GoFirstSpider(): def __init__(self, flight_search_request): self.name = 'goFirst' -> self.date = flight_search_request["FlightSearchRequest"]["FlightDetails"]["DepartureDate"] I've tried: self.date = flight_search_request["FlightSearchRequest"]\ ["FlightDetails"]["DepartureDate"] and got: whitespace before '[' Thanks.
[ "You can use \\ to break lines.\nclass GoFirstSpider():\n def __init__(self, flight_search_request):\n self.name = 'goFirst'\n self.date = flight_search_request[\"FlightSearchRequest\"] \\\n [\"FlightDetails\"][\"DepartureDate\"]\n\n", "You can use \\ to break multiple lines as stated in the PEP 8 style guide:\n\nThe preferred way of wrapping long lines is by using Python’s implied\nline continuation inside parentheses, brackets and braces. Long lines\ncan be broken over multiple lines by wrapping expressions in\nparentheses. These should be used in preference to using a backslash\nfor line continuation.\nBackslashes may still be appropriate at times. For example, long,\nmultiple with-statements could not use implicit continuation before\nPython 3.10, so backslashes were acceptable for that case\n\nIn your case:\nclass GoFirstSpider():\n def __init__(self, flight_search_request):\n self.name = 'goFirst'\n self.date = flight_search_request[\"FlightSearchRequest\"] \\\n [\"FlightDetails\"][\"DepartureDate\"]\n\n" ]
[ 0, 0 ]
[]
[]
[ "flake8", "pep8", "python" ]
stackoverflow_0074560371_flake8_pep8_python.txt
Q: How do I update the current animated line graph every time I draw a new one? I've been new to python, and recently I am trying with the FuncAnimation recently. I was trying to make a graph that shows the diffusion graphs for every different p and q values, so each time it's supposed to mutate on the current line graph with different p and q as parameters for a fixed amount of t. I've been trying to animate this so that the change with respect to p and q changes on the graph can be seen. import matplotlib.animation as ani import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib.animation as ani import math from IPython import display def eq(p,q,t): return (1-pow(math.e,-(p+q)*t))/(1+q/p*pow(math.e,-(p+q)*t)) def diffusion(p,q,t): d=[] for i in range(len(t)): d.append(eq(p,q,t[i])) return np.array(d) t=np.linspace(0,20,200) pq=[] for i in np.linspace(1,0,20,endpoint=False)[::-11]: for j in np.linspace(1,0,20,endpoint=False)[::-11]: pq.append((i,j)) titles = ["Base Diffusion graph (p={}, q={})".format(round(frame[0],2),round(frame[1],2)) for frame in pq] #print(titles) fig = plt.figure() plt.xlabel("t") plt.ylabel("F(t)") def buildmechart(i=int): plt.title(titles[i]) p = plt.plot(t,diffusion(pq[i][0],pq[i][1],t)) #note it only returns return p, animator=ani.FuncAnimation(fig,buildmechart,frames=range(len(pq)),interval=100,repeat=False) animator.save(r'animation.gif') However, when I run the code above there isn't any animated graph saved, instead on jupyter it only shows a static graph of multiple lines on it. This isn't what I intended; I wanted to change on the current line instead of drawing a new line for each p, q values. So how should I change this code? Secondly, when I tried to add blit into the FuncAnimation as a parameter, it doesn't seem to allow me add that due to a error RuntimeError: The animation function must return a sequence of Artist objects. So what should I do? A: The problem is that func argument should be a callable that updates the plot. Currently you plot a new line in your update function. There are some simple examples with good explanation on this page showing how to use the animation feature. Below I slightly modify a few lines of your code to get your desired output. import matplotlib.animation as ani import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib.animation as ani import math def eq(p,q,t): return (1-pow(math.e,-(p+q)*t))/(1+q/p*pow(math.e,-(p+q)*t)) def diffusion(p,q,t): d=[] for i in range(len(t)): d.append(eq(p,q,t[i])) return np.array(d) t=np.linspace(0,20,200) pq=[] for i in np.linspace(1,0,20,endpoint=False)[::-11]: for j in np.linspace(1,0,20,endpoint=False)[::-11]: pq.append((i,j)) titles = ["Base Diffusion graph (p={}, q={})".format(round(frame[0],2),round(frame[1],2)) for frame in pq] #print(titles) fig = plt.figure() plt.xlabel("t") plt.ylabel("F(t)") p, = plt.plot(t,diffusion(pq[0][0],pq[0][1],t)) # Create the line plt.ylim(-0.05, 1.05) # Making sure the plot fits def buildmechart(i=int): plt.title(titles[i]) p.set_data(t,diffusion(pq[i][0],pq[i][1],t)) # Update the line return p, animator=ani.FuncAnimation(fig,buildmechart,frames=range(len(pq)),interval=100,repeat=False) animator.save(r'animation.gif') plt.show()
How do I update the current animated line graph every time I draw a new one?
I've been new to python, and recently I am trying with the FuncAnimation recently. I was trying to make a graph that shows the diffusion graphs for every different p and q values, so each time it's supposed to mutate on the current line graph with different p and q as parameters for a fixed amount of t. I've been trying to animate this so that the change with respect to p and q changes on the graph can be seen. import matplotlib.animation as ani import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib.animation as ani import math from IPython import display def eq(p,q,t): return (1-pow(math.e,-(p+q)*t))/(1+q/p*pow(math.e,-(p+q)*t)) def diffusion(p,q,t): d=[] for i in range(len(t)): d.append(eq(p,q,t[i])) return np.array(d) t=np.linspace(0,20,200) pq=[] for i in np.linspace(1,0,20,endpoint=False)[::-11]: for j in np.linspace(1,0,20,endpoint=False)[::-11]: pq.append((i,j)) titles = ["Base Diffusion graph (p={}, q={})".format(round(frame[0],2),round(frame[1],2)) for frame in pq] #print(titles) fig = plt.figure() plt.xlabel("t") plt.ylabel("F(t)") def buildmechart(i=int): plt.title(titles[i]) p = plt.plot(t,diffusion(pq[i][0],pq[i][1],t)) #note it only returns return p, animator=ani.FuncAnimation(fig,buildmechart,frames=range(len(pq)),interval=100,repeat=False) animator.save(r'animation.gif') However, when I run the code above there isn't any animated graph saved, instead on jupyter it only shows a static graph of multiple lines on it. This isn't what I intended; I wanted to change on the current line instead of drawing a new line for each p, q values. So how should I change this code? Secondly, when I tried to add blit into the FuncAnimation as a parameter, it doesn't seem to allow me add that due to a error RuntimeError: The animation function must return a sequence of Artist objects. So what should I do?
[ "The problem is that func argument should be a callable that updates the plot. Currently you plot a new line in your update function. There are some simple examples with good explanation on this page showing how to use the animation feature. Below I slightly modify a few lines of your code to get your desired output.\nimport matplotlib.animation as ani\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport matplotlib.animation as ani\nimport math\n\ndef eq(p,q,t):\n return (1-pow(math.e,-(p+q)*t))/(1+q/p*pow(math.e,-(p+q)*t))\ndef diffusion(p,q,t):\n d=[]\n for i in range(len(t)):\n d.append(eq(p,q,t[i]))\n return np.array(d)\n\nt=np.linspace(0,20,200)\n\npq=[]\nfor i in np.linspace(1,0,20,endpoint=False)[::-11]:\n for j in np.linspace(1,0,20,endpoint=False)[::-11]:\n pq.append((i,j))\n\ntitles = [\"Base Diffusion graph (p={}, q={})\".format(round(frame[0],2),round(frame[1],2)) for frame in pq]\n#print(titles)\n\nfig = plt.figure()\nplt.xlabel(\"t\")\nplt.ylabel(\"F(t)\")\np, = plt.plot(t,diffusion(pq[0][0],pq[0][1],t)) # Create the line\nplt.ylim(-0.05, 1.05) # Making sure the plot fits\n\ndef buildmechart(i=int):\n plt.title(titles[i])\n p.set_data(t,diffusion(pq[i][0],pq[i][1],t)) # Update the line\n return p,\n\nanimator=ani.FuncAnimation(fig,buildmechart,frames=range(len(pq)),interval=100,repeat=False)\nanimator.save(r'animation.gif')\nplt.show()\n\n" ]
[ 0 ]
[]
[]
[ "animation", "graph", "matplotlib", "python" ]
stackoverflow_0074557632_animation_graph_matplotlib_python.txt
Q: How to get a tree of all xpaths in a website using Python? Approach I While trying to get a hierarchical tree of all the xpaths in a website (https://startpagina.nl) using Python, I first tried to get the xpath for the branch: /html/body using: from selenium import webdriver url = 'https://startpagina.nl' driver = webdriver.Firefox() driver.get(url) test = driver.find_elements_by_xpath('//*') print(len(test)) driver.close() and that yields a list of all elements in the website, according to the answer by @Prophet. However, I did not yet determine how to get the xpaths of these elements, nor how to sort them into a tree-like structure. And the /html/body/div[6] option yields a length of 1 instead of a tree. Approach II Based on the answer by @Micheal Kay, I tried to "Walk the xml" using the following Python code: import requests from bs4 import BeautifulSoup import xml.etree.cElementTree as ET from lxml import etree unformatted_filename = "first.xml" formatted_filename = "first.xml" # Get XML from url. resp = requests.get("https://startpagina.nl") # resp = requests.get('https://stackoverflow.com') with open(unformatted_filename, "wb") as foutput: foutput.write(resp.content) # Improve XML formatting with open(unformatted_filename) as fp: soup = BeautifulSoup(fp, "xml") print(f"soup={soup}") with open(formatted_filename, "w") as f: f.write(soup.prettify()) # Parse XML tree = ET.parse(formatted_filename, parser=ET.XMLParser(encoding="utf-8")) root = tree.getroot() for child in root: child.tag, child.attrib tree = ET.parse(formatted_filename) for elem in tree.getiterator(): if elem.tag: print("my name:") print("\t" + elem.tag) if elem.text: print("my text:") print("\t" + (elem.text).strip()) if elem.attrib.items(): print("my attributes:") for key, value in elem.attrib.items(): print("\t" + "\t" + key + " : " + value) if list(elem): # use elem.getchildren() for python2.6 or before print("my no of child: %d" % len(list(elem))) else: print("No child") if elem.tail: print("my tail:") print("\t" + "%s" % elem.tail.strip()) print("$$$$$$$$$$") However, I did not yet determine how to get the xpaths of the respective elements. Question Hence, I would like to ask: How does one get a tree of all the xpaths in website, using Python? (And I wondered whether this tree will be cyclic or not, though I expect I will find out once I know how to get the Tree.). Expected Output Based on manually going through the HTML: I would expect the output to look something like this: | /html |-- //*[@id="browser-upgrade-notification"] |-- //*[@id="app"] |-- /html/head |-- /html/body |--/-- /html/body/noscript |--/-- /html/body/div[2] |--/-- /html/body/header/section |--/--/-- /html/body/header/section/div |--/--/--/-- /html/body/header/section/div/div[1] .... This would be an example of the list of tree. A: The total number of XPaths that select one or more elements is infinite (for example it will include paths like /a/b/../b/../b/../b), but if you restrict yourself to paths of the form /a[i]/b[j]/c[k] then the number of paths is equal to the number of elements, and the "tree" of XPaths is isomorphic with the original XML tree. If you want the distinct paths without a numerical predicate, for example /a/b/c, /a/b/d, then the simplest approach is probably to walk the XML document, get the path for each element (in this form) and eliminate duplicates. If rather than a flat list of paths you want a tree structure, then build it up as you go using nested maps/dictionaries. The reason it complains about /html/body/ is that a legal XPath expression cannot contain a trailing /. A: /html/body/ is not a valid XPath, /html/body can be used instead. /html/body/div[6] is matching a single element on that page while /html/body/div[6]/* matches 3 elements. //* will return you all the elements on the page. Anyway, driver.find_elements_by_xpath returns a list of web elements matching the passed XPath locator. This will not give you XPaths of the nodes on the page. This method receives XPath as a parameter and returns a list of web elements.
How to get a tree of all xpaths in a website using Python?
Approach I While trying to get a hierarchical tree of all the xpaths in a website (https://startpagina.nl) using Python, I first tried to get the xpath for the branch: /html/body using: from selenium import webdriver url = 'https://startpagina.nl' driver = webdriver.Firefox() driver.get(url) test = driver.find_elements_by_xpath('//*') print(len(test)) driver.close() and that yields a list of all elements in the website, according to the answer by @Prophet. However, I did not yet determine how to get the xpaths of these elements, nor how to sort them into a tree-like structure. And the /html/body/div[6] option yields a length of 1 instead of a tree. Approach II Based on the answer by @Micheal Kay, I tried to "Walk the xml" using the following Python code: import requests from bs4 import BeautifulSoup import xml.etree.cElementTree as ET from lxml import etree unformatted_filename = "first.xml" formatted_filename = "first.xml" # Get XML from url. resp = requests.get("https://startpagina.nl") # resp = requests.get('https://stackoverflow.com') with open(unformatted_filename, "wb") as foutput: foutput.write(resp.content) # Improve XML formatting with open(unformatted_filename) as fp: soup = BeautifulSoup(fp, "xml") print(f"soup={soup}") with open(formatted_filename, "w") as f: f.write(soup.prettify()) # Parse XML tree = ET.parse(formatted_filename, parser=ET.XMLParser(encoding="utf-8")) root = tree.getroot() for child in root: child.tag, child.attrib tree = ET.parse(formatted_filename) for elem in tree.getiterator(): if elem.tag: print("my name:") print("\t" + elem.tag) if elem.text: print("my text:") print("\t" + (elem.text).strip()) if elem.attrib.items(): print("my attributes:") for key, value in elem.attrib.items(): print("\t" + "\t" + key + " : " + value) if list(elem): # use elem.getchildren() for python2.6 or before print("my no of child: %d" % len(list(elem))) else: print("No child") if elem.tail: print("my tail:") print("\t" + "%s" % elem.tail.strip()) print("$$$$$$$$$$") However, I did not yet determine how to get the xpaths of the respective elements. Question Hence, I would like to ask: How does one get a tree of all the xpaths in website, using Python? (And I wondered whether this tree will be cyclic or not, though I expect I will find out once I know how to get the Tree.). Expected Output Based on manually going through the HTML: I would expect the output to look something like this: | /html |-- //*[@id="browser-upgrade-notification"] |-- //*[@id="app"] |-- /html/head |-- /html/body |--/-- /html/body/noscript |--/-- /html/body/div[2] |--/-- /html/body/header/section |--/--/-- /html/body/header/section/div |--/--/--/-- /html/body/header/section/div/div[1] .... This would be an example of the list of tree.
[ "The total number of XPaths that select one or more elements is infinite (for example it will include paths like /a/b/../b/../b/../b), but if you restrict yourself to paths of the form /a[i]/b[j]/c[k] then the number of paths is equal to the number of elements, and the \"tree\" of XPaths is isomorphic with the original XML tree.\nIf you want the distinct paths without a numerical predicate, for example /a/b/c, /a/b/d, then the simplest approach is probably to walk the XML document, get the path for each element (in this form) and eliminate duplicates. If rather than a flat list of paths you want a tree structure, then build it up as you go using nested maps/dictionaries.\nThe reason it complains about /html/body/ is that a legal XPath expression cannot contain a trailing /.\n", "\n/html/body/ is not a valid XPath, /html/body can be used instead.\n/html/body/div[6] is matching a single element on that page while /html/body/div[6]/* matches 3 elements.\n//* will return you all the elements on the page.\nAnyway, driver.find_elements_by_xpath returns a list of web elements matching the passed XPath locator. This will not give you XPaths of the nodes on the page.\nThis method receives XPath as a parameter and returns a list of web elements.\n\n" ]
[ 2, 1 ]
[]
[]
[ "html", "python", "selenium", "tree", "xpath" ]
stackoverflow_0074560320_html_python_selenium_tree_xpath.txt
Q: How to get function value outside the function in python? Code: import logging def main(name: str) -> str: return f"Hello {name}!" print({name}) I wanna get main function output store in variable and use in outside the function. I'm new in python, I cannot see exact same example on net, Check multiple ways but not getting value. There is no any value getting inside the print({name}) or print({main}). A: def main(name: str) -> str: return f"Hello {name}!" # You can use print(main("world")) # or var = main("world") print(var) # or Under the current file if __name__ == '__main__': var = main("world") print(var) A: import logging def main(name: str) -> str: return f"Hello {name}!" return_value = main("your name") To get a function's output you need to call it, and assign its return value to a variable. A: in order to call a function in python you must use its name no its arguments like below main(f'{name}') calls the function main with the f'{name}' as its argument. import logging name = 'world' def main(name: str) -> str: return f"Hello {name}!" print(main(f'{name}')) # If you just want to print it. val = main(f'{name}') # If you want to store the output as[Guf] said.
How to get function value outside the function in python?
Code: import logging def main(name: str) -> str: return f"Hello {name}!" print({name}) I wanna get main function output store in variable and use in outside the function. I'm new in python, I cannot see exact same example on net, Check multiple ways but not getting value. There is no any value getting inside the print({name}) or print({main}).
[ "def main(name: str) -> str:\n return f\"Hello {name}!\"\n\n# You can use\nprint(main(\"world\"))\n# or\nvar = main(\"world\")\nprint(var)\n# or Under the current file\nif __name__ == '__main__':\n var = main(\"world\")\n print(var)\n\n", "import logging\n\ndef main(name: str) -> str:\n return f\"Hello {name}!\"\n\nreturn_value = main(\"your name\")\n\nTo get a function's output you need to call it, and assign its return value to a variable.\n", "in order to call a function in python you must use its name no its arguments like below main(f'{name}') calls the function main with the f'{name}' as its argument.\nimport logging\nname = 'world'\ndef main(name: str) -> str:\n return f\"Hello {name}!\"\n\nprint(main(f'{name}')) # If you just want to print it.\n\nval = main(f'{name}') # If you want to store the output as[Guf] said.\n\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074560395_python.txt
Q: How to track the current user in flask-login? I m trying to use the current user in my view from flask-login. So i tried to g object I m assigning flask.ext.login.current_user to g object @pot.before_request def load_users(): g.user = current_user.username It works if the user is correct. But when i do sign-up or login as with wrong credentials I get this error AttributeError: 'AnonymousUserMixin' object has no attribute 'username' Please enlight me where am i wrong... A: Thanks for your answer @Joe and @pjnola, as you all suggested i referred flask-login docs I found that we can customize the anonymous user class, so i customized for my requirement, Anonymous class #!/usr/bin/python #flask-login anonymous user class from flask.ext.login import AnonymousUserMixin class Anonymous(AnonymousUserMixin): def __init__(self): self.username = 'Guest' Then added this class to anonymous_user login_manager.anonymous_user = Anonymous From this it was able to fetch the username if it was anonymous request. A: Well, the error message says it all. There is no logged in user, so current_user returns an AnonymousUserMixin. AnonymousUserMixin implements the interface described here: http://flask-login.readthedocs.org/en/latest/#your-user-class (which does not include a username property). Try something like this: @pot.before_request def load_users(): if current_user.is_authenticated(): g.user = current_user.get_id() # return username in get_id() else: g.user = None # or 'some fake value', whatever Obviously, the rest of your code has to deal with the possibility that g.user will not refer to a real user. A: AnonymousUserMixin has no username attribute. You need to overwrite the object and call the mixin. Have a look at LoginManager.anonymous_user which is an object which is used when no user is logged in. You also need to get the user from somewhere. There is no point in storing the username in g as you could just use current_user.username. If you wanted to get the username you would need too if current_user.is_authenticated(): g.user = current_user.username This would require that the user object has a property called username. There are lots of ways to customize Flask-Logins use I suggest re-reading the docs and taking a look at the source code: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py Joe A: For finding if there is a loggin session we can do the following: (I have gone through all solutions and noted that when I use the below statements it is failing.) if current_user.is_authenticated(): g.user = current_user.username The correct way is: if current_user.is_authenticated: g.user = current_user.username And then it works fine.
How to track the current user in flask-login?
I m trying to use the current user in my view from flask-login. So i tried to g object I m assigning flask.ext.login.current_user to g object @pot.before_request def load_users(): g.user = current_user.username It works if the user is correct. But when i do sign-up or login as with wrong credentials I get this error AttributeError: 'AnonymousUserMixin' object has no attribute 'username' Please enlight me where am i wrong...
[ "Thanks for your answer @Joe and @pjnola, as you all suggested i referred flask-login docs\nI found that we can customize the anonymous user class, so i customized for my requirement,\nAnonymous class\n#!/usr/bin/python\n#flask-login anonymous user class\nfrom flask.ext.login import AnonymousUserMixin\nclass Anonymous(AnonymousUserMixin):\n def __init__(self):\n self.username = 'Guest'\n\nThen added this class to anonymous_user\nlogin_manager.anonymous_user = Anonymous\nFrom this it was able to fetch the username if it was anonymous request.\n", "Well, the error message says it all. There is no logged in user, so current_user returns an AnonymousUserMixin. AnonymousUserMixin implements the interface described here: http://flask-login.readthedocs.org/en/latest/#your-user-class (which does not include a username property). Try something like this:\n@pot.before_request\ndef load_users():\n if current_user.is_authenticated():\n g.user = current_user.get_id() # return username in get_id()\n else:\n g.user = None # or 'some fake value', whatever\n\nObviously, the rest of your code has to deal with the possibility that g.user will not refer to a real user.\n", "AnonymousUserMixin has no username attribute. You need to overwrite the object and call the mixin. Have a look at LoginManager.anonymous_user which is an object which is used when no user is logged in.\nYou also need to get the user from somewhere. There is no point in storing the username in g as you could just use current_user.username.\nIf you wanted to get the username you would need too\nif current_user.is_authenticated():\n g.user = current_user.username\n\nThis would require that the user object has a property called username. There are lots of ways to customize Flask-Logins use\nI suggest re-reading the docs and taking a look at the source code:\nhttps://github.com/maxcountryman/flask-login/blob/master/flask_login.py\nJoe\n", "For finding if there is a loggin session we can do the following: (I have gone through all solutions and noted that when I use the below statements it is failing.)\nif current_user.is_authenticated():\n g.user = current_user.username\n\nThe correct way is:\nif current_user.is_authenticated:\n g.user = current_user.username\n\nAnd then it works fine.\n" ]
[ 20, 11, 6, 0 ]
[]
[]
[ "flask", "flask_extensions", "flask_login", "python", "python_2.7" ]
stackoverflow_0019274226_flask_flask_extensions_flask_login_python_python_2.7.txt
Q: Map column values by ID based on multiple conditions df = pd.DataFrame({'ID' : ['ID 1', 'ID 1', 'ID 1', 'ID 2', 'ID 2', 'ID 3', 'ID 3'], 'Code' : ['Apple', 'A123', 'Apple', 'Banana', 'Banana', 'K123', 'K123'], 'Code_Type' : ['Code name', 'Code ID', 'Code name', 'Code name', 'Code name', 'Code ID', 'Code ID']} ) df I have a pandas dataframe (~100k rows) that looks something like this. ID Code Code_Type ID 1 Apple Code name ID 1 Apple Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID I am trying to iterate through my dataframe and for each ID take the code based on conditions around the code type. If an ID has both a code name and a code ID associated to it, then take the code ID value and apply it to the code column. If it has only a code name or a code ID then just pass. So far the setup I have is something like this. for index, value, value2 in zip(df.ID, df.Code, df.Code_Type): print(index, value, value2) However I am not quite sure where to go from here and end up with the resulting dataframe below. ID Code Code_Type ID 1 A123 Code name ID 1 A123 Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID Ideally I would like to create a dictionary mapping like this and just apply that to the dataframe. {'ID 1' : 'A123', 'ID 2' : 'Banana', 'ID 3' : 'K123'} Any help at all is greatly appreciated. A: Try df.query("ID == Code_Type") this will output only the rows whith the condition you want. Then you can convert it to a dictionary. A: Here, my logic is to get the last row of each ID and then just selecting Code column turning it to the dictionary. Code: df.groupby(['ID']).last()['Code'].T.to_dict() Output: {'ID 1': 'a123', 'ID 2': 'bANANA', 'ID 3': 'K123'}
Map column values by ID based on multiple conditions
df = pd.DataFrame({'ID' : ['ID 1', 'ID 1', 'ID 1', 'ID 2', 'ID 2', 'ID 3', 'ID 3'], 'Code' : ['Apple', 'A123', 'Apple', 'Banana', 'Banana', 'K123', 'K123'], 'Code_Type' : ['Code name', 'Code ID', 'Code name', 'Code name', 'Code name', 'Code ID', 'Code ID']} ) df I have a pandas dataframe (~100k rows) that looks something like this. ID Code Code_Type ID 1 Apple Code name ID 1 Apple Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID I am trying to iterate through my dataframe and for each ID take the code based on conditions around the code type. If an ID has both a code name and a code ID associated to it, then take the code ID value and apply it to the code column. If it has only a code name or a code ID then just pass. So far the setup I have is something like this. for index, value, value2 in zip(df.ID, df.Code, df.Code_Type): print(index, value, value2) However I am not quite sure where to go from here and end up with the resulting dataframe below. ID Code Code_Type ID 1 A123 Code name ID 1 A123 Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID Ideally I would like to create a dictionary mapping like this and just apply that to the dataframe. {'ID 1' : 'A123', 'ID 2' : 'Banana', 'ID 3' : 'K123'} Any help at all is greatly appreciated.
[ "Try df.query(\"ID == Code_Type\") this will output only the rows whith the condition you want. Then you can convert it to a dictionary.\n", "Here, my logic is to get the last row of each ID and then just selecting Code column turning it to the dictionary.\nCode:\ndf.groupby(['ID']).last()['Code'].T.to_dict()\n\nOutput:\n{'ID 1': 'a123', 'ID 2': 'bANANA', 'ID 3': 'K123'}\n\n" ]
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074560023_dataframe_pandas_python.txt
Q: Logs are missing from commands run via `heroku run` When I use heroku run to run a command, stdout and stderr only seem to go to the terminal where I ran the command. They can't be viewed with heroku logs or via logdrain. Is there a way to get output from heroku run to be treated the same way as logs coming from, say, the scheduler? Repro steps In one terminal, run: $ heroku logs --tail --app my-app In another terminal: $ heroku run python -c "print\(\'hi\'\)" --app my-app Running python -c print\(\'hi\'\) What I expect: The word "hi" should be visible in papertrail via logdrain, as well as via heroku logs -t What actually happens: The output goes to the terminal and it doesn't end up in logdrain or the other terminal. All I get in the logs is metadata about the process having started and exited. The actual stdout and stderr contents are missing. A: This behaviour is documented: One-off dynos run attached to your terminal, with a character-by-character TCP connection for STDIN and STDOUT. This allows you to use interactive processes like a console. Since STDOUT is going to your terminal, the only thing recorded in the app’s logs is the startup and shutdown of the dyno. You can use heroku run:detached if you want to output from a one-off dyno to be captured in your logs, e.g. heroku run:detached python -c "print\(\'hi\'\)" --app my-app Of course, this isn't a great fit for anything interactive, but then I'm not sure it makes sense to log interactive sessions.
Logs are missing from commands run via `heroku run`
When I use heroku run to run a command, stdout and stderr only seem to go to the terminal where I ran the command. They can't be viewed with heroku logs or via logdrain. Is there a way to get output from heroku run to be treated the same way as logs coming from, say, the scheduler? Repro steps In one terminal, run: $ heroku logs --tail --app my-app In another terminal: $ heroku run python -c "print\(\'hi\'\)" --app my-app Running python -c print\(\'hi\'\) What I expect: The word "hi" should be visible in papertrail via logdrain, as well as via heroku logs -t What actually happens: The output goes to the terminal and it doesn't end up in logdrain or the other terminal. All I get in the logs is metadata about the process having started and exited. The actual stdout and stderr contents are missing.
[ "This behaviour is documented:\n\nOne-off dynos run attached to your terminal, with a character-by-character TCP connection for STDIN and STDOUT. This allows you to use interactive processes like a console. Since STDOUT is going to your terminal, the only thing recorded in the app’s logs is the startup and shutdown of the dyno.\n\nYou can use heroku run:detached if you want to output from a one-off dyno to be captured in your logs, e.g.\nheroku run:detached python -c \"print\\(\\'hi\\'\\)\" --app my-app\n\nOf course, this isn't a great fit for anything interactive, but then I'm not sure it makes sense to log interactive sessions.\n" ]
[ 1 ]
[]
[]
[ "heroku", "logging", "python" ]
stackoverflow_0074553942_heroku_logging_python.txt
Q: Is there any way to stream the data to the server using Python requests module? Lets' say that I'm sending very large (but finite) amount of data that keeps growing in real time. I'd like to stream it to the server to prevent myself from running out of memory. When there's no more data to be send, I'm leaving 'EndOfBatch' line in the body, so my server gonna know when it should stop listening for more data. [ it's not the problem ] There's a quick example import time from io import BytesIO import requests as requests stream = BytesIO(b"Foo") requests.post("http://127.0.0.1:8085", data=stream) # -> Server received the initial request body - "Foo" time.sleep(1) # -> Processing more data to be sent stream.write(b'Bar') stream.flush() # -> Server receives another 'Bar' part But of course, it doesn't work. How should I tackle this problem? This case has been covered in many languages, but i don't know how to do it in Python. And yes, I can't modify my server source code - it's good - i just need to stream some data from the Python level, but I have no idea how to do that :| I tried to use the requests module by putting the BytesIO object in the data argument of the requests.post method. https://requests.readthedocs.io/en/latest/user/advanced/#streaming-uploads I expected that when I'll write more data to the stream, it'll be sent right away, but it didn't. A: Using chunk encoded requests helps. import time import requests as requests def data_generator(): yield b"Foo" time.sleep(5) yield b"Bar" requests.post("http://127.0.0.1:8085", data=data_generator())
Is there any way to stream the data to the server using Python requests module?
Lets' say that I'm sending very large (but finite) amount of data that keeps growing in real time. I'd like to stream it to the server to prevent myself from running out of memory. When there's no more data to be send, I'm leaving 'EndOfBatch' line in the body, so my server gonna know when it should stop listening for more data. [ it's not the problem ] There's a quick example import time from io import BytesIO import requests as requests stream = BytesIO(b"Foo") requests.post("http://127.0.0.1:8085", data=stream) # -> Server received the initial request body - "Foo" time.sleep(1) # -> Processing more data to be sent stream.write(b'Bar') stream.flush() # -> Server receives another 'Bar' part But of course, it doesn't work. How should I tackle this problem? This case has been covered in many languages, but i don't know how to do it in Python. And yes, I can't modify my server source code - it's good - i just need to stream some data from the Python level, but I have no idea how to do that :| I tried to use the requests module by putting the BytesIO object in the data argument of the requests.post method. https://requests.readthedocs.io/en/latest/user/advanced/#streaming-uploads I expected that when I'll write more data to the stream, it'll be sent right away, but it didn't.
[ "Using chunk encoded requests helps.\nimport time\nimport requests as requests\n\n\ndef data_generator():\n yield b\"Foo\"\n time.sleep(5)\n yield b\"Bar\"\n\n\nrequests.post(\"http://127.0.0.1:8085\", data=data_generator())\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074560304_python_python_requests.txt
Q: IterableWrapper is not defined when using WikiText2 I am trying to follow along this tutorial https://pytorch.org/tutorials/beginner/transformer_tutorial.html I am getting the following error when calling this function. ----> 6 train_iter = WikiText2(split='train') /usr/local/lib/python3.7/dist-packages/torchtext/datasets/wikitext2.py in WikiText2(root, split) 75 ) 76 ---> 77 url_dp = IterableWrapper([URL]) 78 # cache data on-disk 79 cache_compressed_dp = url_dp.on_disk_cache( NameError: name 'IterableWrapper' is not defined Here is the code: from torchtext.datasets import WikiText2 from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator from torchdata.datapipes.iter import IterableWrapper train_iter = WikiText2(split='train') Let me know if you have any ideas.. Thanks Antoine A: I tried running the snippet of code you provided. I don't see NameError: name 'IterableWrapper' is not defined but I have a different error which says, No module named 'torchdata' I don't have torchdata installed. So in your case, I would make sure if the torchdata is installed correctly. You can look at this official Git and see if it works out https://github.com/pytorch/data Best regards
IterableWrapper is not defined when using WikiText2
I am trying to follow along this tutorial https://pytorch.org/tutorials/beginner/transformer_tutorial.html I am getting the following error when calling this function. ----> 6 train_iter = WikiText2(split='train') /usr/local/lib/python3.7/dist-packages/torchtext/datasets/wikitext2.py in WikiText2(root, split) 75 ) 76 ---> 77 url_dp = IterableWrapper([URL]) 78 # cache data on-disk 79 cache_compressed_dp = url_dp.on_disk_cache( NameError: name 'IterableWrapper' is not defined Here is the code: from torchtext.datasets import WikiText2 from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator from torchdata.datapipes.iter import IterableWrapper train_iter = WikiText2(split='train') Let me know if you have any ideas.. Thanks Antoine
[ "I tried running the snippet of code you provided. I don't see\nNameError: name 'IterableWrapper' is not defined\nbut I have a different error which says,\nNo module named 'torchdata'\nI don't have torchdata installed.\nSo in your case, I would make sure if the torchdata is installed correctly.\nYou can look at this official Git and see if it works out\nhttps://github.com/pytorch/data\nBest regards\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0073590391_python_pytorch.txt
Q: Django override save method with changing field value I need some help with overriding save method with changing field value. I have such structure: models.py class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) to_categories = models.ManyToManyField(Category, blank=True, related_name='categories', ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) So I can't find a correct sollution for save method. I can select category on the "to_category" and categories on "to_categories" field, but I need if I selected one of the categories on the "to_category" field then save the Product, this selected field must be automatically selected on the "to_categories" field. A: I found a sollution. admin.py: class ProductAdmin(admin.ModelAdmin): ... def save_related(self, request, form, formsets, change): super(ProductAdmin, self).save_related(request, form, formsets, change) category = Category.objects.get(id=form.instance.to_category.id) form.instance.to_categories.add(category)
Django override save method with changing field value
I need some help with overriding save method with changing field value. I have such structure: models.py class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) to_categories = models.ManyToManyField(Category, blank=True, related_name='categories', ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) So I can't find a correct sollution for save method. I can select category on the "to_category" and categories on "to_categories" field, but I need if I selected one of the categories on the "to_category" field then save the Product, this selected field must be automatically selected on the "to_categories" field.
[ "I found a sollution.\nadmin.py:\nclass ProductAdmin(admin.ModelAdmin):\n ...\n\n def save_related(self, request, form, formsets, change):\n super(ProductAdmin, self).save_related(request, form, formsets, change)\n category = Category.objects.get(id=form.instance.to_category.id)\n form.instance.to_categories.add(category)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0074560581_django_django_admin_django_models_python.txt
Q: Cannot replace special characters in a Python pandas dataframe I'm working with Python 3.5 in Windows. I have a dataframe where a 'titles' str type column contains titles of headlines, some of which have special characters such as â,€,˜. I am trying to replace these with a space '' using pandas.replace. I have tried various iterations and nothing works. I am able to replace regular characters, but these special characters just don't seem to work. The code runs without error, but the replacement simply does not occur, and instead the original title is returned. Below is what I have tried already. Any advice would be much appreciated. df['clean_title'] = df['titles'].replace('€','',regex=True) df['clean_titles'] = df['titles'].replace('€','') df['clean_titles'] = df['titles'].str.replace('€','') def clean_text(row): return re.sub('€','',str(row)) return str(row).replace('€','') df['clean_title'] = df['titles'].apply(clean_text) A: We can only assume that you refer to non-ASCI as 'special' characters. To remove all non-ASCI characters in a pandas dataframe column, do the following: df['clean_titles'] = df['titles'].str.replace(r'[^\x00-\x7f]', '') Note that this is a scalable solution as it works for any non-ASCI char. A: How to remove escape sequence character in dataframe Data. product,rating pest,<br> test mouse,/ mousetest Solution: scala Code val finaldf = df.withColumn("rating", regexp_replace(col("rating"), "\\\\", "/")).show()
Cannot replace special characters in a Python pandas dataframe
I'm working with Python 3.5 in Windows. I have a dataframe where a 'titles' str type column contains titles of headlines, some of which have special characters such as â,€,˜. I am trying to replace these with a space '' using pandas.replace. I have tried various iterations and nothing works. I am able to replace regular characters, but these special characters just don't seem to work. The code runs without error, but the replacement simply does not occur, and instead the original title is returned. Below is what I have tried already. Any advice would be much appreciated. df['clean_title'] = df['titles'].replace('€','',regex=True) df['clean_titles'] = df['titles'].replace('€','') df['clean_titles'] = df['titles'].str.replace('€','') def clean_text(row): return re.sub('€','',str(row)) return str(row).replace('€','') df['clean_title'] = df['titles'].apply(clean_text)
[ "We can only assume that you refer to non-ASCI as 'special' characters. \nTo remove all non-ASCI characters in a pandas dataframe column, do the following:\ndf['clean_titles'] = df['titles'].str.replace(r'[^\\x00-\\x7f]', '')\n\nNote that this is a scalable solution as it works for any non-ASCI char. \n", "How to remove escape sequence character in dataframe\nData.\nproduct,rating\npest,<br> test\nmouse,/ mousetest\nSolution: scala Code\n val finaldf = df.withColumn(\"rating\", regexp_replace(col(\"rating\"), \"\\\\\\\\\", \"/\")).show()\n\n" ]
[ 4, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "regex", "string" ]
stackoverflow_0050846719_dataframe_pandas_python_regex_string.txt
Q: Serializers not working on multiple levels as expected in Django I have 4 models and 3 serializers. 1 model is a simple through table containing information about which user posted which reaction about which article. models.py class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) ... class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) author = models.ForeignKey(User, related_name='authored', on_delete=models.PROTECT) ... class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='reacted', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_details', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) class Sentiment(models.Model): like = models.IntegerField(default=1) dislike = models.IntegerField(default=-1) serializers.py class UserSerializer(serializers.ModelSerializer): authored = ArticleDetailSerializer(many=True, read_only=True) reacted = ReactedSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'username', 'authored', 'reacted', ) model = User class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Article class ReactedSerializer(serializers.ModelSerializer): article_details = ArticleDetailSerializer(many=True, read_only=True) class Meta: fields = ( 'sentiment', 'article_id', 'article_details', ) model = Reaction Currently, the output for a GET request for a User shows authored correctly. I copied the logic so reacted can be a multi-level object containing sentiment and the relevant article information. I've tried many solutions yet the result for the User field reacted never includes the article_details field. I've ensured the related_name field in in the Reacted model is article_details so what am I missing? I've seen another solution on StackOverflow where someone had multi-level serialization so why is it not working here? A: related_name is useful when you are trying to access reverse relations. For example if you need to acces Reaction from Article object. But in your case you just want to access article details defined inside Reaction model. So you need to use acticle_id field name instead of article_details: class ReactedSerializer(serializers.ModelSerializer): article_id = ArticleDetailSerializer(read_only=True) class Meta: fields = ( 'sentiment', 'article_id', ) model = Reaction UPD: actually article_details is not appropriate naming for related_name here. Since related name is used when you acces list of related objects from other model, in your case it's Article. So it's better ot rename it to reactions: article_id = models.ForeignKey(Article, related_name='reactions', on_delete=models.CASCADE) And you can use it like this: article_obj.reactions.all()
Serializers not working on multiple levels as expected in Django
I have 4 models and 3 serializers. 1 model is a simple through table containing information about which user posted which reaction about which article. models.py class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) ... class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) author = models.ForeignKey(User, related_name='authored', on_delete=models.PROTECT) ... class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='reacted', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_details', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) class Sentiment(models.Model): like = models.IntegerField(default=1) dislike = models.IntegerField(default=-1) serializers.py class UserSerializer(serializers.ModelSerializer): authored = ArticleDetailSerializer(many=True, read_only=True) reacted = ReactedSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'username', 'authored', 'reacted', ) model = User class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Article class ReactedSerializer(serializers.ModelSerializer): article_details = ArticleDetailSerializer(many=True, read_only=True) class Meta: fields = ( 'sentiment', 'article_id', 'article_details', ) model = Reaction Currently, the output for a GET request for a User shows authored correctly. I copied the logic so reacted can be a multi-level object containing sentiment and the relevant article information. I've tried many solutions yet the result for the User field reacted never includes the article_details field. I've ensured the related_name field in in the Reacted model is article_details so what am I missing? I've seen another solution on StackOverflow where someone had multi-level serialization so why is it not working here?
[ "related_name is useful when you are trying to access reverse relations. For example if you need to acces Reaction from Article object. But in your case you just want to access article details defined inside Reaction model. So you need to use acticle_id field name instead of article_details:\nclass ReactedSerializer(serializers.ModelSerializer):\n article_id = ArticleDetailSerializer(read_only=True)\n class Meta:\n fields = (\n 'sentiment',\n 'article_id',\n )\n model = Reaction\n\nUPD: actually article_details is not appropriate naming for related_name here. Since related name is used when you acces list of related objects from other model, in your case it's Article. So it's better ot rename it to reactions:\narticle_id = models.ForeignKey(Article, related_name='reactions', on_delete=models.CASCADE)\n\nAnd you can use it like this:\narticle_obj.reactions.all()\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "serialization" ]
stackoverflow_0074560615_django_python_serialization.txt
Q: BeautifulSoup can't read HTML of the webpage I want to get real estate data from https://www.realtor.com/ I use this code: from bs4 import BeautifulSoup as bs import requests main_url='https://www.realtor.com/realestateandhomes-search/New-York_NY' page=requests.get(main_url).content bs(page,'html.parser') It does not output the full HTML of the page, so can't find the tags I am interested in. Is there another way to get the full HTML?
BeautifulSoup can't read HTML of the webpage
I want to get real estate data from https://www.realtor.com/ I use this code: from bs4 import BeautifulSoup as bs import requests main_url='https://www.realtor.com/realestateandhomes-search/New-York_NY' page=requests.get(main_url).content bs(page,'html.parser') It does not output the full HTML of the page, so can't find the tags I am interested in. Is there another way to get the full HTML?
[]
[]
[ "import requests\n\nmain_url='https://www.realtor.com/realestateandhomes-search/New-York_NY'\n\npage=requests.get(main_url)\nresults = bs(page.content,'html.parser')\nprint(results)\n\nThis should work\n" ]
[ -2 ]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074560840_beautifulsoup_python_web_scraping.txt
Q: Error when joining two time columns with the + operator Be the following python pandas DataFrame. I want to merge the two columns into one to create the full datetime format. num_plate_ID cam entry_date entry_time other_columns 0 XYA 2 2022-02-14 23:20:21 ... 1 JDS 2 2022-02-12 23:20:21 ... 2 OAP 0 2022-02-05 14:30:21 ... 3 ASI 1 2022-04-07 15:30:21 ... However, I get this error. df['entry'] = df['entry_date'] + " " + df['entry_time'] df['entry'] = pd.to_datetime(df['entry']) # TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str' I want to get this result. num_plate_ID cam entry_date entry_time entry other_columns 0 XYA 2 2022-02-14 23:20:21 2022-02-14 23:20:21 1 JDS 2 2022-02-12 23:20:21 2022-02-12 23:20:21 2 OAP 0 2022-02-05 14:30:21 2022-02-05 14:30:21 3 ASI 1 2022-04-07 15:30:21 2022-04-07 15:30:21 A: you can use: df['entry'] = pd.to_datetime(df['entry_date'].astype(str) + " " + df['entry_time'])
Error when joining two time columns with the + operator
Be the following python pandas DataFrame. I want to merge the two columns into one to create the full datetime format. num_plate_ID cam entry_date entry_time other_columns 0 XYA 2 2022-02-14 23:20:21 ... 1 JDS 2 2022-02-12 23:20:21 ... 2 OAP 0 2022-02-05 14:30:21 ... 3 ASI 1 2022-04-07 15:30:21 ... However, I get this error. df['entry'] = df['entry_date'] + " " + df['entry_time'] df['entry'] = pd.to_datetime(df['entry']) # TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str' I want to get this result. num_plate_ID cam entry_date entry_time entry other_columns 0 XYA 2 2022-02-14 23:20:21 2022-02-14 23:20:21 1 JDS 2 2022-02-12 23:20:21 2022-02-12 23:20:21 2 OAP 0 2022-02-05 14:30:21 2022-02-05 14:30:21 3 ASI 1 2022-04-07 15:30:21 2022-04-07 15:30:21
[ "you can use:\ndf['entry'] = pd.to_datetime(df['entry_date'].astype(str) + \" \" + df['entry_time'])\n\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074560891_dataframe_datetime_pandas_python.txt