Dataset Viewer
Auto-converted to Parquet Duplicate
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 hi...
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(number...
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 ...
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 m...
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 datafr...
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 pa...
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_injur...
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 ...
"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 whe...
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 ...
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 t...
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 mo...
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...
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 ...
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 genera...
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 ...
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 ...
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]: ...
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'...
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 simp...
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)....
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...
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&qu...
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...
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...
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]...
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 us...
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_produ...
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 o...
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])So...
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])), Tru...
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 ...
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 ...
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] == y...
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 s...
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...
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 ...
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 ...
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 ...
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 A...
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...
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...
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):...
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.01080...
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=...
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 be...
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')ValueErr...
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...
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 w...
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 ...
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 wh...
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'])['maxPri...
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.ran...
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 c...
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. ...
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...
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'), ...
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-...
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 plt...
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 quer...
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]...
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')# Crea...
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 e...
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 ...
Assuming the following input:text = ''' Name DisciplineNOC United States of America 615 615Japan 586 586Australia 470 470People's Republic of China 401 401Germany ...
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 = ro...
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 prope...
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 in...
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...
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 ...
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 =...
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...
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'], [...
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 clas...
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.Trie...
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'] ...
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 k...
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 ne...
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/*.tx...
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...
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 180...
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 implementa...
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+...
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...
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:...
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, Max...
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, ...
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...
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?...
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], [ ...
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 s...
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 ...
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_bina...
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, s...
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...
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 pl...
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['c...
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(&quo...
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(...
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: Moz...
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-...
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)app...
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', 'Attr1...
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...
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 ...
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_...
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...
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'] ...
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...
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,...
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> ...
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...
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...
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 l...
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 ...
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 __...
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 ...
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 mig...
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...
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 ...
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':...
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 colum...
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 o...
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.90909090909...
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...
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.000449...
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...
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. ...
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 ro...
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....
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 yo...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6