Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
16,000
61,585,682
Select item predictions from a prediction DataFrame in Python
<p>I am very new to DataScience/Pandas in general. I mainly followed <a href="https://beckernick.github.io/matrix-factorization-recommender/" rel="nofollow noreferrer">this guide</a> about recommender systems. </p> <p>The main difference I have is that my movie data starts out from one table, and I want to find the mo...
<p>So, in theory, this is how it works - </p> <ol> <li><p>You first create what is called a Utility matrix. This utility matrix is a (user X item) size matrix (in your case you created it with a pivot). The utility matrix can have different values as measures. For, example it could be the movie rating</p></li> <li><p>...
python|numpy|matrix|prediction|recommendation-system
2
16,001
68,529,463
Pandas group by window range (Follow up question with category)
<p><a href="https://stackoverflow.com/questions/68527072/pandas-group-by-window-range/68527189?noredirect=1#comment121110381_68527189">Follow up question</a>:</p> <p>I have the following data table: I want to extract groups within a certain window and category, for example windows_size= 1000000</p> <pre><code>value ...
<p>Use custom lambda function:</p> <pre><code>window_size = 1000000 f = lambda x: x.diff().abs().gt(window_size).cumsum() df[&quot;group&quot;] = df.groupby('category')[&quot;value&quot;].apply(f)+1 print (df) value category group 0 65951649.0 A 1 1 59397882.0 A 2 2 7633231.0 ...
python|pandas|group-by
2
16,002
68,636,723
Multiple regression, reshaping inputs with multiple independent variables
<p>I am doing multiple regression on my data, but plotting the data throws an error: <code>ValueError: x and y must be the same size</code>.</p> <pre><code>x.shape is (10000, 2) #Since I have two independent x = dataset[['green', 'blue']] y.shape is (10000,) </code></pre> <p>how can I reshape the arrays? since I hav...
<p>for this problem, you need to scatter each dimension in one plot.</p> <p>maybe this code help you:</p> <pre class="lang-py prettyprint-override"><code>color = ['g','b'] plot_number = 1 fig = plt.figure(figsize = (15,5)) for i in range(x_train.shape[1]): ax, plot_number = fig.add_subplot(1, 2, plot_number), plot_...
python|numpy|matplotlib|scikit-learn|regression
1
16,003
53,286,882
How to reindex a MultiIndex dataframe
<p>Is there a way to reindex two dataframes (of differing levels) so that they share a common index across all levels?</p> <p><strong>Demo:</strong></p> <p>Create a basic Dataframe named 'A':</p> <pre><code>index = np.array(['AUD','BRL','CAD','EUR','INR']) data = np.random.randint(1, 20, (5,5)) A = pd.DataFrame(data...
<p>To get the B using <code>reindex</code> </p> <pre><code>B.reindex( pd.MultiIndex.from_product([B.index.levels[0], A.index], names=['Bank', 'Curency']),fill_value=0) Out[62]: Notional Bank Curency Bank_1 AUD 16 BRL 0 CAD 13 EUR ...
pandas|dataframe|multi-index
38
16,004
53,104,629
Use numpy array as arguments for print()
<p>I am struggling on a very simple thing.</p> <p>I would like to print a string with a certain format:</p> <pre><code>import numpy as np array = np.array([123.456789, 1.23456, 12.3456]) print("My First number is %3.4f, second %1.2f and third %2.9f" % array) </code></pre> <p>"array" is an numpy array and include the...
<p>Pass to tuple:</p> <pre><code>print("My First number is %3.4f, second %1.2f and third %2.9f" % tuple(array)) </code></pre> <p>Or use the <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow noreferrer">new format</a></p> <pre><code>array = np.array([123.456789, 1.23456, 12.3456]) pri...
python|arrays|numpy
1
16,005
65,824,624
Data manipulation with date in DataFrame in Python Pandas?
<p>I have DataFrame like below:</p> <pre><code>df = pd.DataFrame({&quot;data&quot; : [&quot;25.01.2020&quot;, and many more other dates...]}) df[&quot;data&quot;] = pd.to_datetime(df[&quot;data&quot;], format = &quot;%d%m%Y&quot;) </code></pre> <p>And I have a series of special dates like below:</p> <pre><code>special_...
<p>You can use broadcasting to create a matrix of time deltas and than calculate the minima for your new columns</p> <pre><code>import numpy as np, pandas as pd df = pd.DataFrame({'data': pd.to_datetime([&quot;01.01.2020&quot;,&quot;25.01.2020&quot;,&quot;20.02.2020&quot;], dayfirst=True)}) s = pd.Series(pd.to_dateti...
python|pandas|dataframe|date
0
16,006
63,369,940
Why got NaN column if have string column in dataframe
<p>code</p> <pre><code>import gspread from oauth2client.service_account import ServiceAccountCredentials from gspread_dataframe import get_as_dataframe, set_with_dataframe scope = [&quot;https://spreadsheets.google.com/feeds&quot;,'https://www.googleapis.com/auth/spreadsheets',&quot;https://www.googleapis.com/auth/dri...
<p>Your question is long, but point I believe is straight forward. After creating data frame</p> <ol> <li>remove columns named <em>Unnamed</em>. Have used a list comprehension for this</li> <li>remove rows that are not relevant (<code>dropna(how=&quot;all&quot;)</code>)</li> </ol> <p>Now whatever I randomly place in...
python|pandas
0
16,007
53,492,258
How to merge using index items with Pandas
<p>I have two dataframes df_a and df_b. Both dataframes have index with three items (id / sub_id / sort_id).</p> <p>I would like to merge these two dataframes with index items.</p> <pre><code>** df_a ** | c1 | c2 | c3 | id | sub_id | sort_id | | | | 1 | 1 | 3 | a| b| ...
<p>Since you are trying to merge on the index, you specify <code>left_index=True, right_index=True</code>, which is correct, but then you can't specify <code>left_on</code> or <code>right_on</code> (the information is redundant, and not accepted):</p> <pre><code>&gt;&gt;&gt; pd.merge(df_a, df_b, left_index=True, right...
python|python-3.x|pandas
2
16,008
72,051,654
How to set specified row values in pandas based on criteria in the first row? using python
<p>Say I want to make a new column in my dataframe with a certain number of rows after the original row criteria to hold to a certain value. I have to do it in a way that does not involve looping through each individual row. How would I do that?</p> <p>Here is my example - a dataframe of random integers:</p> <pre><code...
<p>First, you can create a mask containing the shifted values multiplied 3 times using <code>functools.reduce</code> (a built-in function) . Then, you can use <code>where</code> and <code>ffill</code>:</p> <pre><code>import functools as ft N = 3 new_mask = ft.reduce(lambda x, y: x | y, [df['lt25'].shift(i) for i in ran...
python|pandas|dataframe
0
16,009
71,931,379
Struggling with Pivot table in Python - collapsing rows and performing calculations
<p>I'm wondering if anyone can point me in the right direction. I'm in over my head on a pivot table. I have a Pandas dataframe. I loaded two .csv files, dropped/renamed columns, and used concat to put them together. That all went fine. It's a list of transit stops, showing their latitude and longitude and how many tim...
<p>You can use <code>.groupby()</code> followed by <code>.agg</code>:</p> <pre class="lang-py prettyprint-override"><code>x = df.groupby(&quot;stop_code&quot;).agg( stop_lat=(&quot;stop_lat&quot;, &quot;first&quot;), stop_lon=(&quot;stop_lon&quot;, &quot;first&quot;), daily_wkdy_trips=( &quot;daily_...
python|pandas|dataframe|pivot-table
0
16,010
72,077,874
Python Dataframe subtract a value from each list of a row
<p>I have a data frame consisting of lists as elements. I want to subtract a value from each list and create a new column. My code:</p> <pre><code>df = pd.DataFrame({'A':[[1,2],[4,5,6]]}) df A 0 [1, 2] 1 [4, 5, 6] # lets substract 1 from each list val = 1 df['A_new'] = df['A'].apply(lambda x:[a-b for a...
<p>Convert to <code>numpy</code> <code>array</code></p> <pre><code>df['A_new'] = df.A.map(np.array)-1 Out[455]: 0 [0, 1] 1 [3, 4, 5] Name: A, dtype: object </code></pre>
python|pandas|list|dataframe|numpy
3
16,011
72,013,097
Increase text of the dropdown menu - Python
<p>I am trying to create dropdown menu using the following code on Python.</p> <pre><code>pqrs = ['Segment1', 'Segment2', 'Segment3'] #Segment Criteria Segment_selected = widgets.Text() # print('=' * term_size.columns) # print('\n' +&quot;\033[1m&quot; + 'Select a Segment criteria for Selecting HCP Universe' + &quot;\...
<p>Initially comments widths are fixed. You can set a style to make it bigger - this will reduce the overall other sizes of your widget:</p> <pre><code>pqrs = ['Segment1', 'Segment2', 'Segment3'] int_widget = interactive(lx, Segmentation=pqrs, ) int_widget.children[0].layout = Layout(width='auto',height = '40px') int_...
python|pandas|jupyter-notebook|interactive|ipywidgets
1
16,012
55,514,651
How do i get the value of the neural network predicted for a single image?
<p>I am trying to create a simple python script that will allow you to put in picture of a handwritten digit and the NN model will try to make a guess as to what digit it is so far I have successfully made the model as well as tested it but when it comes to testing a single image i get an output like this.</p> <p><a h...
<p>It's a bit difficult to tell from the information you give. However, I think it is highly likely that the output you are getting are just the logits, before the softmax output layer.</p> <p>Feed this output for a softmax layer and then you get a probability distribution over the outputs. In your particular case the...
python|tensorflow|neural-network|mnist
0
16,013
56,798,056
When using a Tensorflow Estimator in AWS Sagemaker, will the training job automatically save the model artifacts to /opt/ml/model?
<p>I am trying to train a Tensorflow Estimator and upload the created model artifacts to S3. The training job completed successfully, but we get a warning saying "No model artifact is saved under path /opt/ml/model. Your training job will not save any model files to S3." This becomes an issue when we are trying to depl...
<p>The Estimator doesn't save the model, you have do it :) You also need to make sure that you save the model in the the right place. With script mode, SageMaker passes the output location to your code in os.environ['SM_MODEL_DIR'], so just use that value and you'll be fine.</p> <p>If you want to deploy with the SageM...
python|tensorflow|amazon-s3|tensorflow-estimator|amazon-sagemaker
2
16,014
56,526,254
merge multiple columns value of a dataframe into a single column with bracket in middle
<p>I have a dataframe.</p> <pre><code>category value percentage_difference Cosmetics 789.99 300.0 Fruits 27.68 400.0 Clothes 179.20 500.0 </code></pre> <p>I want to add fourth column so that its value is category(value, percentage)</p> <pre><code>category value percentage_differenc...
<p>Another approach is just add the column as strings:</p> <pre><code>df=df.assign(merge_value= df.category+"("+df.value.astype(str)+','+df.percentage_difference.astype(str)+"%)") print(df) </code></pre> <hr> <pre><code> category value percentage_difference merge_value 0 Cosmetics 789.99 ...
python|pandas|dataframe|merge
6
16,015
66,764,656
how to call a function on each group?
<p>Hi I have a data frame and in one of the columns I have a list of titles. I wrote a function called <code>find_freq</code> to find frequency of the elements of these lists. But I need to call this function on each group. Any idea how to call the function on each group <code>G1</code> ,<code>G2</code> and <code>G3</c...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a>:</p> <pr...
pandas|group-by|grouping
2
16,016
47,245,698
numpy: create a 2d numpy array where each row is filled with strings from a regular array
<p>I have a regular list filled with strings of equal length:</p> <pre><code>['FADVAG', 'XXDXFA', 'GDXX..'] </code></pre> <p>I want to transform it into a 2d numpy array, like the following:</p> <pre><code>[['F' 'A' 'D' 'V' 'A' 'G'] ['X' 'X' 'D' 'X' 'F' 'A'] ['G' 'D' 'X' 'X' '.' '.']] </code></pre> <p>How can I do ...
<p><code>list('astring')</code> splits up the characters:</p> <pre><code>In [187]: alist=['FADVAG', 'XXDXFA', 'GDXX..'] In [188]: arr = np.array([list(a) for a in alist]) In [189]: arr Out[189]: array([['F', 'A', 'D', 'V', 'A', 'G'], ['X', 'X', 'D', 'X', 'F', 'A'], ['G', 'D', 'X', 'X', '.', '.']], ...
python|numpy
1
16,017
68,191,956
Does Google Colab use GPU for NLTK based lemmatization?
<p>I'm trying to run below given piece of code on Google Colab, here the <code>corpus['text']</code> is obtained by executing <code>Corpus['text']= [word_tokenize(entry) for entry in Corpus['text']]</code>. Note that before executing the above line, <code>Corpus['text']</code> was a dataframe consisting of 1M sentences...
<p>Something like lematization will not be done on the GPU. Your issue is likely the line where you check for stopwords. NLTK stopwords is a list which is very slow to check in a loop. Try converting it to a set with something like this...</p> <pre><code># Put this at the top stops = set(stopwords.words('english')) ...
python-3.x|pandas|deep-learning|google-colaboratory|lemmatization
0
16,018
68,119,276
pandas long to wide format - splitting based on smaller vs larger value in column X
<p>I have a df with longitudinal data (two observations per individual), their age and score at each point. Currently, the df is in long format:</p> <pre><code>subj = ['subj1', 'subj1', 'subj2', 'subj2', 'subj3', 'subj3'] age = [37, 40, 56, 41, 27, 29] score = [2,1,2,5,3,5] pd.DataFrame(list(zip(subj, age, score)), ...
<p>One way:</p> <pre><code>df1 = df.sort_values(['subj', 'age']) df = pd.concat([df1.iloc[::2,[0,2]].set_index('subj'), df1.iloc[1::2,[0, 2]].set_index('subj')], 1) df.columns = ['score_time1', 'core_time1'] </code></pre> <p>Alternative via <code>pivot_table</code> and <code>rank</code>:</p> <pre><code>df = ( df.pi...
python|pandas|dataframe
2
16,019
68,402,726
Image classification using tensorflow lite without Google Coral USB
<p>I am trying to evaluate a Raspberry Pi performance with a Google Goral Edge TPU USB device and without it for an image classification task on a video file. I have managed to evaluate the peformance using the Edge TPU USB device already. However, when I try running a tensorflow lite code to run inference it gets me a...
<p>I recently came into this for a thesis supervision. We tested face detection in a raspberry pi 4 with Coral USB an without (inference on rpi CPU). Are you using the same model file for both? If this is the case, then this is the problem. You need to use the bare tflite model for the CPU inference and the TPU-compile...
raspberry-pi|tensorflow-lite|tpu|google-coral|edge-tpu
0
16,020
46,114,809
Vectorized lookup on a pandas dataframe
<p>I have two DataFrames . . . </p> <p><code>df1</code> is a table I need to pull values from using index, column pairs retrieved from multiple columns in df2.</p> <p>I see there is a function <code>get_value</code> which works perfectly when given an index and column value, but when trying to vectorize this function...
<blockquote> <p><strong>Deprecation Notice</strong>: <code>lookup</code> was <a href="https://pandas.pydata.org/docs/whatsnew/v1.2.0.html#deprecations" rel="nofollow noreferrer">deprecated in v1.2.0</a></p> </blockquote> <p>There's a function aptly named <code>lookup</code> that does exactly this.</p> <pre><code>df2['l...
python|pandas|dataframe|vectorization|lookup
5
16,021
45,949,736
tensorboard stuck when executed at command prompt
<h3>System information</h3> <ul> <li><strong>Have I written custom code (as opposed to using a stock example script provided in TensorFlow)</strong>: No</li> <li><strong>OS Platform and Distribution (e.g., Linux Ubuntu 16.04)</strong>: Windows 10 Pro 1703</li> <li><strong>TensorFlow installed from (source or binary)</...
<p>There is a github issue filed for this: <a href="https://github.com/tensorflow/tensorflow/issues/12693" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/12693</a></p>
python|tensorflow|tensorboard
0
16,022
45,857,760
NumPy nearest value along axis of multidimensional array
<p>I'd like to create a function, that returns the nearest value in the array along a specified axis to a given value.</p> <p>To get the index of the nearest value I use the following code where <code>arr</code> is a multidimensional array and <code>value</code> is the value to look for:</p> <pre><code>def nearest_in...
<p>For a multi-dimensional array, we need to use <code>advanced-indexing</code>. So, for a generic <code>n-dim</code> array and with a specified axis, we could do something like this -</p> <pre><code>def argmin_values_along_axis(arr, value, axis): argmin_idx = np.abs(arr - value).argmin(axis=axis) shp = arr...
python|arrays|numpy
2
16,023
66,729,869
Regex finding word next to a key word in Pandas column and replace few characters
<p>I have a dataframe which looks like as below</p> <pre><code>df = pd.DataFrame({'A': [0, 1, 2, 3, 4], 'B': ['a is host 0itdsiekivnme0itdxm', 'mmm pc is host sesoltsm09sds', 'winter on is host sesdfdfdf9', 'd is host SESCPIWM1344 sdfds asd', 'check my host sesdfdsm1dsdd0 friendly']}) </code></pre> <p>I am t...
<p>Your regex is almost there, but you need to modify your capture group to <code>(\s+)</code> so you only capture the spaces after <code>host</code>.</p> <p>Leave the <code>\w{2}</code> outside the capture parentheses -- if you put <code>\w{2}</code> inside the parentheses, then you include those 2 characters in the c...
python|regex|pandas
1
16,024
57,524,548
Reuse opened datafiles in Pandas
<p>I have created a number of different functions to perform analysis of the same data. The data is in a large csv file, and I don't want to open it multiple times to be able to use the data.</p> <p>I have created a function just to open the data - this function will check if the dataframe is empty, and then open the ...
<p>There is no reason why you can't split your methods the way you want. Try this:</p> <pre><code># get_data.py DATA = pd.Dataframe() def get_data(): global DATA if DATA.empty: DATA = pd.open_csv('file.csv') return DATA else: return DATA __all__ = ['get_data'] </code></pre> <p>A...
python|python-3.x|pandas
1
16,025
57,359,008
Why does calling transpose in my data switch the row's index from a MultiIndex to a flat Index?
<p>I have a CSV that looks like this:</p> <pre><code>name,location,sales,customer_count john,fairfax,1000,400 jane,daly city,500,350 john,springfield,800,240 john,richmond,200,80 jane,san jose,300,90 george,albany,200,60 john,centreville,600,150 </code></pre> <p>I iterate through each row 3 records at a time:</p> <p...
<p>The original <code>MultiIndex</code> <em>in its entirety</em> becomes the columns. The <em>remaining</em> columns from <em>before</em> the transpose (<code>customer_count</code>, <code>sales</code>) become the <em>new</em> index, with no names.</p> <p>You'll see this when you inspect the <code>pivot_table_row.index...
python|pandas
1
16,026
73,115,894
How do I get the first non-null value from multiple columns based on another datetime column order and grouped by ID?
<p>What I've got right now is a DataFrame like this:</p> <pre><code> id ts site type 0 111 2022-07-25 19:07:00.938365 A NaN 1 111 2022-07-25 19:07:00.938371 NaN 1.0 2 222 2022-07-25 19:07:00.938372 NaN NaN 3 222 2022-07-25 19:07:00.938373 NaN 2.0 4 222 2022-07-...
<p>You can do like this:</p> <pre><code>df = df.sort_values('ts', ascending=False) df.groupby('id', as_index=False)[['site', 'type']].agg(lambda x: x.dropna().iloc[0]) </code></pre> <p>or using <code>first_valid_index</code>:</p> <pre><code>df.groupby('id', as_index=False)[['site', 'type']].agg(lambda x: x[x.first_val...
python|pandas|dataframe
0
16,027
70,390,630
Create numpy array once while having easy access
<p>I am currently working with a large numpy array which contains several thousand elements.<br /> The array is basically 'static' and is never modified. There are several functions that need this array and therefore I want to have easy access to it.<br /> If I understood correctly it should be avoided to make variable...
<p>You can try this:</p> <p><a href="https://numpy.org/doc/stable/user/basics.creation.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/user/basics.creation.html</a></p> <p>arrays can easily be made with</p> <pre><code>import numpy as np array = np.array([1, 2, 3, 4]) </code></pre> <p>and, every time you c...
python|arrays|numpy
0
16,028
51,391,745
Pandas, subsorting/ordering a grouped series within a super-date/series
<p>Kind of at a loss for words as to how to describe. I have a dataset that I want to keep in datetime order but somehow the hour value got jumbled and I'd liked it be in ascending order as well, 1,2,3.... I've tried df.group(['XX','hour']).sort_by('hour'); and using .groupby().size('hour'). Not seeing how to do it wit...
<p>You can create a helper key by using <code>cumcount</code> , then <code>sort_values</code></p> <pre><code>new_df=df.assign(helperkey=df.groupby('hour').cumcount()).sort_values(['datetime','helperkey','hour']) new_df Out[524]: id datetime hour XX YY helperkey 1 1 2018/01/01 1 chairs 3 ...
python|pandas
1
16,029
70,786,391
Pandas group_by string column which values contained in a separate list
<p>I have a hierarchy-based event stream, where each hierarchy parent node(represented as level0/1) has multiple children (level0(0/1/2) and sub child (level00(0/1/2)). &quot;level&quot; is just a placeholder, each hierarchy level has its own unique name. The only rule is that a parent node hierarchy string is always i...
<p>You can try:</p> <pre><code>count = [df['hierarchystr'].str.startswith(hstr).sum() for hstr in hstrs] out = pd.DataFrame({'hstr': hstrs, 'count': count}) print(out) # Output hstr count 0 level0 6 1 level1 3 2 level0level01 1 3 lev...
regex|pandas|group-by|extract|contains
0
16,030
71,040,077
Adding a dimension to a numpy arrray
<p>I'm working on the MNIST dataset and have my <code>train_x.shape = (60000, 28, 28, )</code>,<br /> but my model requires a shape <code>(60000, 28, 28, 1)</code>.<br /> So my questions are:</p> <ol> <li>Why does it have a 'null' dimension instead of just <code>(60000, 28, 28)</code>?</li> <li>How can I convert the sa...
<p>Good question! I too pondered why it had to be like this when I first started.</p> <p>Looping through the first dimension can be easily done with</p> <pre class="lang-py prettyprint-override"><code>for image in train_x: image </code></pre> <p>as looping through NumPy, PyTorch and TensorFlows arrays/tensors will ...
python|arrays|numpy
1
16,031
51,758,626
Pandas empty dataframe resulting from an isin function that keeps objects with an ID if the ID is present in a dataFrame of just IDs
<p>I've got 2 data frames, one with 1 column currentWorkspaceGuid (workspacesDF) and another with 4 columns currentWorkspaceGuid, modelGuid, memoryUsage, lastModified (extrasDF) and I'm trying to get isin to result in a dataFrame that shows the values from the second dataframe only if the workspaceGuid exists in the wo...
<p>I think need compare columns (<code>Series</code>):</p> <pre><code>mask = extrasDF['currentWorkspaceGuid'].isin(workspacesDF['currentWorkspaceGuid']) in_workspaces = extrasDF[mask] print (in_workspaces) currentWorkspaceGuid modelGuid \ 0 8a81b09c56cdf89c0157345759d75644 63...
python|python-3.x|pandas|dataframe
1
16,032
51,989,702
Pandas Sampling Every Time Condition is Met
<p>Given a pandas dataframe, I want to get the indices of each row when the sum of the previous row's column value (or current row's column value) is equal to or greater than n, then the sum restarts back to zero. So for example, if our dataframe has values:</p> <pre><code>index colB 1 10 2 20 3 5 ...
<p>There may be a clever way with some combination of <code>cumsum()</code> but this is a tough problem because the value needs to reset after the sum is greater than <code>n</code>. So it's kind of like a rolling sum with a window no greater than <code>n</code>.</p> <p>I would probably use a custom function for this....
python|pandas
0
16,033
51,959,431
Efficiently assign columns headers to csv file
<p>I'm enquiring about efficiently assigning column headers to CSV files with a comma delimiter. At the moment time I'm manually assigning the headers once I know how many columns there are. The problem is, the number of columns varies with different files.</p> <p>So the first <code>Dataframe</code> below has 3 column...
<p>Use the <em>list comprehension</em>, <code>string</code> built-in module and the length of your dictionary <code>d</code>:</p> <pre><code>df.columns = ([x for x in string.ascii_uppercase if ord(x) &lt; ord("A") + len(d)]) </code></pre> <p>as <code>string.ascii_uppercase</code> is the <code>'ABCDEFGHIJKLMNOPQRSTUVW...
python|pandas|csv|dataframe
1
16,034
36,201,528
How can I retrieve a row by index value from a Pandas DataFrame?
<p>I have created a dataframe and set an index:</p> <pre><code>df = pd.DataFrame(np.random.randn(8, 4),columns=['A', 'B', 'C', 'D']) df = df.set_index('A') </code></pre> <p>The dataframe looks like this:</p> <pre><code> B C D A 0.687263 -1.700568 0.140175 1.420394 -0.212621 -0.700...
<p>pandas rounds values when it prints a dataframe. The actual value you are trying to index on is: </p> <p>1.764052345967664</p> <pre><code>import pandas as pd import numpy as np np.random.seed(0) df = pd.DataFrame(np.random.randn(8, 4),columns=['A', 'B', 'C', 'D']) df = df.set_index('A') print df ...
python|pandas
28
16,035
36,070,040
TypeError: unique() got an unexpected keyword argument 'return_counts'
<p>I am trying to count unique values in an array by using these statements:</p> <pre><code>unique, counts = np.unique(temp, return_counts= True) print np.asarray((unique, counts)).T </code></pre> <p>But I'm getting below error,</p> <pre><code>TypeError: unique() got an unexpected keyword argument 'return_counts' </...
<p>I made use of dictionary to count the unique values and and the logic is working great with the tool, I am using.</p> <pre><code>if temp[k][l] in dict_temp: cnt = dict_temp.get(temp[k][l]) cnt =cnt+1 dict_temp.update({temp[k][l]:cnt}) else: ...
python|numpy|python-2.x
0
16,036
37,498,537
How to remove everything after the last occurence of a character in a Dataframe?
<p>I have a dataframe <code>DF</code> that looks like this (This is a sample): </p> <pre><code> EQ1 EQ2 EQ3 0 Apple.fruit Oranage.eatable.fruit NaN 1 Pear.eatable.fruit Banana.fruit NaN 2 Orange.fruit Tomato.eatable ...
<p>You could do:</p> <pre><code>df_temp = df.apply(lambda x: x.str.split('.').str[:-1].str.join('.')) </code></pre> <p>output:</p> <pre><code> EQ1 EQ2 EQ3 0 Apple Oranage.eatable NaN 1 Pear.eatable Banana NaN 2 Orange To...
python|python-3.x|pandas
8
16,037
37,300,623
Function that extracts value from one array depending on the value of another array
<p>my data consists from two numpy arrays 'a' and 'b':</p> <pre><code>In: a # numpy array, type int64 Out: array([4, 3, 1, ..., 3, 2, 3]) In: b # numpy array, type float 64 Out: array([[-0.07], [ 0.08], [-0.53], ..., [ 0.25], [ 0.52], [ 0.11]]) </code></pre> <p>Both arrays...
<p>This should work. Note the way I made the b array is different than how you have it formatted up there. Basically, you just need an incrementer, in this case I used j. Then loop through a, and whenever a is equal to 5, append the corresponding b value to results</p> <pre><code>import numpy as np a = np.array([4,3,...
python|numpy
1
16,038
41,964,212
Conflict Protobuf version when using Opencv and Tensorflow c++
<p>I am currently trying to use Tensorflow's shared library in a non-bazel project, so I creat a .so file from tensorflow using bazel.</p> <p>but when I launch a c++ program that uses both Opencv and Tensorflow, it makes me the following error :</p> <blockquote> <p>[libprotobuf FATAL external/protobuf/src/google/pr...
<p>You should rebuild TensorFlow with a linker script to avoid making third party symbols global in the shared library that Bazel creates. This is how the Android Java/JNI library for TensorFlow is able to coexist with the pre-installed protobuf library on the device (look at the build rules in <a href="https://github....
c++|opencv|tensorflow|protocol-buffers
6
16,039
37,843,864
How to control index returned by pandas groupby with rolling summary function
<p>I have data with a MultiIndex, like this:</p> <pre><code>import itertools idx1 = list('XYZ') idx2 = range(3) idx = pd.MultiIndex.from_tuples(list(itertools.product(idx1,idx2))) df = pd.DataFrame(np.random.rand(9,4), columns=list('ABCD'), index=idx) A B C D first second ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>group_keys=False</code></a>:</p> <pre><code>In [43]: df.groupby(level=0, group_keys=False).rolling(2).sum() Out[43]: A B C D X 0 NaN NaN NaN ...
python|pandas
4
16,040
37,924,379
How can I add an optional input to a graph in TensorFlow?
<p>I basically want to have the option to feed input to the middle of the graph and compute the output going from there. One idea I had is to use <code>tf.placeholder_with_default</code> that defaults to a zero tensor. Then I could mix the optional inputs using addition, however addition on a large shape this seems to ...
<p>I understand better thanks to your code.</p> <p>Basically the schema is:</p> <pre><code> input &lt;- you can feed here | (encoder) | bottleneck &lt;- you can also feed here instead | (decoder) | output </code></pre> <hr /> <p>You want t...
tensorflow
16
16,041
37,918,787
What is fastest in reading data: dict, array np-array
<p>I created three versions to store, but more important to read data in python3:</p> <ol> <li>1st: a dict with 970200 key - value pairs</li> <li>2nd: an 3-D np-array with dimension 100 and the same 907200 entries</li> <li>3rd: an array same as the np-array</li> </ol> <p>Reading times for 500.000 reading operations a...
<p>NumPy is fast for numerical calculations on (large) arrays. You are measuring the access time for one element from Python code. Take this example: </p> <pre><code>import numpy as np n = 10 a = np.arange(n) d = dict.fromkeys(range(n)) </code></pre> <p>The access to the dictionary is faster:</p> <pre><code>%timeit...
arrays|python-3.x|numpy|dictionary
0
16,042
31,443,337
Passing Variable Via Name (not value) from IPython Terminal to Python Script
<p>Python novice here. I'm attempting to pass a tuple of large numpy arrays to a script for processing, so I need to use their variable names to pass them from the IPython terminal. </p> <p>The capability I'm looking for can be simplified to the following:</p> <p>Suppose script.py is a script that simply prints the v...
<p>IPython is calling the program on the command line. It's passing <code>t</code>, which you think is a variable name, as a string. So the only argument your script is getting is <code>"t"</code>.</p> <p>If you want to pass variables into a script, what you want to do is import the script, and then call the functio...
python|numpy
2
16,043
31,247,190
pseudo increasing the 'resolution' of a value table
<p>I have an measurement array with 16.000 entries in the form of</p> <pre><code>[t] [value] </code></pre> <p>the problem is my data logger is too slow and i only have measurement points every second. For my simulation i need the resolution pseudo increased. So that every time step is divided by 1000 and every measur...
<p>Though it's difficult to tell exactly what you're asking, I'm guessing that you're just looking to interpolate between the values that you've already got. Good thing <code>numpy</code> has a simple built-in for this, the <code>interp1d</code> module (<a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generate...
python|arrays|numpy|indexing
0
16,044
47,800,200
Replace first n elements in pandas dataframe column
<p>I want to replace the first <code>n</code> elements of a column in my data frame with another pd.series I have saved. So as an example,</p> <pre><code> category price store testscore 0 Cleaning 11.42 Walmart NaN 1 Cleaning 23.50 Dia NaN 2 Entertainment 19.99 Walm...
<p>Simply use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html#pandas-dataframe-loc" rel="noreferrer">df.loc</a>:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'], ...
python|pandas
6
16,045
47,666,070
Scraped CSV pandas dataframe I get: ValueError('Length of values does not match length of ' 'index')
<p>I run below code and get:</p> <pre><code>raise ValueError('Length of values does not match length of ' 'index') </code></pre> <p>ValueError: Length of values does not match length of index</p> <p>for:</p> <pre><code>print(df3) zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan) df3['O2'] = zz #Error Line </...
<p>The correct syntax is:</p> <pre><code>df3['O2'] = pd.Series(za) </code></pre> <p>Not a scraping problem at all upon investigation with isolated python script and simplified.</p>
python|python-3.x|pandas|selenium|web-scraping
0
16,046
49,264,518
Bokeh not reading sorted Pandas Dataframe correctly
<p>I'm trying to make a sorted bar graph with a dual y-axis. So far, I have the graph in place but I am trying to sort it from the most to the least enrollment.</p> <p>Here is the code for how I've sorted my data frame:</p> <pre><code> #Merging the Two DFs viz_df = pd.merge(totenrl_df, gpaAvg_df, on = 'Institution') ...
<p>I just had this same issue. The problem is, Bokeh is referring to the index column to provide data. When you sort, Pandas doesn't automatically reset the index (you can observe this in the index column of the table you shared) so all you have to do is, after the sort, put .reset_index() and it should run fine.</p>
python|python-3.x|pandas|visualization|bokeh
0
16,047
48,962,755
Generating dataset to fit to LogisticRegression, but not DecisionTreeClassifier
<p>Have a study case, need some help. I have 2 classifiers, LogisticRegression, and DecisionTreeClassifier with depth 3. Need to generate 3 datasets 1000x2, 500 objects in each class. First dataset should have score > 0.9 with LR and score &lt; 0.7 with Trees, second dataset should do the opposite. Third should have sc...
<p>I can give you approach which might work as per my understanding but can not give you code :D</p> <p>Main Difference between Logistic Regression and Decision Tree: 1) Logistic regression draws straight line to differentiate 2 classes where Decision Tree can be useful when when it's not possible to differentiate bet...
python|numpy|scikit-learn|logistic-regression|decision-tree
1
16,048
49,041,110
CSV data to Numpy structured array?
<pre class="lang-none prettyprint-override"><code>Name Class Species a 1 3 b 2 4 c 3 2 a 1 3 b 2 1 c 3 2 </code></pre> <p>This above mentioned data will be from CSV file. need to convert this to structured array using numpy. need header from the csv become the colu...
<p>This is one way to create a <code>numpy</code> structured array from a csv file:</p> <pre><code>import pandas as pd arr = pd.read_csv('file.csv').to_records(index=False) # rec.array([('a', 1, 3), ('b', 2, 4), ('c', 3, 2), ('a', 1, 3), ('b', 2, 1), # ('c', 3, 2)], # dtype=[('Name', 'O'), ('Cl...
python|arrays|python-3.x|numpy|csv
1
16,049
58,794,731
Desperately Need Advice on Converting Date Column
<p>I have a dataset that has mixed data types in the Date column. For example, the column looks like this:</p> <pre><code>ID Date 1 2019-01-01 2 2019-01-02 3 2019-11-01 4 40993 5 40577 6 39949 </code></pre> <p>When I just try to convert the column using pd.to_datetime, I get an error mess...
<p>I'm guessing those are excel date format?</p> <p><a href="https://stackoverflow.com/questions/38454403/convert-excel-style-date-with-pandas">Convert Excel style date with pandas</a></p> <pre><code>import xlrd def read_date(date): try: return xlrd.xldate.xldate_as_datetime(int(date), 0) except: ...
python|pandas|date|datetime
1
16,050
59,000,083
How to disable e.g. Dropout in tf.keras.Model to generate activation maximation images using transfer learning
<p>I am using transfer learning and keras.applications.InceptionV3. I manage to train the model successfully.</p> <p>However, when I want to generate "activation maximisation" images (e.g. the input image that maximizes the activation of one of the custom classes, ref eg <a href="https://arxiv.org/pdf/1512.02017v3.pd...
<p>I just came across the same question. After reading some documentation and having a look on the source code of TensorFlows implementations of <code>tf.keras.layers.Layer</code>, <code>tf.keras.layers.Dense</code>, and <code>tf.keras.layers.BatchNormalization</code> I got the following understanding.</p> <p>If <code>...
tensorflow2.0|tf.keras
0
16,051
70,336,649
Finding the min and max date from a timeseries range in pandas
<p>I have a dataframe laid out like the following with site names and a range of dates for each site.</p> <pre><code>Site Date Site_1 02/09/2011 Site_1 03/09/2011 Site_1 04/09/2011 Site_1 05/09/2011 Site_2 14/01/2010 Site_2 15/01/2010 Site_2 16/01/2010 Site_2 17/01/2010 </code></pr...
<p>I would advise using a <code>groupby</code> on the &quot;site&quot; column and aggregating each group into a <code>min</code> and <code>max</code> date.</p> <pre><code>df.groupby(&quot;Site&quot;).agg({'date': ['min', 'max']}) </code></pre> <p>This will return the <code>min</code> and <code>max</code> date for each ...
python|pandas|time-series
3
16,052
70,349,195
R to Python stochastic process translation
<p>I want to translate the R code below into Python.</p> <p>It is mainly a stochastic process that i need to translate it into Python.</p> <p>The code implements a markov chain simulation of a jump process with two volatility stages.</p> <pre><code>set.seed(42) nSim &lt;- 1E5 tau &lt;- 3 K &lt;- 105 S0 &...
<p>Your error is in the condition <code>if (t+dt)&gt;tau</code>. <code>dt</code> is an array which makes <code>(t+dt)&gt;tau</code> an array of boolean values.</p> <p>Use <code>((t+dt)&gt;tau).any()</code> or <code>((t+dt)&gt;tau).all()</code> to give the if statement meaning. <code>.all()</code> means you want every v...
python|r|pandas|numpy
1
16,053
56,210,689
Why numpy.var is O(N) space?
<p>I have an array of ~13GB. I call <code>numpy.var</code> on it to compute the variance. However, it allocates another ~13GB to do this. Why does it need O(N) space? Or am I calling <code>numpy.var</code> in a wrong way?</p> <pre><code>import numpy as np # data = ... print('Variance: ', np.var(data)) </code></pre>
<p>NumPy will create an intermediate array to compute <code>abs(data - data.mean()) ** 2</code> in order to compute the variance. You can write your own variance function with a loop and make it fast with Numba:</p> <pre><code>import numpy as np import numba as nb @nb.njit(parallel=True) def var_nb(a, ddof=0): n ...
python|numpy|memory-management|variance|space-complexity
3
16,054
64,626,217
Intersection of two 2-D numpy arrays with unequal rows and columns
<p>I have 2 arrays, one of shape (455,98) and a second with shape (182,472). A geometric description is as per the attached image. Is there a pythonic way to do this? I would also be happy to receive guidance on how to write a function to achieve this.</p> <p><a href="https://i.stack.imgur.com/h35Z0.jpg" rel="nofollow ...
<p>Don't know if I understood your question completely. However this code will add the numbers from <code>a</code> and <code>b</code> arrays within the intersection.</p> <pre><code>import numpy as np a = np.ones((455,98)) b = np.ones((182,472)) c = a[:b.shape[0], :a.shape[1]] + b[:b.shape[0], :a.shape[1]] print(c) p...
python|arrays|numpy|indexing|intersection
1
16,055
64,966,105
Counting the top 10 most frequent words per row
<p>I have the sample dataset like this:</p> <pre><code>&quot;Author&quot;, &quot;Normal_Tokenized&quot; x , [&quot;I&quot;,&quot;go&quot;,&quot;to&quot;,&quot;war&quot;,&quot;I&quot;,..] y , [&quot;me&quot;,&quot;you&quot;,&quot;and&quot;,&quot;us&quot;,..] z , [&quot;let&quot;,&quot;us&quot;,&quo...
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique(return_counts=True)</code></a> seems to be what you're looking for.</p> <h2>Data</h2> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ &quot;Author&quot;: [&quot;x&quot;, &...
python|pandas
0
16,056
64,996,801
Python convert dateTime to seconds
<p>I have a column in my dataframe formatted like 11/24/2020 7:09:45. I would like to create another column that is the delta in seconds between the previous row and current row. I may be making this way more complicated than it needs to be.</p> <pre><code>import pandas as pd import numpy as np df run run_ts 11:...
<p>Try <code>.total_seconds()</code>. See the answer to the identical question <a href="https://stackoverflow.com/a/40993004/10099100">here</a>.</p>
python|pandas|numpy|datetime
0
16,057
64,626,114
Sum of column values based on a condition in pandas
<pre><code>daychange SS 0.017065 0 -0.009259 100 0.031542 0 -0.004530 0 0.000709 0 0.004970 100 -0.021900 0 0.003611 0 </code></pre> <p>I have two columns and I want to calculate the sum of next 5 'daychange' if SS = 100.</p> <p>I am using the following right now but it does not work quite the wa...
<p>Since <code>pandas 1.1</code> you can create a <a href="https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.api.indexers.FixedForwardWindowIndexer.html" rel="nofollow noreferrer">forward rolling window</a> and select the rows you want to include in your dataframe. With different arguments my notebook kern...
python|pandas|dataframe
3
16,058
39,576,757
Assign value to a slice of a numpy array
<p>I want to get slices from a numpy array and assign them to a larger array. The slices should be 64 long and should be taken out evenly from the source array. I tried the following:</p> <pre><code>r = np.arange(0,magnitude.shape[0],step) magnitudes[counter:counter+len(r),ch] = magnitude[r:r+64] </code></pre> <p>I ...
<p><code>magnitude[r:r+64]</code> where <code>r</code> is an array is wrong. The variables in the slice must be scalars, <code>magnitude[3:67]</code>, not <code>magnitude[[1,2,3]:[5,6,7]]</code>.</p> <p>If you want to collect multiple slices you have to do something like</p> <pre><code>In [345]: x=np.arange(10) In [...
python|arrays|numpy|indexing
2
16,059
44,297,427
drop a column in numpy ndarray
<p>I've try delete numpy ndarray's 1st column (eg. A, B, C ... A, B ) through </p> <pre><code>x = np.delete(x, 0, axis=1) </code></pre> <p>or </p> <pre><code>x = np.delete(x, 0, axis=0) </code></pre> <p>However, it's not work.</p> <pre><code>ndarray shape = ( 30000, 120, 15) [[['A' 0.0 0.0 ..., 0.0 0.0 'Y']...
<p>The column is the 3rd dimension of the array, you need <code>axis = 2</code>:</p> <pre><code>import numpy as np x = np.array([[['A', 1, 2], ['B', 2, 3]], [['A', 1, 2], ['B', 2, 3]]]) x.shape #(2, 2, 3) np.delete(x, 0, axis=2) #array([[['1', '2'], # ['2', '3']], # #...
python|numpy
3
16,060
44,307,952
How to average vertically over a list containing a void list?
<p>I have a list containing the following:</p> <pre><code> list1 = [(4.974874129422414, 0.4384932775564907, 0.1879318517703546, 5.820735609514166, 0, 0), (0.15069597326856923, 0.2961961688603689, 0.21595885700786707, 5.848923022691187, 1, 0), (0.15085612758502492, 0.28850876174946627, 0.18977362640233908,...
<p>The issue you are having with numpy is the declaration of the matrix in your example. </p> <p>Given:</p> <pre><code>list1 = [(4.974874129422414, 0.4384932775564907, 0.1879318517703546, 5.820735609514166, 0, 0), (0.15069597326856923, 0.2961961688603689, 0.21595885700786707, 5.848923022691187, 1, 0), (0.15...
python|list|numpy|average|void
2
16,061
69,559,950
Selecting rows in dataframe where a value is larger than the categorical mean
<p>I'm trying to find employees that have higher salaries above the average departmental salary, but I'm having a bit of trouble in Pandas.</p> <p>In SQL, my query would look something like this:</p> <pre class="lang-sql prettyprint-override"><code>SELECT name, department, salary FROM employees e1 WHERE salary &gt; (SE...
<p>this is not as readable as i would like but i think it works:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['employees', 'department', 'salary', 'other_features'], data=[['A', 'C1', 1300, 5], ['B', 'C1', 1250, 10], ['C', 'C1', 2000, 18], ['D', 'C3', 1240, 2...
python|sql|pandas|dataframe|filtering
1
16,062
69,533,042
Python flag if word is in a dataframe dictionary
<p>I currently have dataframe which contains a column holding a dictionary.</p> <pre><code>data={'id':['1','2','3','4'], 'results':['''[{'env':, 'global', 'name':, 'example1', 'label':, 'find'}, {'env':, 'global', 'name':, 'example2', 'label':, 'test'}]''', '''[{'env':, 'global', 'name':, ...
<p>I have provided a function based off the data you gave me. just enter the dat followed by the flag.</p> <p>Here it is:</p> <pre class="lang-py prettyprint-override"><code>data={'id':['1','2','3','4'], 'results':['''[{'env':, 'global', 'name':, 'example1', 'label':, 'find'}, {'env':, 'global', 'name':, 'example2', 'l...
python|pandas
0
16,063
53,837,289
For each column value [substring], find match in other column [string]
<p>I'm quite new to python to this might be a basic question. If so, sorry in advance!</p> <p>I'm trying to accomplish the following:</p> <ol> <li>For each row, search for the value of <code>df3['court_short']</code> in column <code>court_region_df[['court_long']]</code>. </li> <li>If there is a match in the column <...
<p>This is a toy example, but it's roughly the same as yours:</p> <pre><code>d = pd.DataFrame([['aa', 'bb'], ['cc', 'dd']], columns=['a', 'b']) e = pd.DataFrame([['a', 'E'], ['c', '.']], columns=['a', 'b']) e['c'] = e['a'].apply(lambda x: (d[d['a'].str.contains(x)]['b']))[0] </code></pre> <p>Output:</p> <pre><code>...
python|pandas
1
16,064
54,054,950
In pandas, how can I set the number format in a single cell?
<p>In pandas, one can use either <code>map</code> or <code>applymap</code> to display a set of ints or floats to look like typical number format. For example....</p> <pre><code>df['Big_num'] = df['Big_num'].map('{:,.0f}'.format) </code></pre> <p>... will turn a column with 123456.789 into string that looks nicer: 123...
<p>Your problem is that you cannot run <code>df['Big_num'] = df['Big_num'].map('{:,.0f}'.format)</code> twice. Even just once right after the other.</p> <p>Also I advise using df.update.</p> <p>Here is some working code:</p> <pre><code>import pandas as pd import numpy as np df_data = {'Location' : ['Denver', 'Boul...
python|pandas
2
16,065
38,387,062
Pandas DataFrame update one column using another column
<p>I have a two-column DataFrame <code>df</code>, its columns are <code>phone</code> and <code>label</code>, which <code>label</code> can only be 0 or 1.<br> Here is an example: </p> <pre><code>phone label a 0 b 1 a 1 a 0 c 0 b 0 </code></pre> <p>What I want t...
<p>taking into account that the <code>label</code> column can only have <code>0</code> or <code>1</code>, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow">.trasnform('sum')</a> method:</p> <pre><code>In [4]: df.label = df.groupby('ph...
python|pandas|dataframe|group-by
1
16,066
65,938,576
List index out of range when importing csv file
<pre><code>import csv with open('teachers.csv', newline='') as f: reader = csv.reader(f) df = list(reader) </code></pre> <p>I am practically new to panda and its functions. I created a csv file with the input as shown below: <a href="https://i.stack.imgur.com/oV7ry.png" rel="nofollow noreferrer">enter image des...
<p>Don't you want to try pandas implementation of reading csv?</p> <pre><code>import pandas as pd df = pd.read_csv('teachers.csv') </code></pre>
python|pandas|csv
1
16,067
66,064,591
Counting NaN values in pandas group by
<p>I have a <code>df</code> like this:</p> <pre><code>Country product date_install date_purchase id BR yearly 2020-11-01-01:11:36 2020-11-01-01:11:26 10660236 CA monthly 2020-11-01-01:11:49 2020-11-01-01:...
<p>Indeed, if you follow @Paul Brennan's advice, the solution comes quite easier. As an example consider the following data</p> <pre><code> Country product date_install date_purchase id 0 BR yearly 2020-01-01-01:00:00 2020-01-01-01:00:00 10660236 3 BR monthly 2020-01-01-04:00...
python|pandas
1
16,068
52,677,658
AttributeError("module 'pandas' has no attribute 'read_csv'")
<p>I am new to Python and I have been stuck on a problem for some time now. I recently installed the module <code>pandas</code> and at first, it worked fine. However, for some reason it keeps saying </p> <blockquote> <p>AttributeError("module 'pandas' has no attribute 'read_csv'").</p> </blockquote> <p>I have looke...
<p>Your problem is this:</p> <p>The command</p> <pre><code>import pandas as pd </code></pre> <p>in your case didn't import the <em>genuine</em> pandas module, but some <em>other</em> one - and in that <em>other one</em> the <code>read_csv()</code> function <em>is not defined</em>.</p> <p><strong>Highly likely you h...
python|pandas|attributeerror
3
16,069
58,552,318
Parse csv object time to datetime in python
<p>I have a csv file with <code>Timestamp</code> column below. I want to change the format to <code>2013-08-12 10:29:19.673</code> or granularity of one second. Currently <code>Timestamp</code> is type <code>object</code>. </p> <p>I could change its format in excel manually but the file is too big and some rows would ...
<p>EDIT: If convert times to datetimes with no information about dates, pandas obviously add date of actual day.</p> <p>If need some another days, check this solution:</p> <p>Idea is create consecutive datetimes cganged if times starts with <code>0</code>:</p> <pre><code>df = df[['Timestamp']] print (df) Timestam...
python|pandas|csv|datetime
1
16,070
58,221,243
Splitting list items into separate columns - pandas data-frame
<p>I have initial pandas data-frame that looks like this - each cell is a list of values <a href="https://i.stack.imgur.com/St8ut.png" rel="nofollow noreferrer">initial input</a></p> <p>Python script - to get the initial dataframe - like mentioned by Ian Thompson in this answer - </p> <pre><code>import pandas as pd ...
<p>If this is your starting dataframe:</p> <pre><code>df = pd.DataFrame({ 0 : [ [None, 'A', 'B', 'C', 'D'], [None, 'A1', 'B1', 'C1', 'D1'], [None, 'A2', 'B2', 'C2', 'D2'], ], 1 : [ [None]*5, [None]*5, [None]*5, ], 2 : [ ['V', 'W', 'X', 'Y', 'Z...
python|pandas|list|dataframe
1
16,071
58,175,521
Iterate nltk.tokenize across all rows of a pandas dataframe
<p>grateful for your help for what feels like a stupid question. I've pulled a sqlite table into a pandas dataframe so I can tokenize and count the frequency of words from a series of tweets. </p> <p>With the code below, I can produce this for the first tweet. How do I iterate for the whole table? </p> <pre><code>...
<p>I think your problem can be solved more concisely using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow noreferrer">CountVectorizer</a>. I'll give you an example. Given the following inputs:</p> <pre><code>from sklearn.feature_extraction...
python|pandas|nltk|tokenize
1
16,072
58,370,765
Convert CSV with one column to several columns in Python
<p>I have a dataset with one column and several rows per data item (the number of rows per data item is not unique). The data items are differentiated by a line '------------------------------- '</p> <p>I want to transpose the data to (3) columns. The data should be split by the line '------------------------------- '...
<p>My source test file is as follows:</p> <pre><code>r0 xxxx r1 xxxx, yyy r2 xxxx, zzz -------- r3 xxxx r4 xxxx -------- r6 xxxx </code></pre> <p>The first step is to read it with a non-existing separator (I chose <em>'&amp;'</em>), so that each source line is the content of a <strong>single</strong> field (I named i...
python|regex|pandas|csv
0
16,073
68,940,715
how can I add values in front of a column dataframe with pandas
<p>I have this dataframe bellow and I want to add &quot;lap&quot; in front of intire column 0, like &quot;lap 1&quot; and &quot;lap 2&quot;</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 ... 12 13 14 15 \ 1 1 FAR FAG FAN PAR BIR DGR MAR GIR ROS ... HAR HAM MUR CHI 2 2 FAR...
<p>use the df.insert() function</p> <pre><code>df.insert(0, &quot;lap 1&quot;, ['TEMP']*5) </code></pre> <p>1st argument: index that you wish to insert the new column into<br /> 2nd argument: column name<br /> 3rd argument: column data</p>
python|pandas|dataframe
0
16,074
44,652,117
How are the different batches from training data being obtained in Tensorflow rnn tutorial code?
<p>In the Tensorflow tutorial code for RNN how is the next batch obtained? In reader.py the function ptb_producer produces one batch of dimension [batch_size x num_steps] at a time through a dequeue method But it is not called multiple times in ptb_word_lm.py to get all the batches. Any help in understanding how differ...
<p>Have you noticed that these code at ptb_word_lm.py(line 376) as below:</p> <pre><code>sv = tf.train.Supervisor(logdir=FLAGS.save_path) with sv.managed_session() as session: for i in range(config.max_max_epoch):#LOOK!The param max_max_epoch. lr_decay = config.lr_decay ** max(i + 1 - config.max_epo...
tensorflow
0
16,075
60,825,989
Splitting ImageFolder into train and validation datasets
<p>I have loaded my dataset as follows :</p> <pre class="lang-py prettyprint-override"><code>full_dataset = ImageFolder(root = os.path.join(root, 'train'), transform=train_transforms) </code></pre> <p>Now to split my dataset into training and validation sets, I used the following code :</p> <pre class="lang-py prett...
<p>You should be able to iterate through a Subset just fine, since it has the <code>__getitem__</code> method implemented as you can see from the <a href="https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html#Subset" rel="nofollow noreferrer">source code</a> :</p> <pre><code>class Subset(Dataset): ...
python|deep-learning|computer-vision|pytorch
1
16,076
61,180,180
Pandas get_dummies include columns for missing categories?
<p>For an example:</p> <pre><code>import numpy as np import pandas as pd df1 = pd.DataFrame({ 'id': [1, 2, 3, 4], 'category': ['A', 'B', 'C', 'D'] }) df1_dummy = pd.get_dummies(df1) print(df1_dummy) </code></pre> <p>I then got:</p> <pre><code> id category_A category_B category_C category_D 0 1 ...
<p>Assuming <code>df2</code>'s categories are the same categories as <code>df1</code>, you can "sync" them so <code>pd.get_dummies</code> handles the missing categories appropriately:</p> <pre><code>pd.get_dummies( pd.Categorical(df2['category'], categories=df1['category'].unique())) A B C D 0 1 0 0 0 1...
python|pandas|dataframe
1
16,077
61,156,017
Calculating and using Euclidean Distance in Python
<p>I am trying to calculate the Euclidean Distance between two datasets in python. I can do this using the following:</p> <pre><code>np.linalg.norm(df-signal) </code></pre> <p>With <code>df</code> and <code>signal</code> being my two datasets. This returns a single numerical value (i.e, 8258155.579535276), which is f...
<p>To have the columnwise norm with column headers you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.aggregate.html" rel="nofollow noreferrer">pandas.DataFrame.aggregate</a> together with <code>np.linalg.norm</code>:</p> <pre class="lang-py prettyprint-override"><code>imp...
python|pandas|numpy|euclidean-distance
2
16,078
61,180,875
How to create a 3d surface plot with matplotlib when x and y are stated as 1d arrays?
<p>I would like to create a 3d surface plot from the arrays x,y,z where len(x) and len(z) = 250 and len(y)= 7</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(X,...
<p>You need to expand your data to have x and y for each data point. This is done by combining <code>x</code> and <code>y</code> to form an array with the same shape as <code>z</code>.</p> <p>You can do this using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow norefer...
python|numpy|matplotlib|surface
1
16,079
71,530,185
Remove reduction from cosine similarity for prototypical network
<p>I've implemented a prototypical network in tensorflow that uses cosine similarity to compare the output of the model with the prototypes calculated before. This works fine but the problem is that it's very slow. The reason it's slow is because im having to do seperate cosine similarity calculations for each individu...
<p>Actually, I figured it out, you just need to set the cosine loss to be:</p> <pre><code>cosine_loss = tf.keras.losses.CosineSimilarity(reduction='none') </code></pre>
python|tensorflow|machine-learning|computer-vision|cosine-similarity
0
16,080
71,707,052
Pandas Dataframes: Addition of float to column value based on if condition
<p>Relative newbie with Python and Pandas, finally admitting defeat on not being able to figure this out myself. I have a pandas Dataframe from our energy suppliers API, each row is a 30min interval showing wholesale energy costs in p/kWH 'value_exc_vat', the solar output for the house 'export' and a datetime stamp 'da...
<p>Does this work:</p> <pre><code>peak_rate = [16,17,18,19] for i in range(len(df)): if df.hour.iloc[i].isin(peak_rate): df['export_rate_var'] = (df['export_rate'] + peak_rate_uplift) else: df['export_rate_var'] = df['export_rate'] </code></pre>
python|pandas
0
16,081
71,744,788
Subclass of PyTorch DataLoader for changing batch output
<p>I'm interested in a way of applying a transform to a batch generated by a <code>PyTorch</code> <code>DataLoader</code> class. My minimal example is something like this:</p> <pre><code>class CustomLoader(torch.utils.data.DataLoader): def __iter__(self): result = super().__iter__() return some_func...
<p><code>__iter__()</code> is a generator. You will need to yield the result instead of returning it. You can read more about generators <a href="https://www.guru99.com/python-yield-return-generator.html" rel="nofollow noreferrer">here</a></p> <p>Regarding your problem to apply a transform to a batch, you can create a ...
pytorch|dataset|pytorch-dataloader
0
16,082
71,444,095
How to convert a pandas datetime column from UTC to EST
<p>There is another <a href="https://stackoverflow.com/questions/5997570/how-to-convert-datetime-to-eastern-time">question</a> that is eleven years old with a similar title.</p> <p>I have a pandas dataframe with a column of datetime.time values.</p> <pre><code>val time a 12:30:01.323 b 12:48:04.583 c ...
<p><code>tz_localize</code> and <code>tz_convert</code> work on the index of the DataFrame. So you can do the following:</p> <ol> <li>convert the &quot;time&quot; to Timestamp format</li> <li>set the &quot;time&quot; column as index and use the conversion functions</li> <li><code>reset_index()</code></li> <li>keep only...
python|pandas|time
4
16,083
72,373,266
JSON_EXTRACT_PATH_TEXT equivalent in python?
<p>SQL has a very useful function called JSON_EXTRACT_PATH_TEXT, which allows to extract data from a json file just by providing the full json path.</p> <p>What is the easiest way to achieve the same result in python?</p> <p>I am particularly interested in pandas solutions: <em>json_normalize</em> and <em>read_json</em...
<p>I'm not familiar with anything that does this out of the box, but it is fairly simple to do. try something like this:</p> <pre><code>from functools import reduce class JsonPath: @classmethod def get(cls, data, path): return reduce(cls._get_item, path, data) @classmethod def _get_item(cls, ...
python|sql|json|pandas
3
16,084
72,253,750
cumulative problem if date is expired after 30 days
<p>I still cannot find the solution for cumulative problem. Anyone can help or suggest any solution. Many thanks.</p> <p>I have 2 tables: transactions (date, user_id, price, service group) and point (service group, point). The point user get is price * point.</p> <p>I left join transactions and point table then I calcu...
<ol> <li>Tested on <a href="https://dbfiddle.uk/?rdbms=mysql_8.0&amp;fiddle=ddfacb74c48012384f4c74fdf32707b3" rel="nofollow noreferrer">dbfiddle</a></li> <li>Please let me know if I have misunderstood your question.</li> </ol> <pre><code>WITH new_sum AS ( SELECT t.user_id, t.date, t.price, p.point, t.price+COALESC...
mysql|pandas
0
16,085
50,330,993
How to use tf.datasets with iterator in Tensorflow
<p>I am trying to use tf.data.TextLineDataset to read from a csv file, shard the dataset over multiple worker nodes and then create an iterator to iterate over them to feed the data in batches. I used the programmer's guide on tf.datasets from TensorFlow (<a href="https://www.tensorflow.org/programmers_guide/datasets" ...
<p>These two lines seem to be the source of the problem:</p> <pre><code>ds_file = tf.data.TextLineDataset(file) ds = ds_file.flat_map(lambda file: (tf.data.TextLineDataset(file).skip(1))) #remove CSV headers </code></pre> <p>The first line creates a dataset from the lines of the file (or files) in named in <code>fil...
python|tensorflow|tensorflow-datasets
1
16,086
50,280,640
Open / load image as numpy ndarray directly
<p>I used to use scipy which would load an image from file straight into an ndarray.</p> <pre><code>from scipy import misc img = misc.imread('./myimage.jpg') type(img) &gt;&gt;&gt; numpy.ndarray </code></pre> <p>But now it gives me a <code>DeprecationWarning</code> and the <a href="https://docs.scipy.org/doc/scipy/re...
<p>The result of <code>imageio.imread</code> is already a NumPy array; <code>imageio.core.util.Image</code> is an ndarray subclass that exists primarily so the array can have a <code>meta</code> attribute holding image metadata.</p> <p>If you want an object of type exactly <code>numpy.ndarray</code>, you can use <code...
python|image|numpy|scipy|numpy-ndarray
12
16,087
50,352,547
df.columns.tolist() to return strings not tuples
<p>in pandas to find the columns of a df you do:</p> <p><code>df.columns</code> which returns a multiindex array.</p> <p>If you want to add it to a variable you do:</p> <p><code>columns=df.columns.tolist()</code></p> <p>which would create a tuple for every columns name </p> <p>e.g <code>columns=[('A'),('B'),...]<...
<p>If you have a multiindex, it's not always clear that <code>tolist()</code> would produce a list of single strings, since it's possible there are, well, multiple indexes.</p> <p>However, as suggested by @jezreal in the comments, you can select the first level like so:</p> <pre><code>df.columns.get_level_values(0).t...
python-3.x|pandas|tolist
2
16,088
50,552,448
pandas groupby is returning two groups for the same unique id
<p>I have a large pandas dataframe, where I am running groups by operations.</p> <pre><code>CHROM POS Data01 Data02 ...... 1 .................... 1 ................... 2 .................. 2 ............ scaf_9 ............. scaf_9 ............ </code></pre> <p><strong>So, i a...
<p>In my opinion there is data problem, obviously some whitespaces, so pandas processes each group separately.</p> <p>Solution should be remove traling whitespaces first:</p> <pre><code>df.index = df.index.astype(str).str.strip() </code></pre> <p>You can also check unique strings values of <code>index</code>:</p> <...
python|pandas|group-by|pandas-groupby
1
16,089
50,434,784
Python: Plot month-wise normalised histogram
<p>I have a <code>CSV</code> file with data that look like this:</p> <pre><code>Time Pressure 1/1/2017 0:00 5.8253 ... ... 3/1/2017 0:10 4.2785 4/1/2017 0:20 5.20041 5/1/2017 0:30 4.40774 6/1/2017 0:40 4.03228 7/1/2017 0:50 5.011924 12/1/2017 1:00 ...
<p>A few simple steps. First you need to read your data file, into an array of cells. once you have your list of lists or rows of entry ( what ever you want to call them ) you need to collect all the observations for each month and take the average of each collection. Here I have implemented a simple buckets class to f...
python|numpy|matplotlib|seaborn|date-histogram
1
16,090
50,438,206
Is there any way to replace a for loop with something more efficient in python
<p>My code below checks surrounding pixels to my object's pixel in python.</p> <pre><code>self.surr = [None, None, None, None, None, None, None, None] for i in range(9): #for x in range(-1, 2): #for y in range(-1, 2): if i != 5: x = i % 3 - 2 y = int((i % 3) / 3) - 1 if x ...
<p>What you're doing inherently requires looping—but if you can move that looping into numpy, it'll often get 5-20x faster.</p> <p>In your case, what you're trying to do is to compare each pixel to its neighbors. How can you do that as an array-wide operation? Simple: compare the array to the same array shifted by 1.<...
python|performance|numpy|pygame
3
16,091
45,326,917
sort dataframe using MULTIINDEX
<p>I am a newbie and in a huge need of help of changeing my dataframe with use of multi-indexing, </p> <p>How my dataframe looks like, Notice Reading it from a csv file. </p> <p><a href="https://i.stack.imgur.com/MowCz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MowCz.png" alt="enter image desc...
<p>Let's use <code>melt</code> and <code>set_index</code>:</p> <pre><code>import pandas as pd from io import StringIO csv_file = StringIO("""date,2017,2016,2015,2014 total members, 150, 140, 100, 150 lions, 20, 10, 5, 25 demokrats, 60, 50, 15, 25 liberals, 20, 5, 40, 25 partizans, 50, 75, 40, 25""") df = pd.read_csv...
python|pandas|stack|multi-index
1
16,092
45,623,830
Is there a way to use str.count() function with a LIST of values instead of a single string?
<p>I am trying to count the number of times that any string from a list_of_strings appears in a csv file cell.</p> <p>For example, the following would work fine.</p> <pre><code>import pandas as pd data_path = "SurveryResponses.csv" df = pd.read_csv(data_path) totalCount = 0 for row in df['rowName']: if type(ro...
<p>Perhaps something along the lines of</p> <pre><code>totalCount = 0 words_of_interst = ['cat','dog','foo','bar'] for row in df['rowName']: if type(row) == str: if sum([word in row for word in words_of_interst]) &gt; 0: totalCount += 1 </code></pre>
python|pandas
0
16,093
45,611,335
Python numpy performance - selection on very large array
<p>I'm trying to optimize some code and one of the time consuming operations is the following: </p> <pre><code>import numpy as np survivors = np.where(a &gt; 0)[0] pos = len(survivors) a[:pos] = a[survivors] b[:pos] = b[survivors] c[:pos] = c[survivors] </code></pre> <p>In my code <code>a</code> is a very large (more...
<p>As far as I see it there's nothing that could speed it up with pure NumPy. However if you have numba you could write your own version of this &quot;selection&quot; using a jitted function:</p> <pre><code>import numba as nb @nb.njit def selection(a, b, c): insert_idx = 0 for idx, item in enumerate(a): ...
python|arrays|performance|numpy|indexing
3
16,094
62,679,328
Slicing sections around every index of an array
<p>I need to slice sections out of a NumPy array in a specific way. Say I have a <code>(200,200, 4)</code> shape NumPy array. Then for every index in <code>(200, 200)</code>, I want to select the 5x5x4 surrounding indexes, flatten it, and then put it into another array. So finally, the shape of the final array would be...
<p>Using @hpaulj helpful comments I designed a solution that I think works for my purposes. It's similar to what was suggested here: <a href="https://stackoverflow.com/questions/61711831/rolling-windows-for-ndarrays">Rolling windows for ndarrays</a> but has the additional border of np.nan values. If anyone else finds ...
python|numpy
0
16,095
62,538,683
Recommendations table sort dataframe result in descending order Pandas
<p>The recommendation tables output scores are not truly descending, the recommendations don't match the scores of the recommendationTable.</p> <p>Currently, the input does work and it does give a correct recommendationTable_df.</p> <pre><code>recommendationTable_df = recommendationTable_df.sort_values(ascending=False)...
<p>As pointed out by PMende in comments I changed</p> <pre><code>df.loc[df.index.isin(recommendationTable_df.head(3).keys())] </code></pre> <p>into</p> <pre><code>df.loc[recommendationTable_df.head(6).index, :] </code></pre> <p>Now it does match</p> <pre><code>#Multiply the genres by the weights and then take the weig...
python|pandas|nlp|pandas-groupby|data-science
0
16,096
54,513,420
pandas dtype output has extra row
<p>While playing around with pandas I started wondering about the output.</p> <pre><code>&gt; df = pd.DataFrame({'col_1':[1,2,3], 'col_2':['a','b','c']}) &gt; df.dtypes col_1 int64 col_2 object dtype: object </code></pre> <p>The <code>df.dtypes</code> call gives three rows. </p> <ol> <li>The first row s...
<p>The object returned by <code>dtypes</code> is a <code>pandas.Series</code> object, by default a <code>Series</code> shows it's dtype when printed, it's telling you it is a <code>Series</code> od mixed types (since you have <code>int64</code> and <code>object</code>)</p>
python|pandas
2
16,097
54,449,528
geopandas color closest shapes the same color
<p>I have a geopandas file with 100+ polygons and a sparse set (~10 of which) have a value of interest. Is there an easy way for me to assign the remaining 90+ polygons a value based on the value of the nearest non-zero polygon?</p> <p>Thank you in advance</p>
<p>The code below indicates an algorithm that will join the polygons with 'no value' to the closest polygons with a valid value, using a spatial join (nearest neighbor) based on their centroids.</p> <p>Note the code is a draft of the code you need; it indicates the general algorithm but you need to complete the functi...
python|geospatial|polygon|geopandas
0
16,098
54,325,205
Using data from a numpy array in a function
<p>I'm trying to make a simply solar system simulation as practice, but I'm running into a small problem.</p> <p>I want to store simple planet data in a numpy array, then use the data from that array to draw the planets. However, I can't seem to get my custom functions to properly use the data.</p> <p>For example, th...
<p>I would use a dictionary or like in this example a list of tuples. Simple and effective. Then you can feed your list to a class an generate your solar system and then you can easily access your planets and attributes with the . notation:</p> <pre><code> class Body: def __init__(self, data): # data repr...
python|numpy
0
16,099
54,616,526
How to save subarray in npy file?
<p>My data tracks has following shape :</p> <p>(13044,) Its data types are </p> <pre><code>tracks.dtype.names ('frame_num','mean_x','mean_y','var_x','var_y', 'length', 'scale', 'x_pos','y_pos', 't_pos', 'coords', 'trajectory', 'hog', 'hof', 'mbh_x','mbh_y') dtype([('frame_num', '&lt;i4'), ('mean_x', '&lt;f4'), ('m...
<p>You can save a numpy array of all of your (16,2) y's:</p> <pre><code>ys = [] for i in range(len(tracks)): y=tracks['coords'][i] ys.append(y) print(y) np.save('test.npy',np.array(ys)) </code></pre> <p>Also note that you are traversing along <code>tracks</code> with <code>i</code>, but reading <code>trac...
python-3.x|numpy|numpy-ndarray
1