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
5,500
68,726,586
Fillna pandas doesnt fill all the missing values in the column
<p>I have a column Sulphate with missing values. I'm trying to fill in the missing values with predictions from a model I made. But, it does not fill in all the missing values. Instead it only fills in some of the missing values.</p> <p><a href="https://i.stack.imgur.com/LT8Ze.png" rel="nofollow noreferrer"><img src="h...
<p><code>fillna</code>'s input is used by index, so if the first value in dataframe is not empty, the first value of the <code>sulfate_predictions</code> is ignored, and so on. You need to pass the array of the same size as your dataframe. Or try this:</p> <pre><code>df.loc[df['Sulfate'].isnull(),'Sulfate'] = sulfate_p...
python|pandas|dataframe
1
5,501
68,746,619
Parse nested JSON and iterate into Pandas Dataframe
<p>I'm using a Foursquare API call to find venues associated with particular ZIP codes in the US.</p> <p>I am able to generate the JSON with information, but am having trouble looping and parsing to construct a pandas dataframe.</p> <p>So far:</p> <pre><code># scraping the foursquare website for the information we want...
<p>After 4 days of communication I think I see your real question that will get you moving forward. You need to look up and troubleshoot the below two errors. Please mark my answer as correct if you agree amd with some more work troubleshooting on your own, create a new question around your insights, errors and questio...
python|json|pandas|nested|flatten
1
5,502
5,446,522
data type not understood
<p>I'm trying to use a matrix to compute stuff. The code is this</p> <pre><code>import numpy as np # some code mmatrix = np.zeros(nrows, ncols) print mmatrix[0, 0] </code></pre> <p>but I get 'data type not understood', and it works if I do it from terminal.</p>
<p>Try:</p> <pre><code>mmatrix = np.zeros((nrows, ncols)) </code></pre> <p>Since the shape parameter has to be an int or sequence of ints</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html</a></p>...
python|matrix|numpy
162
5,503
5,134,932
numpy - pretty printing
<p>I have a numpy array of strings. When a value in the array is undefined, None is printed as you would expect. Is it possible to provide a default value for None values?</p> <p>e.g. in the following I want "_" instead of None</p> <pre><code>[[None B C] [M None O] [X Y None]] </code></pre> <p>would become</p> <p...
<p>You might also consider using a masked array:</p> <pre><code>import numpy as np x=np.array([[None, 'B', 'C'], ['M', None, 'O'], ['X', 'Y', None]]) print(x) # [[None B C] # [M None O] # [X Y None]] x=np.ma.masked_equal(x,None) print(x) # [[-- B C] # [M -- O] # [X Y --]] </code></pre>
python|numpy
7
5,504
53,116,468
name 'pd' is not defined
<pre><code># Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') print(dataset) </code></pre> <p>Error:</p> <pre><code>dataset = pd.read_csv('Data.csv') Traceback (most recent call last): File "&lt;ipython-input-6...
<p>From your comments, you're using Spyder. The traceback confirms to me that you're running <code>dataset = pd.read_csv('Data.csv')</code> in the IPython interactive console. </p> <p>Spyder has configurable namespace sharing between scripts and the console. Running:</p> <pre><code>import numpy as np import matplotli...
python|pandas
2
5,505
65,538,068
Find string in data frame and store new values in a new column
<p>I am creating a script that takes a csv file which columns organisation and columns name are unknown. However I know that only one of the column contains some values in which the str 'rs' and 'del' appears.</p> <p>I need to create an extra column (called 'Type') and store 'dbsnp' in the row where 'rs' was found and ...
<p>You can do it without the loop. Here's an approach. You can use applymap and search all the columns.</p> <pre><code>import pandas as pd data = {'Number': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharsanpur', 'MERrs', 'rsAdela', 'aa...
python|pandas
1
5,506
65,623,939
Faster way to filter pandas dataframe and create new columns
<p>Given df</p> <pre><code> ticker close open 0 AAPL 1.2 1.1 1 TSLA 25.0 27.0 2 TSLA 83.0 80.0 3 TSLA 95.0 93.0 4 CCL 234.0 234.2 5 AAPL 512.0 520.0 </code></pre> <p>My purpose:</p> <p>(1) Apply functions to each ticker dataframe (subset)</p> <p>(2) Create new column with v...
<p>I think you need <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p> <pre><code>df['candlestick'] = np.where(df['close'] &gt; df['open'], 'bullish', 'bearish') print (df) ticker close open candlestick 0 AAPL 1.2 1.1 ...
python|pandas
1
5,507
65,795,980
ValueError: Shape must be rank 2 but is rank 4 for 'in_top_k/InTopKV2' (op: 'InTopKV2') with input shapes: [?,28,28,10], [?], []
<p>I'm new to Tensorflow and I am trying to train on MNIST. However, the code fails on</p> <pre><code>correct = tf.nn.in_top_k(logits, tf.argmax(y, axis=1), 1) </code></pre> <p>with the error &quot;ValueError: Shape must be rank 2 but is rank 4 for 'in_top_k/InTopKV2' (op: 'InTopKV2') with input shapes: [?,28,28,10], [...
<p>Thanks JacoSolari and Jarom Allen. For the benefit of community providing complete working code here</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.python.framework import graph_util from tensorflow.python.framework import graph_io tf.reset_default_graph() x = tf.placeholder(tf.float32, ...
python|tensorflow
0
5,508
21,362,843
Interpret numpy.fft.fft2 output
<p>My goal is to obtain a plot with the spatial frequencies of an image - kind of like doing a fourier transformation on it. I don't care about the position on the image of features with the frequency f (for instance); I'd just like to have a graphic which tells me how much of every frequency I have (the amplitude for ...
<p><code>freq</code> has a few very large values, and lots of small values. You can see that by plotting </p> <pre><code>plt.hist(freq.ravel(), bins=100) </code></pre> <p>(See below.) So, when you use</p> <pre><code>ax1.imshow(freq, interpolation="none") </code></pre> <p>Matplotlib uses <code>freq.min()</code> as t...
python|numpy|fft|frequency-distribution
13
5,509
63,701,600
How to choose my primary key column in saving pandas dataframe to sql
<p>I am trying to save a dataframe to mysql with the following:</p> <pre><code>df.to_sql('dedupe__df', con=to_conn, if_exists='replace') </code></pre> <p>This adds the <code>index</code> as the primary key. However, if I add the actual primary key, which is called <code>path</code>, I get the following error:</p> <pre>...
<p>Unfortunately, it is not possible with df.to_sql(). But you can do it in below given way:</p> <pre><code>df.to_sql('dedupe__df', engine, if_exists=&quot;replace&quot;, index=False) with engine.connect() as con: con.execute('ALTER TABLE dedupe__df ADD PRIMARY KEY (path);') </code></pre> <p>Table name &amp; index ...
python|sql|pandas
2
5,510
63,323,336
expected Inputs to have shape (150,) but got array with shape (1,)
<p>I'm running a keras model but it is showing shape error, although i did check the shape and it is correct.</p> <pre><code>predict = model.predict(sequences_matrix) </code></pre> <p>its showing the error:</p> <pre><code>ValueError: Error when checking input: expected Inputs to have shape (150,) but got array with sha...
<p>That is because the first channel is reserved for the batches. The function should work if you reshape your sequence_matrix to (1,150)</p> <pre><code>sequence_matrix = sequence_matrix.reshape(1,-1) </code></pre> <p>Then the model separates the batch of 1 and gets a (150,) input to the model. Right now it is assuming...
python-3.x|numpy|machine-learning|keras|vectorization
1
5,511
63,710,974
How to create a bar graph using pandas Dataframe in Python
<p>so I have created a dataframe that holds the len of tweets (in characters) for a specific user. I am having trouble creating the bar graph.Below is what I have:</p> <pre><code>data ={ 'Length of Tweets' : '0-32 ','33-64','65-96 ','97-128 ','129-160+ ' 'Length': [len(Tweeted_word032),len(Tweeted_word3264),len...
<p>Try this instead:</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt // Defining Tweeded_word variables... data = { &quot;Length of Tweets&quot; : (&quot;0-32 &quot;,&quot;33-64 &quot;,&quot;65-96 &quot;,&quot;97-128 &quot;,&quot;129-160+ &quot;), &quot;Length&quot;: [len(Tweeted_word0...
python|pandas|matplotlib
0
5,512
63,425,356
Function to get top left and bottom right indexes of nonzero elements in an array
<p>So the goal is to write a function that gives the top left and bottom right indexes of a group of nonzero elements of an array. Two groups cant be next to eachother in the array. And if the group exist of just one element, the top left and bottom right indexes are the same. It was easy to get a function that gets al...
<p>I traversed on matrix in increasing order of for loop to find top left indexes of non-zero element, and to get bottom right indexes of non-zero element I traversed decreasing order of for loop. Here the code:</p> <pre><code>import numpy as np A= np.array([ [0, 7, 7, 0, 0, 0, 0, 0, 0], [0, 7, 7, 0, 0, 9, 0, 0, 0], [...
python|arrays|numpy
2
5,513
63,721,340
How to split the values of a column to differenet columns in a dataframe
<p>I have a dataframe in the below format. I want to split the values of <strong>points</strong> column into different columns like A,B,C and so on based on the number of items in the list by deleting the original column.</p> <pre><code>df: x y points 0 82.123610 16.724781 [107...
<p>I think best here is create numeric columns names:</p> <pre><code>df = df.join(pd.DataFrame(df.pop('points').tolist(), index=df.index)) </code></pre> <p>If length of list is less like 27 is possible use:</p> <pre><code>import string d = dict(enumerate(string.ascii_lowercase)) df = df.join(pd.DataFrame(df.pop('poin...
python|pandas|list|dataframe
1
5,514
21,797,889
Divide ndarray by scalar - Numpy / Python
<p>I'm just wondering how could I do such thing without using loops.</p> <p>I made a simple test trying to call a division as we do with a numpy.array, but I got the same ndarray.</p> <pre><code>N = 2 M = 3 matrix_a = np.array([[15., 27., 360.], [180., 265., 79.]]) matrix_b = np.array([[.5, 1., .3], ...
<p>I think that you want to modify <code>matrix_c</code> in-place:</p> <pre><code>matrix_c /= (N * M) </code></pre> <p>Or probably less effective:</p> <pre><code>matrix_c = matrix_c / (N * M) </code></pre> <p>Expression <code>matrix_c / (N * M)</code> doesn't change <code>matrix_c</code> - it creates a new matrix....
python|numpy|matrix|division
16
5,515
24,761,662
In Python/Pandas how do I convert century-months to DateTimeIndex?
<p>I am working with a dataset that encodes dates as the integer number of months since December 1899, so month 1 is January 1900 and month 1165 is January 1997. I would like to convert to a pandas DateTimeIndex. So far the best I've come up with is:</p> <pre><code>month0 = np.datetime64('1899-12-15') one_month = np...
<p>You can use built-in <code>pandas</code> date-time functionality.</p> <pre><code>import pandas as pd import numpy as np indexed_months = np.random.random_integers(0, high=1165, size=100) month0 = pd.to_datetime('1899-12-01') date_list = [month0 + pd.DateOffset(months=mnt) for mnt in indexed_months] birthdates = pd...
python|pandas
3
5,516
24,918,287
Total size of array must be unchanged
<p>I am using a Python module called emcee to sample a distribution. I need to pass a (37,100) (which I have named Ntrig and Nsamp, respectively) array called <code>events</code> to the below function. </p> <pre><code>def mp(SNR2, *events): events = np.asarray(events).reshape((Ntrig,Nsamp)) bessel = special.iv...
<blockquote> <p>As I understand, <code>events</code> will break up the events array into 37*100 separate arguments.</p> </blockquote> <p>This is not true. If you call <code>mp</code> using</p> <pre><code>mp(SNR2, events) </code></pre> <p>then inside <code>mp</code>, <code>events</code> will be a 1-element tuple, <...
python|arrays|numpy|distribution|emcee
3
5,517
17,644,259
How do I provide slider control to a matplotlib plot of a pandas timeseries
<p>I am able to plot a a couple of pandas time series as to slots</p> <p>Stock= A pandas timeseries of stock data</p> <p>Signal=A pandas timesries if signals from Stock above has the same range</p> <p>The following displays it the way I want where the dates between the 2 plots are in sync</p> <pre><code>fig=figure(...
<p>I would use java script. For this. Look at <a href="http://www.highcharts.com/demo/line-time-series" rel="nofollow">http://www.highcharts.com/demo/line-time-series</a> </p>
matplotlib|pandas
-1
5,518
17,471,176
Equality not working as expected with ndarray sub-class
<p>The following example:</p> <pre><code>import numpy as np class SimpleArray(np.ndarray): __array_priority__ = 10000 def __new__(cls, input_array, info=None): return np.asarray(input_array).view(cls) def __eq__(self, other): return False a = SimpleArray(10) print (np.int64(10) == a) p...
<p>This is somewhere between a bug and a wart. When you call <code>a op b</code> and <code>b</code> is a subclass of <code>a</code> python checks to see if <code>b</code> has a reflected version of <code>op</code> and calls that (<code>__eq__</code> is the reflected version of itself), So for example this <code>np.arra...
python|numpy
1
5,519
17,375,383
multidimensional numpy array -- reverse along a given axis
<p>Let's say I have a multidimensional array with a shape that I don't know until runtime.</p> <p>How can I reverse it along a given axis k, also not known until runtime?</p> <p>The notation <code>somearray[:,:,::-1,:,:]</code> relies on static dimension references, <a href="https://stackoverflow.com/questions/741617...
<p>You can either construct a tuple of <code>slice</code> objects such as @ali_m suggests, or do something like this:</p> <pre><code>reversed_arr = np.swapaxes(np.swapaxes(arr, 0, k)[::-1], 0, k) </code></pre> <p>This places the desired axis at the front of the shape tuple, then reverses that first axis, and then ret...
python|arrays|numpy
9
5,520
12,203,901
pandas crashes on repeated DataFrame.reset_index()
<p>Very weird bug here: I'm using pandas to merge several dataframes. As part of the merge, I have to call reset_index several times. But when I do, it crashes unexpectedly on the second or third use of reset_index.</p> <p>Here's minimal code to reproduce the error:</p> <pre><code>import pandas A = pandas.DataFrame...
<p>Inspecting frame.py, it looks like pandas tries to insert a column 'index' or 'level_0'. If either/both(??) of them are already taken, then it throws the error.</p> <p>Fortunately, there's a "drop" option. AFAICT, this drops an existing index with the same name and replaces it with the new, reset index. This mig...
python|pandas
92
5,521
72,137,980
Can i make dataframe "active" in pandas
<p>I dont know if i'm asking this question right but fell free ask more info if needed.</p> <p>So i do this dataframe where i read csv file. Then i want to use the file to do another tasks. i want that df to be &quot;active&quot; but it seems like it dont recognise that dataframe outside of button.</p> <pre><code>def o...
<p>Your dataframe named <code>df</code> is declared inside of a function. If you do this you cannot access to it outside of that function.</p> <p>I suggest you the check out <a href="https://stackoverflow.com/questions/14051916/how-to-make-a-local-variable-inside-a-function-global">this thread</a>.</p> <p>I hope it hel...
python|pandas
0
5,522
71,909,501
how to count the duplicates in pandas?
<p>just say I want to check for the duplicates in this df column:</p> <pre><code>df = pd.DataFrame( {&quot;column_with_some_duplicates&quot; : ['a', 'b', 'b', 'c', 'c']}, index = [1, 2, 3, 4, 5]) </code></pre> <p>in <code>r</code> I would check for duplicates like:</p> <pre><code>table(duplicated(df...
<p>to check if the column provides duplicate values, i will suggest to do a function</p> <p>you could use the builtin <code>set</code> class, wich eliminates the duplicates, re-transforming it to a <code>list</code>, and then checking for equality:</p> <pre><code>def isduplicate(df,col): return list(set(df[col]))==...
python|r|pandas
0
5,523
71,887,751
Pandas zip multiple internal corresponding lists to long records
<p>I don't think this is a typical wide to long question because the items I'm looking to turn to long are actually nested in list fields.</p> <p>I have a uid field which is a list of integers, and another array which is a list of booleans that corresponds to the uid fields. I'd like to turn this array records into lo...
<p><strong>Better Answer:</strong></p> <p>In pandas 1.3 you can use multi-column explode:</p> <pre><code>df.explode(['uid','is_left']) </code></pre> <p>For older versions, <code>explode</code> each column individually:</p> <pre><code>df.apply(pd.Series.explode) </code></pre> <p><strong>Old Answer:</strong></p> <p>You c...
pandas|dataframe
1
5,524
16,613,546
Using arctan / arctan2 to plot a from 0 to 2π
<p>I am trying to replicate a plot in <em>Orbital Mechanics</em> by Curtis, but I just can't quite get it. However, I have made head way by switching to <code>np.arctan2</code> from <code>np.arctan</code>.</p> <p>Maybe I am implementing <code>arctan2</code> incorrectly?</p> <pre><code>import pylab import numpy as np e...
<p>The common practice is to sum 2<em>pi in the negative results of <code>arctan()</code>, <a href="https://stackoverflow.com/questions/10335090/numpy-replace-negative-values-in-array/10335159#10335159">which can be done efficiently</a>. The OP's suggestion to replace arctan(x) by arctan2(1, 1/x), also suggested by Map...
python|numpy|matplotlib
12
5,525
19,084,423
Simple classification in scikit-learn
<p>I am trying to develop a simple classification program using scikit-learn. I want to pull in my set of tsv values, save them in an array. Then, save a csv containing the first value of my tsv from above and simply a random 1 or 0. So it will be output to the csv as follows:</p> <pre><code>tsvValue1, random1or0 eg s...
<p>Having the file <code>input.tsv</code> with the content (separated by tabs):</p> <pre><code>foo1 foo2 foo3 foo4 fooN RelevantString123123123 RelevantString456456456 RelevantString789789789 </code></pre> <p>This shows how to get the output you want:</p> <pre><code>&gt;&gt;&gt; import nu...
python|numpy|pandas|scikit-learn|export-to-csv
1
5,526
22,086,619
how to apply a function to multiple columns in a pandas dataframe at one time
<p>I frequently deal with data which is poorly formatted (I.e. number fields are not consistent etc)</p> <p>There may be other ways, which I am not aware of but the way I format a single column in a dataframe is by using a function and mapping the column to that function.</p> <pre><code>format = df.column_name.map(fo...
<p>You can do <code>df[['Col1', 'Col2', 'Col3']].applymap(format_number)</code>. Note, though that this will return new columns; it won't modify the existing DataFrame. If you want to put the values back in the original, you'll have to do <code>df[['Col1', 'Col2', 'Col3']] = df[['Col1', 'Col2', 'Col3']].applymap(form...
python|pandas|filtering|slice
18
5,527
56,770,790
Splitting text of a single row into multiple rows of the same column in a CSV file using Python
<p>The dictionary has the following key-value pairs:</p> <pre><code> { 'Target_Tab': 'employees', ' Target_Col': 'empp_id last_name first_name', 'Source_Col': 'emp_id l_name f_name', 'Source_Tab': 'employee' } </code></pre> <p>I'm writing this dictionary into a CSV file and so far I've ...
<p>Use list comprehension with <code>split</code> for list of <code>Series</code> and join together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>, last replace missing values by <a href="http://pandas.pydata.org/pandas-docs/st...
python|pandas|csv|dictionary
2
5,528
56,853,418
How to convert np.int64 into python int64 for PandasSeries?
<p>I try to insert data from pandas DataFrame into the PostgreSQL table, </p> <p>table that a try to insert looks like:</p> <pre><code>city_id date forecast 5 29.05.2019 0 1 29.05.2019 0 151 29.05.2019 0 55 29.05.2019 0 ... </code></pre> <p><strong>types:</strong></p> <ul> <li><code>...
<p>The problem was in wrong indexation: </p> <ul> <li>first index was from 83 to 1161 and after 1161, where should've been 1161, was 83 again and next values were 83 + 1 etc.</li> </ul> <p>Thus, problem was solved by <code>.reset_index()</code></p> <p><code>df_with_new_one.reset_index(drop = True, inplace = True)</c...
python|pandas|postgresql|numpy|types
2
5,529
56,835,971
split string for a range of columns Pandas
<p>How can I split the string to list for each column for the following Pandas dataframe with many columns?</p> <pre><code>col1 col2 0/1:9,12:21:99 0/1:9,12:22:99 0/1:9,12:23:99 0/1:9,15:24:99 </code></pre> <p>Desired output:</p> <pre><code>col1 col2 [0/1,[9,12],21,99] [0/1,[9,12],22,99] [0/1...
<p>If the data is like your sample, you can make use of <code>stack</code>:</p> <pre><code>new_df = (df.iloc[:,0:2] .stack() .str.split(':',expand=True) ) </code></pre> <p>Then <code>new_df</code> is double indexed:</p> <pre><code> 0 1 2 3 0 col1 0/1 9,12 21 99 ...
pandas
1
5,530
25,701,513
conda update numpy to 1.8.x for 64-bit windows
<p>I'm using a 64-bit machine with Spyder by Anaconda and want to upgrade numpy from 1.7.1 to 1.8.x. But when I use this command: </p> <pre><code>conda update numpy </code></pre> <p>I get the following message:</p> <p><img src="https://i.stack.imgur.com/Q1LtD.png" alt="enter image description here"></p> <p>In other...
<p>I found the solution in this thread: </p> <p><a href="https://stackoverflow.com/questions/11200137/installing-numpy-on-64bit-windows-7-with-python-2-7-3">Installing Numpy on 64bit Windows 7 with Python 2.7.3</a></p> <p>There was an answer saying:</p> <blockquote> <p>But you need to modify your environment varia...
python|numpy|anaconda|spyder
1
5,531
66,767,350
Keeping only the first occurrences of a data in column on a given date without removing other occurrences in pandas
<p>I'm pretty new to pandas so bear with me. I have 1 min interval wise data time frame for few years. Each row have a <code>Long signal</code> column . My index for data frame is date time column.</p> <p><a href="https://i.stack.imgur.com/u8apk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u8apk.p...
<p>To keep only the first occurence of <code>Long Signal</code> and fill with 0 the remaining ones, you can use a combination of <code>loc</code>, <code>groupby</code> with <code>dt.day</code>, and <code>idxmax()</code>.</p> <p>The <code>idxmax()</code> function is used to get the row label of the maximum value and if ...
python|pandas
1
5,532
67,123,730
Saving dataframes with a key
<p>I'm trying to parse a csv file and print certain timeseries graphs.</p> <p><strong>About csv file:</strong> The csv file contains a lot of data from which I need to parse a certain sections of it based on the id inside a for loop. <em>The csv file looks like that:</em></p> <pre><code>ID,name,date,confirmedInfections...
<p>The problem is that you're assigning the key-filtered dataframe to 'df' within your 'for' loop, thus overwriting the original dataframe. To fix, you need to assign the filtered dataframe to another variable. Try:</p> <pre><code>for key in id_array: df_temp = df.loc[key] print(key) df_temp.plot() plt...
python|pandas|csv
2
5,533
66,908,476
xlwings removes ' from my string stored in a dataframe object when I try to paste it into excel
<p>I am trying to paste a dataframe into excel using xlwings.</p> <p>one of the columns holds the name of the item and some of those names starts with ' eg. 'FIRST' itemname</p> <p>When I use</p> <pre><code>xw.Range(startcell, index=False, header=False).value = df </code></pre> <p>xlwings removes the ' at the beginning...
<p>I'll answer my own question.</p> <p>Someone informed me Excel will always treat a leading ' as text so if I want to actually have it write ' to begin with I have to make it a double ' so ''FIRST' itemname. I'll handle that in the dataframe before pasting it</p>
python|excel|pandas|dataframe|xlwings
1
5,534
67,007,721
AssertionError with Keras 2.4
<p>The other answers already asked on SO did not answer my question.</p> <p>I have the following versions:</p> <pre><code>pip list | egrep -i '(keras|tensor)' Keras 2.4.3 Keras-Preprocessing 1.1.2 tensorboard 2.4.1 tensorboard-plugin-wit 1.8...
<p>It seems that a different version of Tensorflow + Python combination is causing this. Since this was happening on a AWS instance with a DeepLearning AMI I was able to switch a different environment with different version where the code started to work.</p>
python|tensorflow|machine-learning|keras|deep-learning
0
5,535
47,343,838
How to change column names in pandas Dataframe using a list of names?
<p>I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:</p> <pre><code>df.rename(columns = list_of_names, inplace=True) </code></pre> <p>However I got a Type Error each time, with an error message that says "<strong>list object is not callable</s...
<p>you could use</p> <pre><code>df.columns = ['Leader', 'Time', 'Score'] </code></pre>
python|pandas|numpy
51
5,536
11,071,490
numpy, mapping one array to parts of another
<p>lets say i have one array</p> <pre><code> a = numpy.arange(8*6*3).reshape((8, 6, 3)) #and another: l = numpy.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" #and yet another: b = numpy.array([[0,0,5],[0,1,0],[1,1,3]]) </code></pre> <p>where "l" and "b" are of equal length, and i wan...
<pre><code>import numpy as np a = np.arange(8*6*3).reshape((8, 6, 3)) l = np.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" b = np.array([[0,0,5],[0,1,0],[1,1,3]]) a[tuple(l.T)] = b print(a[0,0]) # [0 0 5] print(a[0,1]) # [0 1 0] print(a[1,1]) # [1 1 3] </code></pre> <p><a href="http://mail.scipy.org...
python|numpy
3
5,537
68,211,850
TypeError: __array__() takes 1 positional argument but 2 were given
<p>I've been doing the pytorch tutorial (<a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html</a>) and have been getting this error that I don't know how to fix. The full error is below:</p> <pre><co...
<p>PyTorch has already considered this <a href="https://github.com/pytorch/pytorch/issues/61125#issuecomment-872624273" rel="noreferrer">issue</a>. It does not seem to be a PyTorch problem.</p> <p>As <a href="https://github.com/xwang233" rel="noreferrer">xwang233</a> mentioned in the issue, we can fix it by downgrading...
python|machine-learning|computer-vision|pytorch|torchvision
7
5,538
68,056,122
AttributeError: can't set attribute in splitting MNIST dataset
<p>I'm work with pytorch <code>torchvision.datasets.MNIST</code></p> <p>to load the dataset I use:</p> <pre><code>mnist_data = datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose( [transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,))])) <...
<p>If you use <code>torchvision.dataset.MNIST</code> you can change <code>train=True/False</code> for your train or test set.</p> <p>From <a href="https://pytorch.org/vision/stable/_modules/torchvision/datasets/mnist.html#MNIST" rel="nofollow noreferrer">docs</a>, MNIST class has <code>@property</code> train_data, so y...
python|pytorch|torchvision
0
5,539
59,450,901
pandas dataframe group by max on one column
<p>I'm trying to group by the 'keyword' column and get the characteristic with the larger number of records.</p> <p>Let's consider the pandas df:</p> <pre><code>pd.DataFrame([['a', 'A'], ['b', 'A'], ['a', 'B'], ['b', 'B'], ['a', 'A'], ['c', 'B']], columns=['Keywords', 'Char']) </code></pre> <p>For the keyword a the ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a> in lambda function per groups by <code>Keywords</code> and return first value of index. Idea of solution is use <code>value_counts</code> because sort...
python|pandas|dataframe
3
5,540
59,339,689
Compair 2 columns and add a value in a new column
<p>There are so many suggestions in here on how to solve thes problem, but I can´t find anything I can get to work.</p> <p>How do I run through a DataFrame to compare the value in 2 cells from 2 different columns but on the same row, and add a value in a new column. I know that the code I wrote cannot be used since "f...
<p>You don't need make a loop , using numpy is more easy do a comparison like this :</p> <pre><code>import numpy as np import pandas as pd from io import StringIO data = """ Col1,Adj,MA3 A,1,2 B,8,5 C,7,7 """ # Here just to create a csv df = pd.read_csv(StringIO(data),sep=',') # With 2 Logical operators &gt; &lt; d...
python|pandas|dataframe
-1
5,541
57,146,153
Reduce multiclass to binary classification problem
<p>I'm doing an experiment with the well known <a href="https://archive.ics.uci.edu/ml/datasets/Heart+Disease" rel="nofollow noreferrer">UCI heart disease dataset</a> but it's not showing good results (~58% acc.). </p> <p>This dataset has 5 ordinal classes with "levels of heart disease presence" going from 0 to 4, whe...
<p>Its simple, currently your <code>y_train</code> data looks like: <code>[1,2,5,2,1,3,2,4,4,4,5,5,5]</code> what you do is you create an empty array <code>binary_labels</code>, then iterate through each row in the PD, if the label is 1-4 you append 0 to binary_labels, else you append 1. Then you introduce a new column...
python|pandas|machine-learning|scikit-learn|classification
0
5,542
57,187,839
Use numpy array as lambda argument?
<p>Is there a reasonable way to get the following done on one line? I'd really like to avoid creating a temporary variable or a separate function.</p> <pre><code>import numpy as np x = np.array([1,2,3,4,5]) x = np.ma.masked_where(x&gt;2, x) </code></pre> <p>I tried</p> <pre><code>x = map(lambda x: np.ma.masked_where...
<p>You don't need <code>map</code> at all, just an anonymous function. All you will do is replace the initial assignment to <code>x</code> with a parameter binding in a function call.</p> <pre><code>import numpy as np # x = np.array([1,2,3,4,5]) # x = np.ma.masked_where(x&gt;2, x) x = (lambda x: np.ma.masked_where(x&...
python|numpy|lambda|functional-programming
1
5,543
46,067,729
Pandas : series object of one column based on another column
<p>I have data like this :</p> <pre><code> end station name User Type 0 Carmine St &amp; 6 Ave Subscriber 1 South End Ave &amp; Liberty St Subscriber 2 Christopher St &amp; Greenwich St Subscriber 3 Lafayette St &amp; Jersey St Subscriber 4 ...
<p>I think you need filter first by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df1 = rides[rides['User Type'] == 'Customer'] five_popular_station_end_trip = df1['end station name'].value_counts().head(...
python|python-2.7|pandas
0
5,544
35,607,662
Combine sparse and masked array in numpy
<p>Is there a convenient way to use masked array over sparse matrices ?</p> <p>Because it seems that mask not work when creating masked array with scipy sparse matrix...</p> <p>And a typical application would be a adjacency matrix where values could be {0,1,?} for representing links in a network {0,1} and unknown/uns...
<p>I'm not surprised that trying to give a sparse matrix to masked does not work. The few <code>numpy</code> functions that work with sparse ones are ones that delegate to the task to the sparse code.</p> <p>It might be possible to construct a <code>coo</code> format matrix with the <code>data</code> attribute being ...
numpy|sparse-matrix
2
5,545
35,339,139
What values are valid in Pandas 'Freq' tags?
<p>I am new to Pandas, and am trying to use <code>date_range</code>. I came across all kinds of good things for <code>freq</code>, like <code>BME</code> and <code>BMS</code> and I would like to be able to quickly look up the proper strings to get what I want. Yesterday I found a nicely formatted table somewhere in th...
<p>You can find it called <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases" rel="noreferrer">Offset Aliases</a>:</p> <blockquote> <p>A number of string aliases are given to useful common time series frequencies. We will refer to these aliases as offset aliases.</p> </bl...
python|pandas|documentation|dataframe|frequency
228
5,546
50,773,556
How to list all the pairs of numbers which fall under a group of range?
<p>Suppose I have dataframe df1 which includes two columns - A &amp; B. Value of A represents the lower range and value of B represents the upper range.</p> <pre><code> A B 10.5 20.5 30.5 40.5 50.5 60.5 </code></pre> <p>I've another dataframe which includes two columns - C &amp; D containing a different range...
<p>It is not blazing fast (~ 30 secs) on my computer) but could easily be accelerated with the <code>multiprocessing</code> package if you have multiple cores.</p> <p>Generating data : </p> <pre><code>def get_fake(n): df = pd.DataFrame(np.random.rand(n * 2).reshape(-1, 2)) df.loc[:, 1] += 1 return df df1...
python|performance|pandas|data-science
2
5,547
50,787,213
Look up values when the columns names of two dataframes are a match
<p>I would like to write a function that updates the values of df1 when the column names of df1 and df2 match each other. </p> <p>For example: df1: </p> <pre><code> Name | Graduated | Employed | Married AAA 1 2 3 BBB 0 1 2 CCC 1 0 ...
<p>You can use <code>map</code>.</p> <p>Example:</p> <pre><code>df1.Graduated.map(df2.Graduated) </code></pre> <p>yields</p> <pre><code>0 Yes 1 No 2 Yes </code></pre> <p>Thus just do that for every column, as follows</p> <pre><code>for col in df1.columns: if col in df2.columns: df1[col] = df...
python|pandas|dataframe|match|insert-update
1
5,548
51,059,001
Python - apply lambda with an if condition
<p>I want to transform a <code>pandas</code> column that contains <code>Nan</code> from string to float. This is the code I tried but it keeps returning me an invalid syntax error</p> <pre><code>data.VAL_DEAL=data.VAL_DEAL.apply(lambda x: float(x.replace(",","")) if math.isnan(x)!=True) </code></pre>
<p>The following lambda expression should work: </p> <pre><code>lambda x: float(x.replace(",","") if not math.isnan(x) else x) </code></pre> <p>Note the mandatory <code>else</code>-part. This assumes that you want the nan's unchanged. See the docs on <a href="https://docs.python.org/3/reference/expressions.html#condi...
python|pandas
2
5,549
50,762,963
Getting all other columns based on a value Pandas Dataframe
<p>Lets say I have the following df:</p> <pre><code>&gt; Name A B C D John Nan 1 2 Nan Mike 2 Nan Nan Nan Fred Nan 5 6 7 Ana 3 Nan 3 2 Fran 2 Nan 1 1 </code></pre> <p>What I want to do is sorting some columns so, ...
<h3>isnull + all</h3> <p>Your syntax is incorrect. You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow noreferrer"><code>pd.DataFrame.isnull</code></a>:</p> <pre><code>mask1 = df['A'] &gt; 0 mask2 = df[['B', 'C', 'D']].isnull().all(1) df_1 = df_1[ma...
python|pandas|dataframe
2
5,550
50,772,489
Different results when calculating quantile in pandas (Python) and R
<p>Could you please tell me, why the results differ, when quantiles are calculated in pandas (Python) and R?</p> <p>Pandas code:</p> <pre><code> print('p_new: {:&gt;5} {:&gt;5} {:&gt;5}'.format( round(self.pandas_data_frame['pending_new'].quantile(0.50), 2), round(self.pandas_data_frame['pend...
<p>When doing this function in Python, all functions of the <code>np.percentile()</code> family have an optional argument interpolation. Set this argument to 'midpoint' and your results with match the result in R. You can also read more about the python function here: <a href="https://stackoverflow.com/questions/459262...
python|r|python-3.x|pandas
0
5,551
50,679,638
Python - data.to_csv output format
<p>From a csv file having the following format:</p> <pre><code>Date,Data 01-01-01,111 02-02-02,222 03-03-03,333 </code></pre> <p>I am calculating the monthly average of the values using the following code:</p> <pre><code>data = pd.read_csv("input.csv") data['Month'] = pd.DatetimeIndex(data.reset_index()['Date']).mon...
<p>Need specify column after <code>groupby</code>:</p> <pre><code>#convert first column to datetime data = pd.read_csv("input.csv", parse_dates=[0]) </code></pre> <hr> <pre><code>df['Month'] = df['Date'].dt.month mean_data = data.groupby('Month')['Data'].agg(['mean', 'count']) </code></pre> <p>should be simplify:</...
python|pandas|csv|aggregate|columnname
1
5,552
20,508,968
Series.fillna() in a MultiIndex DataFrame Does not Fill; Is This a Bug?
<p>For me, the following snippet leaves the NaN value as NaN:</p> <pre><code>import pandas a = [12, 23] b = [123, None] c = [1234, 2345] d = [12345, 23456] tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'), ('ears', 'right')] events = {('eyes', 'left'): a, ('eyes', 'right'): b, ('ears', 'left'): c, ('ear...
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>update</code></a> here since it's more explicit... and avoids the whole <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy" rel="nofo...
python|pandas
2
5,553
33,467,477
How to find all variables with identical id?
<p>Let's say I have a <code>numpy</code> array <code>a</code> and create <code>b</code> like this:</p> <pre><code>a = np.arange(3) b = a </code></pre> <p>If I now change <code>b</code> e.g. like this</p> <pre><code>b[0] = 100 </code></pre> <p>and print <code>a</code>, <code>b</code>, their <code>id</code>s and <cod...
<p>There are 2 issues - how do you identify the variables that you want to compare, and how to do you compare them.</p> <p>Take the second first.</p> <p>My version (1.8.2) does not have a <code>np.shares_memory</code> function. It does have a <code>np.may_share_memory</code>. </p> <p><a href="https://github.com/nu...
python|arrays|numpy|copy
5
5,554
66,379,473
How to augment text datasets in Tensorflow?
<p>I'm trying to augment the imdb movie reviews dataset by adding a random swap of some words. Unlike with image data, I don't think this function is originally in tensorflow. For example with images, you could do something like</p> <pre><code>def transform(image, label): image = tf.image.flip_left_right(image) ...
<p>By loading the dataset with <code>imdb.load_data()</code> you don't get the film reviews as text. It has already been preprocessed: the reviews (sequences of words) have been turned into sequences of integers, where each integer stands for a specific word in a dictionary.</p> <p>For this reason, you cannot apply <co...
python|tensorflow|text|nlp|data-augmentation
1
5,555
66,650,233
Pixel operations in batches
<p>I have a batch of depth images, shape -&gt; [B, 1, H, W]. For each pixel in each image of the batch I need to perform:</p> <p><code>X = d * Kinverse @ [u, v, 1] #therefore X is in R^3</code> where d is float tensor[0;1] representing depth at pixel u,v; Kinverse is a constant 3X3 matrix and u, v refer to the pixel ...
<p>You can use <a href="https://pytorch.org/docs/stable/generated/torch.meshgrid.html#torch.meshgrid" rel="nofollow noreferrer"><code>torch.meshgrid</code></a> to produce the <code>u</code> and <code>v</code> tensors. Once you have them, you can use <a href="https://stackoverflow.com/a/55894780/1714410"><code>torch.ein...
python|computer-vision|pytorch|vectorization
1
5,556
66,719,029
Why Keras Embedding layer's input_dim = vocab_size + 1
<p>In this code snippet from TensorFlow tutorial <a href="https://www.tensorflow.org/tutorials/keras/text_classification#create_the_model" rel="nofollow noreferrer">Basic text classification</a>,</p> <pre><code>model = tf.keras.Sequential([ layers.Embedding(max_features + 1, embedding_dim), layers.Dropout(0.2), l...
<p>Vocabulary Size = Maximum Integer Index + 1</p> <p>Example:<br/> a[0] = 'item 1'<br /> a[1] = 'item 2'<br /> a[2] = 'item 3'<br /> ................<br /> Maximum Integer Index = 2 <br /> Vocabulary Size = 3</p>
tensorflow|keras|embedding
1
5,557
66,498,659
Function to generate incremental weights based on np.select conditions
<p>Objective: Define function to use flags (1,2,3) as conditions that trigger different weights (.2,.4,0). Output is a new df with the weights only.</p> <p>The np.select is generating this error:</p> <p>TypeError: invalid entry 0 in condlist: should be boolean ndarray</p> <p>Image shows desired output as &quot;incremen...
<p>np.select was unnecessary. simple solution using df.replace with a mapping dict.</p> <pre><code>import pandas as pd import numpy as np flags = pd.DataFrame({'Date': ['2020-01-01','2020-02-01','2020-03-01'], 'flag_1': [1, 2, 3], 'flag_2': [1, 1, 1], 'flag_3':...
python-3.x|pandas|loops|cumulative-sum
1
5,558
16,212,232
How to merge and split numpy array along the axis?
<p>I have the data in the following form the shape of the array is </p> <pre><code> (10,4,4,3) </code></pre> <p>First i want to create an array with shape (merging, or flattening)</p> <pre><code> (10,48) </code></pre> <p>such that data (4,4,3) is converted to one row.</p> <p>Secondly I want to go back to the or...
<pre><code>b = a.reshape(10,48) a = b.reshape(10,4,4,3) </code></pre>
python|arrays|numpy|merge|split
2
5,559
16,548,560
check if numpy array is subset of another array
<p>Similar questions have already been asked on SO, but they have more specific constraints and their answers don't apply to my question.</p> <p>Generally speaking, what is the most pythonic way to determine if an arbitrary numpy array is a subset of another array? More specifically, I have a roughly 20000x3 array and...
<p>One can also use <code>np.isin</code> which might be more efficient than the list comprehension in <a href="https://stackoverflow.com/a/16548813/1534017">@petrichor's answer</a>. Using the same set up:</p> <pre><code>import numpy as np x = np.arange(30).reshape(10, 3) searchKey = [4, 5, 8] x[[0, 3, 7], :] = searchK...
python|numpy|set
4
5,560
57,556,182
Generating heatmap from frames
<p>I have an issue as follow, i have coordinates x, y, z and r. Each of point is a Frame. Based on Frames want to generate heat-map with python. What i did till now, i imported the following frames:</p> <pre><code>-1.52588e-05 -1.52588e-05 8.17212e-06 300 -220.414 -220.305 217.847 79.5859 -220.899 220.54 -219.881...
<p>Try following code:</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt with open('data.txt', 'r') as f: data = f.read().replace(' ', ' ') with open('data.txt', 'w') as f: f.write(data) df = pd.read_csv('data.txt', sep=' ', header=None) sns.heatmap(df, annot=True) plt....
python|pandas|heatmap
1
5,561
57,323,598
Is Tensorflow Federated-Learning only for simulating federated learning on one machine?
<p>I read multiple guides on <a href="https://www.tensorflow.org/federated/federated_learning" rel="nofollow noreferrer">https://www.tensorflow.org/federated/federated_learning</a> e.g. the image classification or text generation example.</p> <p>From what I have read I can not see how to use tensorflow federated-learn...
<p>As of today TFF only provides a simulation environment for use in Federated Learning (FL) research.</p> <p>There is work being done on a supporting multi-machine simulation environment, but this is still ongoing work (see <a href="https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/core/...
tensorflow|tensorflow-federated
4
5,562
57,377,894
Pandas, count if time difference is within x seconds
<p>I want to group values, if they are within the same x amount of seconds. e.g. I got this by doing this:</p> <pre><code>m_failed = df[(df[&quot;Signal&quot;] == &quot;Alarm&quot;) &amp; (df[&quot;State&quot;] == &quot;Active&quot;)] dd_failed = m_failed.groupby(['Country', 'Lane', 'Unit', 'Datetime']).size().to_frame...
<p>Use <code>pd.Grouper</code> along with <code>Country</code> and <code>City</code> as your <code>groupby</code> keys. I chose <code>60S</code> as the frequency, but change this as needed.</p> <hr> <pre><code>keys = ['Country', 'City', pd.Grouper(key='Datetime', freq='60S')] df.groupby(keys, sort=False).agg(Unit=(...
python-3.x|pandas
2
5,563
57,317,159
doing math operations using numpy in python3
<p>I have a <code>numpy</code> <code>array</code> like this example:</p> <p>example:</p> <pre><code>arr = array([[31, 18], [ 27, 9], [21, 20]]) </code></pre> <p>and I want to get the <code>mean</code> of every inner list separately and also <code>standard deviation</code> of every inner list separatel...
<p>There are two issues in your code. First, you are calling <code>np.mean</code> without an argument, which should result in an error. Instead, you want to call either <code>arr.mean(...)</code> or <code>np.mean(arr, ...)</code>. Second, you are overwriting the <code>result</code> variable in every iteration of the lo...
numpy|math
2
5,564
57,684,367
In Pandas, is there an elegant way to assign a category to an item based on whether it contains particular strings?
<p>I have a .csv file with the following column headers:</p> <p>Identifier, Date, Task, Category, Person</p> <p>I want to assign a category or categories to each task, based on whether the task string contains any of a number of substrings, such as:</p> <p>“met”, “fix, “corresp”, “particip”, “update”, “sent”, “atten...
<pre><code>df.loc[masked_df,'Category'] == 'whatever_you_want' </code></pre> <p>where masked_df is your boolean result</p>
python|pandas|csv|dataframe|categories
0
5,565
57,674,270
Appending a dataframe row with specific values of other dataframes - python
<p>I am working on implementing the Connexion Scan Algorithm in python because I need to have access to shortests public transport paths. So I am trying to create a connexion table from gtfs files.</p> <p>I have a dataframe (stop_times) that contains the following columns:</p> <pre class="lang-py prettyprint-override...
<p>If I got your question right, you don't need <code>groupby</code> at all and can use a combination of <code>shift(1)</code> and concat to get, what you want:</p> <pre><code>import numpy as np # make sure the dataframe is sorted by trip_id and arrival_time # please choose what is better according your data arrival_t...
python|pandas|loops|dataframe|gtfs
0
5,566
73,151,593
Iterative time difference between two column entries in a data frame column
<p>I have a pandas data frame that has a column of Date that is in this format as an example, 2022-07-22. The table is also below for a better understanding. I would like to get the time elapsed between each entry in hours. So far I have managed to get the elapsed time using this code:</p> <pre><code>startTime = data.D...
<p>The 'Date' column is converted from string to datetime64[ns]. Here the difference function diff is used to calculate the 'dif ' column. Further, the differences are divided by the pd.Timedelta in one hour. I think the cycle is redundant here. And I added more hour difference in each value.</p> <pre><code>import pand...
python|pandas
1
5,567
72,892,050
Mark repeated id with a-b relationship in dataframe
<p>I'm trying to create a relationship between repeated ID's in dataframe. For example take 91, so 91 is repeated 4 times so for first 91 entry <strong>first</strong> column row value will be updated to <strong>A</strong> and <strong>second</strong> will be updated to <strong>B</strong> then for next row of 91, first w...
<p>You can perform a mapping using a <code>cumcount</code> per group as source:</p> <pre><code>from string import ascii_uppercase # mapping dictionary # this is an example, you can use any mapping d = dict(enumerate(ascii_uppercase)) # {0: 'A', 1: 'B', 2: 'C'...} g = df.groupby('id') c = g.cumcount() m = g['id'].tran...
python|pandas
2
5,568
73,042,918
Converting MATLAB random function to python
<p>My task is to convert one big MATLAB file into python.</p> <p>There is a line in MATLAB</p> <pre><code>weightsEI_slow = random('binom',1,0.2,[EneuronNum_slow,IneuronNum_slow]); </code></pre> <p>I am trying to convert this into python code, I am not quite finding the right documentation. I looked for numpy libr...
<p>It looks like you generate a random number that follows the Binomial distribution with probability <code>p=0.2</code> and sample size <code>n=1</code>. In turn, you can leverage numpy</p> <pre><code>import numpy as np np.random.binomial(n=1, p=0.2) &gt;0 </code></pre> <p>If you require replicability, add <code>np.r...
python|numpy|matlab
0
5,569
73,009,611
How to drop specific pandas rows by value
<p>Is there any way that I can drop the value if its index = column index.</p> <p>I mean, this is my toy dataframe</p> <pre class="lang-py prettyprint-override"><code>d = {'Non': [1, 2,4,5,2,7], 'Schzerando': [3, 4,8,4,7,7], 'cc': [1,2,0.75,0.25,0.3,1]} df = pd.DataFrame(data=d) df </code></pre> <p>Then I just want to ...
<p>You can filter out the rows by converting the <code>cc</code> column to int type then filter by applying mask.</p> <pre><code>df['cc'] = df['cc'].astype('Int64') df = df[df['cc'] == 1 | df['cc'] == 2 | df['cc'] == 3] </code></pre> <p>or you can declare a list with all the values you want to filter for then use panda...
python|pandas
1
5,570
42,938,994
Inconsistent loading of keras backend between theano and tensorflow
<p>My <code>keras.json</code> has backend specified to be <code>tensorflow</code> and if I open Spyder and Jupyter IDE then <code>tensorflow</code> is used as a backend.</p> <p>Strangely if I open <code>python</code> or <code>ipython</code> shell within my WinPython installation, the backend defaults into <code>theano...
<p>Looks like existing notebooks still say Theano. But If I create new one and enter the following then I get proper result as tensorflow import os</p> <pre><code>os.environ['KERAS_BACKEND']='tensorflow' import keras keras.backend.backend() </code></pre> <p>Using TensorFlow backend. Out[1]: 'tensorflow' In [ ]:</...
python|windows|tensorflow|theano|keras
0
5,571
42,728,532
List of Lists in dataframe, need to access a single value for all
<p>I have a dataframe with lists in the cells.</p> <pre><code>player1 player2 player3 0 ['PF/C', 'DeMarcus Cousins', 11000] ['PG', 'John Wall', 10700] ['SF', 'LeBron James', 10600] 1 ['PF/C', 'DeMarcus Cousins', 11000] ['PG', 'John Wall', 10700] ['PG/SF', 'Giannis Antetokounmpo', 10200] 2 ['PF/C', 'DeMarcus Co...
<pre><code>df['total_salary'] = df.apply(lambda x: x['player1'][2] + \ x['player2'][2] + \ x['player3'][2], axis=1) </code></pre> <p>That said, I would like to put in a vote for your splitting each of those li...
pandas|dataframe
0
5,572
43,025,963
Pandas foreach row multiplication - Speedup
<p>I have extrem slow code:</p> <p>A DataFrame called <code>tmp</code> with a MultiIndex (date and id) with around 2.000.000 lines and 2 columns (V1,V2). </p> <pre><code> V1 V2 Date ID 2000-01-01 1 0.3 0.1 2000-01-01 2 0.3 0.1 2000-01-02 1 0.1 0.1 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>mul</code></a>, then remove level <code>id</code> of <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" ...
python|pandas
0
5,573
42,701,863
Pandas: cross dataset column matching
<p>There are multiple datasets and I would like to find out how they potentially connected with each other. E.g. if string columns in datasets A and B have lots of values in common, that might be a link. Is it possible to do this kind of analysis automatically?</p>
<p>you could always make them into dataframes and check that way. Might be slow depending on size of your data. But this is a very basic way and the code below creates extra dataframes for learning purposes, not the best code but I wanted you to see the progression.</p> <pre><code>import pandas as pd import numpy as n...
python|pandas
0
5,574
27,277,381
Plot arrays same extension Matlotlib
<p>I've several time series stored in numpy arrays with de same extension (*.corr.npy). I would like to plot it in the same figure with matplotlib.</p> <p>Now I'm plotting like that:</p> <pre><code>import pylab as plt import numpy as num a=num.load('100.corr.npy') b=num.load('2345.corr.npy') ... plt.plot(a) plt.plot(...
<p>This is where the <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> standard module shines! It will generate lists of files matching simple format rules.</p> <p>In your case:</p> <pre><code>import glob import numpy as np array_files = glob.glob('*.corr.npy') for fname in a...
python|numpy|matplotlib
4
5,575
27,346,930
Remove quotations from numpy array
<p>I have a numpy array which includes unnecessary quotations ("):</p> <pre><code>array(["'sf64user_Number__c':'tKey'", "'PreferredFirstName__c':'tPreferredFirstName'"], dtype=object) </code></pre> <p>How can I go about removing the opening and closing "s so my numpy result would read as follows:</p> <pre><code>['s...
<pre><code>array(["'sf64user_Number__c':'tKey'", "'PreferredFirstName__c':'tPreferredFirstName'"], dtype=object) </code></pre> <p>is an array of 'objects', though the objects look like strings.</p> <pre><code>['sf64user_Number__c':'tKey', 'PreferredFirstName__c':'tPreferredFirstName'] </code></pre> <p>does not look...
python|arrays|numpy
1
5,576
25,321,357
Counting qualitative values based on the date range in Pandas
<p>I am learning to use Pandas library and need to perform analysis and plot the crime data set below. Each row represents one occurrence of crime. date_rep column contains daily dates for a year. </p> <p><img src="https://i.stack.imgur.com/Eshxx.png" alt="enter image description here"></p> <p>Data needs to be groupe...
<p>To replicate something of your data:</p> <pre><code>In [29]: df = pd.DataFrame({'date_rep':pd.date_range('2012-01-01', periods=100), ...: 'crm_cd_desc':np.random.choice(['robbery', 'traffic', 'assault'], size=100)}) In [30]: df.head() Out[30]: crm_cd_desc date_rep 0 traffic 2012-01...
python|pandas|data-analysis
3
5,577
26,571,741
Splitting one NumPy array into two arrays
<p>Suppose I have a <code>NumPy</code> <code>2D</code> array <code>A</code>: </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A=np.arange(30).reshape(3,10) &gt;&gt;&gt; A 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, 25, 26, 27...
<p>One of the simplest ways is to use indexing to select the appropriate columns:</p> <pre><code>&gt;&gt;&gt; A[:, [1, 2]] # choose all rows from columns 1-2 (gives C) array([[ 1, 2], [11, 12], [21, 22]]) &gt;&gt;&gt; A[:, np.r_[0, 3:10]] # choose all rows from columns 0, 3-9 (gives B) array([[ 0, 3, ...
python|arrays|numpy
14
5,578
39,064,212
BinaryNet implementation in TensorFlow
<p>I recently read a very interesting paper (<a href="http://arxiv.org/pdf/1602.02830v3.pdf" rel="noreferrer">http://arxiv.org/pdf/1602.02830v3.pdf</a>) suggesting a method for training a CNN with weights and activations constrained to [-1,1]. This is highly beneficial from power/speed perspective.</p> <p>There are i...
<p>Take a look at the TensorFlow <a href="http://github.com/tensorflow/tensorflow/issues/1592" rel="nofollow" title="GitHub issue 1592">GitHub issue #1592</a>. It tracks the progress of the current attempt to add support for binary networks in TensorFlow.</p>
tensorflow|conv-neural-network|quantization
3
5,579
39,335,535
Label smoothing (soft targets) in Pandas
<p>In Pandas there is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="noreferrer"><code>get_dummies</code></a> method that one-hot encodes categorical variable. Now I want to do label smoothing as described in section 7.5.1 of <a href="http://www.deeplearningbook.org/" rel="...
<p>First, lets use much simpler equation (<code>ϵ</code> denotes how much probability mass you move from "true label" and distribute to all remaining ones).</p> <pre><code>1 -&gt; 1 - ϵ 0 -&gt; ϵ / (k-1) </code></pre> <p>You can simply use nice mathematical property of the above, since all you have to do is</p> <pr...
python|pandas|machine-learning
10
5,580
39,150,020
Pandas select columns and data dependant on header
<p>I have a large .csv file. I want to select only the column with he time/date and 20 other columns which I know by header. </p> <p>As a test I try to take only the column with the header 'TIMESTAMP' I know this is 4207823 rows long in the .csv and it only contains dates and times. The code below selects the TIMESTA...
<p>The problem was due to an error in the input file so simple use of <code>usecols</code> in <code>pandas.read_csv</code> worked.</p> <p>code below demonstrates the selection of a few columns of data</p> <pre><code>import csv import pandas low_memory=False #read only the selected columns df = pandas.read...
python|python-2.7|csv|pandas|columnheader
0
5,581
39,377,229
csv file to numpy array via Python
<p>I have a csv file of the following format that I am trying to normalise. The numbers represent the counts for associated strings. The file contains close to 100K entries.</p> <pre><code>159028,CASSVDGSYEQYFGPG 86832,CASSLQLYFGEG 74720,CASSQDQDTQYFGPG 71701,CASSRVGSDYTFGSG 69360,CARNVTPPKSYAVFFGKG 52458,CAAEQFFGPG 5...
<p>Use Numpy loadtxt to import, then use a dict comprehension if you need it as a dict.</p> <pre><code>import numpy as np arr = np.loadtxt('data.csv', dtype=str, delimiter=",") b = dict([(y, x) for (x, y) in arr]) </code></pre>
python|list|csv|numpy|dictionary
1
5,582
39,345,624
Can pandas dataframe have dtype of list?
<p>I'm new to Pandas, I process a dataset, where one of the columns is string with pipe (<code>|</code>) separated values. Now I have a task to remove any text in this |-separated field that's not fulfilling certain criteria.</p> <p>My naive approach is to iterate the dataframe row by row and explode the field into li...
<p>IIUC you can use:</p> <pre><code>dataframe = pd.DataFrame({'field':['aasd|bbuu|cccc|ddde|e','ffff|gggg|hhhh|i|j','cccc|u|k'], 'G':[4,5,6]}) print (dataframe) G field 0 4 aasd|bbuu|cccc|ddde|e 1 5 ffff|gggg|hhhh|i|j 2 6 cccc|u|k print (dataframe....
python|string|list|pandas|list-comprehension
1
5,583
13,213,039
Reshape a group of Pandas Series into a DataFrame and fillin missing values
<p>I have several Pandas Series objects that look like this:</p> <pre><code>r = pd.Series({'a': [1,2,3,4]}) s = pd.Series({'b': [2,4,1]}) u = pd.Series({'c': [8,6]}) v = pd.Series({'d': [4,3,1]}) </code></pre> <p>I'd like to convert these Series objects into a data fram with the dictionay keys as column names and the...
<p>I think the easiest way to do this is to <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#joining-on-index" rel="nofollow"><code>join</code> on index</a>. I've tweaked the original variables to DataFrames to enable this <em>(Note: they ought to be DataFrames rather than Series anyway)</em>:</p> <pr...
scipy|pandas
2
5,584
33,885,051
Using Spyder / Python to Open .npy File
<p>Sorry. I'm just now learning Python and everything there is to do with data analysis. </p> <p>How on earth do I open a .npy file with Spyder? Or do I have to use another program? I'm using a Mac, if that is at all relevant.</p>
<p><code>*.npy</code> files are binary files to store numpy arrays. They are created with</p> <pre><code>import numpy as np data = np.random.normal(0, 1, 100) np.save('data.npy', data) </code></pre> <p>And read in like</p> <pre><code>import numpy as np data = np.load('data.npy') </code></pre>
python|file|numpy
45
5,585
23,645,484
Elements arrangement in a numpy array
<pre><code>import numpy as np data = np.array([[0, 0, 1, 1, 2, 2], [1, 0, 0, 1, 2, 2], [1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 2, 0]]) </code></pre> <p>How can I do the followings?</p> <p>Within 2 by 2 patch:</p> <pre><code>if any element is 2: put 2 if any element is 1: ...
<p>Using <code>extract_patches</code> from scikit-learn you can write this as follows (copy and paste-able code):</p> <pre><code>import numpy as np from sklearn.feature_extraction.image import extract_patches data = np.array([[0, 0, 1, 1, 2, 2], [1, 0, 0, 1, 2, 2], [1, 0, 1, 0, 0, 0]...
python|arrays|numpy|scipy|scikit-learn
4
5,586
29,745,968
Finding Given Coordinate Positions in NumPy Array
<pre><code>import numpy as np ref_cols = [11, 5, 12, 13, 15] ref_rows = [1, 11, 2, 3, 5] rows, cols = np.mgrid[1:6, 11:16] print cols [[11 12 13 14 15] [11 12 13 14 15] [11 12 13 14 15] [11 12 13 14 15] [11 12 13 14 15]] print rows [[1 1 1 1 1] [2 2 2 2 2] [3 3 3 3 3] [4 4 4 4 4] [5 5 5 5 5]] </code></pre> ...
<p>The reason that your try goes wrong is that you first need to evaluate each pair separately and you cannot evaluate first all rows and columns separately and then combine them in a logical operation.</p> <p>Here is one way to fix it:</p> <pre><code>out = np.zeros(rows.shape, dtype=bool) for r, c in zip(ref_rows, r...
python|numpy|scipy
2
5,587
62,387,274
Create CSV with referencing in pandas
<p>I am working on creating a csv file using to_csv($outfile.csv') in python pandas, Basically i wanted to create macro variable name for csv file rather then giving it into the to_csv function. Any lead would really appriciated : )</p> <pre><code>outfile = CNR_FCS_MAY_T_2020_FX df.to_csv('outfile.csv') print("query ...
<p>Below part is working for me now : )</p> <pre><code> outfile = 'CNR_FCS_MAY_T_2020_FX.csv' df.to_csv(outfile) print("query export ran") </code></pre>
python|pandas|export-to-csv
0
5,588
62,285,072
How to replace certain values of a multiindex?
<p>I have a dataframe looking like <a href="https://i.stack.imgur.com/XPnQ4.png" rel="nofollow noreferrer">this</a> with a multiindex. Now I want to replace all values in the cluster column equal to 1 with a 4, if the date in the row before is a Saturday.</p> <p>I managed to get a boolean-array which is true for all ...
<p>It's not easy. A MultiIndex is made of tuples, which are immutable, and the Index itself is immutable, so we need to recreate the entire MultiIndex. </p> <p>Re-create the entire MultiIndex from the arrays, where we modify the second level using <code>np.where</code> to change it to 4 when your condition is satisfie...
python|pandas|dataframe|indexing|replace
0
5,589
62,414,658
TensorFlow dataset .map() method not working for built-in tf.keras.preprocessing.image functions
<p>I load in a dataset as such:</p> <pre><code>import tensorflow_datasets as tfds ds = tfds.load( 'caltech_birds2010', split='train', as_supervised=False) </code></pre> <p>And this function works fine:</p> <pre><code>import tensorflow as tf @tf.function def pad(image,label): return (tf.image.resize...
<p>I would try using tf.py_function in here for the random_rotation. For eg:</p> <pre><code>def rotate(image, label): im_shape = image.shape [image, label,] = tf.py_function(random_rotate,[image, label], [tf.float32, tf.string]) image.set_shape(im_shape) return image...
python|tensorflow|keras|tensorflow-datasets
2
5,590
62,156,753
Plotly express line chart - get default colors (how to color lines as specified by a dictionary object?)
<p>I have a data frame of a multivariate time series, for which I've created a interactive plotly express plot. I'm adding vertical lines at particular locations specified by a dictionary, each line associated to one of the time series, and wish to set the line color to agree with that of the corresponding variable. In...
<p>Cool question. There might be a better solution, but here's the one I found. Replace the code that creates the vertical lines with the following: </p> <pre><code># fetch the colors of the traces from the figure. colors = [trace.line["color"] for trace in fig.data] for inx, (channel,times) in enumerate(HFOs.items(...
python|pandas|plotly
2
5,591
62,300,836
KeyError when using non-default models in Huggingface transformers pipeline
<p>I have no problems using the default model in the sentiment analysis pipeline. </p> <pre class="lang-py prettyprint-override"><code># Allocate a pipeline for sentiment-analysis nlp = pipeline('sentiment-analysis') nlp('I am a black man.') &gt;&gt;&gt;[{'label': 'NEGATIVE', 'score': 0.5723695158958435}] </code></p...
<p>I am facing the same problem. I am working with a model from XML-R fine-tuned with squadv2 data set (&quot;a-ware/xlmroberta-squadv2&quot;). In my case, the KeyError is 16.</p> <p><strong>Link</strong></p> <p>Looking for help on the issue I have found this information: <a href="https://www.gitmemory.com/issue/huggin...
huggingface-transformers
2
5,592
51,503,717
Alternative to groupby for generating a summary table from tidy pandas DataFrame
<p>I want to generate a summary table from a <a href="https://en.wikipedia.org/wiki/Tidy_data" rel="nofollow noreferrer">tidy</a> pandas DataFrame. I now use <code>groupby</code> and two <code>for</code> loops, which does not seem efficient. Seems stacking and unstacking would get me there, but I have failed. </p> <p>...
<p>A simple solution from <code>crosstab</code></p> <pre><code>pd.crosstab(index=df.Cat,columns=df.Stage,values=df.Score,aggfunc='sum', margins = True, margins_name = 'Total').iloc[:-1,:] Out[342]: Stage EOL FUEL OP Total Cat CC NaN 1.521572 1.21...
python|pandas
3
5,593
51,382,253
Pandas - InvalidIndexError: Reindexing only valid with uniquely valued Index objects
<p>I have 2 dataframes, with one that contains company data and the other that has some employee count details as shown below:</p> <p><strong>df1:</strong></p> <pre><code>cust_id,name,count 1,abc, 2,def, </code></pre> <p><strong>df2:</strong></p> <pre><code>account,count abc,4 klm,1 </code></pre> <p><strong>I am t...
<p>This should work: </p> <pre><code>result = pd.merge(df1, df2, left_on='name', right_on='account', how='left', sort=False) </code></pre>
python|python-3.x|pandas|duplicates
0
5,594
51,256,020
How to save data from `console.log` to MySQL database?
<p>`</p> <pre><code>var imageScaleFactor = 0.5; var outputStride = 16; var flipHorizontal = false; var imageElement = document.getElementById('video'); posenet.load().then(function(net){ return net.estimateSinglePose(imageElement, imageScaleFactor, flipHorizontal, outputStride) }).then(function(pose){ console.lo...
<p>You could create a PHP handler that you could send the console.log() JS dump to via an ajax POST. That's the only way to bridge the gap I could think of.</p> <p>In your Javascript you could override the built-in <code>console.log</code> function to accomplish this:</p> <pre><code>console.log = function(value){ ...
javascript|php|mysql|tensorflow
-2
5,595
48,316,149
Replace row value by comparing dates
<p>I have a date in a list:</p> <pre><code>[datetime.date(2017, 8, 9)] </code></pre> <p>I want replace the value of a dataframe matching that date with zero.</p> <p>Dataframe:</p> <pre><code> Date Amplitude Magnitude Peaks Crests 0 2017-06-21 6.953356 1046.656154 4 3 1 2017-06-27 ...
<p>First your solution working nice with your sample data.</p> <p>Another faster solution is creating each mask in loop and then reduce by logical <code>or</code>, <code>and</code> - what need. Better it is explained <a href="https://stackoverflow.com/q/20528328/2901002">here</a>.</p> <pre><code>L = [datetime.date(20...
python|pandas|datetime|dataframe
1
5,596
48,285,891
For loops with Dask arrays and/or h5py
<p>I have a time series with over a hundred million rows of data. I am trying to reshape it to include a time window. My sample data is of shape (79499, 9) and I am trying to reshape it to (79979, 10, 9). The following for loop works fine in numpy. </p> <pre><code>def munge(data, backprop_window): result = [] ...
<p>This doesn't necessarily solve your dask issue, but as a much faster alternative to <code>munge</code>, you could instead use numpy's <code>stride_tricks</code> to create a rolling view into your data (based on example <a href="http://arogozhnikov.github.io/2015/09/30/NumpyTipsAndTricks2.html#Rolling-window,--stride...
python|numpy|dask|h5py
2
5,597
48,160,197
Adding a column from the original data frame to a groupby data frame?
<p>I have a data frame df1 with data that looks like this: </p> <pre><code> Item Store Sales Dept 0 1 1 5 A 1 1 2 3 A 2 1 3 4 A 3 2 1 3 A 4 2 2 3 A </code></pre> <p>I then want to use group by to see the total sales by item: </p> ...
<pre><code>df.groupby(['Item']).agg({'Item':'first','Sales':'sum','Dept': 'first'}).\ assign(Itemrank=df.Sales.rank(ascending=False,method='min').astype(int) ) Out[64]: Item Dept Sales Itemrank Item 1 1 A 12 3 2 2 A 6 2 </code></pre>
python|pandas|pandas-groupby
2
5,598
48,449,087
Imputing means using pivot table in pandas?
<p>I am working on the Titanic data set right now, which as some missing values in the "Age" feature. I have the following Pivot Table created by pandas using the non-missing data:</p> <pre><code>+---------+-----------+-----------+ | Pclass | Sex | Age | +---------+-----------+-----------+ | 1 | fem...
<p>Using <code>fillna</code> </p> <pre><code>Originaldf=Originaldf.set_index(['Pclass','Sex']).Age.fillna(piv.Age).reset_index() </code></pre>
python|pandas
2
5,599
48,865,554
using dynamic_rnn with multiRNN gives error
<p>I want to create a dynamic_rnn using tensorflow in python with Multi LSTM cells. form searches on internet I have found this code:</p> <pre><code>import tensorflow as tf batch_size = 30 truncated_series_length = 4 num_layers = 3 state_size = 300 x_input = tf.placeholder(tf.float32, [batch_size, truncated_series_l...
<p>I think the problem is roughly addressed here: <a href="https://github.com/tensorflow/tensorflow/issues/16186" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/16186</a></p> <p>Basically, to elaborate the answer from this issue: Using <code>[cell]*num_layers</code> will create a list of tw...
python|tensorflow|lstm|rnn
2