questions
stringlengths
56
48k
answers
stringlengths
13
43.8k
Why doesn't the for loop save each roll value in each iteration to the histogram? I am creating a for loop to inspect regression to the mean with dice rolls.Wanted outcome would that histogram shows all the roll values that came on each iteration.Why doesn't the for loop save each roll value in each iteration to the histogram?Furthermore PyCharm takes forever to load if n> 20000 values therefore the code doesn't execute fully in that case.import numpy as npimport matplotlib.pyplot as pltsums = 0values = [1, 2, 3, 4, 5, 6]numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]n = np.random.choice(numbers)for i in range(n): roll = np.random.choice(values) + np.random.choice(values) sums = roll + sums h, h2 = np.histogram(sums, range(2, 14)) plt.bar(h2[:-1], h / n) plt.title(n)plt.show()Current output
You are now overwriting h and h2 in every iteration. Instead, you could append the values to a list and make a histogram of the entire list:import numpy as npimport matplotlib.pyplot as pltsums = 0values = [1, 2, 3, 4, 5, 6]numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]n = np.random.choice(numbers)all_rolls = []for i in range(n): roll = np.random.choice(values) + np.random.choice(values) all_rolls.append(roll)h, h2 = np.histogram(all_rolls, range(2, 14))plt.bar(h2[:-1], h / n)plt.title(n)plt.show()Output:
How to sort strings with numbers in Pandas? I have a Python Pandas Dataframe, in which a column named status contains three kinds of possible values: ok, must read x more books, does not read any books yet, where x is an integer higher than 0.I want to sort status values according to the order above. Example: name status0 Paul ok1 Jean must read 1 more books2 Robert must read 2 more books3 John does not read any book yetI've found some interesting hints, using Pandas Categorical and map but I don't know how to deal with variable values modifying strings.How can I achieve that?
Use:a = df['status'].str.extract('(\d+)', expand=False).astype(float)d = {'ok': a.max() + 1, 'does not read any book yet':-1}df1 = df.iloc[(-df['status'].map(d).fillna(a)).argsort()]print (df1) name status0 Paul ok2 Robert must read 2 more books1 Jean must read 1 more books3 John does not read any book yetExplanation:First extract integers by regex \d+Then dynamically create dictionary for map non numeric valuesReplace NaNs by fillna for numeric SeriesGet positions by argsortSelect by iloc for sorted values
Bar Plot with recent dates left where date is datetime index I tried to sort the dataframe by datetime index and then plot the graph but no change still it was showing where latest dates like 2017, 2018 were in right and 2008, 2009 were left.I wanted the latest year to come left and old to the right.This was the dataframe earlier. Title Date 2001-01-01 0 2002-01-01 9 2003-01-01 11 2004-01-01 17 2005-01-01 23 2006-01-01 25 2007-01-01 51 2008-01-01 55 2009-01-01 120 2010-01-01 101 2011-01-01 95 2012-01-01 118 2013-01-01 75 2014-01-01 75 2015-01-01 3 2016-01-01 35 2017-01-01 75 2018-01-01 55Ignore the values.Then I sort the above dataframe by index, and then plot but still no change in plotsdf.sort_index(ascending=False, inplace=True)
I guess you've not change your index to year. This is why it is not working.you can do so by:df.index = pd.to_datetime(df.Date).dt.year#then sort index in descending orderdf.sort_index(ascending = False , inplace = True)df.plot.bar()
Using matplotlib to obtain an overlaid histogram I am new to python and I'm trying to plot an overlaid histogram for a manipulated data set from Kaggle. I tried doing it with matplotlib. This is a dataset that shows the history of gun violence in USA in recent years. I have selected only few columns for EDA. import pandas as pd data_set = pd.read_csv("C:/Users/Lenovo/Documents/R related Topics/Assignment/Assignment_day2/04 Assignment/GunViolence.csv") state_wise_crime = data_set[['date', 'state', 'n_killed', 'n_injured']] date_value = pd.to_datetime(state_wise_crime['date']) import datetime state_wise_crime['Month']= date_value.dt.month state_wise_crime.drop('date', axis = 1) no_of_killed = state_wise_crime.groupby(['state','Year']) ['n_killed','n_injured'].sum() no_of_killed = state_wise_crime.groupby(['state','Year'] ['n_killed','n_injured'].sum()I want an overlaid histogram that shows the no. of people killed and no.of people injured with the different states on the x-axis
Welcome to Stack Overflow! From next time, please post your data like in below format (not a link or an image) to make us easier to work on the problem. Also, if you ask about a graph output, showing the contents of desired graph (even with hand drawing) would be very helpful :)df state Year n_killed n_injured0 Alabama 2013 9 31 Alabama 2014 591 3252 Alabama 2015 562 3853 Alabama 2016 761 4884 Alabama 2017 856 5445 Alabama 2018 219 1356 Alaska 2014 49 297 Alaska 2015 84 708 Alaska 2016 103 889 Alaska 2017 70 69As I commented in your original post, a bar plot would be more appropriate than histogram in this case since your purpose appears to be visualizing the summary statistics (sum) of each year with state-wise comparison. As far as I know, the easiest option is to use Seaborn. It depends on how you want to show the data, but below is one example. The code is as simple as below.import seaborn as sns sns.barplot(x='Year', y='n_killed', hue='state', data=df)Output:Hope this helps.
Local scripts conflict with builtin modules when loading numpy There are many posts about relative/absolute imports issues, and most of them are about Python 2 and/or importing submodules. This is not my case: I am using Python 3, so absolute import is the default;(I have also reproduced this issue with Python 2);I am not trying to import a submodule from within another submodule, or any other complicated situation. I am just trying to import numpy in a script.My problem is simple:.└── foo ├── a.py └── math.py1 directory, 2 fileswhere a.py just contains import nupmy, and math.py contains x++ (intentionally invalid).In that case, running python3 foo/a.py causes an error, due to NumPy seemingly not being able to import the standard math module:Traceback (most recent call last): File "foo/a.py", line 1, in <module> import numpy File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/__init__.py", line 158, in <module> from . import add_newdocs File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/add_newdocs.py", line 13, in <module> from numpy.lib import add_newdoc File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/lib/__init__.py", line 3, in <module> import math File "/private/tmp/test-import/foo/math.py", line 1 x++ ^SyntaxError: invalid syntaxI am relatively inexperienced with Python, but this looks like a bug to me. I thought statements like import math in Python 3 behaved as absolute imports; how can a local file conflict with a standard module? Am I doing something wrong?To clarify, what I find surprising is that NumPy is unable to load the standard math module with import math, because I have a file in my local folder named math.py. Note that I never try to import that module myself.EDITThis seems to be an issue specific to conda (reproduced with both Anaconda and Miniconda). I am using Anaconda 5.2.0 (on OSX 10.13.6), and people in comments have been able to reproduce with different versions of python/anaconda, and different systems.I was able to reproduce this issue with:Anaconda3 v5.2.0, using python 3.4, 3.5, 3.6 and 3.7, within a conda environment, or simply using the default binaries (ie /path/to/anaconda3/bin).Miniconda2, and Miniconda3 (manual install of numpy required), again either within or outside a conda environment.A clean Homebrew install brew install python.In all cases, it looks like the builtin-modules might be incomplete:> python3 -c "import sys; print(sys.builtin_module_names)"('_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', '_stat', '_string', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time', 'xxsubtype', 'zipimport')> python2 -c "import sys; print sys.builtin_module_names"('__builtin__', '__main__', '_ast', '_codecs', '_sre', '_symtable', '_warnings', '_weakref', 'errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'pwd', 'signal', 'sys', 'thread', 'xxsubtype', 'zipimport')REPRODUCE THIS ISSUEMake sure you have a version of Python that can import numpy. Open a terminal and type:D=$(mktemp -d) # temporary folderpushd "$D" # move there mkdir foo # create subfolderecho 'import numpy' >| foo/a.py # script a.pyecho 'x++' >| foo/math.py # script math.py (invalid)python foo/a.py # run a.pypopd # leave temp folder
"Absolute import" does not mean "standard library import". It means that import math always tries to import the math module, rather than the old behavior of trying currentpackage.math first if the import occurs inside a package. It does not mean that Python will skip non-stdlib entries on sys.path when figuring out where the math module is. In your situation, by the rules of the Python import system, your math.py is the math module.The tutorial link you found with the line When a module named spam is imported, the interpreter first searches for a built-in module with that name.is referring to modules that are directly compiled into the Python executable, like sys. Such modules say built-in in their repr:>>> sys<module 'sys' (built-in)>You can see the names of all such modules in sys.builtin_module_names. For me, those names are>>> sys.builtin_module_names('_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', '_stat', '_string', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time', 'xxsubtype', 'zipimport')math isn't built-in in that sense.
How do I apply this function to each group in my DataFrame Relatively new to Pandas, coming from an R background. I have a DataFrame like soimport pandas as pdimport numpy as npdf = pd.DataFrame({'ProductID':[0,5,9,3,2,8], 'StoreID':[0,0,0,1,1,2]}) ProductID StoreID0 0 01 5 02 9 03 3 14 2 15 8 2For each StoreID, how do I label the rows of df as 1, 2, ... based on the ordered ProductID? Then, how do I normalize those ranks? In other words, How do I achieve the followingdf['Product_Rank_Index'] = np.array([1,2,3,2,1,1])df['Product_Rank_Index_Normalized'] = np.array([1/3, 2/3, 3/3, 2/2, 1/2, 1/1]) ProductID StoreID Product_Rank_Index Product_Rank_Index_Normalized0 0 0 1 0.3333331 5 0 2 0.6666672 9 0 3 1.0000003 3 1 2 1.0000004 2 1 1 0.5000005 8 2 1 1.000000I've tried doing some things with df.groupby('StoreID') but couldn't get anything to work.
Figured it out thanks to this answer.df.groupby('StoreID').ProductID.apply(lambda x: x.rank()/len(x))
Appending columns during groupby-apply operations ContextI have several groups of data (defined by 3 columns w/i the dataframe) and would like perform a linear fit and each group and then append the estimate values (with lower + upper bounds of the fit).ProblemAfter performing the operation, I get an error related to the shapes of the final vs original dataframesExample that demonstrates the problem:from io import StringIO # modern python#from StringIO import StringIO # old pythonimport numpyimport pandasdef fake_model(group, formula): # add the results to the group modeled = group.assign( fit=numpy.random.normal(size=group.shape[0]), ci_lower=numpy.random.normal(size=group.shape[0]), ci_upper=numpy.random.normal(size=group.shape[0]) ) return modeledraw_csv = StringIO("""\location,days,era,chemical,concMW-A,2415,modern,"Chem1",5.4MW-A,7536,modern,"Chem1",0.21MW-A,7741,modern,"Chem1",0.15MW-A,2415,modern,"Chem2",33.0MW-A,2446,modern,"Chem2",0.26MW-A,3402,modern,"Chem2",0.18MW-A,3626,modern,"Chem2",0.26MW-A,7536,modern,"Chem2",0.32MW-A,7741,modern,"Chem2",0.24""")data = pandas.read_csv(raw_csv)modeled = ( data.groupby(by=['location', 'era', 'chemical']) .apply(fake_model, formula='conc ~ days') .reset_index(drop=True))That raises a very long traceback, the crux of which is:[snip] C:\Miniconda3\envs\puente\lib\site-packages\pandas\core\internals.py in construction_error(tot_items, block_shape, axes, e) 3880 raise e 3881 raise ValueError("Shape of passed values is {0}, indices imply {1}".format(-> 3882 passed,implied)) 3883 3884 ValueError: Shape of passed values is (8, 9), indices imply (8, 6)I understand that I added three columns, hence a shape of (8, 9) vs (8, 6).What I don't understand is that if I inspect the dataframe subgroup in the slightest way, the above error is not raised:def fake_model2(group, formula): _ = group.name return fake_model(group, formula)modeled = ( data.groupby(by=['location', 'era', 'chemical']) .apply(fake_model2, formula='conc ~ days') .reset_index(drop=True))print(modeled)Which produces: location days era chemical conc ci_lower ci_upper fit0 MW-A 2415 modern Chem1 5.40 -0.466833 -0.599039 -1.1438671 MW-A 7536 modern Chem1 0.21 -1.790619 -0.532233 -1.3563362 MW-A 7741 modern Chem1 0.15 1.892256 -0.405768 -0.7186733 MW-A 2415 modern Chem2 33.00 0.428811 0.259244 -1.2592384 MW-A 2446 modern Chem2 0.26 -1.616517 -0.955750 -0.7272165 MW-A 3402 modern Chem2 0.18 -0.300749 0.341106 0.6023326 MW-A 3626 modern Chem2 0.26 -0.232240 1.845240 1.3401247 MW-A 7536 modern Chem2 0.32 -0.416087 -0.521973 -1.4777488 MW-A 7741 modern Chem2 0.24 0.958202 0.634742 0.542667QuestionMy work-around feels far too hacky to use in any real-world application. Is there a better way to apply my model and include the best-fit estimates to each group within the larger dataframe?
Yay, a non-hacky workaround existsIn [18]: gr = data.groupby(['location', 'era', 'chemical'], group_keys=False)In [19]: gr.apply(fake_model, formula='')Out[19]: location days era chemical conc ci_lower ci_upper fit0 MW-A 2415 modern Chem1 5.40 -0.105610 -0.056310 1.3442101 MW-A 7536 modern Chem1 0.21 0.574092 1.305544 0.4119602 MW-A 7741 modern Chem1 0.15 -0.073439 0.140920 -0.6798373 MW-A 2415 modern Chem2 33.00 1.959547 0.382794 0.5441584 MW-A 2446 modern Chem2 0.26 0.484376 0.400111 -0.4507415 MW-A 3402 modern Chem2 0.18 -0.422490 0.323525 0.5207166 MW-A 3626 modern Chem2 0.26 -0.093855 -1.487398 0.2226877 MW-A 7536 modern Chem2 0.32 0.124983 -0.484532 -1.1621278 MW-A 7741 modern Chem2 0.24 -1.622693 0.949825 -1.049279That actually saves you a .reset_index too :)group_keys was the culprit behind the error.The maybe bug in pandas come from a regular concat of each group. With group_keys=True thats[('MW-A', 'modern', 'Chem1'), ('MW-A', 'modern', 'Chem2')]which pandas wasn't expecting. This smells like a bug in pandas, but haven't dug more to confirm.
Handling value rollover in data frame I'm processing a dataframe that contains a column that consists of an error count. The problem I'm having is the counter rolls over after 64k. Additionally, on long runs the rollover occurs multiple times. I need a method to correct these overflows and get an accurate count.
I'm not sure that it always work correctly, but let's try:# groupsg = df.groupby((df['count'].diff() < 0).cumsum())# mapping cumulative summandmp = df.groupby((df['count'].diff() < 0).cumsum(), as_index=False).max().shift(1).fillna(0)['count']# mathfor grp, chunk in g: df['count'] += (df['count'].diff() < 0).cumsum().map(mp) Original DF:In [416]: dfOut[416]: count0 01 12 23 34 45 56 07 18 29 310 411 012 113 214 315 416 517 618 719 8Result:In [414]: dfOut[414]: count0 0.01 1.02 2.03 3.04 4.05 5.06 5.07 6.08 7.09 8.010 9.011 9.012 10.013 11.014 12.015 13.016 14.017 15.018 16.019 17.0Explanation:helper for grouping (monotonically increasing groups):In [418]: (df['count'].diff() < 0).cumsum()Out[418]:0 01 02 03 04 05 06 17 18 19 110 111 212 213 214 215 216 217 218 219 2Name: count, dtype: int32Summand for each group:In [420]: df.groupby((df['count'].diff() < 0).cumsum(), as_index=False).max().shift(1).fillna(0)['count']Out[420]:0 0.01 5.02 4.0Name: count, dtype: float64already mapped summands - they will be added N times (where N is number of groups - 3 for this example):In [421]: (df['count'].diff() < 0).cumsum().map(mp)Out[421]:0 0.01 0.02 0.03 0.04 0.05 0.06 5.07 5.08 5.09 5.010 5.011 4.012 4.013 4.014 4.015 4.016 4.017 4.018 4.019 4.0Name: count, dtype: float64setup test DF:df = pd.DataFrame({'count': np.arange(20)})df.ix[6:10, 'count'] = range(5)df.ix[11:19, 'count'] = range(9)
Why do I have to import this from numpy if I am just referencing it from the numpy module Aloha!I have two blocks of code, one that will work and one that will not. The only difference is a commented line of code for a numpy module I don't use. Why am I required to import that model when I never reference "npm"?This command works:import numpy as npimport numpy.matlib as npmV = np.array([[1,2,3],[4,5,6],[7,8,9]])P1 = np.matlib.identity(V.shape[1], dtype=int)P1This command doesn't work:import numpy as np#import numpy.matlib as npmV = np.array([[1,2,3],[4,5,6],[7,8,9]])P1 = np.matlib.identity(V.shape[1], dtype=int)P1The above gets this error:AttributeError: 'module' object has no attribute 'matlib'Thanks in advance!
Short AnswerThis is because numpy.matlib is an optional sub-package of numpy that must be imported separately. The reason for this feature may be:In particular for numpy, the numpy.matlib sub-module redefines numpy's functions to return matrices instead of ndarrays, an optional feature that many may not wantMore generally, to load the parent module without loading a potentially slow-to-load module which many users may not often needPossibly, namespace separationWhen you import just numpy without the sub-package matlib, then Python will be looking for .matlib as an attribute of the numpy package. This attribute has not been assigned to numpy without importing numpy.matlib (see discussion below)Sub-Modules and BindingIf you're wondering why np.matlib.identity works without having to use the keyword npm, that's because when you import the sub-module matlib, the parent module numpy (named np in your case) will be given an attribute matlib which is bound to the sub-module. This only works if you first define numpy.From the reference: When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in import()) a binding is placed in the parent module’s namespace to the submodule object.Importing and __init__.pyThe choice of what to import is determined in the modules' respective __init__.py files in the module directory. You can use the dir() function to see what names the respective modules define.>> import numpy>> 'matlib' in dir(numpy)# False>> import numpy.matlib>> 'matlib' in dir(numpy)# TrueAlternatively, if you look directly at the __init__.py file for numpy you'll see there's no import for matlib.Namespace across Sub-ModulesIf you're wondering how the namespace is copied over smoothly;The matlib source code runs this command to copy over the numpy namespace:import numpy as np # (1)...# need * as we're copying the numpy namespacefrom numpy import * # (2)...__all__ = np.__all__[:] # copy numpy namespace # (3)Line (2), from numpy import * is particularly important. Because of this, you'll notice that if you just import numpy.matlib you can still use all of numpy modules without having to import numpy! Without line (2), the namespace copy in line (3) would only be attached to the sub-module. Interestingly, you can still do a funny command like this because of line (3).import numpy.matlib numpy.matlib.np.matlib.np.array([1,1])This is because the np.__all__ is attached to the np of numpy.matlib (which was imported via line (1)).
append two data frame with pandas When I try to merge two dataframes by rows doing:bigdata = data1.append(data2)I get the following error:Exception: Index cannot contain duplicate values!The index of the first data frame starts from 0 to 38 and the second one from 0 to 48. I didn't understand that I have to modify the index of one of the data frame before merging, but I don't know how to.Thank you.These are the two dataframes:data1: meta particle ratio area type 0 2 part10 1.348 0.8365 touching1 2 part18 1.558 0.8244 single 2 2 part2 1.893 0.894 single 3 2 part37 0.6695 1.005 single ....clip...36 2 part23 1.051 0.8781 single 37 2 part3 80.54 0.9714 nuclei 38 2 part34 1.071 0.9337 single data2: meta particle ratio area type 0 3 part10 0.4756 1.025 single 1 3 part18 0.04387 1.232 dusts 2 3 part2 1.132 0.8927 single ...clip...46 3 part46 13.71 1.001 nuclei 47 3 part3 0.7439 0.9038 single 48 3 part34 0.4349 0.9956 single the first column is the index
The append function has an optional argument ignore_index which you should use here to join the records together, since the index isn't meaningful for your application.
Using first row in Pandas groupby dataframe to calculate cumulative difference I have the following grouped dataframe based on daily dataStudentid Year Month BookLevel JSmith 2015 12 1.4 2016 1 1.6 2 1.8 3 1.2 4 2.0 MBrown 2016 1 3.0 2 3.2 3 3.6 I want to calculate the difference from the starting point in BookLevel for each Studentid. The current BookLevel is a .max calculation from the GroupBy to get the highest bookLevel for each month for each studentWhat I am looking for is something like this: Studentid Year Month BookLevel Progress Since Start JSmith 2015 12 1.4 0 (or NAN) 2016 1 1.6 .2 2 1.8 .4 3 1.2 -.2 4 2.0 .6 2016 1 3.0 0 (or NAN) MBrown 2 3.2 .2 3 3.6 .6I'm new to Python/Pandas and have tried a number of things and nothing comes close.
OK, this should work, if we groupby on the first level and subtract BookLevel from the series returned by calling transform with first then we can add this as the new desired column:In [47]:df['ProgressSinceStart'] = df['BookLevel'] - df.groupby(level='Studentid')['BookLevel'].transform('first')dfOut[47]: BookLevel ProgressSinceStartStudentid Year Month JSmith 2015 12 1.4 0.0 2016 1 1.6 0.2 2 1.8 0.4 3 1.2 -0.2 4 2.0 0.6MBrown 2016 1 3.0 0.0 2 3.2 0.2 3 3.6 0.6
Column Order in Pandas Dataframe from dict of dict I am creating a pandas dataframe from a dictionary of dict in the following way :df = pd.DataFrame.from_dict(stats).transpose()I want the columns in a particular order but cant seem to figure out how to do so. I have tried this:df = pd.DataFrame(columns=['c1','c2','c3']).from_dict(stats).transpose() but the final output is always c3, c2, c1. Any ideas ?
You could do:df = pd.DataFrame.from_dict(stats).transpose().loc[:, ['c1','c2','c3']]or just df = pd.DataFrame.from_dict(stats).transpose()[['c1','c2','c3']]
Vectorization on nested loop I need to vectorize the following program : y = np.empty((100, 100, 3)) x = np.empty((300,)) for i in xrange(y.shape[0]): for j in xrange(y.shape[1]): y[i, j, 0] = x[y[i, j, 0]]Of course, in my example, we suppose that y[:, :, :]<=299Vectorization, as far as I know, can't simply work here as we are using the native python indexing on lists ...I've heard of np.apply_along_axis, but it doesn't work on this special case, or may I missed something ?Thank you very much for any help.
np.apply_along_axis could work, but it's overkill.First, there's a problem in your nested loop approach. np.empty, used to define y, returns an array of np.float values, which cannot be used to index an array. To take care of this, you have to cast the array as integers, e.g. y = np.empty((100, 100, 3)).astype(np.int).Once you do that, you can index using y, as follows:y = np.empty((100, 100, 3)).astype(np.uint8)x = np.empty((300,))y[:,:,0] = x[y[:,:,0]]Of course, y is all 0's, so it's not quite clear what this accomplishes.
Converting pandas dataframe to numeric; seaborn can't plot I'm trying to create some charts using weather data, pandas, and seaborn. I'm having trouble using lmplot (or any other seaborn plot function for that matter), though. I'm being told it can't concatenate str and float objects, but I used convert_objects(convert_numeric=True) beforehand, so I'm not sure what the issue is, and when I just print the dataframe I don't see anything wrong, per se.import numpy as npimport pandas as pdimport seaborn as snsnew.convert_objects(convert_numeric=True)sns.lmplot("AvgSpeed", "Max5Speed", new)Some of the examples of unwanted placeholder characters that I saw in the few non-numeric spaces just glancing through the dataset were "M", " ", "-", "null", and some other random strings. Would any of these cause a problem for convert_objects? Does seaborn know to ignore NaN? I don't know what's wrong. Thanks for the help.
You need to assign the result to itself:new = new.convert_objects(convert_numeric=True)See the docsconvert_objects is now deprecated as of version 0.21.0, you have to use to_numeric:new = new.convert_objects()if you have multiple columns:new = new.apply(pd.to_numeric)
Repeating Data and Incorrect Names in Pandas DataFrame count Function Results I have a question about the Pandas DataFrame count function.I'm working on the following code:d = {'c1': [1, 1, 1, 1, 1], 'c2': [1, 1, 1, 1, 1], 'c3': [1, 1, 1, 1, 1], 'Animal': ["Cat", "Cat", "Dog", "Cat", "Dog"]}import pandas as pddf = pd.DataFrame(data=d)So I end up with DataFrame df, which contains the following: c1 c2 c3 Animal0 1 1 1 Cat1 1 1 1 Cat2 1 1 1 Dog3 1 1 1 Cat4 1 1 1 DogColumns c1, c2, and c3 contain information about my Animal collection which is not relevant to this question. My goal is to count the number of animals by species, i.e., the contents of the Animal column.When I run:df.groupby("Animal").count()the result is a DataFrame that contains: c1 c2 c3Animal Cat 3 3 3Dog 2 2 2As you can see, the desired result, counting the number times Cat and Dog appear in column Aninal is correctly computed. However, this result is a bit unsatisfying to me for the following reasons:The counts of Cat and Dog are each repeated three times in the output, one for each column header c1, c2, and c3.The headers of the columns in this resulting DataFrame are really wrong: the entries are not c1, c2, or c3 items anymore (those could be heights, weights, etc. for example), but rather animal species counts. To me this is a problem, since it is easy for client code (for example, code that uses a function that I write returning this DataFrame) to misinterpret these as entries instead of counts.My questions are:Why is the count function implemented this way, with repeating data and unchanged column headers?Is it ever possible for each column to be different in a given row in the result of count?Is there are cleaner way to do this in Pandas that addresses my two concerns listed above?I realize the following code will partially address these problems:df.groupby("Animal").count()['c1']which results in a Series with the contents:AnimalCat 3Dog 2Name: c1, dtype: int64But this still isn't really what I'm looking for, since:It's inelegant, what's the logic of filtering on c1 (or c2 or c3, which would result in the same Series except the name)?The name (analogous to the argument with the column header above) is still c1, which is misleading and inelegant.I realize I can rename the Series as follows:df.groupby("Animal").count()['c1'].rename("animal_count")which results in the following Series:AnimalCat 3Dog 2Name: animal_count, dtype: int64That's a satisfactory result; it does not repeat data and is reasonably named, though I would have preferred a DataFrame at this point (I realize I could covert it). However, the code I used to get this,df.groupby("Animal").count()['c1'].rename("animal_count")is very unsatisfying for elegance and length.Another possible solution I've found is:df.groupby("Animal").size()which results in:AnimalCat 3Dog 2dtype: int64however it's not clear to me if this is coincidently correct or if size and count really do the same thing. If so, why are both implemented in Pandas?Is there a better way to do this in Pandas?Thanks to everyone for your input!
The count function counts (for each column as you've noted) the number of non-na / non-empty cells. In general, this could differ for each column if they have different missing values. After a groupby though, I don't think this would ever be the case.Like you mentioned though, I believe .size() is the function you want to just get the size of each grouping. I think this should also exist on a normal DataFrame, but it looks like it's a property not a function there (since it just returns a single number of rows; its not a mapping to apply to each group)
How to count number of unique values in pandas while each cell includes list I have a data frame like this:import pandas as pdimport numpy as npOut[10]: samples subject trial_num0 [0 2 2 1 11 [3 3 0 1 22 [1 1 1 1 33 [0 1 2 2 14 [4 5 6 2 25 [0 8 8 2 3I want to have the output like this: samples subject trial_num frequency0 [0 2 2 1 1 2 1 [3 3 0 1 2 22 [1 1 1 1 3 13 [0 1 2 2 1 34 [4 5 6 2 2 35 [0 8 8 2 3 2The frequency here is the number of unique values in each list per sample. For example, [0, 2, 2] only have one unique value.I can do the unique values in pandas without having a list, or implement it using for loop to go through each row access each list and .... but I want a better pandas way to do it.Thanks.
You can use collections.Counter for the task:from collections import Counterdf['frequency'] = df['samples'].apply(lambda x: sum(v==1 for v in Counter(x).values()))print(df)Prints: samples subject trial_num frequency0 [0, 2, 2] 1 1 11 [3, 3, 0] 1 2 12 [1, 1, 1] 1 3 03 [0, 1, 2] 2 1 34 [4, 5, 6] 2 2 35 [0, 8, 8] 2 3 1EDIT: For updated question:df['frequency'] = df['samples'].apply(lambda x: len(set(x)))print(df)Prints: samples subject trial_num frequency0 [0, 2, 2] 1 1 21 [3, 3, 0] 1 2 22 [1, 1, 1] 1 3 13 [0, 1, 2] 2 1 34 [4, 5, 6] 2 2 35 [0, 8, 8] 2 3 2
TensorFlow: `tf.data.Dataset.from_generator()` does not work with strings on Python 3.x I need to iterate through large number of image files and feed the data to tensorflow. I created a Dataset back by a generator function that produces the file path names as strings and then transform the string path to image data using map. But it failed as generating string values won't work, as shown below. Is there a fix or work around for this?2017-12-07 15:29:05.820708: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMAproducing data/miniImagenet/val/n01855672/n0185567200001000.jpg2017-12-07 15:29:06.009141: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str2017-12-07 15:29:06.009215: W tensorflow/core/framework/op_kernel.cc:1192] Unimplemented: Unsupported object type str [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]]Traceback (most recent call last): File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1323, in _do_call return fn(*args) File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1302, in _run_fn status, run_metadata) File "/Users/me/.tox/tf2/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status))tensorflow.python.framework.errors_impl.UnimplementedError: Unsupported object type str [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_STRING], token="pyfunc_1"](arg0)]] [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,21168]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]]The test codes are shown below. It can work correctly with from_tensor_slices or by first putting the the file name list in a tensor. however, either work around would exhaust GPU memory.import tensorflow as tfif __name__ == "__main__": file_names = ['data/miniImagenet/val/n01855672/n0185567200001000.jpg', 'data/miniImagenet/val/n01855672/n0185567200001005.jpg'] # note: converting the file list to tensor and returning an index from generator works # path_to_indexes = {p: i for i, p in enumerate(file_names)} # file_names_tensor = tf.convert_to_tensor(file_names) def dataset_producer(): for s in file_names: print('producing', s) yield s dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string), output_shapes=(tf.TensorShape([]))) # note: this would also work # dataset = tf.data.Dataset.from_tensor_slices(tf.convert_to_tensor(file_names)) def read_image(filename): # filename = file_names_tensor[filename_index] image_file = tf.read_file(filename, name='read_file') image = tf.image.decode_jpeg(image_file, channels=3) image.set_shape((84,84,3)) image = tf.reshape(image, [21168]) image = tf.cast(image, tf.float32) / 255.0 return image dataset = dataset.map(read_image) dataset = dataset.batch(2) data_iterator = dataset.make_one_shot_iterator() images = data_iterator.get_next() print('images', images) max_value = tf.argmax(images) with tf.Session() as session: result = session.run(max_value) print(result)
This is a bug affecting Python 3.x that was fixed after the TensorFlow 1.4 release. All releases of TensorFlow from 1.5 onwards contain the fix.If you just use an earlier version, the workaround is to convert the strings to bytes before returning them from the generator. The following code should work:def dataset_producer(): for s in file_names: print('producing', s) yield s.encode('utf-8') # Convert `s` to `bytes`.dataset = tf.data.Dataset.from_generator(dataset_producer, output_types=(tf.string), output_shapes=(tf.TensorShape([])))
Error while importing a file while working with jupyter notebook Recently I've been working with jupyter notebooks and was trying to read an excel file with pandas and it gives me the following error: FileNotFoundError: [Errno 2] No such file or directoryBut it works fine and reads the file with the exact same lines of code when i run it on Spyder. Any advice on how to solve this issue?
Seems like an installation error,Do this,For Python 2pip install --upgrade --force-reinstall --no-cache-dir jupyterFor Python 3pip3 install --upgrade --force-reinstall --no-cache-dir jupyter
Python Dataframe: How to get alphabetically ordered list of column names I currently am able to get a list of all the column names in my dataframe using: df_EVENT5.columns.get_values()But I want the list to be in alphabetical order ... how do I do that?
In order to get the list of column names in alphabetical order, try:df_EVENT5.columns.sort_values().values
How to reduce the processing time of reading a file using numpy I want to read a file and comparing some values, finding indexes of the repeated ones and deleting the repeated ones.I am doing this process in while loop.This is taking more processing time of about 76 sec.Here is my code:Source = np.empty(shape=[0,7])Source = CalData (# CalData is the log file data)CalTab = np.empty(shape=[0,7])Source = Source[Source[:, 4].argsort()] # Sort by Azimuthwhile Source.size >=1: temp = np.logical_and(Source[:,4]==Source[0,4],Source[:,5]==Source[0,5]) selarrayindex = np.argwhere(temp) # find indexes selarray = Source[temp] CalTab = np.append(CalTab, [selarray[selarray[:,6].argsort()][-1]], axis=0) Source = np.delete(Source, selarrayindex, axis=0) #delete other rows with similar AZ, ELwhile loop processing is taking more time.Any other methods(Using normal python) with out using numpy or Efficient numpyPlease help!!
In any case, this should imporve your timings, I think:def lex_pick(Source): idx = np.lexsort((Source[:, 6], Source[:, 5], Source[:, 4])) # indices to sort by columns 4, then 5, then 6 # if dtype = float mask = np.r_[np.logical_not(np.isclose(Source[idx[:-1], 5], Source[idx[1:], 5])), True] # if dtype = int or string mask = np.r_[Source[idx[:-1], 5] != Source[idx[1:], 5], True] # `mask` is `True` in rows before where column 5 changes return Source[idx[mask], 6]
Select subset of numpy.ndarray based on other array's values I have two numpy.ndarrays and I would like to select a subset of Array #2 based on the values in Array #1 (Criteria: Values > 1):#Array 1 - print(type(result_data):<class 'numpy.ndarray'>#print(result_data):[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 3 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]#Array #2 - print(type(test_data):<class 'numpy.ndarray'>#print(test_data):[[-1.38693584 0.76183275] [-1.38685102 0.76187584] [-1.3869291 0.76186742] ..., [-1.38662322 0.76160456] [-1.38662322 0.76160456] [-1.38662322 0.76160456]]I tried:x=0selArray = np.emptyfor i in result_data: x+=1 if i > 1: selArray = np.append(selArray,[test_data[x].T[0],test_data[x].T[1]])...but this gives me:#print(type(selArray)):<class 'numpy.ndarray'>#print(selArray):[<built-in function empty> -1.3868538952656493 0.7618747030055314 -1.3868543839578398 0.7618746157390688 -1.3870217784863983 0.7618121504051398 -1.3870217784863983 0.7618121504051398 -1.3870217784863983 0.7618121504051398 -1.3869304105000566... -1.3869682317849474 0.7617139232748376 -1.3869103741202438 0.7616839734248734 -1.3868025127724706 0.7616153994385625 -1.3869751607420777 0.761730050117126 -1.3866515941520503 0.7615994122226143 -1.3866515941520503 0.7615994122226143]Clearly, [] are missing around elements - and I don't understand where the <built-in function empty> comes from.
It turned out to be pretty straight forward:selArray = test_data[result_data_>1]See also possible solution in comment from Nain!
Transforming extremely skewed data for regression analysis I have a Pandas Series from a housing data-set (size of the series = 48,2491), named "exempt_land". The first 10 entries of this series are: 0 0.02 17227.03 0.07 0.010 0.014 7334.015 0.016 0.018 0.019 8238.0Name: exempt_land, dtype: float64As the data size is quite large, I did not perform dummy_variable transformation. Now, my goal is to carry out regression analysis. Hence, I would like to transform this data to appear Normal.The original data has a Skewness of 344.58 and Kurtosis = 168317.32. To better understand the original data, I am also including the Distribution plot and Probability plot of the original data.Distribution Plot BEFORE transformationProbability Plot BEFORE transformationAfter performing Log transformation, I get the Skewness of 5.21 and Kurtosis = 25.96. The transformed Distribution and Probability plots now look as follows:Distribution Plot AFTER np.log10(exempt_land + 1) transformationProbability Plot AFTER np.log10(exempt_land + 1) transformationI also performed various other transformations ("power", "exp", "box-cox", "reciprocal") and I got similar bad results (in reciprocal transformation case, the results were quite worse).So my question is, how can I 'tame' this data to behave nicely when doing regression analysis. Furthermore, upon transformation, the skew of 5.21 is still quite high, will this create any problem?What other transformations can I perform to make the data look more Normal?I hope my questions are clear here. Any help from the community is greatly appreciated. Thank you so much in advance.
With all the zeros, you need to use a non-normal distribution. Some variety of Tobit might make sense here. (You can't transform discrete data and get less discrete data.)
pandas fillna is not working on subset of the dataset I want to impute the missing values for df['box_office_revenue'] with the median specified by df['release_date'] == x and df['genre'] == y . Here is my median finder function below.def find_median(df, year, genre, col_year, col_rev): median = df[(df[col_year] == year) & (df[col_rev].notnull()) & (df[genre] > 0)][col_rev].median()return medianThe median function works. I checked. I did the code below since I was getting some CopyValue error.pd.options.mode.chained_assignment = None # default='warn'I then go through the years and genres, col_name = ['is_drama', 'is_horror', etc] . i = df['release_year'].min()while (i < df['release_year'].max()):for genre in col_name: median = find_median(df, i, genre, 'release_year', 'box_office_revenue') df[(df['release_year'] == i) & (df[genre] > 0)]['box_office_revenue'].fillna(median, inplace=True)print(i)i += 1However, nothing changed! len(df['box_office_revenue'].isnull())The output was 35527. Meaning none of the null values in df['box_office_revenue'] had been filled. Where did I go wrong?Here is a quick look at the data: The other columns are just binary variables
You mentionedI did the code below since I was getting some CopyValue error...The warning is important. You did not give your data, so I cannot actually check, but the problem is likely due to:df[(df['release_year'] == i) & (df[genre] > 0)]['box_office_revenue'].fillna(..)Let's break this down:First you select some rows with:df[(df['release_year'] == i) & (df[genre] > 0)]Then from that, you select a columns with:...['box_office_revenue']And now you have a problem...Why?The problem is that when you selected some rows (ie: not all), pandas was forced to create a copy of your dataframe. You then select a column of the copy!. Then you fillna() on the copy. Not super useful.How do I fix it?Select the column first:df['box_office_revenue'][(df['release_year'] == i) & (df[genre] > 0)].fillna(..)By selecting the entire column first, pandas is not forced to make a copy, and thus subsequent operations should work as desired.
Is there support for functional layers api support in tensorflow 2.0? I'm working on converting our model from tensorflow 1.8.0 to 2.0 but using sequential api's is quite difficult for our current model.So if there any support for functional api's in 2.0 as it is not easy to use sequential api's.
Tensorflow 2.0 is more or less made around the keras apis. You can use the tf.keras.Model for creating both sequential as well as functional apis.
Conditional ffill based on another column I'm trying to conditionally ffill a value until a second column encounters a value and then reset the first column value. Effectively the first column is an 'on' switch until the 'off' switch (second column) encounters a value. I've yet to have a working example using ffill and where.Example input:Index Start End0 0 01 0 02 1 03 0 04 0 05 0 06 0 17 0 08 1 09 0 010 0 011 0 012 0 113 0 114 0 0Desired output:Index Start End0 0 01 0 02 1 03 1 04 1 05 1 06 1 17 0 08 1 09 1 010 1 011 1 012 1 113 0 114 0 0EDIT:There are issues when dealing with values set based on another column. The logic is as follows: Start should be zero until R column is below 25, then positive until R column is above 80 and the cycle should repeat. Yet on row 13 Start is inexplicably set 1 despite not matching criteria.df = pd.DataFrame(np.random.randint(0, 100, size=100), columns=['R'])df['Start'] = np.where((df.R < 25), 1, 0)df['End'] = np.where((df.R > 80), 1, 0)df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int) R Start End0 58 0 01 98 0 12 91 0 13 69 0 04 55 0 05 57 0 06 64 0 07 75 0 18 78 0 19 90 0 110 24 1 011 89 1 112 36 0 013 70 **1** 0
Try:df.loc[df['End'].shift().eq(0), 'Start'] = df['Start'].replace(0, np.nan).ffill().fillna(0).astype(int)[out] Start End0 0 01 0 02 1 03 1 04 1 05 1 06 1 17 0 08 1 09 1 010 1 011 1 012 1 113 0 114 0 0
Why does calling np.array() on this list comprehension produce a 3d array instead of 2d? I have a script produces the first several iterations of a Markov matrix multiplying a given set of input values. With the matrix stored as A and the start values in the column u0, I use this list comprehension to store the output in an array:out = np.array([ ( (A**n) * u0).T for n in range(10) ])The output has shape (10,1,6), but I want the output in shape (10,6) instead. Obviously, I can fix this with .reshape(), but is there a way to avoid creating the extra dimension in the first place, perhaps by simplifying the list comprehension or the inputs?Here's the full script and output:import numpy as np# Random 6x6 Markov matrixn = 6A = np.matrix([ (lambda x: x/x.sum())(np.random.rand(n)) for _ in range(n)]).Tprint(A)#[[0.27457312 0.20195133 0.14400801 0.00814027 0.06026188 0.23540134]# [0.21526648 0.17900277 0.35145882 0.30817386 0.15703758 0.21069114]# [0.02100412 0.05916883 0.18309142 0.02149681 0.22214047 0.15257011]# [0.17032696 0.11144443 0.01364982 0.31337906 0.25752732 0.1037133 ]# [0.03081507 0.2343255 0.2902935 0.02720764 0.00895182 0.21920371]# [0.28801424 0.21410713 0.01749843 0.32160236 0.29408092 0.07842041]]# Random start valuesu0 = np.matrix(np.random.randint(51, size=n)).Tprint(u0)#[[31]# [49]# [44]# [29]# [10]# [ 0]]# Find the first 10 iterations of the Markov processout = np.array([ ( (A**n) * u0).T for n in range(10) ])print(out)#[[[31. 49. 44. 29. 10.# 0. ]]## [[25.58242101 41.41600236 14.45123543 23.00477134 26.08867045# 32.45689942]]## [[26.86917065 36.02438292 16.87560159 26.46418685 22.66236879# 34.10428921]]## [[26.69224394 37.06346073 16.59208202 26.48817955 22.56696872# 33.59706504]]## [[26.68772374 36.99727159 16.49987315 26.5003184 22.61130862# 33.7035045 ]]## [[26.68766363 36.98517264 16.50532933 26.51717543 22.592951# 33.71170797]]## [[26.68695152 36.98895204 16.50314718 26.51729716 22.59379049# 33.70986161]]## [[26.68682195 36.98848867 16.50286371 26.51763013 22.59362679# 33.71056876]]## [[26.68681128 36.98850409 16.50286036 26.51768807 22.59359453# 33.71054167]]## [[26.68680313 36.98851046 16.50285038 26.51769497 22.59359219# 33.71054886]]]print(out.shape)#(10, 1, 6)out = out.reshape(10,n)print(out)#[[31. 49. 44. 29. 10. 0. ]# [25.58242101 41.41600236 14.45123543 23.00477134 26.08867045 32.45689942]# [26.86917065 36.02438292 16.87560159 26.46418685 22.66236879 34.10428921]# [26.69224394 37.06346073 16.59208202 26.48817955 22.56696872 33.59706504]# [26.68772374 36.99727159 16.49987315 26.5003184 22.61130862 33.7035045 ]# [26.68766363 36.98517264 16.50532933 26.51717543 22.592951 33.71170797]# [26.68695152 36.98895204 16.50314718 26.51729716 22.59379049 33.70986161]# [26.68682195 36.98848867 16.50286371 26.51763013 22.59362679 33.71056876]# [26.68681128 36.98850409 16.50286036 26.51768807 22.59359453 33.71054167]# [26.68680313 36.98851046 16.50285038 26.51769497 22.59359219 33.71054886]]
I think your confusion lies with how arrays can be joined. Start with a simple 1d array (in numpy 1d is a real thing, not just a 'row vector' or 'column vector'):In [288]: arr = np.arange(6) In [289]: arr Out[289]: array([0, 1, 2, 3, 4, 5])np.array joins element arrays along a new 1st dimension:In [290]: np.array([arr,arr]) Out[290]: array([[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]])np.stack with the default axis value does the same thing. Read its docs.We can make a 2d array, a column vector:In [291]: arr1 = arr[:,None] In [292]: arr1 Out[292]: array([[0], [1], [2], [3], [4], [5]])In [293]: arr1.shape Out[293]: (6, 1)Using np.array on its transpose the (1,6) arrays:In [294]: np.array([arr1.T, arr1.T]) Out[294]: array([[[0, 1, 2, 3, 4, 5]], [[0, 1, 2, 3, 4, 5]]])In [295]: _.shape Out[295]: (2, 1, 6)Note the middle size 1 dimension, that bothered you.np.vstack joins the arrays along the existing 1st dimension. It does not add one:In [296]: np.vstack([arr1.T, arr1.T]) Out[296]: array([[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]])Or we could join the arrays horizontally, on the 2nd dimension:In [297]: np.hstack([arr1, arr1]) Out[297]: array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])That is (6,2) which can be transposed to (2,6):In [298]: np.hstack([arr1, arr1]).T Out[298]: array([[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]])
pandas df.at utterly slow in some lines I've got a .txt logfile with IMU sensor measurements which need to be parsed to a .CSV file. Accelerometer, gyroscope have 500Hz ODR (output data rate) magnetomer 100Hz, gps 1Hz and baro 1Hz. Wi-fi, BLE, pressure, light etc. is also logged but most is not needed. The smartphone App doesn't save all measurements sequentially. It takes 1000+ seconds to parse a file of 200k+ lines to a pandas DataFrame sort the DataFrame on the timestamps and save it as a csv file.When assigning values of sensor measurements at a coordinate (Row=Timestamp, column=sensor measurement) in the DataFrame, some need ~40% of the runtime, while others take +- 0.1% of the runtime. What could be the reason for this? It shouldn't take a 1000+ seconds.. What is in the logfile:ACCE;AppTimestamp(s);SensorTimestamp(s);Acc_X(m/s^2);Acc_Y(m/s^2);Acc_Z(m/s^2);Accuracy(integer)GYRO;AppTimestamp(s);SensorTimestamp(s);Gyr_X(rad/s);Gyr_Y(rad/s);Gyr_Z(rad/s);Accuracy(integer)MAGN;AppTimestamp(s);SensorTimestamp(s);Mag_X(uT);;Mag_Y(uT);Mag_Z(uT);Accuracy(integer)MAGN;AppTimestamp(s);SensorTimestamp(s);Mag_X(uT);;Mag_Y(uT);Mag_Z(uT);Accuracy(integer)PRES;AppTimestamp(s);SensorTimestamp(s);Pres(mbar);Accuracy(integer)LIGH;AppTimestamp(s);SensorTimestamp(s);Light(lux);Accuracy(integer)PROX;AppTimestamp(s);SensorTimestamp(s);prox(?);Accuracy(integer)HUMI;AppTimestamp(s);SensorTimestamp(s);humi(Percentage);Accuracy(integer)TEMP;AppTimestamp(s);SensorTimestamp(s);temp(Celsius);Accuracy(integer)AHRS;AppTimestamp(s);SensorTimestamp(s);PitchX(deg);RollY(deg);YawZ(deg);RotVecX();RotVecY();RotVecZ();Accuracy(int)GNSS;AppTimestamp(s);SensorTimeStamp(s);Latit(deg);Long(deg);Altitude(m);Bearing(deg);Accuracy(m);Speed(m/s);SatInView;SatInUseWIFI;AppTimestamp(s);SensorTimeStamp(s);Name_SSID;MAC_BSSID;RSS(dBm);BLUE;AppTimestamp(s);Name;MAC_Address;RSS(dBm);BLE4;AppTimestamp(s);MajorID;MinorID;RSS(dBm);SOUN;AppTimestamp(s);RMS;Pressure(Pa);SPL(dB);RFID;AppTimestamp(s);ReaderNumber(int);TagID(int);RSS_A(dBm);RSS_B(dBm);IMUX;AppTimestamp(s);SensorTimestamp(s);Counter;Acc_X(m/s^2);Acc_Y(m/s^2);Acc_Z(m/s^2);Gyr_X(rad/s);Gyr_Y(rad/s);Gyr_Z(rad/s);Mag_X(uT);;Mag_Y(uT);Mag_Z(uT);Roll(deg);Pitch(deg);Yaw(deg);Quat(1);Quat(2);Quat(3);Quat(4);Pressure(mbar);Temp(Celsius)IMUL;AppTimestamp(s);SensorTimestamp(s);Counter;Acc_X(m/s^2);Acc_Y(m/s^2);Acc_Z(m/s^2);Gyr_X(rad/s);Gyr_Y(rad/s);Gyr_Z(rad/s);Mag_X(uT);;Mag_Y(uT);Mag_Z(uT);Roll(deg);Pitch(deg);Yaw(deg);Quat(1);Quat(2);Quat(3);Quat(4);Pressure(mbar);Temp(Celsius)POSI;Timestamp(s);Counter;Latitude(degrees); Longitude(degrees);floor ID(0,1,2..4);Building ID(0,1,2..3)A part of the RAW .txt logfile:MAGN;1.249;343268.933;2.64000;-97.50000;-69.06000;0GYRO;1.249;343268.934;0.02153;0.06943;0.09880;3ACCE;1.249;343268.934;-0.24900;0.53871;9.59625;3 GNSS;1.250;1570711878.000;52.225976;5.174543;58.066;175.336;3.0;0.0;23;20ACCE;1.253;343268.936;-0.26576;0.52674;9.58428;3GYRO;1.253;343268.936;0.00809;0.06515;0.10002;3ACCE;1.253;343268.938;-0.29450;0.49561;9.57710;3GYRO;1.253;343268.938;0.00015;0.06088;0.10613;3PRES;1.253;343268.929;1011.8713;3GNSS;1.254;1570711878.000;52.225976;5.174543;58.066;175.336;3.0;0.0;23;20ACCE;1.255;343268.940;-0.29450;0.49801;9.57710;3GYRO;1.255;343268.940;-0.00596;0.05843;0.10979;3ACCE;1.260;343268.942;-0.30647;0.50280;9.55795;3GYRO;1.261;343268.942;-0.01818;0.05721;0.11529;3MAGN;1.262;343268.943;2.94000;-97.74000;-68.88000;0fileContent are the strings of the txt file as showed above.Piece of the code: def parseValues(line): valArr = [] valArr = np.fromstring(line[5:], dtype=float, sep=";") return (valArr)i = 0while i < len(fileContent): if (fileContent[i][:4] == "ACCE"): vals = parseValues(fileContent[i]) idx = vals[1] - initialSensTS df.at[idx, 'ax'] = vals[2] df.at[idx, 'ay'] = vals[3] df.at[idx, 'az'] = vals[4] df.at[idx, 'accStat'] = vals[5] i += 1The code works, but it's utterly slow at some of the df.at[idx, 'xx'] lines. See Line # 28.Line profiler output:Line # Hits Time Per Hit % Time Line Contents==============================================================22 1 1.0 1.0 0.0 i = 023 232250 542594.0 2.3 0.0 while i < len(fileContent):24 232249 294337000.0 1267.3 23.8 update_progress(i / len(fileContent))25 232249 918442.0 4.0 0.1 if (fileContent[i][:4] == "ACCE"):26 54602 1584625.0 29.0 0.1 vals = parseValues(fileContent[i])27 54602 316968.0 5.8 0.0 idx = vals[1] - initialSensTS28 54602 504189480.0 9233.9 40.8 df.at[idx, 'ax'] = vals[2]29 54602 8311109.0 152.2 0.7 df.at[idx, 'ay'] = vals[3]30 54602 4901983.0 89.8 0.4 df.at[idx, 'az'] = vals[4]31 54602 4428239.0 81.1 0.4 df.at[idx, 'accStat'] = vals[5]32 54602 132590.0 2.4 0.0 i += 1
This doesn't address the part of your question about sorting timestamps etc, but should be an efficient replacement for your 'ACCE' parsing code. import pandas as pdimport collections as collslogs_file_path = '../resources/imu_logs_raw.txt'msmt_type_dict = colls.defaultdict(list)with open(logs_file_path, 'r') as file_1: for line in file_1: curr_measure_type, *rest_str = line.split(';') rest_str[-1] = rest_str[-1].strip() msmt_type_dict[curr_measure_type].append(rest_str)acce_df = pd.DataFrame(data=msmt_type_dict['ACCE'], columns=['app_timestamp', 'sensor_timestamp', 'acc_x', 'acc_y', 'acc_z', 'accuracy'])If you can provide some more information/context I would love to take a look at the timestamp sorting aspect.
Count values from different columns of a dataframe Let's say I have the following dataframe.import pandas as pddata = { 'home': ['team1', 'team2', 'team3', 'team2'], 'away': ['team2', 'team3', 'team1', 'team1'] }df = pd.DataFrame(data)How can I count the number of time each element (team) appears in both columns ?The expected result isteam1 3team2 3team3 2
You can concatenate the columns and use .value_counts method:out = pd.concat([df['home'], df['away']]).value_counts()Output:team1 3team2 3team3 2dtype: int64You can also get the underlying numpy array, flatten it, find unique values and their counts, wrap it in a dictionary (this is by far the fastest method):out = dict(np.array(np.unique(df.values.flatten(), return_counts=True)).T)Output:{'team1': 3, 'team2': 3, 'team3': 2}
Rename items from a column in pandas I'm working in a dataset which I faced the following situation:df2['Shape'].value_counts(normalize=True)Round 0.574907Princess 0.093665Oval 0.082609Emerald 0.068820Radiant 0.059752Pear 0.041739Marquise 0.029938Asscher 0.024099Cushion 0.010807Marwuise 0.005342Uncut 0.004720Marquis 0.003602Name: Shape, dtype: float64and my goal is to make the variables 'Marquis' and 'Marwise' be included into the variable 'Marquise'. How can I combine they?
Since you didn't state any restrictions, a quick fix will be that you can first change the entries the way you desire as shown below-df2['Shape'][df2['Shape'] == 'Marquis'] = 'Marquise'df2['Shape'][df2['Shape'] == 'Marwise'] = 'Marquise'Now, run this command,df2['Shape'].value_counts(normalize=True)
Replacing href dynamic tag in python (html body) I have a script that generates some body email from a dataframe to then send them to every user.The problem is that my content is dynamic and so the links I am sending to every user (different links for different users)The html body of the email is like:<table border="2" class="dataframe"> <thead> <tr style="text-align: center;"> <th style = "background-color: orange">AF</th> <th style = "background-color: orange">Enlaces Forms</th> </tr> </thead> <tbody> <tr> <td>71</td> <td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uIG64v4DfECWMjVIRUVBVjVBSCQlQCNjPTEkJUAjdD1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uIG64v4DfECWofS8D1EufUjVIRUVBVjVBSCQlQCNjPTEkJUAjdD1n</a></td> </tr> <tr> <td>64</td> <td><a href="https://forms.office.com/Pages/ResponsePage.aspx?id=uIG64v4DfECWofS8D1EufU4jQyVDREMk4zOSQlQCNjPTEkJUAjdD1n" target="_blank">https://forms.office.com/Pages/ResponsePage.aspx?id=uIG64v4DfECWofS8D1EufUVVGWFRUNjQyVDREMk4zOSQlQCNjPTEkJUAjdD1n</a></td> </tr> </tbody></table>I am replacing html tags like this:table2=df[['AF','Links']].to_html(index=False, render_links=True, escape=False).replace('<tr style="text-align: right;">','<tr style="text-align: center;">').replace('<table border="1"','<table border="2"').replace('<th>','<th style = "background-color: orange">').replace(f'<td><a href="{enlace}"','<td><a href="LINK"')but I do not know how to make it work for the tag "href".My goal is to rename the hyperlinks with some words to make them more readable in the body mail.How can I do that?EDIT:When I try to implement jinja2 Template:import jinja2from jinja2 import Templatetemp2='<a href=""> </a>'linkdef=Template(temp2).render(url=f"{enlace_tabla['LINKS']}",enlace="Flask") table2=enlace_tabla[['AF',linkdef]].to_html(index=False, render_links=True, escape=False).replace('<tr style="text-align: right;">','<tr style="text-align: center;">').replace('<table border="1"','<table border="2"').replace('<th>','<th style = "background-color: orange">')The following error is raised:KeyError: '[\'<a href=""> </a>\'] not in index'
I would do this in different way.First I would create column with <a href="{url}">SOME TEXT</a>def convert(row): return f'<a href={row["LINKS"]}>CLICK THIS LINK</a>'df['LINKS_HTML'] = df.apply(convert, axis=1)If I would have column with text for every link then it could bedef convert(row): return f'<a href={row["LINKS"]}>{row["TEXT"]}</a>'df['LINKS_HTML'] = df.apply(convert, axis=1)And later I would render table using column LINKS_HTML instead of LINKS(and without render_links=True)html = df[['AF', 'LINKS_HTML']].to_html(escape=False, index=False)Minimal working example:import pandas as pddata = { 'AF': [1, 2, 3], 'LINKS': [ 'https://httpbin.org/get?arg=101', 'https://httpbin.org/get?arg=102', 'https://httpbin.org/get?arg=103', ], 'TEXT': ['Text 1', 'Text 2', 'Text 3']}df = pd.DataFrame(data)#print(df)def convert(row): #return f'<a href={row["LINKS"]}>CLICK THIS LINK</a>' return f'<a href={row["LINKS"]}>{row["TEXT"]}</a>'df['LINKS_HTML'] = df.apply(convert, axis=1) html = df[['AF', 'LINKS_HTML']].to_html(escape=False, index=False)print(html)Result:<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>AF</th> <th>LINKS_HTML</th> </tr> </thead> <tbody> <tr> <td>1</td> <td><a href=https://httpbin.org/get?arg=101>Text 1</a></td> </tr> <tr> <td>2</td> <td><a href=https://httpbin.org/get?arg=102>Text 2</a></td> </tr> <tr> <td>3</td> <td><a href=https://httpbin.org/get?arg=103>Text 3</a></td> </tr> </tbody></table>Or I would use jinja2 to generate table without to_html()import pandas as pdimport jinja2data = { 'AF': [1, 2, 3], 'LINKS': [ 'https://httpbin.org/get?arg=101', 'https://httpbin.org/get?arg=102', 'https://httpbin.org/get?arg=103', ], 'TEXT': ['Text 1', 'Text 2', 'Text 3']}df = pd.DataFrame(data)template = '''<table border="2" class="dataframe"> <thead> <tr style="text-align: center;"> <th style="background-color: orange">AF</th> <th style="background-color: orange">Enlaces Forms</th> </tr> </thead> <tbody> {%- for index, row in data.iterrows() %} <tr> <td>{{ row["AF"] }}</td> <td><a href="{{ row["LINKS"] }}">{{ row["TEXT"] }}</a></td> </tr> {%- endfor %} </tbody></table>'''html = jinja2.Template(template).render(data=df)print(html)Result:<table border="2" class="dataframe"> <thead> <tr style="text-align: center;"> <th style="background-color: orange">AF</th> <th style="background-color: orange">Enlaces Forms</th> </tr> </thead> <tbody> <tr> <td>1</td> <td><a href="https://httpbin.org/get?arg=101">Text 1</a></td> </tr> <tr> <td>2</td> <td><a href="https://httpbin.org/get?arg=102">Text 2</a></td> </tr> <tr> <td>3</td> <td><a href="https://httpbin.org/get?arg=103">Text 3</a></td> </tr> </tbody></table>
xgboost model prediction error : Input numpy.ndarray must be 2 dimensional I have a model that's trained locally and deployed to an engine, so that I can make inferences / invoke endpoint. When I try to make predictions, I get the following exception.raise ValueError('Input numpy.ndarray must be 2 dimensional')ValueError: Input numpy.ndarray must be 2 dimensional My model is a xgboost model with some pre-processing (variable encoding) and hyper-parameter tuning. Code to train the model:import pandas as pdimport picklefrom xgboost import XGBRegressorfrom sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCVfrom sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import OneHotEncoder # split df into train and testX_train, X_test, y_train, y_test = train_test_split(df.iloc[:,0:21], df.iloc[:,-1], test_size=0.1)X_train.shape(1000,21)# Encode categorical variables cat_vars = ['cat1','cat2','cat3']cat_transform = ColumnTransformer([('cat', OneHotEncoder(handle_unknown='ignore'), cat_vars)], remainder='passthrough')encoder = cat_transform.fit(X_train)X_train = encoder.transform(X_train)X_test = encoder.transform(X_test)X_train.shape(1000,420)# Define a xgboost regression modelmodel = XGBRegressor()# Do hyper-parameter tuning.....# Fit modelmodel.fit(X_train, y_train)Here's what model object looks like:XGBRegressor(colsample_bytree=xxx, gamma=xxx, learning_rate=xxx, max_depth=x, n_estimators=xxx, subsample=xxx)My test data is a string of float values which is turned into an array as the data must be passed as numpy array.testdata = [........., 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2000, 200, 85, 412412, 123, 41, 552, 50000, 512, 0.1, 10.0, 2.0, 0.05]I have tried to reshape the numpy array from 1d to 2d, however, that doesn't work as the number of features between test data and trained model do not match.My question is how do I pass a numpy array same as the length of # of features in trained model? Any work around ideas? I am able to make predictions by passing test data as a list locally.More info on inference script here: https://github.com/aws-samples/amazon-sagemaker-local-mode/blob/main/xgboost_script_mode_local_training_and_serving/code/inference.pyTraceback (most recent call last):File "/miniconda3/lib/python3.6/site-packages/sagemaker_containers/_functions.py", line 93, in wrapperreturn fn(*args, **kwargs)File "/opt/ml/code/inference.py", line 75, in predict_fnprediction = model.predict(input_data)File "/miniconda3/lib/python3.6/site-packages/xgboost/sklearn.py", line 448, in predicttest_dmatrix = DMatrix(data, missing=self.missing, nthread=self.n_jobs)File "/miniconda3/lib/python3.6/site-packages/xgboost/core.py", line 404, in __init__self._init_from_npy2d(data, missing, nthread)File "/miniconda3/lib/python3.6/site-packages/xgboost/core.py", line 474, in _init_from_npy2draise ValueError('Input numpy.ndarray must be 2 dimensional')ValueError: Input numpy.ndarray must be 2 dimensionalWhen I attempt to reshape the test data to 2d numpy array, using testdata.reshape(-1,1), I run into feature_names mismatch exception.File "/opt/ml/code/inference.py", line 75, in predict_fn3n0u6hucsr-algo-1-qbiyg | prediction = model.predict(input_data)3n0u6hucsr-algo-1-qbiyg | File "/miniconda3/lib/python3.6/site-packages/xgboost/sklearn.py", line 456, in predict3n0u6hucsr-algo-1-qbiyg | validate_features=validate_features)3n0u6hucsr-algo-1-qbiyg | File "/miniconda3/lib/python3.6/site-packages/xgboost/core.py", line 1284, in predict3n0u6hucsr-algo-1-qbiyg | self._validate_features(data)3n0u6hucsr-algo-1-qbiyg | File "/miniconda3/lib/python3.6/site-packages/xgboost/core.py", line 1690, in _validate_features3n0u6hucsr-algo-1-qbiyg | data.feature_names))3n0u6hucsr-algo-1-qbiyg | ValueError: feature_names mismatch: ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15',Update: I can retrieve the feature names for the model by running model.get_booster().feature_names. Is there a way I can use these names and assign to test data point so that they are consistent?['f0', 'f1', 'f2', 'f3', 'f4', 'f5',......'f417','f418','f419']
I think the solution is to provide the test data as the same data type as the train data.Thank you for the comment. With the added information that after encoding the datatype of X_train is scipy.sparse.csr.csr_matrix and y_train is a Pandas series. If there are no memory constrains we can transform both to numpy array by using:model.fit(X_train.toarray(), y_train.to_numpy())Reference to:scipy manual: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.toarray.htmlpandas manual: https://pandas.pydata.org/docs/reference/api/pandas.Series.to_numpy.html
Get the average mean of entries per month with datetime in Pandas I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).My df is something like this: ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')ufo['Time']=pd.to_datetime(ufo.Time)Where the head looks like this: So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?I have tried: ufo.groupby(ufo.Time.month).mean()But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months. EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.
You could do something like this:# count the total months in the recordsdef total_month(x): return x.max().year -x.min().year + 1new_df = ufo.groupby(ufo.Time.dt.month).Time.agg(['size', total_month])new_df['mean_count'] = new_df['size'] /new_df['total_month']Output: size total_month mean_countTime 1 862 57 15.1228072 817 70 11.6714293 1096 55 19.9272734 1045 68 15.3676475 1168 53 22.0377366 3059 71 43.0845077 2345 65 36.0769238 1948 64 30.4375009 1635 67 24.40298510 1723 65 26.50769211 1509 50 30.18000012 1034 56 18.464286
How do I select the minimum and maximum values for a horizontal lollipop plot/dumbbell chart? I have created a dumbbell chart but I am getting too many minimum and maximum values for each category type. I want to display only one skyblue dot (the minimum price) and one green dot (the maximum price) per area. This is what the chart looks like so far:My dumbbell chartHere is my DataFrame:The DataFrameHere is a link to the full dataset:https://drive.google.com/open?id=1PpI6PlO8ox2vKfM4aGmEUexCPPWa59S_ And here is my code so far: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns db = df[['minPrice','maxPrice', 'neighbourhood_hosts']] ordered_db = db.sort_values(by='minPrice') my_range=db['neighbourhood_hosts'] plt.figure(figsize=(8,6)) plt.hlines(y=my_range, xmin=ordered_db['minPrice'], xmax=ordered_db['maxPrice'], color='grey', alpha=0.4) plt.scatter(ordered_db['minPrice'], my_range, color='skyblue', alpha=1, label='minimum price') plt.scatter(ordered_db['maxPrice'], my_range, color='green', alpha=0.4 , label='maximum price') plt.legend() plt.title("Comparison of the minimum and maximum prices") plt.xlabel('Value range') plt.ylabel('Area')How can I format my code so that I only have one minimum and one maximum value for each area?
As per conversation, here is the script:import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.read_csv('dumbbell data.csv')db = df[['minPrice','maxPrice', 'neighbourhood_hosts']]#create max and min price based on area namemax_price = db.groupby(['neighbourhood_hosts'])['maxPrice'].max().reset_index()min_price = db.groupby(['neighbourhood_hosts'])['minPrice'].min().reset_index()var_price = pd.DataFrame()var_price['range'] = max_price.maxPrice-min_price.minPricevar_price['neighbourhood_hosts'] = min_price['neighbourhood_hosts']var_price = var_price.sort_values(by='range')#sort max and min price according to variancemax_price = max_price.reindex(var_price.index)min_price = min_price.reindex(var_price.index)plt.figure(figsize=(8,6))plt.hlines(y=min_price['neighbourhood_hosts'], xmin=min_price['minPrice'], xmax=max_price['maxPrice'], color='grey', alpha=0.4)plt.scatter(min_price['minPrice'], min_price['neighbourhood_hosts'], color='skyblue', alpha=1, label='minimum price')plt.scatter(max_price['maxPrice'], max_price['neighbourhood_hosts'], color='green', alpha=0.4 , label='maximum price')plt.legend()plt.title("Comparison of the minimum and maximum prices")plt.xlabel('Value range')plt.ylabel('Area')
Finding the indexes of the N maximum values across an axis in Pandas I know that there is a method .argmax() that returns the indexes of the maximum values across an axis.But what if we want to get the indexes of the 10 highest values across an axis? How could this be accomplished?E.g.:data = pd.DataFrame(np.random.random_sample((50, 40)))
IIUC, say, if you want to get the index of the top 10 largest numbers of column col:data[col].nlargest(10).index
How to create multiple line graph using seaborn and find rate? I need help to create a multiple line graph using below DataFrame num user_id first_result second_result result date point1 point2 point3 point40 0 1480R clear clear pass 9/19/2016 clear consider clear consider1 1 419M consider consider fail 5/18/2016 consider consider clear clear2 2 416N consider consider fail 11/15/2016 consider consider consider consider3 3 1913I consider consider fail 11/25/2016 consider consider consider clear4 4 1938T clear clear pass 8/1/2016 clear consider clear clear5 5 1530C clear clear pass 6/22/2016 clear clear consider clear6 6 1075L consider consider fail 9/13/2016 consider consider clear consider7 7 1466N consider clear fail 6/21/2016 consider clear clear consider8 8 662V consider consider fail 11/1/2016 consider consider clear consider9 9 1187Y consider consider fail 9/13/2016 consider consider clear clear10 10 138T consider consider fail 9/19/2016 consider clear consider consider11 11 1461Z consider clear fail 7/18/2016 consider consider clear consider12 12 807N consider clear fail 8/16/2016 consider consider clear clear13 13 416Y consider consider fail 10/2/2016 consider clear clear clear14 14 638A consider clear fail 6/21/2016 consider clear consider cleardata file linke data.xlsx or data as dictdata = {'num': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14}, 'user_id': {0: '1480R', 1: '419M', 2: '416N', 3: '1913I', 4: '1938T', 5: '1530C', 6: '1075L', 7: '1466N', 8: '662V', 9: '1187Y', 10: '138T', 11: '1461Z', 12: '807N', 13: '416Y', 14: '638A'}, 'first_result': {0: 'clear', 1: 'consider', 2: 'consider', 3: 'consider', 4: 'clear', 5: 'clear', 6: 'consider', 7: 'consider', 8: 'consider', 9: 'consider', 10: 'consider', 11: 'consider', 12: 'consider', 13: 'consider', 14: 'consider'}, 'second_result': {0: 'clear', 1: 'consider', 2: 'consider', 3: 'consider', 4: 'clear', 5: 'clear', 6: 'consider', 7: 'clear', 8: 'consider', 9: 'consider', 10: 'consider', 11: 'clear', 12: 'clear', 13: 'consider', 14: 'clear'}, 'result': {0: 'pass', 1: 'fail', 2: 'fail', 3: 'fail', 4: 'pass', 5: 'pass', 6: 'fail', 7: 'fail', 8: 'fail', 9: 'fail', 10: 'fail', 11: 'fail', 12: 'fail', 13: 'fail', 14: 'fail'}, 'date': {0: '9/19/2016', 1: '5/18/2016', 2: '11/15/2016', 3: '11/25/2016', 4: '8/1/2016', 5: '6/22/2016', 6: '9/13/2016', 7: '6/21/2016', 8: '11/1/2016', 9: '9/13/2016', 10: '9/19/2016', 11: '7/18/2016', 12: '8/16/2016', 13: '10/2/2016', 14: '6/21/2016'}, 'point1': {0: 'clear', 1: 'consider', 2: 'consider', 3: 'consider', 4: 'clear', 5: 'clear', 6: 'consider', 7: 'consider', 8: 'consider', 9: 'consider', 10: 'consider', 11: 'consider', 12: 'consider', 13: 'consider', 14: 'consider'}, 'point2': {0: 'consider', 1: 'consider', 2: 'consider', 3: 'consider', 4: 'consider', 5: 'clear', 6: 'consider', 7: 'clear', 8: 'consider', 9: 'consider', 10: 'clear', 11: 'consider', 12: 'consider', 13: 'clear', 14: 'clear'}, 'point3': {0: 'clear', 1: 'clear', 2: 'consider', 3: 'consider', 4: 'clear', 5: 'consider', 6: 'clear', 7: 'clear', 8: 'clear', 9: 'clear', 10: 'consider', 11: 'clear', 12: 'clear', 13: 'clear', 14: 'consider'}, 'point4': {0: 'consider', 1: 'clear', 2: 'consider', 3: 'clear', 4: 'clear', 5: 'clear', 6: 'consider', 7: 'consider', 8: 'consider', 9: 'clear', 10: 'consider', 11: 'consider', 12: 'clear', 13: 'clear', 14: 'clear'} }I need to create a bar graph and a line graph, I have created the bar graph using point1 where x = consider, clear and y = count of consider and clearbut I have no idea how to create a line graph by this scenariox = datey = pass rate (%)Pass Rate is a number of clear/(consider + clear)graph the rate for first_result, second_result, result all on the same graphand the graph should look like belowplease comment or answer how can I do it. if I can get an idea of grouping dates and getting the ratio then also great.
Here's my idea how to do it:# first convert all `clear`, `consider` to 1,0tmp_df = df[['first_result', 'second_result']].apply(lambda x: x.eq('clear').astype(int))# convert `pass`, `fail` to 1,0tmp_df['result'] = df.result.eq('pass').astype(int)# copy the datetmp_df['date'] = df['date']# groupby and compute mean, i.e. number_pass/total_counttmp_df = tmp_df.groupby('date').mean()tmp_df.plot()Output for this dataset
How to compare columns with equal values? I have a dataframe which looks as follows: colA colB0 2 11 4 22 3 73 8 54 7 2I have two datasets one with customer code and other information and the other with addresses plus related customer code.I did a merge with the two bases and now I want to return the lines where the values ​​in the columns are the same, but I'm not able to do it.Can someone help me?Thanks
you can try :dfs=df.loc[df['colA']==df['colB']]
rename the pandas Series I have some wire thing when renaming the pandas Series by the datetime.dateimport pandas as pda = pd.Series([1, 2, 3, 4], name='t')I got a is:0 11 22 33 4Name: t, dtype: int64Then, I have:ts = pd.Series([pd.Timestamp('2016-05-16'), pd.Timestamp('2016-05-17'), pd.Timestamp('2016-05-18'), pd.Timestamp('2016-05-19')], name='time')with ts as:0 2016-05-161 2016-05-172 2016-05-183 2016-05-19Name: time, dtype: datetime64[ns]Now, if I do:ts_date = ts.apply(lambda x: x.date())dates = ts_date.unique()I got dates as:array([datetime.date(2016, 5, 16), datetime.date(2016, 5, 17), datetime.date(2016, 5, 18), datetime.date(2016, 5, 19)], dtype=object)I have two approaches. The wired thing is, if I do the following renaming (approach 1):for one_date in dates: a.rename(one_date) print one_date, a.nameI got:2016-05-16 t2016-05-17 t2016-05-18 t2016-05-19 tBut if I do it like this (approach 2):for one_date in dates: a = pd.Series(a, name=one_date) print one_date, a.name2016-05-16 2016-05-162016-05-17 2016-05-172016-05-18 2016-05-182016-05-19 2016-05-19My question is: why the method rename does not work (in approach 1)?
Because rename does not change the object unless you set the inplace argument as True, as seen in the docs.Notice that the copy argument can be used so you don't have to create a new series passing the old series as argument, like in your second example.
Pandas Filter on date for quarterly ends In the index column I have a list of dates:DatetimeIndex(['2010-12-31', '2011-01-02', '2011-01-03', '2011-01-29', '2011-02-26', '2011-02-28', '2011-03-26', '2011-03-31', '2011-04-01', '2011-04-03', ... '2016-02-27', '2016-02-29', '2016-03-26', '2016-03-31', '2016-04-01', '2016-04-03', '2016-04-30', '2016-05-31', '2016-06-30', '2016-07-02'], dtype='datetime64[ns]', length=123, freq=None)However I want to filter out all those which the month and day equal to 12/31, 3/31, 6/30, 9/30 to get the value at the end of the quarter. Is there a good way of going about this?
You can use is_quarter_end to filter the row labels:In [151]:df = pd.DataFrame(np.random.randn(400,1), index= pd.date_range(start=dt.datetime(2016,1,1), periods=400))df.loc[df.index.is_quarter_end]Out[151]: 02016-03-31 -0.4741252016-06-30 0.9317802016-09-30 -0.2812712016-12-31 0.325521
Cannot get pandas to open CSV [Python, Jupyter, Pandas] OBJECTIVEUsing Jupyter notebooks, import a csv file for data manipulationAPPROACHImport necessary libraries for statistical analysis (pandas, matplotlib, sklearn, etc.)Import data set using pandasManipulate dataCODEimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib import stylestyle.use("ggplot")import pandas as pdfrom sklearn.cluster import KMeansdata = pd.read_csv("../data/walmart-stores.csv")print(data)ERROROSError: File b'../data/walmart-stores.csv' does not existFOLDER STRUCTUREAnconda env kmean.ipynb data walmart-stores.csv (other folders [for anaconda env]) (other folders)QUESTION(S)The error clearly states that the csv file cannot be found. I imagine it has to do with the project running in an Anaconda environment, but I thought this was the purpose of Anaconda environments in the first place. Am I wrong?After answering the question, are there any other suggestions on how I should structure my Jupyter Notebooks when using Anaconda?NOTES: I am new to python, anaconda, and jupyter notebooks so please disregard are naivety/stupidity. Thank you!
Fellow newbie here!Try removing the "../" from your data locationChangedata = pd.read_csv("../data/walmart-stores.csv")to data = pd.read_csv("data/walmart-stores.csv")
Find values in numpy array space-efficiently I am trying to create a copy of my numpy array that contains only certain values. This is the code I was using:A = np.array([[1,2,3],[4,5,6],[7,8,9]])query_val = 5B = (A == query_val) * np.array(query_val, dtype=np.uint16)... which does exactly what I want.Now, I'd like query_val to be more than just one value. The answer here: Numpy where function multiple conditions suggests using a logical and operation, but that's very space inefficient because you use == several times, creating multiple intermediate results.In my case, that means I don't have enough RAM to do it. Is there a way to do this properly in native numpy with minimal space overhead?
Here's one approach using np.searchsorted -def mask_in(a, b): idx = np.searchsorted(b,a) idx[idx==b.size] = 0 return np.where(b[idx]==a, a,0)Sample run -In [356]: aOut[356]: array([[5, 1, 4], [4, 5, 6], [2, 4, 9]])In [357]: bOut[357]: array([2, 4, 5])In [358]: mask_in(a,b)Out[358]: array([[5, 0, 4], [4, 5, 0], [2, 4, 0]])
tensorflow.python.framework.errors_impl.AlreadyExistsError I trained a ImageClassifier model using Teachable Machine and I tried to run the following code on VScode in python 3.8from keras.models import load_modelfrom PIL import Image, ImageOpsimport numpy as np# Load the modelmodel = load_model('keras_model.h5')# Create the array of the right shape to feed into the keras model# The 'length' or number of images you can put into the array is# determined by the first position in the shape tuple, in this case 1.data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)# Replace this with the path to your imageimage = Image.open('1.jpeg')#resize the image to a 224x224 with the same strategy as in TM2:#resizing the image to be at least 224x224 and then cropping from the centersize = (224, 224)image = ImageOps.fit(image, size, Image.ANTIALIAS)#turn the image into a numpy arrayimage_array = np.asarray(image)# Normalize the imagenormalized_image_array = (image_array.astype(np.float32) / 127.0) - 1# Load the image into the arraydata[0] = normalized_image_array# run the inferenceprediction = model.predict(data)print(prediction)And I got the following errors2021-09-29 11:37:52.587380: E tensorflow/core/lib/monitoring/collection_registry.cc:77] Cannot register 2 metrics with the same name: /tensorflow/api/keras/dropout/temp_rate_is_zeroTraceback (most recent call last): File "c:/Users/sumuk/OneDrive/Documents/ML/converted_keras/1.py", line 1, in <module> from keras.models import load_model File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\__init__.py", line 25, in <module> from keras import models File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\models.py", line 20, in <module> from keras import metrics as metrics_module File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\metrics.py", line 26, in <module> from keras import activations File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\activations.py", line 20, in <module> from keras.layers import advanced_activations File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\__init__.py", line 31, in <module> from keras.layers.preprocessing.image_preprocessing import CenterCrop File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\preprocessing\image_preprocessing.py", line 24, in <module> from keras.preprocessing import image as image_preprocessing File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\preprocessing\__init__.py", line 26, in <module> from keras.utils import all_utils as utils File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\all_utils.py", line 34, in <module> from keras.utils.multi_gpu_utils import multi_gpu_model File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\multi_gpu_utils.py", line 20, in <module> from keras.layers.core import Lambda File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\core\__init__.py", line 20, in <module> from keras.layers.core.dropout import Dropout File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\core\dropout.py", line 26, in <module> keras_temporary_dropout_rate = tf.__internal__.monitoring.BoolGauge( File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\monitoring.py", line 360, in __init__ super(BoolGauge, self).__init__('BoolGauge', _bool_gauge_methods, File "C:\Users\sumuk\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\monitoring.py", line 135, in __init__ self._metric = self._metric_methods[self._label_length].create(*args)tensorflow.python.framework.errors_impl.AlreadyExistsError: Another metric with the same name already exists.Here is the model,I couldn't find any related solutions online, what should be done?Thank you
To run this code , You need to usefrom tensorflow.keras.models import load_modelin place offrom keras.models import load_modelThis issue comes due to mismatch of tensorflow and keras version available in your system. Make sure you are using same version of tensorflow and keras or atleast latest tensorflow 2.7 and try executing the same code again. Let us know if issue still persists.
Parsing (from text) a table with two-row header I'm parsing the output of a .ipynb. The output was generated as plain text (using print) instead of a dataframe (not using print), in the spirit of:print( athletes.groupby('NOC').count() )I came up with hacks (e.g. using pandas.read_fwf()) to the various cases, but I was wondering if anyone has an idea for a more elegant solution.It keeps nagging me that it's weird (bad design?) that the default print of a pandas.dataframe can't be parsed by pandas.EDIT: added more examples to the first tableTable 1 Name DisciplineNOC United States of America 615 615Japan 586 586Australia 470 470People's Republic of China 401 401Germany 400 400Table 2 NameNOC DisciplineUnited States of America Athletics 144Germany Athletics 95Great Britain Athletics 75Italy Athletics 73Japan Athletics 70Bermuda Triathlon 1Libya Athletics 1Palestine Athletics 1San Marino Swimming 1Kiribati Athletics 1Table 3 Name NOC Discipline1410 CA Liliana Portugal Athletics1411 CABAL Juan-Sebastian Colombia Tennis1412 CABALLERO Denia Cuba Athletics1413 CABANA PEREZ Cristina Spain Judo1414 CABECINHA Ana Portugal Athletics
Assuming the following input:text = ''' Name DisciplineNOC United States of America 615 615Japan 586 586Australia 470 470People's Republic of China 401 401Germany 400 400'''You can use pandas.read_csv with the '\s\s+' separator:import pandas as pdimport iodf = pd.read_csv(io.StringIO(text), sep='\s\s+', engine='python')Output:>>> df.indexIndex(['United States of America', 'Japan', 'Australia', 'People's Republic of China', 'Germany'], dtype='object', name='NOC')>>> df.columnsIndex(['Name', 'Discipline'], dtype='object')>>> df Name DisciplineNOC United States of America 615 615Japan 586 586Australia 470 470People's Republic of China 401 401Germany 400 400
Apply fuzzy ratio to two dataframes I have two dataframes where I want to fuzzy string compare & apply my function to two dataframes:sample1 = pd.DataFrame(data1.sample(n=200, random_state=42))sample2 = pd.DataFrame(data2.sample(n=200, random_state=13))def get_ratio(row): sample1 = row['address'] sample2 = row['address'] return fuzz.token_set_ratio(sample1, sample2)match = data[data.apply(get_ratio, axis=1) >= 78] #I want to apply get_ratio to both sample1 and sample2no_matched = data[data.apply(get_ratio, axis=1) <= 77] #I want to apply get_ratio to both sample1 and sample2Thanks in advance for your help!
You need to create the permutations of your addresses. Then use that to compare the matching ones. You can find a similar question here.For your case first you need to create permutations:combs = list(itertools.product(data1["address"], data2["address"]))combs = pd.DataFrame(combs)Then use the proper method for matching:combs['score'] = combs.apply(lambda x: fuzz.token_set_ratio(x[0],x[1]), axis=1)now based on the score you can find the ones that have matched or have not matched.I advise you do try to group and clean the addresses first (i.e., lowering the case, removing the duplicates) Otherwise it might take a very long time to compute.
How can I reshape a Mat to a tensor to use in deep neural network in c++? I want to deploy a trained deep neural network in c++ application. After reading image and using blobFromImage( I used opencv 4.4 ) function I received the blew error which is indicate I have problem with dimensions and shape of my tensor. The input of deep neural network is (h=150, w=100, channel=3). Is blobFromImage function the only way to make tensor? how can I fix this problem? Thanks in advance.I put my code and the error.#include <iostream>#include <opencv2/opencv.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <opencv2/highgui/highgui.hpp>#include <vector>int main() { std::vector< cv::Mat > outs; std::cout << "LOAD DNN in CPP Project!" << std::endl; cv::Mat image = cv::imread("example.png",1/*, cv::IMREAD_GRAYSCALE*/); cv::dnn::Net net; net = cv::dnn::readNetFromONNX("model.onnx"); cv::Mat blob; cv::dnn::blobFromImage(image, blob, 1/255, cv::Size(100,150), cv::Scalar(0,0,0), false,false); net.setInput(blob); net.forward( outs, "output"); return 0; }and the error is:global /home/hasa/opencv4.4/opencv-4.4.0/modules/dnn/src/dnn.cpp (3441) getLayerShapesRecursively OPENCV/DNN: [Convolution]:(model/vgg19/block1_conv1/BiasAdd:0): getMemoryShapes() throws exception. inputs=1 outputs=0/1 blobs=2[ERROR:0] global /home/hasa/opencv4.4/opencv-4.4.0/modules/dnn/src/dnn.cpp (3447) getLayerShapesRecursively input[0] = [ 1 100 3 150 ][ERROR:0] global /home/hasa/opencv4.4/opencv-4.4.0/modules/dnn/src/dnn.cpp (3455) getLayerShapesRecursively blobs[0] = CV_32FC1 [ 64 3 3 3 ][ERROR:0] global /home/hasa/opencv4.4/opencv-4.4.0/modules/dnn/src/dnn.cpp (3455) getLayerShapesRecursively blobs[1] = CV_32FC1 [ 64 1 ][ERROR:0] global /home/hasa/opencv4.4/opencv-4.4.0/modules/dnn/src/dnn.cpp (3457) getLayerShapesRecursively Exception message: OpenCV(4.4.0) /home/hasa/opencv4.4/opencv- 4.4.0/modules/dnn/src/layers/convolution_layer.cpp:346: error: (-2:Unspecified error) Number of input channels should be multiple of 3 but got 100 in function 'getMemoryShapes'terminate called after throwing an instance of 'cv::Exception'what(): OpenCV(4.4.0) /home/hasa/opencv4.4/opencv- 4.4.0/modules/dnn/src/layers/convolution_layer.cpp:346: error: (-2:Unspecified error) Number of input channels should be multiple of 3 but got 100 in function 'getMemoryShapes'Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
The following code works for me. The only difference is that I'm loading tensorflow model.inputNet = cv::dnn::readNetFromTensorflow(pbFilePath);// load image of rowsxcols = 160x160cv::Mat img, imgn, blob;img = cv::imread("1.jpg");//cv::cvtColor(img, img, CV_GRAY2RGB);// convert gray to color image// normalize image (if needed)//img.convertTo(imgn, CV_32FC3);//float32, 3channels (depends on your model)//imgn = (imgn-127.5)/128.0;//normalized crop (in rgb)//extract feature vectorcv::dnn::blobFromImage(imgn, blob, 1.0, cv::Size(160, 160),0, false, false);inputNet.setInput(blob);cv::Mat feature_vector = inputNet.forward();
Tensorflow Object-API: convert ssd model to tflite and use it in python I have a hard time to convert a given tensorflow model into a tflite model and then use it. I already posted a question where I described my problem but didn't share the model I was working with, because I am not allowed to. Since I didn't find an answer this way, I tried to convert a public model (ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu).Here is a colab tutorial from the object detection api. I just run the whole script without changes (its the same model) and downloaded the generated models (with and without metadata). I uploaded them here together with a sample picture from the coco17 train dataset.I tried to use those models directly in python, but the results feel like garbage.Here is the code I used, I followed this guide. I changed the indexes for rects, scores and classes because otherwise the results were not in the right format.#interpreter = tf.lite.Interpreter("original_models/model.tflite")interpreter = tf.lite.Interpreter("original_models/model_with_metadata.tflite")interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()size = 640def draw_rect(image, box): y_min = int(max(1, (box[0] * size))) x_min = int(max(1, (box[1] * size))) y_max = int(min(size, (box[2] * size))) x_max = int(min(size, (box[3] * size))) # draw a rectangle on the image cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (255, 255, 255), 2)file = "images/000000000034.jpg"img = cv2.imread(file)new_img = cv2.resize(img, (size, size))new_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2RGB)interpreter.set_tensor(input_details[0]['index'], [new_img.astype("f")])interpreter.invoke()rects = interpreter.get_tensor( output_details[1]['index'])scores = interpreter.get_tensor( output_details[0]['index'])classes = interpreter.get_tensor( output_details[3]['index'])for index, score in enumerate(scores[0]): draw_rect(new_img,rects[0][index]) #print(rects[0][index]) print("scores: ",scores[0][index]) print("class id: ", classes[0][index]) print("______________________________")cv2.imshow("image", new_img)cv2.waitKey(0)cv2.destroyAllWindows()This leads to the following console outputscores: 0.20041436class id: 51.0______________________________scores: 0.08925027class id: 34.0______________________________scores: 0.079722285class id: 34.0______________________________scores: 0.06676647class id: 71.0______________________________scores: 0.06626186class id: 15.0______________________________scores: 0.059938848class id: 86.0______________________________scores: 0.058229476class id: 34.0______________________________scores: 0.053791136class id: 37.0______________________________scores: 0.053478718class id: 15.0______________________________scores: 0.052847564class id: 43.0______________________________and the resulting image.I tried different images from the orinal training dataset and never got good results. I think the output layer is broken or maybe some postprocessing is missing?I also tried to use the converting method given from the offical tensorflow documentaion.import tensorflow as tfsaved_model_dir = 'tf_models/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/saved_model/' # Convert the model converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) # path to the SavedModel directorytflite_model = converter.convert() # Save the model.with open('model.tflite', 'wb') as f: f.write(tflite_model)But when I try to use the model, I get a ValueError: Cannot set tensor: Dimension mismatch. Got 640 but expected 1 for dimension 1 of input 0.Has anyone an idea what I am doing wrong?Update: After Farmmakers advice, I tried changing the input dimensions of the model generating by the short script at the end. The shape before was:[{'name': 'serving_default_input_tensor:0', 'index': 0, 'shape': array([1, 1, 1, 3], dtype=int32), 'shape_signature': array([ 1, -1, -1, 3], dtype=int32), 'dtype': numpy.uint8, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]So adding one dimension would not be enough. Therefore I used interpreter.resize_tensor_input(0, [1,640,640,3]) . Now it works to feed an image through the net.Unfortunately I sill can't make any sense of the output. Here is the print of the output details:[{'name': 'StatefulPartitionedCall:6', 'index': 473, 'shape': array([ 1, 51150, 4], dtype=int32), 'shape_signature': array([ 1, 51150, 4], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:0', 'index': 2233, 'shape': array([1, 1], dtype=int32), 'shape_signature': array([ 1, -1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:5', 'index': 2198, 'shape': array([1], dtype=int32), 'shape_signature': array([1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:7', 'index': 493, 'shape': array([ 1, 51150, 91], dtype=int32), 'shape_signature': array([ 1, 51150, 91], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:1', 'index': 2286, 'shape': array([1, 1, 1], dtype=int32), 'shape_signature': array([ 1, -1, -1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:2', 'index': 2268, 'shape': array([1, 1], dtype=int32), 'shape_signature': array([ 1, -1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:4', 'index': 2215, 'shape': array([1, 1], dtype=int32), 'shape_signature': array([ 1, -1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}, {'name': 'StatefulPartitionedCall:3', 'index': 2251, 'shape': array([1, 1, 1], dtype=int32), 'shape_signature': array([ 1, -1, -1], dtype=int32), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}] I added the so generated tflite model to the google drive.Update2: I added a directory to the google drive which contains a notebook that uses the full size model and produces the correct output. If you execute the whole notebook it should produce the following image to your disk.
For the models from Object Detection APIs to work well with TFLite, you have to convert it to TFLite-friendly graph that has custom op.https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md(TF1 doc)You can also try using TensorFlow Lite Model Maker
Comparing a `tf.constant` to an integer In TensorFlow, I have a tf.while_loop, where the body argument is defined as the following function:def loop_body(step_num, x): if step_num == 0: x += 1 else: x += 2 step_num = tf.add(step_num, 1) return step_num, xThe problem is that the line step_num == 0 is never True, even though the initial value of step_num is 0. I am assuming that this is because step_num is not an integer, but in fact, a tf.constant which was defined outside the loop: step_num = tf.constant(0). So I am comparing a tf.constant to a Python integer, which will be False.What should I use instead for this comparison?
First approach: using tf.cond:def loop_body(step_num, x): x = tf.cond(tf.equal(step_num,0),lambda :x+1,lambda :x+2) step_num = tf.add(step_num, 1) return step_num, xSecond approach: using autograph:from tensorflow.contrib import autograph as agag.to_graph(loop_body2)(step_num, x)An example:import tensorflow as tffrom tensorflow.contrib import autograph as agdef loop_body(step_num, x): x = tf.cond(tf.equal(step_num,0),lambda :x+1,lambda :x+2) step_num = tf.add(step_num, 1) return step_num, xdef loop_body2(step_num, x): if step_num == 0: x += 1 else: x += 2 step_num = tf.add(step_num, 1) return step_num, xstep_num = tf.constant(0)x = tf.constant(2)result1 = loop_body(step_num, x)result2 = ag.to_graph(loop_body2)(step_num, x)with tf.Session() as sess: print(sess.run(result1)) print(sess.run(result2))#print (1, 3)(1, 3)
How to match a column entry in pandas against another similar column entry in a different row? Say for a given table :d.DataFrame([['Johnny Depp', 'Keanu Reeves'], ['Robert De Niro', 'Nicolas Cage'], ['Brad Pitt', 'Johnny Depp'], ['Leonardo DiCaprio', 'Morgan Freeman'], ['Tom Cruise', 'Hugh Jackman'], ['Morgan Freeman', 'Robert De Niro']], columns=['Name1', 'Name2'])I wish the output as :pd.DataFrame([['Johnny Depp', 'Johnny Depp'], ['Robert De Niro', 'Robert De Niro'], ['Brad Pitt', NaN], ['Leonardo DiCaprio', NaN], ['Tom Cruise', NaN], ['Morgan Freeman', 'Morgan Freeman'], [NaN ,'Keanu Reeves'], [NaN ,'Nicolas Cage'], [NaN ,'Hugh Jackman']], columns=['Name1', 'Name2'])I wish to map similar names in the two columns against each other, and the rest as seperate row entries.I know Regex can solve this, but I want this at scale since I have a lot of rows. I tried using different inbuilt pandas functions and word libraries like FastText but couldn't solve this. I wish to map column Name1 to Name2.How do i solve this ? PS. I still think am making some silly errors.
First, you make a list with all the actors' names.actors = ['Johnny Depp', 'Keanu Reeves', 'Robert De Niro', 'Nicolas Cage', 'Brad Pitt', 'Johnny Depp', 'Leonardo DiCaprio', 'Morgan Freeman', 'Tom Cruise', 'Hugh Jackman', 'Morgan Freeman', 'Robert De Niro',]Then use the collections.Counter class. It is a powerful class which is used when wewant to find the frequency of an element.from collections import Counteractors_counts = Counter(actors)actors_list = list(actors_counts.items())print(actors_list)Then we make a pandas DataFrame,import pandas as pdactors_df = pd.DataFrame(actors_list, columns=['Name','Frequency'])print(actors_df)It outputs, Name Frequency0 Johnny Depp 21 Keanu Reeves 12 Robert De Niro 23 Nicolas Cage 14 Brad Pitt 15 Leonardo DiCaprio 16 Morgan Freeman 27 Tom Cruise 18 Hugh Jackman 1I make a dict with keys the actos names and values the actor name of Nan stringactors_dict = {}for item in range(len(actors_df)): name = str(actors_df['Name'].iloc[item]) freq = actors_df['Frequency'].iloc[item] if freq>1: actors_dict[name] = name else: actors_dict[name] = 'NaN'The actors_dict is{'Johnny Depp': 'Johnny Depp','Keanu Reeves': 'NaN','Robert De Niro': 'Robert De Niro','Nicolas Cage': 'NaN','Brad Pitt': 'NaN','Leonardo DiCaprio': 'NaN','Morgan Freeman': 'Morgan Freeman','Tom Cruise': 'NaN','Hugh Jackman': 'NaN'}Lastly, add the keys in a 'Name1' column and the values in a 'Name2' column of a DataFrame,a = list(actors_dict.keys())b = list(actors_dict.values())actors = pd.concat([pd.DataFrame([(a[i], b[i])], columns=['Name1', 'Name2']) for i in range(len(a))],ignore_index=True)The output should be, Name1 Name20 Johnny Depp Johnny Depp1 Keanu Reeves NaN2 Robert De Niro Robert De Niro3 Nicolas Cage NaN4 Brad Pitt NaN5 Leonardo DiCaprio NaN6 Morgan Freeman Morgan Freeman7 Tom Cruise NaN8 Hugh Jackman NaNI hope this helps you.
ValueError: Plan shapes are not aligned I have four data frames that are importing data from different excel files ( Suppliers) and I am trying to combine these frames. When I include df3 when concatenating I get an error. I referred a lot of articles on similar error but not getting clue. I tried upgrading pandas.Tried the following code as well Data = DataFrame([df1,df2,df3,df4],columns= 'Supplier','Entity','Address','Site','State','Waste Description','Quantity','UOM','Disposal Facility','Disposal Cost','Trans Cost']) df1 = data1[['Supplier','Entity','Address','Site','State','Waste Description','Quantity','UOM','Disposal Facility']] Shape: (3377, 9) df2 = data2[['Supplier','Entity','Address','Site','State','Waste Description','Quantity','UOM','unit price','Invoice Total','Disposal Facility']] Shape:(13838, 11) df3 = data3[['Supplier','Entity','Address','Site','State','Waste Description','Quantity','UOM','Disposal Facility']] Shape:(1185, 10) df4 = data4[['Supplier','Entity','Address','Site','State','Waste Description','Quantity','UOM','Disposal Facility','Disposal Cost','Trans Cost']] Shape: (76, 11) data = [df1,df2,df3,df4] data1 = pd.concat(data) ValueError: Plan shapes are not aligned When I remove df3 the data gets combined. I read that number of columns between dataframe doesn't matter.
It worked after entering the following codedata3['Quantity'] = data3['Quantity'].replace(" ","")
Weighted mean in pandas - string indices must be integers I am going to calculate weighted average based on csv file. I have already loaded columns: A, B which contains float values.My csv file:A B170.804 2854140.924 510164.842 3355Pattern(w1*x1 + w2*x2 + ...) / (w1 + w2 + w3 + ...)My code:c = df['B'] # okwa = (df['B'] * df['A']).sum() / df['B'].sum() # TypeError: string indices must be integers
IIUC, you might try this (the line of code you wrote should work as well):wa = df['A'].dot(df['B']) / df['B'].sum()print(wa)165.55897693109094
Flexibly select pandas dataframe rows using dictionary Suppose I have the following dataframe:df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]}) brand color year0 Ford red 20161 fiat green 20162 opel blue 2017I know that to select using multiple columns I can do something like:new_df = df[(df['color']=='red')&(df['year']==2016)]Now what I would like to do is find a way to use a dictionary to select the rows I want where the keys of the dictionary represent the columns mapping to the allowed values. For example applying the following dictionary {'color':'red', 'year':2016} on df would yield the same result as new_df. I can already do it with a for loop, but I'd like to know if there are any faster and/or more 'pythonic' ways of doing it!Please include time taken of method.
With single expression:In [728]: df = pd.DataFrame({'color':['red', 'green', 'blue'], 'brand':['Ford','fiat', 'opel'], 'year':[2016,2016,2017]})In [729]: d = {'color':'red', 'year':2016}In [730]: df.loc[np.all(df[list(d)] == pd.Series(d), axis=1)]Out[730]: brand color year0 Ford red 2016
Storing more than a million .txt files into a pandas dataframe I have a set of more than million records all of them in the .txt format. Each file.txt has just one line: 'user_name', 'user_nickname', 24, 45I need to run a distribution check on the aggregated list of numeric features from the million files. Hence, I needed to aggregate these files into large data frame. The approach I have been following is as follows:import globimport osimport pandas as pdimport sqlite3connex = sqlite3.connect("data/processed/aggregated-records.db")files_lst = glob.glob("data/raw/*.txt")files_read_count = 1for file_name in files_lst: data_df = pd.read_csv(file_name, header=None, names=['user_name', 'user_nickname', 'numeric_1', 'numeric_2']) data_df['date_time'] = os.path.basename(file_name).strip(".txt") data_df.to_sql(name=file_name, con=connex, if_exists="append", index=False) files_read_count += 1 if (files_read_count % 10000) == 0: print(files_read_count, " files read")The issue I have is that with this approach, I am able to write to the database at a very slow pace (about 10,000 files in an hour). Is there any way to run this faster?
The following code cuts the processing time to 10,000 files a minute. This is an implementation of the suggestion from @DYZ here.import csv, globwith open('data/processed/aggregated-data.csv', 'w') as aggregated_csv_file: writer = csv.writer(aggregated_csv_file, delimiter=',') files_lst = glob.glob("data/raw/*.txt") files_merged_count = 1 for file in files_lst: with open(file) as input_file: csv_reader = csv.reader(input_file, delimiter=',') for row in csv_reader: writer.writerow(row) if (files_merged_count % 10000) == 0: print(files_merged_count, "files merged") files_merged_count += 1
How to use melt function in pandas for large table? I currently have data which looks like this: Afghanistan_co2 Afghanistan_income Year Afghanistan_population Albania_co21 NaN 603 1801 3280000 NaN2 NaN 603 1802 3280000 NaN3 NaN 603 1803 3280000 NaN4 NaN 603 1804 3280000 NaNand I would like to use melt to turn it into this: But with the labels instead as 'Year', 'Country', 'population Value',' co2 Value', 'income value'It is a large dataset with many rows and columns, so I don't know what to do, I only have this so far: pd.melt(merged_countries_final, id_vars=['Year']) I've done this since there does exist a column in the dataset titled 'Year'. What should I do?
Just doing with str.split with your columnsdf.set_index('Year',inplace=True)df.columns=pd.MultiIndex.from_tuples(df.columns.str.split('_').map(tuple))df=df.stack(level=0).reset_index().rename(columns={'level_1':'Country'})df Year Country co2 income population0 1801 Afghanistan NaN 603.0 3280000.01 1802 Afghanistan NaN 603.0 3280000.02 1803 Afghanistan NaN 603.0 3280000.03 1804 Afghanistan NaN 603.0 3280000.0
Scipy.linalg.logm produces an error where matlab does not The line scipy.linalg.logm(np.diag([-1.j, 1.j])) produces an error with scipy 0.17.1, while the same call to matlab, logm(diag([-i, i])), produces valid output. I already filed a bugreport on github, now I am here to ask for a workaround. Is there any implementation of logm in Python, that can do logm(np.diag([-1.j, 1.j]))? EDIT: The error is fixed in scipy 0.18.0rc2, so this thread is closed.
I don't know enough about the calculation to understand the error. But it has something to do division by zero - probably in the real part.Replacing the zero real part of the array with a small value works:In [40]: linalg.logm(np.diag([1e-16-1.j,1e-16+1.j]))Out[40]: array([[ 5.00000000e-33-1.57079633j, 0.00000000e+00+0.j ], [ 0.00000000e+00+0.j , 5.00000000e-33+1.57079633j]])So the small real part could be removed withIn [47]: linalg.logm(np.diag([1e-16-1.j,1e-16+1.j])).imag*1jOut[47]: array([[-0.-1.57079633j, 0.+0.j ], [ 0.+0.j , 0.+1.57079633j]])
Properly shifting irregular time series in Pandas What's the proper way to shift this time series, and re-align the data to the same index? E.g. How would I generate the data frame with the same index values as "data," but where the value at each point was the last value seen as of 0.4 seconds after the index timestamp?I'd expect this to be a rather common operation among people dealing with irregular and mixed frequency time series ("what's the last value as of an arbitrary time offset to my current time?"), so I would expect (hope for?) this functionality to exist...Suppose I have the following data frame:>>> import pandas as pd>>> import numpy as np>>> import time>>> >>> x = np.arange(10)>>> #t = time.time() + x + np.random.randn(10)... t = np.array([1467421851418745856, 1467421852687532544, 1467421853288187136,... 1467421854838806528, 1467421855148979456, 1467421856415879424,... 1467421857259467264, 1467421858375025408, 1467421859019387904,... 1467421860235784448])>>> data = pd.DataFrame({"x": x})>>> data.index = pd.to_datetime(t)>>> data["orig_time"] = data.index>>> data x orig_time2016-07-02 01:10:51.418745856 0 2016-07-02 01:10:51.4187458562016-07-02 01:10:52.687532544 1 2016-07-02 01:10:52.6875325442016-07-02 01:10:53.288187136 2 2016-07-02 01:10:53.2881871362016-07-02 01:10:54.838806528 3 2016-07-02 01:10:54.8388065282016-07-02 01:10:55.148979456 4 2016-07-02 01:10:55.1489794562016-07-02 01:10:56.415879424 5 2016-07-02 01:10:56.4158794242016-07-02 01:10:57.259467264 6 2016-07-02 01:10:57.2594672642016-07-02 01:10:58.375025408 7 2016-07-02 01:10:58.3750254082016-07-02 01:10:59.019387904 8 2016-07-02 01:10:59.0193879042016-07-02 01:11:00.235784448 9 2016-07-02 01:11:00.235784448I can write the following function:def time_shift(df, delta): """Shift a DataFrame object such that each row contains the last known value as of the time `df.index + delta`.""" lookup_index = df.index + delta mapped_indicies = np.searchsorted(df.index, lookup_index, side='left') # Clamp bounds to allow us to index into the original DataFrame cleaned_indicies = np.clip(mapped_indicies, 0, len(mapped_indicies) - 1) # Since searchsorted gives us an insertion point, we'll generally # have to shift back by one to get the last value prior to the # insertion point. I choose to keep contemporaneous values, # rather than looking back one, but that's a matter of personal # preference. lookback = np.where(lookup_index < df.index[cleaned_indicies], 1, 0) # And remember to re-clip to avoid index errors... cleaned_indicies = np.clip(cleaned_indicies - lookback, 0, len(mapped_indicies) - 1) new_df = df.iloc[cleaned_indicies] # We don't know what the value was before the beginning... new_df.iloc[lookup_index < df.index[0]] = np.NaN # We don't know what the value was after the end... new_df.iloc[mapped_indicies >= len(mapped_indicies)] = np.NaN new_df.index = df.index return new_dfwith the desired behavior:>>> time_shift(data, pd.Timedelta('0.4s')) x orig_time2016-07-02 01:10:51.418745856 0.0 2016-07-02 01:10:51.4187458562016-07-02 01:10:52.687532544 1.0 2016-07-02 01:10:52.6875325442016-07-02 01:10:53.288187136 2.0 2016-07-02 01:10:53.2881871362016-07-02 01:10:54.838806528 4.0 2016-07-02 01:10:55.1489794562016-07-02 01:10:55.148979456 4.0 2016-07-02 01:10:55.1489794562016-07-02 01:10:56.415879424 5.0 2016-07-02 01:10:56.4158794242016-07-02 01:10:57.259467264 6.0 2016-07-02 01:10:57.2594672642016-07-02 01:10:58.375025408 7.0 2016-07-02 01:10:58.3750254082016-07-02 01:10:59.019387904 8.0 2016-07-02 01:10:59.0193879042016-07-02 01:11:00.235784448 NaN NaTAs you can see, getting this calculation right is a bit tricky, so I'd much prefer a supported implementation vs. 'rolling my own'.This doesn't work. It shifts truncates the first argument and shifts all rows by 0 positions:>>> data.shift(0.4) x orig_time2016-07-02 01:10:51.418745856 0.0 2016-07-02 01:10:51.4187458562016-07-02 01:10:52.687532544 1.0 2016-07-02 01:10:52.6875325442016-07-02 01:10:53.288187136 2.0 2016-07-02 01:10:53.2881871362016-07-02 01:10:54.838806528 3.0 2016-07-02 01:10:54.8388065282016-07-02 01:10:55.148979456 4.0 2016-07-02 01:10:55.1489794562016-07-02 01:10:56.415879424 5.0 2016-07-02 01:10:56.4158794242016-07-02 01:10:57.259467264 6.0 2016-07-02 01:10:57.2594672642016-07-02 01:10:58.375025408 7.0 2016-07-02 01:10:58.3750254082016-07-02 01:10:59.019387904 8.0 2016-07-02 01:10:59.0193879042016-07-02 01:11:00.235784448 9.0 2016-07-02 01:11:00.235784448This is just adds an offset to data.index...:>>> data.shift(1, pd.Timedelta("0.4s")) x orig_time2016-07-02 01:10:51.818745856 0 2016-07-02 01:10:51.4187458562016-07-02 01:10:53.087532544 1 2016-07-02 01:10:52.6875325442016-07-02 01:10:53.688187136 2 2016-07-02 01:10:53.2881871362016-07-02 01:10:55.238806528 3 2016-07-02 01:10:54.8388065282016-07-02 01:10:55.548979456 4 2016-07-02 01:10:55.1489794562016-07-02 01:10:56.815879424 5 2016-07-02 01:10:56.4158794242016-07-02 01:10:57.659467264 6 2016-07-02 01:10:57.2594672642016-07-02 01:10:58.775025408 7 2016-07-02 01:10:58.3750254082016-07-02 01:10:59.419387904 8 2016-07-02 01:10:59.0193879042016-07-02 01:11:00.635784448 9 2016-07-02 01:11:00.235784448And this results in Na's for all time points:>>> data.shift(1, pd.Timedelta("0.4s")).reindex(data.index) x orig_time2016-07-02 01:10:51.418745856 NaN NaT2016-07-02 01:10:52.687532544 NaN NaT2016-07-02 01:10:53.288187136 NaN NaT2016-07-02 01:10:54.838806528 NaN NaT2016-07-02 01:10:55.148979456 NaN NaT2016-07-02 01:10:56.415879424 NaN NaT2016-07-02 01:10:57.259467264 NaN NaT2016-07-02 01:10:58.375025408 NaN NaT2016-07-02 01:10:59.019387904 NaN NaT2016-07-02 01:11:00.235784448 NaN NaT
Just like on this question, you are asking for an asof-join. Fortunately, the next release of pandas (soon-ish) will have it! Until then, you can use a pandas Series to determine the value you want.Original DataFrame:In [44]: dataOut[44]: x2016-07-02 13:27:05.249071616 02016-07-02 13:27:07.280549376 12016-07-02 13:27:08.666985984 22016-07-02 13:27:08.410521856 32016-07-02 13:27:09.896294912 42016-07-02 13:27:10.159203328 52016-07-02 13:27:10.492438784 62016-07-02 13:27:13.790925312 72016-07-02 13:27:13.896483072 82016-07-02 13:27:13.598456064 9Convert to Series:In [45]: ser = pd.Series(data.x, data.index)In [46]: serOut[46]: 2016-07-02 13:27:05.249071616 02016-07-02 13:27:07.280549376 12016-07-02 13:27:08.666985984 22016-07-02 13:27:08.410521856 32016-07-02 13:27:09.896294912 42016-07-02 13:27:10.159203328 52016-07-02 13:27:10.492438784 62016-07-02 13:27:13.790925312 72016-07-02 13:27:13.896483072 82016-07-02 13:27:13.598456064 9Name: x, dtype: int64Use the asof function:In [47]: ser.asof(ser.index + pd.Timedelta('4s'))Out[47]: 2016-07-02 13:27:09.249071616 32016-07-02 13:27:11.280549376 62016-07-02 13:27:12.666985984 62016-07-02 13:27:12.410521856 62016-07-02 13:27:13.896294912 72016-07-02 13:27:14.159203328 92016-07-02 13:27:14.492438784 92016-07-02 13:27:17.790925312 92016-07-02 13:27:17.896483072 92016-07-02 13:27:17.598456064 9Name: x, dtype: int64(I used four seconds above to make the example easier to read.)
I am trying to use CNN for stock price prediction but my code does not seem to work, what do I need to change or add? import mathimport numpy as npimport pandas as pdimport pandas_datareader as pddfrom sklearn.preprocessing import MinMaxScalerfrom keras.layers import Dense, Dropout, Activation, LSTM, Convolution1D, MaxPooling1D, Flattenfrom keras.models import Sequentialimport matplotlib.pyplot as pltdf = pdd.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2020-12-31')data = df.filter(['Close'])dataset = data.valueslen(dataset)# 2265training_data_size = math.ceil(len(dataset)*0.7)training_data_size# 1586scaler = MinMaxScaler(feature_range=(0,1))scaled_data = scaler.fit_transform(dataset)scaled_data# array([[0.04288701],# [0.03870297],# [0.03786614],# ...,# [0.96610873],# [0.98608785],# [1. ]])train_data = scaled_data[0:training_data_size,:]x_train = []y_train = []for i in range(60, len(train_data)): x_train.append(train_data[i-60:i, 0]) y_train.append(train_data[i,0]) if i<=60: print(x_train) print(y_train) '''[array([0.04288701, 0.03870297, 0.03786614, 0.0319038 , 0.0329498 , 0.03577404, 0.03504182, 0.03608791, 0.03640171, 0.03493728, 0.03661088, 0.03566949, 0.03650625, 0.03368202, 0.03368202, 0.03598329, 0.04100416, 0.03953973, 0.04110879, 0.04320089, 0.04089962, 0.03985353, 0.04037657, 0.03566949, 0.03640171, 0.03619246, 0.03253139, 0.0294979 , 0.03033474, 0.02960253, 0.03002095, 0.03284518, 0.03357739, 0.03410044, 0.03368202, 0.03472803, 0.02803347, 0.02792885, 0.03556487, 0.03451886, 0.0319038 , 0.03127613, 0.03274063, 0.02688284, 0.02635988, 0.03211297, 0.03096233, 0.03472803, 0.03713392, 0.03451886, 0.03441423, 0.03493728, 0.03587866, 0.0332636 , 0.03117158, 0.02803347, 0.02897494, 0.03546024, 0.03786614, 0.0401674 ])][0.03933056376752886]'''x_train, y_train = np.array(x_train), np.array(y_train)x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))x_train.shape# (1526, 60, 1)model = Sequential()model.add(Convolution1D(64, 3, input_shape= (100,4), padding='same'))model.add(MaxPooling1D(pool_size=2))model.add(Convolution1D(32, 3, padding='same'))model.add(MaxPooling1D(pool_size=2))model.add(Flatten())model.add(Dense(1))model.add(Activation('linear'))model.summary()model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])model.fit(X_train, y_train, batch_size=50, epochs=50, validation_data = (X_test, y_test), verbose=2)test_data = scaled_data[training_data_size-60: , :]x_test = []y_test = dataset[training_data_size: , :]for i in range(60, len(test_data)): x_test.append(test_data[i-60:i, 0])x_test = np.array(x_test)x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))predictions = model.predict(x_test)predictions = scaler.inverse_transform(predictions)rsme = np.sqrt(np.mean((predictions - y_test)**2))rsmetrain = data[:training_data_size]valid = data[training_data_size:]valid['predictions'] = predictionsplt.figure(figsize=(16,8))plt.title('PFE')plt.xlabel('Date', fontsize=18)plt.ylabel('Close Price in $', fontsize=18)plt.plot(train['Close'])plt.plot(valid[['Close', 'predictions']])plt.legend(['Train', 'Val', 'predictions'], loc='lower right')plt.showimport numpy as npy_test, predictions = np.array(y_test), np.array(predictions)mape = (np.mean(np.abs((predictions - y_test) / y_test))) * 100accuracy = 100 - mapeprint(accuracy)This above is my code. I tried to edit it but does not seem to be working. I am suspecting that I did not format my dataset well but I am new to this field so I do not know what should I do to my codes such that it will fit in. I hope you guys can enlighten me on this, Thank you!I encountered errors like : ''IndexError: index 2264 is out of bounds for axis 0 with size 2264'' and'' ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 800 but received input with shape [None, 480]''
Your model doesn't tie to your data.Change this line:model.add(Convolution1D(64, 3, input_shape= (60,1), padding='same'))
randomly choose different sets in numpy? I am trying to randomly select a set of integers in numpy and am encountering a strange error. If I define a numpy array with two sets of different sizes, np.random.choice chooses between them without issue:Set1 = np.array([[1, 2, 3], [2, 4]])In: np.random.choice(Set1)Out: [4, 5]However, once the numpy array are sets of the same size, I get a value error:Set2 = np.array([[1, 3, 5], [2, 4, 6]])In: np.random.choice(Set2)ValueError: a must be 1-dimensional Could be user error, but I've checked several times and the only difference is the size of the sets. I realize I can do something like:Chosen = np.random.choice(N, k)Selection = Set[Chosen]Where N is the number of sets and k is the number of samples, but I'm just wondering if there was a better way and specifically what I am doing wrong to raise a value error when the sets are the same size.Printout of Set1 and Set2 for reference:In: Set1Out: array([list([1, 3, 5]), list([2, 4])], dtype=object)In: type(Set1)Out: numpy.ndarrayIn: Set2Out: array([[1, 3, 5], [2, 4, 6]])In: type(Set2)Out: numpy.ndarray
Your issue is caused by a misunderstanding of how numpy arrays work. The first example can not "really" be turned into an array because numpy does not support ragged arrays. You end up with an array of object references that points to two python lists. The second example is a proper 2xN numerical array. I can think of two types of solutions here.The obvious approach (which would work in both cases, by the way), would be to choose the index instead of the sublist. Since you are sampling with replacement, you can just generate the index and use it directly:Set[np.random.randint(N, size=k)]This is the same asSet[np.random.choice(N, k)]If you want to choose without replacement, your best bet is to use np.random.choice, with replace=False. This is similar to, but less efficient than shuffling. In either case, you can write a one-liner for the index:Set[np.random.choice(N, k, replace=False)]Or:index = np.arange(Set.shape[0])np.random.shuffle(index)Set[index[:k]]The nice thing about np.random.shuffle, though, is that you can apply it to Set directly, whether it is a one- or many-dimensional array. Shuffling will always happen along the first axis, so you can just take the top k elements afterwards:np.random.shuffle(Set)Set[:k]The shuffling operation works only in-place, so you have to write it out the long way. It's also less efficient for large arrays, since you have to create the entire range up front, no matter how small k is.The other solution is to turn the second example into an array of list objects like the first one. I do not recommend this solution unless the only reason you are using numpy is for the choice function. In fact I wouldn't recommend it at all, since you can, and probably should, use pythons standard random module at this point. Disclaimers aside, you can coerce the datatype of the second array to be object. It will remove any benefits of using numpy, and can't be done directly. Simply setting dtype=object will still create a 2D array, but will store references to python int objects instead of primitives in it. You have to do something like this:Set = np.zeros(N, dtype=object)Set[:] = [[1, 2, 3], [2, 4]]You will now get an object essentially equivalent to the one in the first example, and can therefore apply np.random.choice directly.NoteI show the legacy np.random methods here because of personal inertia if nothing else. The correct way, as suggested in the documentation I link to, is to use the new Generator API. This is especially true for the choice method, which is much more efficient in the new implementation. The usage is not any more difficult:Set[np.random.default_rng().choice(N, k, replace=False)]There are additional advantages, like the fact that you can now choose directly, even from a multidimensional array:np.random.default_rng().choice(Set2, k, replace=False)The same goes for shuffle, which, like choice, now allows you to select the axis you want to rearrange:np.random.default_rng().shuffle(Set)Set[:k]
Selecting vector of 2D array elements from column index vector I have a 2D array A:28 39 5277 80 66 7 18 24 9 97 68And a vector array of column indexes B:1 0 2 0How, in a pythonian way, using base Python or Numpy, can I select the elements from A which DO NOT correspond to the column indexes in B?I should get this 2D array which contains the elements of A, Not corresponding to the column indexes stored in B:28 5280 66 7 18 97 68
You can make use of broadcasting and a row-wise mask to select elements not contained in your array for each row:SetupB = np.array([1, 0, 2, 0])cols = np.arange(A.shape[1])Now use broadcasting to create a mask, and index your array.mask = B[:, None] != colsA[mask].reshape(-1, 2)array([[28, 52], [80, 66], [ 7, 18], [97, 68]])
subtracting strings in array of data python I am trying to do the following:create an array of random datacreate an array of predefined codes (AW, SS)subtract all numbers as well as any instance of predefined code. if a string called "HL" remains after step 3, remove that as well and take the next alphabet pair. If a string called "HL" is the ONLY string in the array then take that.I do not know how to go about completing steps 3 - 4. 1.array_data = ['HL22','PG1234-332HL','1334-SF-21HL','HL43--222PG','HL222AW11144RH','HLSSDD','SSDD']2.predefined_code = ['AW','SS']3.ideally, results for this step will look like result_data = [['HL'],['PG,HL'],['SF','HL'],['HL','PG'],['HL','RH'], ['HL','DD'],['DD']4. ideally, results for this step will look like this:result_data = [['HL'],['PG'],['SF'],['PG'],['RH'], ['DD'],['DD']for step 3, I have tried the following code not_in_predefined = [item for item in array_data if item not in predefined_code]but this doesnt produce the result im looking for, because it it checking item against item. not a partial string match.
This is fairly simple using Regex.re.findall(r'[A-Z].',item) should give you the text from your strings, and then you can do the required processing on that.You may want to convert the list to a set eventually and use the difference operation, instead of looping and removing the elements defined in the predefined_code list.
What's the LSTM model's output_node_names? all. I want generate a freezed model from one LSTM model (https://github.com/roatienza/Deep-Learning-Experiments/tree/master/Experiments/Tensorflow/RNN). In my option, I should freeze the last prediction node and use "bazel-bin/tensorflow/python/tools/freeze_graph --input_binary=true --input_graph=model_20170913/model.pb --input_checkpoint=model_20170913/model.ckpt --output_graph=model_20170913/frozen_graph.pb --output_node_names=ArgMax_52"(ArgMax_52 is last default node name). However, I got one notice "Converted 0 variables to const ops." (freeze command's result). Now, I have no idea about which node_name should be as output_node_name?
As mentioned above, "lstm_prediction" is output_node_name. And Tensorboard help me a lot to understand the graph.
Discrepancy of the state of `numpy.random` disappears There are two python runs of the same project with different settings, but with the same random seeds.The project contains a function that returns a couple of random numbers using numpy.random.uniform.Regardless of other uses of numpy.random in the python process, series of the function calls in both of the runs generate the same sequences, until some point.And after generating different results for one time at that point, they generate the same sequences again, for some period.I haven't tried using numpy.random.RandomState yet, but how is this possible?Is it just a coincidence that somewhere something which uses numpy.random caused the discrepancy and fixed it again?I'm curious if it is the only possibility or there is another explanation.Thanks in advance.ADD: I forgot to mention that there was no seeding at that point.
When you use the random module in numpy, each randomly generated number (regardless of the distribution/function) uses the same "global" instance of RandomState. When you set the seed using numpy.random.seed(), you set the seed of the 'global' instance of RandomState. This is the same principle as the random library in Python.I'm not sure of the specific implementation of the numpy random functions, but I suspect that each random function will make the underlying Mersenne Twister advance a number of 'steps', with the number of steps not necessarily being the same between different random functions.So, if the order of every call to a random function is not the same between separate runs, then you may see divergence in the generated sequence of random numbers, with convergence again if the Mersenne Twister 'steps' line up again.You could get around this by initialising a separate RandomState instance for each function you are using. For example:import numpy as npseed = 12345r_uniform = np.random.RandomState(seed)r_randint = np.random.RandomState(seed)a_random_uniform_number = r_uniform.uniform()a_random_int = r_randint.randint(10)You might want to set different seeds for each instance - this will depend on what you are using these pseudo-random numbers for.
Remove duplicate strings within a pandas dataframe entry I need to remove duplicate strings within a pandas dataframe entry. But Im only find solutions for removing duplicate rows.The entries I want to clean look like this:Dataframe looks like this:I want each string between the commas to occur only once.Can someone please help me?
Try this (I've added a simple example of my own df):import pandas as pddata = ['a,b,c','a,b,b,e,d','a,a,e,d,f']df = pd.DataFrame(data,columns={"cleaned_data"})def remove_dups_letters(row): sentences = set(row.split(",")) new_str = ','.join(sentences) return new_strdf['cleaned_data'] = df['cleaned_data'].apply(remove_dups_letters)print(df)
Parallelize a function with multiple inputs/outputs geodataframe-variables Using a previous answer (merci Booboo),The code idea is:from multiprocessing import Pooldef worker_1(x, y, z): ... t = zip(list_of_Polygon,list_of_Point,column_Point)return tdef collected_result(t): x, y, z = t # unpack save_shp("polys.shp",x) save_shp("point.shp",y,z)if __name__ == '__main__':gg = gpd.read_file("name.shp")pool = Pool()for index, pol in gg.iterrows(): xlon ,ylat = gg.centroid result = pool.starmap(worker_1, zip(pol,xlon,ylat)) # or # result = mp.Process(worker_1,args = (pol,xlon,ylat)) pool.close() pool.join() collected_result(result)But the geodataframe (Polygon,Point) is not iterable so I can't use pool, any suggestions to parallelize?How to compress the (geodataframe) outputs in worker_1 and then save them independently (or multiple layers in a shapefile), its better to use global parameters? ... because zip only saves lists (right*)?
Well, if I understand what you are trying to do, perhaps the following is what you need. Here I am building up the args list that will be used as the iterable argument to starmap by iterating on gg.iterrows() (there is no need to use zip):from multiprocessing import Pooldef worker_1(pol, xlon, ylat): ... t = zip(list_of_Polygon, list_of_Point, column_Point) return tdef collected_result(t): x, y, z = t # unpack save_shp("polys.shp", x) save_shp("point.shp", y, z)if __name__ == '__main__': gg = gpd.read_file("name.shp") pool = Pool() args = [] for index, pol in gg.iterrows(): xlon, ylat = gg.centroid args.append((pol, xlon, ylat)) result = pool.starmap(worker_1, args) pool.close() pool.join() collected_result(result)You were creating a single Pool instance and in your loop doing repeatedly calls to methods starmap, close and join. But once you call close on the Pool instance you cannot submit any more tasks to the pool (i.e. call starmap again), so I think your looping/indentation was all wrong.
Arange ordinal number for range of values in column So I have some kind of data frame which, and in one column values range from 139 to 150 (rows with values repeat). How to create new column, which will assign ordinal value based on the mentioned column? For example, 139 -> 0, 140 -> 1, ..., 150 -> 10UPD: Mozway's answer is suitable, thanks!
Simply subtract 139: df['col'] -= 139Or, to get a new column: df['new'] = df['col'] - 139
Creating a function that operates different string cleaning operations I built a function that performs multiple cleaning operations, but when I run it on an object column, I get the AttributeError: 'str' object has no attribute 'str' error. Why is that?news = {'Text':['bNikeb invests in shoes', 'bAdidasb invests in t-shirts', 'dog drank water'], 'Source':['NYT', 'WP', 'Guardian']}news_df = pd.DataFrame(news)def string_cleaner(x): x = x.str.strip() x = x.str.replace('.', '') x = x.str.replace(' ', '')news_df['clean'] = news_df['Text'].apply(string_cleaner)
news = {'Text':['bNikeb invests in shoes', 'bAdidasb invests in t-shirts', 'dog drank water'], 'Source':['NYT', 'WP', 'Guardian']}news_df = pd.DataFrame(news)def string_cleaner(x): x = x.strip() x = x.replace('.', '') x = x.replace(' ', '') return xnews_df['clean'] = news_df['Text'].apply(string_cleaner)apply is used to apply a function on a pandas Series objects, the final return type is inferred from the return type of the applied function. So, you can think of passing a list of values to a function one at a time to transform those values, in your case you are sending a list of string to clean each string.As, x is a string, the operations you're applying (strip, replace) works directly, there's no .str operation on python strings. So, it gives an error. There is a str function which is used this way str(x) to cast another python type to a string.
How to break down a numpy array into a list and create a dictionary? I have a following list and a numpy array : For the list :features = np.array(X_train.columns).tolist() results :['Attr1', 'Attr2', 'Attr3', 'Attr4', 'Attr5', 'Attr6', 'Attr7', 'Attr8', 'Attr9', 'Attr10', 'Attr11', 'Attr12', 'Attr13', 'Attr14', 'Attr15', 'Attr16', 'Attr17', 'Attr18', 'Attr19', 'Attr20', 'Attr21', 'Attr22', 'Attr23', 'Attr24', 'Attr25', 'Attr26', 'Attr27', 'Attr28', 'Attr29', 'Attr30', 'Attr31', 'Attr32', 'Attr33', 'Attr34', 'Attr35', 'Attr36', 'Attr37', 'Attr38', 'Attr39', 'Attr40', 'Attr41', 'Attr42', 'Attr43', 'Attr44', 'Attr45', 'Attr46', 'Attr47', 'Attr48', 'Attr49', 'Attr50', 'Attr51', 'Attr52', 'Attr53', 'Attr54', 'Attr55', 'Attr56', 'Attr57', 'Attr58', 'Attr59', 'Attr60', 'Attr61', 'Attr62', 'Attr63', 'Attr64']and array name abaa=(lr.coef_) #I put a regression result on numpy array so I can split them, I want to put them as a listab=np.split(aa,len(aa))results :[array([[ 0.04181571, 0.62369216, -0.23559375, 0.78663624, -0.13935947, -0.1118698 , -0.05672835, -1.73851643, -0.42134655, 0.79001534, 0.05048936, -0.09287526, 0.10103251, -0.0587092 , -0.05300849, 0.72827807, 1.15870475, -0.13861187, -0.42572654, 0.19369654, -0.33319238, -0.06805035, 0.14067888, -0.07418516, -0.04400882, -0.78701564, -0.10921816, -0.26166642, 0.06800944, 0.07672145, 0.22109349, -0.15389544, 2.41697614, 0.21749429, -0.0766771 , 0.77580103, 0.04128744, -0.92835969, -0.41802274, 0.89865658, -0.12102089, -0.28887104, 0.10421332, 0.14445757, 0.02719274, -1.73622976, -0.34980593, 0.35199196, 0.56110135, 0.4460968 , -1.13265322, 0.26188587, 0.14336352, 0.2341355 , -0.10077637, 0.43080231, -0.05521557, -0.1996818 , 0.00513076, -0.14477274, 0.04712721, 0.15380395, -2.51974007, -0.03988658]])]Now, I want to make a dictionary for them but here I'm confused of how should I turn the array into list.This is what I've done :for x in features : for y in ab: print({x:y})and the result is not as desired, since it's failed to break down the array :{'Attr1': array([[ 0.04181571, 0.62369216, -0.23559375, 0.78663624, -0.13935947, -0.1118698 , -0.05672835, -1.73851643, -0.42134655, 0.79001534, 0.05048936, -0.09287526, 0.10103251, -0.0587092 , -0.05300849, 0.72827807, 1.15870475, -0.13861187, -0.42572654, 0.19369654, -0.33319238, -0.06805035, 0.14067888, -0.07418516, -0.04400882, -0.78701564, -0.10921816, -0.26166642, 0.06800944, 0.07672145, 0.22109349, -0.15389544, 2.41697614, 0.21749429, -0.0766771 , 0.77580103, 0.04128744, -0.92835969, -0.41802274, 0.89865658, -0.12102089, -0.28887104, 0.10421332, 0.14445757, 0.02719274, -1.73622976, -0.34980593, 0.35199196, 0.56110135, 0.4460968 , -1.13265322, 0.26188587, 0.14336352, 0.2341355 , -0.10077637, 0.43080231, -0.05521557, -0.1996818 , 0.00513076, -0.14477274, 0.04712721, 0.15380395, -2.51974007, -0.03988658]])}{'Attr2': array([[ 0.04181571, 0.62369216, -0.23559375, 0.78663624, -0.13935947, -0.1118698 , -0.05672835, -1.73851643, -0.42134655, 0.79001534, 0.05048936, -0.09287526, 0.10103251, -0.0587092 , -0.05300849, 0.72827807, 1.15870475, -0.13861187, -0.42572654, 0.19369654, -0.33319238, -0.06805035, 0.14067888, -0.07418516, -0.04400882, -0.78701564, -0.10921816, -0.26166642, 0.06800944, 0.07672145, 0.22109349, -0.15389544, 2.41697614, 0.21749429, -0.0766771 , 0.77580103, 0.04128744, -0.92835969, -0.41802274, 0.89865658, -0.12102089, -0.28887104, 0.10421332, 0.14445757, 0.02719274, -1.73622976, -0.34980593, 0.35199196, 0.56110135, 0.4460968 , -1.13265322, 0.26188587, 0.14336352, 0.2341355 , -0.10077637, 0.43080231, -0.05521557, -0.1996818 , 0.00513076, -0.14477274, 0.04712721, 0.15380395, -2.51974007, -0.03988658]])}{'Attr3': array([[ 0.04181571, 0.62369216, -0.23559375, 0.78663624, -0.13935947, -0.1118698 , -0.05672835, -1.73851643, -0.42134655, 0.79001534, 0.05048936, -0.09287526, 0.10103251, -0.0587092 , -0.05300849, 0.72827807, 1.15870475, -0.13861187, -0.42572654, 0.19369654, -0.33319238, -0.06805035, 0.14067888, -0.07418516, -0.04400882, -0.78701564, -0.10921816, -0.26166642, 0.06800944, 0.07672145, 0.22109349, -0.15389544, 2.41697614, 0.21749429, -0.0766771 , 0.77580103, 0.04128744, -0.92835969, -0.41802274, 0.89865658, -0.12102089, -0.28887104, 0.10421332, 0.14445757, 0.02719274, -1.73622976, -0.34980593, 0.35199196, 0.56110135, 0.4460968 , -1.13265322, 0.26188587, 0.14336352, 0.2341355 , -0.10077637, 0.43080231, -0.05521557, -0.1996818 , 0.00513076, -0.14477274, 0.04712721, 0.15380395, -2.51974007, -0.03988658]])}.......Could you help me to build a list for ab array?And how should I turn them into dictionary?Th expected results : {[Attr1 : 0.04181571], Attr2 : 0.623692160, and so on...}Thank you very much!
you could use the built-in function zip :dict(zip(features, ab[0].ravel()))you can check the docs for numpy.ravel Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned.since your ab variable is obtained with numpy.split ab is a list with one numpy array as you showed
Mapping values from one Dataframe to another and updating existing column I have a dataframeIdNameScore1John102Mary103Tom94857And another dataframeIdName4Jerry5PatAnd I want a resulting dataframe like thisIdNameScore1John102Mary103Tom94Jerry85Pat7Is there a way to do it in Python?
Does this suffice:df1.set_index('Id').fillna({'Name' : df2.set_index('Id').Name}).reset_index() Id Name Score0 1 John 101 2 Mary 102 3 Tom 93 4 Jerry 84 5 Pat 7
Convolve2d just by using Numpy I am studying image-processing using NumPy and facing a problem with filtering with convolution.I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)Does anyone have an idea to refine my method?I know that SciPy supports convolve2d but I want to make a convolve2d only by using NumPy.What I have doneFirst, I made a 2d array the submatrices.a = np.arange(25).reshape(5,5) # original matrixsubmatrices = np.array([ [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]], [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]], [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])the submatrices seems complicated but what I am doing is shown in the following drawing.Next, I multiplied each submatrices with a filter.conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)and summed them.np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)#array([[ 6, 7, 8],# [11, 12, 13],# [16, 17, 18]])Thus this procedure can be called my convolve2d.def my_convolve2d(a, conv_filter): submatrices = np.array([ [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]], [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]], [a[2:,:-2], a[2:,1:-1], a[2:,2:]]]) multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices) return np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)However, I find this my_convolve2d troublesome for 3 reasons.Generation of the submatrices is too awkward that is difficult to read and can only be used when the filter is 3*3The size of the variant submatrices seems to be too big, since it is approximately 9 folds bigger than the original matrix.The summing seems a little non intuitive. Simply said, ugly.Thank you for reading this far.Kind of update. I wrote a conv3d for myself. I will leave this as a public domain.def convolve3d(img, kernel): # calc the size of the array of submatrices sub_shape = tuple(np.subtract(img.shape, kernel.shape) + 1) # alias for the function strd = np.lib.stride_tricks.as_strided # make an array of submatrices submatrices = strd(img,kernel.shape + sub_shape,img.strides * 2) # sum the submatrices and kernel convolved_matrix = np.einsum('hij,hijklm->klm', kernel, submatrices) return convolved_matrix
You could generate the subarrays using as_strided:import numpy as npa = np.array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])sub_shape = (3,3)view_shape = tuple(np.subtract(a.shape, sub_shape) + 1) + sub_shapestrides = a.strides + a.stridessub_matrices = np.lib.stride_tricks.as_strided(a,view_shape,strides)To get rid of your second "ugly" sum, alter your einsum so that the output array only has j and k. This implies your second summation.conv_filter = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])m = np.einsum('ij,ijkl->kl',conv_filter,sub_matrices)# [[ 6 7 8]# [11 12 13]# [16 17 18]]
Concat two values into string Pandas? I tried to concat two values of two columns in Pandas like this:new_dfr["MMYY"] = new_dfr["MM"]+new_dfr["YY"]I got warning message:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy new_dfr["MMYY"] = new_dfr["MM"]+new_dfr["YY"]How to fix it?
new_dfr["MMYY"] = new_dfr["MM"].astype(str) + new_dfr["YY"].astype(str)
Is there a faster way to do this loop? I want to create a new column using the following loop. The table just has the columns 'open', and 'start'. I want to create a new column 'startopen', where if 'start' equals 1, then 'startopen' is equal to 'open'. Otherwise, 'startopen' is equal to whatever 'startopen' was in the row above of this newly created column. Currently I'm able to achieve this using the following:for i in range(df.shape[0]): if df['start'].iloc[i] == 1: df.loc[df.index[i],'startopen'] = df.loc[df.index[i],'open'] else: df.loc[df.index[i],'startopen'] = df.loc[df.index[i-1],'startopen']This works, but is very slow for large datasets. Are there any built in functions that can do this faster?
I want to create a new column 'startopen', where if 'start' equals 1, then 'startopen' is equal to 'open'Otherwise, 'startopen' is equal to whatever 'startopen' was in the row above of this newly created column.IIUC, otherwise part is equal to forward fill the not 1 startopen with last equal 1 startopendf['startopen'] = pd.Series(np.where(df['start'].eq(1), df['open'], np.nan), index=df.index).ffill()
Aggregating multiple columns Pandas Currently my csv looks like this:titlefield1field2field3field4AA1A115530AA1A12940AA1A13300AA1{n/a}09586AA2A212000AA2{n/a}03950AA3A31350AA3{n/a}02929But I am wanting it to look like this:titlefield1field2field3field4AA1A115539586AA1A12949586AA1A13309586AA2A212003950AA3A31352929This is my code:def fun(df, cols_to_aggregate, cols_order): df = df.groupby(['field1', 'field2'], as_index=False)\ .agg(cols_to_aggregate) df['title'] = 'A' df = df[cols_order] return dfdef create_csv(df, month_date): cols_to_aggregate = {'field3': 'sum', 'field4': 'sum'} cols_order = ['title', 'field1', 'field2', 'field3'] funCSV = fun(df, cols_to_aggregate, cols_order) return funCSVAny help would be appreciated as I can't figure out how to match field4 to all of the relevant field2's.
Use:def fun(df, cols_to_aggregate, cols_order): df = df.groupby(['field1', 'field2'], as_index=False)\ .agg(cols_to_aggregate) df['title'] = 'A' #aggregate field4 to new column df['field4'] = df.groupby('field1')['field4'].transform('sum') df = df[cols_order] return dfdef create_csv(df, month_date): cols_to_aggregate = {'field3': 'sum', 'field4': 'sum'} #aded value 'field4' cols_order = ['title', 'field1', 'field2', 'field3','field4'] funCSV = fun(df, cols_to_aggregate, cols_order) return funCSVprint (create_csv(df, '2015-01').loc[lambda x: x['field2'].ne('{n/a}')]) title field1 field2 field3 field40 A A1 A11 553 95861 A A1 A12 94 95862 A A1 A13 30 95864 A A2 A21 200 39506 A A3 A31 35 2929Or if need first non 0 value per field1 use:def fun(df, cols_to_aggregate, cols_order): df = df.groupby(['field1', 'field2'], as_index=False)\ .agg(cols_to_aggregate) df['title'] = 'A' df['field4'] = df.groupby('field1')['field4'].transform('first') df = df[cols_order] return dfdef create_csv(df, month_date): cols_to_aggregate = {'field3': 'sum', 'field4': 'first'} cols_order = ['title', 'field1', 'field2', 'field3','field4'] funCSV = fun(df, cols_to_aggregate, cols_order) return funCSVprint (create_csv(df.replace({'field4':{0:np.nan}}), '2015-01').loc[lambda x: x['field2'].ne('{n/a}')]) title field1 field2 field3 field40 A A1 A11 553 9586.01 A A1 A12 94 9586.02 A A1 A13 30 9586.04 A A2 A21 200 3950.06 A A3 A31 35 2929.0
TypeError: 'module' object is not callable when using Keras I've been having lots of imports issues when it comes to TensorFlow and Keras and now I stumbled upon this error:TypeError Traceback (most recent call last)~\AppData\Local\Temp/ipykernel_17880/703187089.py in <module> 75 #model.compile(loss="categorical_crossentropy",optimizers.rmsprop(lr=0.0001),metrics=["accuracy"]) 76 ---> 77 model.compile(optimizers.rmsprop_v2(lr=0.0001, decay=1e-6),loss="categorical_crossentropy",metrics=["accuracy"]) 78 79 STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_sizeTypeError: 'module' object is not callableThese are the imports:from tensorflow import kerasfrom keras_preprocessing.image import ImageDataGeneratorfrom keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalizationfrom keras.layers import Conv2D, MaxPooling2Dfrom keras import regularizers, optimizersfrom keras.models import Sequentialfrom keras import optimizersfrom keras.optimizers import rmsprop_v2, adadelta_v2
kerns.optimizers.rmsprop_v2 and kerns.optimizers.adadelta_v2 are the modules. You want:from keras.optimizers import RMSprop, AdadeltaAnd:optimizers.RMSprop(lr=0.0001, decay=1e-6) (or just RMSprop(lr=0.0001, decay=1e-6)) instead of optimizers.rmsprop_v2(lr=0.0001, decay=1e-6)
Sort pandas Series both on values and index I want to sort a Series in descending by value but also I need to respect the alphabetical order of the index.Suppose the Series is like this:(index)a 2b 5d 3z 1t 1g 2n 3l 6f 6f 7I need to convert it to the following Series without converting to DataFrame and then convert it to Series,out:(index)f 7f 6l 6b 5d 3n 3a 2g 2t 1z 1I used lexsort but It wasn't suitable. It sorts both the value and index in ascending.
You can first sort the index, then sort the values with a stable algorithm:s.sort_index().sort_values(ascending=False, kind='stable')output:f 7l 6b 5d 3n 3a 2g 2t 1z 1dtype: int64used input:s = pd.Series({'a': 2, 'b': 5, 'd': 3, 'z': 1, 't': 1, 'g': 2, 'n': 3, 'l': 6, 'f': 7})
Tensorflow linear regression house prices I am trying to solve a linear regression problem using neural networks but my loss is coming to the power of 10 and is not reducing for training. I am using the house price prediction dataset(https://www.kaggle.com/c/house-prices-advanced-regression-techniques) and can't figure whats going wrong. Please help someoneX_train, X_test, y_train, y_test = train_test_split(df2, y, test_size=0.2)X_tr=np.array(X_train)y_tr=np.array(y_train)X_te=np.array(X_test)y_te=np.array(y_test)def get_weights(shape,name): #(no of neurons*no of columns) s=tf.truncated_normal(shape) w=tf.Variable(s,name=name) return wdef get_bias(number,name): s=tf.truncated_normal([number]) b=tf.Variable(s,name=name) return bx=tf.placeholder(tf.float32,name="input")w=get_weights([34,100],'layer1')b=get_bias(100,'bias1')op=tf.matmul(x,w)+ba=tf.nn.relu(op)fl=get_weights([100,1],'output')b2=get_bias(1,'bias2')op2=tf.matmul(a,fl)+b2y=tf.placeholder(tf.float32,name='target')loss=tf.losses.mean_squared_error(y,op2)optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)with tf.Session() as sess: for i in range(0,1000): sess.run(tf.global_variables_initializer()) _,l=sess.run([optimizer,loss],feed_dict={x:X_tr,y:y_tr}) print(l)
You are simple randomly initializing the variables in every training step. Just call sess.run(tf.global_variables_initializer()) only once before the loop.
Multiple Aggregate Functions based on Multiple Columns in Pandas I am working with a Pandas df in Python. I have the following input df:Color Shape ValueBlue Square 5Red Square 2Green Square 7Blue Circle 9Blue Square 2Green Circle 6Red Circle 2Blue Square 5Blue Circle 1I would like the following output:Color Shape Count SumBlue Square 3 12Red Square 1 2Green Square 1 7Blue Circle 2 10Green Circle 1 6Red Circle 1 2Looking for something like pivot_table() but do not want the hierarchical index.
OK, so I did more research and will answer this one myself, because it may be helpful for others.The problem I am having is associated with indexing more than pivot tables. To remove the multiple index a simple: df.reset_index()does the trick just fine.As a side note, I don't understand why a question like this would be down-voted. It is something not obvious in the documentation, or any of the literature I have read. It simply involves gaining a deeper insight into how these modules work, which is why people come here.To down-vote something like this is, frankly, smug. In my opinion it defeats the purpose of this site.
Adding a pickle-able attribute to a subclass of numpy.ndarray I would like to add a property (.csys) to a subclass of numpy.ndarray:import numpy as npclass Point(np.ndarray): def __new__(cls, arr, csys=None): obj = np.asarray(arr, dtype=np.float64).view(cls) obj._csys = csys return obj def __array_finalize__(self, obj): if obj is None: return self._csys = getattr(obj, '_csys', None) @property def csys(self): print('Getting .csys') return self._csys @csys.setter def csys(self, csys): print('Setting .csys') self._csys = csysHowever, when I run this test code:pt = Point([1, 2, 3])pt.csys = 'cmm'print("pt.csys:", pt.csys)# Pickle, un-pickle, and check againimport picklepklstr = pickle.dumps(pt)ppt = pickle.loads(pklstr)print("ppt.csys:", ppt.csys)it appears that the attribute cannot be pickled:Setting .csysGetting .csyspt.csys: cmmGetting .csys---------------------------------------------------------------------------AttributeError Traceback (most recent call last)C:\Rut\Vanes\bin\pointtest.py in <module>() 39 ppt = pickle.loads(pklstr) 40 ---> 41 print("ppt.csys:", ppt.csys)C:\Rut\Vanes\bin\point.py in csys(self) 15 def csys(self): 16 print('Getting .csys')---> 17 return self._csys 18 19 @csys.setterAttributeError: 'Point' object has no attribute '_csys'I tried doing the same thing without using decorators (e.g. defining get_csys() and set_csys(), plus csys = property(__get_csys, __set_csys), but had the same result with that.I'm using numpy 1.13.3 under Python 3.6.3
This question has already been asked and answered here. In a nutshell, numpy uses __reduce__ and __setstage__ to pickle itself. The overrides, adapted to the case above, look like this:def __reduce__(self): # Get the parent's __reduce__ tuple pickled_state = super().__reduce__() # Create our own tuple to pass to __setstate__ new_state = pickled_state[2] + (self._csys,) # Return a tuple that replaces the parent's __setstate__ tuple with our own return (pickled_state[0], pickled_state[1], new_state)def __setstate__(self, state): self._csys = state[-1] # Set the _csys attribute # Call the parent's __setstate__ with the other tuple elements. super().__setstate__(state[0:-1])Also note that the getter and setter methods (under the @property and @csys.getter decorators, respectively) are not strictly required in this simple case. If they are dispensed with, access .csys directly, rather than through the 'private' ._csys attribute.
Looking for help on installing a numpy extension I found a numpy extension on github that would be really helpful for a program I'm currently writting, however I don't know how to install it.Here's the link to the extension: https://pypi.python.org/pypi?name=py_find_1st&:action=displayI'm using windows 10 which might be the reason why the installer provided doesn't work, I found a file looking like a numpy extension as described here: https://docs.scipy.org/doc/numpy-1.10.0/user/c-info.how-to-extend.htmlBut there's no mention on this page of where to put the code of the numpy extension, and I didn't manage to find any explanations online.Would anyone have an idea on how to install this?
To build any extension modules for Python, you’ll need a C compiler. Various NumPy modules use FORTRAN 77 libraries, so you’ll also need a FORTRAN 77 compiler installed.However, if you just want to install the tar.gz file that they have on the website, follow these steps:Open cmd (Command Prompt)Write set path=%path%;C:\Python27\Extract the tar.gz file (use a program like PeaZip)Change directories within the command line (if you are confused on how to do this look here for reference)Get to your files' directory (something like cd c:\Users\pdxNat\Downloads\py_find_1st1.0.6)Run python setup.py install
How to split a dataframe heaving a list of column values and counts? I have a CSV based dataframename valueA 5B 5C 5D 1E 2F 1and a values count dictionary like this:{ 5: 2, 1: 1}How to split original dataframe into two:name valueA 5B 5D 1name valueC 5E 2F 1So how to split a dataframe heaving a list of column values and counts in pandas?
This worked for me:def target_indices(df, value_count): indices = [] for index, row in df.iterrows(): for key in value_count: if key == row['value'] and value_count[key] > 0: indices.append(index) value_count[key] -= 1 return(indices)df = pd.DataFrame({'name': ['A', 'B', 'C', 'D', 'E', 'F'], 'value': [5, 5, 5, 1, 2, 1]})value_count = {5: 2, 1: 1}indices = target_indices(df, value_count)df1 = df.iloc[indices]print(df1)df2 = df.drop(indices)print(df2)Output: name value0 A 51 B 53 D 1 name value2 C 54 E 25 F 1
sentiment analysis using python pandas and scikit learn I have a dataset of product review.I want to count words in a way that instead of counting all the words I want to count some specific words like ('Amazing','Great','Love' etc) and put this counting in a column called 'word_count'.Now our goal is to create a column products[‘awesome’] where each row contains the number of times the word ‘awesome’ showed up in the review for the corresponding product.we will use the .apply() method to iterate the the logic above for each row of the ‘word_count’ column.First,we have to use a Python function to define the logic above. we have to write a function called awesome_count which takes in the word counts and returns the number of times ‘awesome’ appears in the reviews.Next, we have to use .apply() to iterate awesome_count for each row of ‘word_count’ and create a new column called ‘awesome’ with the resulting counts. Here is what that looks like:products['awesome'] = products['word_count'].apply(awesome_count)Can anyone please help me with the code need for the problem mentioned above.Thanks in advance.
Alright I lied; for standalone getting word frequency over a corpus we can combine pandas and numpy like so:word_A = np.array(df.series.str.findall('word'))getlength = np.vectorize(len)getlength(word_A)Whats going on under the hood:LINE1pd.series.str to convert the series to string;str.finall() return all occurrences of the "pattern" matched to a list element (findall is a re function); since we're inputting a string, it's going to return the string over and over each time it's matched. The result will be X number of list elements, where X is the amount of documents you searched, and Y strings of your word in each element, where Y is a copy of the string for each time it matched in that document;For example, if you have 3 documents, and each document has the following matches of 'word': 1, 2, 4, you're list will look like:[['word'], ['word', 'word'], ['word', 'word', 'word', 'word']]np.array() converts the list to an array (so we can vectorize it);array([list(['word']), list(['word', 'word']), list(['word', 'word', 'word', 'word'])], dtype=object)LINE2np.vectorize() makes the function we pass it a vectorized function (primes it for numpy broadcasting);LINE3apply our vectorized function to the array;When the vectorized function (In this case, len()) is called in line 3, it goes through each array element and applies that function. The result is an array that index matches the initial document series, but contains an integer count of the search term. For example:array([ 1, 2, 4])Note: I'd still recommend going the slightly longer route - and at least preprocessing your data before you do frequency statistics.Hope this helps!updateHow many words are you wanting, and how big is your dataset?If your computer can handle it, you can use Sklearn’s CountVectorizer to transform your corpus into a dense matrix of ‘document rows’ (documents x words) where each value is the frequency of the word in that document.From there, you can query the documents relative to their category using document indexes and get aggregate counts for all of the words.This approach is more computationally rigorous and will take longer computing, but if you are going to be drawing a lot of EDA from the frequency it’s a good idea to just get the data in a matrix/frame if you can store it.If you’re only doing a couple of words and aren’t expecting to do much analysis, then we can use NumPy arrays to return the index position of a document each time the word is found, then sum all of the returns (ie word frequency across the documents you searched).Ideally before you aggregate word frequency and whatnot we want to preprocess the data (I.e. remove non-word characters, make lowercase, tokenize, lemmatize, etc.) This way you have better accuracy collecting your ‘Features,’ ie the words. “This is amazing!”, “I’m so amazed”, and, “She amazes me.” All return a different ‘token’ or feature for ‘Amaze’ though they all use it similarly.If we don’t need to preprocess and we aren’t making many observations or data manipulations then we can do a quick array to capture words. You’ll still probably want to manually alter your words (Amazing -> amaz, etc), lowercase them, and tokenize your document strings.An alternative approach would be to use regex and .apply() with a user function that appends the return of re.findall() to a list; but this is computationally inefficient so really only good for a handful of words across <500,000 documents; and even then depending on your processing power that’ll take minutes.Or you might use listcomp to set the value directly to the cell location.Sorry I’m not at computer; will check back later and add some code when I can. Let me know a little more about your dataset size please. Thanks!
Need help in debugging Shallow Neural network using numpy I'm doing a hands-on for learning and have created a model in python using numpy that's being trained on breast cancer dataSet from sklearn library. Model is running without any error and giving me Train and Test accuracy as 92.48826291079813% and 90.9090909090909% respectively. However somehow I'm not able to complete the hands-on since (probably) my result is different than expected. I don't know where the problem is because I don't know the right answer, also don't see any error.Would request someone to help me with this. Code is given below.#Import numpy as np and pandas as pd"""import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_breast_cancer**Define method initialiseNetwork() initilise weights with zeros of shape(num_features, 1) and also bias b to zeroparameters: num_features(number of input features)returns : dictionary of weight vector and bias**def initialiseNetwork(num_features): W = np.zeros((num_features,1)) b = 0 parameters = {"W": W, "b": b} return parameters** define function sigmoid for the input z. parameters: zreturns: $1/(1+e^{(-z)})$ **def sigmoid(z): a = 1/(1 + np.exp(-z)) return a** Define method forwardPropagation() which implements forward propagtion defined as Z = (W.T dot_product X) + b, A = sigmoid(Z)parameters: X, parametersreturns: A **def forwardPropagation(X, parameters): W = parameters["W"] b = parameters["b"] Z = np.dot(W.T,X) + b A = sigmoid(Z) return A** Define function cost() which calculate the cost given by −(sum(Y\*log(A)+(1−Y)\*log(1−A)))/num_samples, here * is elementwise productparameters: A,Y,num_samples(number of samples)returns: cost ** def cost(A, Y, num_samples): cost = -1/num_samples * np.sum(Y*np.log(A) + (1-Y)*(np.log(1-A))) #cost = Y*np.log(A) + (1-Y)*(np.log(1-A)) return cost** Define method backPropgation() to get the derivatives of weigths and biasparameters: X,Y,A,num_samplesreturns: dW,db **def backPropagration(X, Y, A, num_samples): dZ = A - Y dW = (np.dot(X,dZ.T))/num_samples #(X dot_product dZ.T)/num_samples db = np.sum(dZ)/num_samples #sum(dZ)/num_samples return dW, db** Define function updateParameters() to update current parameters with its derivatives w = w - learning_rate \* dw b = b - learning_rate \* db parameters: parameters,dW,db, learning_rate returns: dictionary of updated parameters ** def updateParameters(parameters, dW, db, learning_rate): W = parameters["W"] - (learning_rate * dW) b = parameters["b"] - (learning_rate * db) return {"W": W, "b": b}** Define the model for forward propagation parameters: X,Y, num_iter(number of iterations), learning_ratereturns: parameters(dictionary of updated weights and bias) **def model(X, Y, num_iter, learning_rate): num_features = X.shape[0] num_samples = X.shape[1] parameters = initialiseNetwork(num_features) #call initialiseNetwork() for i in range(num_iter): #A = forwardPropagation(X, Y, parameters) # calculate final output A from forwardPropagation() A = forwardPropagation(X, parameters) if(i%100 == 0): print("cost after {} iteration: {}".format(i, cost(A, Y, num_samples))) dW, db = backPropagration(X, Y, A, num_samples) # calculate derivatives from backpropagation parameters = updateParameters(parameters, dW, db, learning_rate) # update parameters return parameters** Run the below cell to define the function to predict the output.It takes updated parameters and input data as function parameters and returns the predicted output **def predict(X, parameters): W = parameters["W"] b = parameters["b"] b = b.reshape(b.shape[0],1) Z = np.dot(W.T,X) + b Y = np.array([1 if y > 0.5 else 0 for y in sigmoid(Z[0])]).reshape(1,len(Z[0])) return Y** The code in the below cell loads the breast cancer data set from sklearn.The input variable(X_cancer) is about the dimensions of tumor cell and targrt variable(y_cancer) classifies tumor as malignant(0) or benign(1) **(X_cancer, y_cancer) = load_breast_cancer(return_X_y = True)** Split the data into train and test set using train_test_split(). Set the random state to 25. Refer the code snippet in topic 4 **X_train, X_test, y_train, y_test = train_test_split(X_cancer, y_cancer, random_state = 25)** Since the dimensions of tumor is not uniform you need to normalize the data before feeding to the networkThe below function is used to normalize the input data. **def normalize(data): col_max = np.max(data, axis = 0) col_min = np.min(data, axis = 0) return np.divide(data - col_min, col_max - col_min)** Normalize X_train and X_test and assign it to X_train_n and X_test_n respectively **X_train_n = normalize(X_train)X_test_n = normalize(X_test)** Transpose X_train_n and X_test_n so that rows represents features and column represents the samplesReshape Y_train and y_test into row vector whose length is equal to number of samples.Use np.reshape() **X_trainT = X_train_n.T#print(X_trainT.shape)X_testT = X_test_n.T#print(X_testT.shape)y_trainT = y_train.reshape(1,X_trainT.shape[1])y_testT = y_test.reshape(1,X_testT.shape[1])** Train the network using X_trainT,y_trainT with number of iterations 4000 and learning rate 0.75 **parameters = model(X_trainT, y_trainT, 4000, 0.75) #call the model() function with parametrs mentioned in the above cell** Predict the output of test and train data using X_trainT and X_testT using predict() method> Use the parametes returned from the trained model **yPredTrain = predict(X_trainT, parameters) # pass weigths and bias from parameters dictionary and X_trainT as input to the functionyPredTest = predict(X_testT, parameters) # pass the same parameters but X_testT as input data** Run the below cell print the accuracy of model on train and test data. ***accuracy_train = 100 - np.mean(np.abs(yPredTrain - y_trainT)) * 100accuracy_test = 100 - np.mean(np.abs(yPredTest - y_testT)) * 100print("train accuracy: {} %".format(accuracy_train))print("test accuracy: {} %".format(accuracy_test))My Output:train accuracy: 92.48826291079813 %test accuracy: 90.9090909090909 %
I figured out where the problem was. It was the third line in predict function where I was reshaping bias which was not at all necessary.def predict(X, parameters): W = parameters["W"] b = parameters["b"] **b = b.reshape(b.shape[0],1)** Z = np.dot(W.T,X) + b Y = np.array([1 if y > 0.5 else 0 for y in sigmoid(Z[0])]).reshape(1,len(Z[0])) return Yand third line in back-propagation function needed to be corrected as np.sum(dZ)/num_samples.def backPropagration(X, Y, A, num_samples): dZ = A - Y dW = (np.dot(X,dZ.T))/num_samples ** db = sum(dZ)/num_samples ** return dW, dbAfter I corrected both functions, the model gave me train accuracy as 98.59154929577464% and test accuracy as 93.00699300699301%.
Numpy Histogram over very tiny floats I have an array with small float numbers, here is an exempt:[-0.000631510156545283, 0.0005999252334386763, 2.6784775066479167e-05, -6.171351407584846e-05, -2.0256783283654057e-05, -5.700196588437318e-05, 0.0006830172130385885, -7.862102776837944e-06, 0.0008167604859504389, 0.0004497656945683915, -0.00017132944173890756, -0.00013510823579343265, 0.00019666267095029728, -9.0271602657355e-06, 0.0005219852103996746, 4.010928726736523e-05, -0.0005287787999295592, 0.00023883106926381664, 0.0006348661301799839, 0.0003881285984411852](Edit: The whole array contains ~40k floats)The numbers show the change of a measurement over time, e.g. +0.0001 means the measurement increases by 0.0001.I'd like to plot a histogram over the whole array. Currently, pyplot.hist creates a plot which plugs all values in one bin (This image shows the current histogram., created with the following code (edited):import matplotlib.pyplot as pltfig, axs = plt.subplots(1, 1, figsize=(20,20))array = [] # floats hereaxs.hist(array,bins=10)axs.set_ylabel("Histogram of temperature/weight ratio")axs.set_xlabel("Bins")).I guess this is due to the very small numbers - am I right here?I tried using hist, bins = numpy.histogram() and plot this, with the same results. (Following this question here).How can I create a histogram over such small numbers, so that the values are distributed over e.g. 100 bins, and not all plugged into the first bin? Do I need to preprocess my data?
For other people looking for an answer:As Jody Klymak suggested in a comment to my question, manually specify the bins.I did not need to preprocess the data further, as I thought I had to do.Example:import matplotlib.pyplot as pltimport bumpy as nparray = [...] # large array with tiny floatsfig, axs = plt.subplots(1, 1, figsize=(20,20))hist = axs.hist(array, np.arange(-0.01, 0.01, 0.0001)) #numpy to create bins over rangeplt.show()
Change bar colors in pandas matplotlib bar chart by passing a list/tuple There are several threads on this topic, but none of them seem to directly address my question. I would like to plot a bar chart from a pandas dataframe with a custom color scheme that does not rely on a map, e.g. use an arbitrary list of colors. It looks like I can pass a concatenated string with color shorthand names (first example below). When I use the suggestion here, the first color is repeated (see second example below). There is a comment in that post which eludes to the same behavior I am observing. Of course, I could do this by setting the subplot, but I'm lazy and want to do it in one line. So, I'd like to use the final example where I pass in a list of hex codes and it works as expected. I'm using pandas versions >=0.24 and matplotlib versions >1.5. My questions are:Why does this happen?What am I doing wrong?Can I pass a list of colors?pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color="brgmk" )pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "b", "r", "g", "m", "k" ] )pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ] )
When plotting a dataframe, the first color information is used for the first column, the second for the second column etc. Color information may be just one value that is then used for all rows of this column, or multiple values that are used one-by-one for each row of the column (repeated from the beginning if more rows than colors). See the following example:pd.DataFrame( [[ 1, 4], [2, 5], [3, 6]] ).plot(kind="bar", color=[[ "b", "r", "g" ], "m"] )So in your case you just need to put the list of color values in a list (specifically not a tuple):pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "b", "r", "g", "m", "k" ]] )orpd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ]] ) The first case in the OP (color="brgmk") works as expected as pandas internally puts the color string in a list (strings are not considered list-like).
How to compute hash of all the columns in Pandas Dataframe? df.apply is a method that can apply a certain function to all the columns in a dataframe, or the required columns. However, my aim is to compute the hash of a string: this string is the concatenation of all the values in a row corresponding to all the columns. My current code is returning NaN.The current code is:df["row_hash"] = df["row_hash"].apply(self.hash_string)The function self.hash_string is:def hash_string(self, value): return (sha1(str(value).encode('utf-8')).hexdigest())Yes, it would be easier to merge all columns of Pandas dataframe but current answer couldn't help me either.The file that I am reading is(the first 10 rows):16012,16013,16014,16015,16016,16017,16018,16019,16020,16021,1602216013,16014,16015,16016,16017,16018,16019,16020,16021,16022,1602316014,16015,16016,16017,16018,16019,16020,16021,16022,16023,1602416015,16016,16017,16018,16019,16020,16021,16022,16023,16024,1602516016,16017,16018,16019,16020,16021,16022,16023,16024,16025,16026The col names are: col_test_1, col_test_2, .... , col_test_11
You can create a new column, which is concatenation of all others:df['new'] = df.astype(str).values.sum(axis=1)And then apply your hash function on itdf["row_hash"] = df["new"].apply(self.hash_string)or this one-row should work:df["row_hash"] = df.astype(str).values.sum(axis=1).apply(hash_string)However, not sure if you need a separate function here, so: df["row_hash"] = df.astype(str).values.sum(axis=1).apply(lambda x: sha1(str(x).encode('utf-8')).hexdigest())
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card