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
355,200
57,702,699
Applying a function on specific Dataframe rows with datetime index as arguments
<p>Given the following Dataframe</p> <pre><code>import pandas as pd from collections import OrderedDict d = OrderedDict([ ('Date_Time', ['2016-01-18 00:00:00', '2016-01-18 12:00:00', '2016-01-19 00:00:00', '20...
<p>If you want to create a new column you could just do:</p> <pre><code>def dosomething(x, y): return something df['New Column'] = dosomething(df_col1, df_col2) </code></pre> <p>This should create a new column with the logic dependent on those two columns.</p>
python|python-3.x|pandas
0
355,201
57,504,922
Is there a way to extract only one column from all the 30 dataframes?
<p>I have 30 dataframes, but from each of these dataframes i just want one column from them. Each of these dataframes contain stock prices OHLC, Adj Close and volumes. I want to extract only one column from 30 dataframes i.e. "Adj Close"</p> <p>How do i do that without making the code lengthy?</p>
<p>Use list comprehension:</p> <pre><code>dfs = [df1, df2, df3...df30] #if need Series out = [df['Adj Close'] for df in dfs] #if need one column DataFrames #out = [df[['Adj Close']] for df in dfs] </code></pre> <p>Or loop:</p> <pre><code>out = [] for df in dfs: #if need Series out.append(df['Adj Close']) ...
python|pandas
1
355,202
57,512,984
i want to drop 2 rows in the dataframe if zero comes in the column
<p>if 0 comes on odd index drop previous row as well as current row using pandas </p> <p>example </p> <pre><code>column1 column2 a 1 b 0 c 2 b 3 e 7 f 0 </code></pre> <p>output</p> <pre><code>column1 column2 c 2 b ...
<p>Assuming your dataframe is indexed starting from 0</p> <pre><code># Rows with column2 = 0 and on odd index idx = df[(df['column2'] == 0) &amp; (df.index % 2 == 1)].index # The rows above them idx = idx.append(idx-1) # A new dataframe with those rows removed result = df.drop(idx) </code></pre>
python-3.x|pandas
0
355,203
57,450,218
Tensorflow/Keras - how to expose relations between categories?
<p>I have data which is labelled with 5 categories.</p> <p>Each category represent the same event of different intensity in physical world.</p> <p>The importance of that fact is that category 5 is basically must stronger version of the same event as category 1 (eg earthquake).</p> <p>Can someone please offer an idea...
<p>One-Hot Encoding is common for multi-class classification problems. In your case, a category 3 event label would be encoded as [0, 0, 1, 0, 0]. You would create a model with a dense output layer with softmax activations, then to get a prediction you would take the argmax of the output layer to get the category.</p> ...
tensorflow|machine-learning|keras|deep-learning
3
355,204
57,347,898
Changing datatime in several columns in dataframe
<p>I'm trying to change the <code>datatime</code> format of several columns in my dataset however I get:</p> <pre class="lang-none prettyprint-override"><code>ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing </code></pre> <p>I'm not sure why as it wo...
<p>You need call function <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> to each column separately, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow nor...
python|pandas|dataframe
0
355,205
57,711,103
Difference between tf.data.Dataset.repeat() vs iterator.initializer
<p>Tensorflow has <code>tf.data.Dataset.repeat(x)</code> that iterates through the data <code>x</code> number of times. It also has <code>iterator.initializer</code> which when <code>iterator.get_next()</code> is exhausted, <code>iterator.initializer</code> can be used to restart the iteration. My question is is there ...
<p>As we know, each epoch in the training process of a model takes in the whole dataset and breaks it into batches. This happens on every epoch. Suppose, we have a dataset with 100 samples. On every epoch, the 100 samples are broken into 5 batches ( of 20 each ) for feeding them to the model. But, if I have to train th...
python|tensorflow|repeat
9
355,206
57,714,830
Convert from naive local daylight time to naive local standard time in pandas
<p>I have hourly data records that were recorded in local daylight time (for me this is US/Pacific). These will be read in through csv. A gap exists at the beginning of DST at 02:00 when we spring forward. In fall, I believe that the data collected at 01:00 PDT is labeled 01:00 and the next hour is labeled 02:00 (and a...
<p>If you cannot use "infer" as you don't have redundant values, you can pass in a boolean array to indicate True if day light times is in effect (in this case lets assume its not in effect)</p> <pre><code>print(tndx.tz_localize('US/Pacific',ambiguous=[False, False, False]).tz_convert('Etc/GMT+8')) </code></pre> <p>A...
python|pandas|timestamp|timezone|timezone-offset
0
355,207
57,488,467
How to calculate % while keeping structure of the Dataframe
<p>Could somebody kindly advise on how to use pandas to add and calculate the Winning percentage while keeping the structure of the dataframe?</p> <p>Original dataframe: </p> <pre><code>Date Name Place 21-Mar John 1 22-Apr John 2 23-May John 1 22-Apr Alex 2 23-May Alex 2 21-Mar Jeff 1 22...
<p>Compare values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> for <code>==</code> and count <code>mean</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transfor...
python|pandas|csv|pandas-groupby|percentage
3
355,208
57,406,428
pandas merge df many to many without duplicates
<p>suppose i have two df like below:</p> <pre><code>import pandas as pd data_dic = { "a": [0,0,1,2], "b": [3,3,4,5], "c": [6,7,8,9] } df1 = pd.DataFrame(data_dic) data_dic = { "a": [0,0,1,2], "b": [3,3,4,5], "d": [10,10,12,13] } df2 = pd.DataFrame(data_dic) </code></pre> <p>Result:</p> <p>d...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter columns in both <code>DataFrames</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" ...
python|pandas|dataframe
4
355,209
57,549,448
how to convert perreplica to tensor?
<p>When training with multi gpu in tensorflow2.0, perreplica would be reduce by below code:</p> <pre class="lang-py prettyprint-override"><code>strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None) </code></pre> <p>However, if I just want to collect(no 'sum reduce' or 'mean reduce') all gpu's pre...
<p>In short, you can convert <code>PerReplica</code> result into a tuple of tensors like this:</p> <pre><code>tensors_tuple = per_replica_predicitions.values </code></pre> <p>the return <code>tensors_tuple</code> will be a tuple of <code>predictions</code> from each replicas/devices:</p> <pre><code>(predicton_tensor...
python|tensorflow|tensorflow2.0
9
355,210
57,685,508
Numpy sum over all dimension of the outer product
<p>If I want to implement this function: <a href="https://i.stack.imgur.com/Gx9Bm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gx9Bm.png" alt="enter image description here"></a></p> <p>I know I can write a loop like this:</p> <pre><code>result = 0 for i in range(len(x)): for j in range(len(y...
<p>With <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('i,j-&gt;',x,y) </code></pre> <p>Or simply sum-reduce and then get product of the scalars -</p> <pre><code>x.sum()*y.sum() </code></pre>
numpy
1
355,211
57,370,083
how to bin unix timestamp time into 10 minutes interval?
<p>I have a data like this,</p> <pre><code> ID datetime 0 2 2015-01-09 19:05:39 1 1 2015-01-10 20:33:38 2 1 2015-01-10 21:10:00 </code></pre> <p>I've converted this datetime into unix time stamp</p> <pre><code> ID timestamp 0 2 14...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> for binning by 10 minutes:</p> ...
python|python-3.x|pandas
4
355,212
57,705,230
Detect end of file (cols & rows) in dataframe and delete all extra
<p><strong>BACKGROUND:</strong> I have a large excel file converted to .csv. Need to be able to detect the end of the file/dataframe and delete all rows and columns after that. The data has the following format (approx 100 cols and 200 rows):</p> <pre><code>&gt;&gt;&gt;&gt;&gt;Spec. No Text ..... LastColum...
<p>I have been able to solve this for my particular case of data. It is a non-elegant and round-about way of solving but it addresses my problem. </p> <p>Posting in case the code can help/inspire others for their own projects. </p> <p>(EoF - End of File)</p> <pre><code> # Determining the title of the last relevan...
python-3.x|pandas|dataframe
0
355,213
57,312,604
Accessing the current row's index value for a calculation in a Python dataframe
<p>I have a dataframe with a datetime index. I'm attempting to add a new column that will contain that row's date time index value and subtract 1 workday. </p> <p>I'm using a function in the workday library which simply takes a <code>datetime</code>, an integer and subtracts that many workdays from the starting <code>...
<p>You can try using <strong>timedelta</strong> object from library <strong>datetime</strong>. Timedelta object represents a duration, the difference between two dates or times.</p> <blockquote> <p>from datetime import date, time, datetime, timedelta</p> <p>Original_date=pd.to_datetime(df.iloc[:,0])</p> <p>df[&quot;Up...
python|pandas|dataframe|datetime
0
355,214
57,405,811
Performing functions on multiindex in groupby
<p>I have a dataframe with a MultiIndex. Here's a minimal working example:</p> <pre><code>df = pd.DataFrame({'note':[1,1,1,2,2,2,2],'t': [0.5,0.7,1.2,0.3,0.9,1.3,1.7],'val':[1,-1,0,0,1,0,0]}) dfs = df.set_index(['note','t']) </code></pre> <p>which gives</p> <pre><code>&gt;&gt;&gt; dfs val note t 1 0.5 ...
<p>It is possible, but not very clean:</p> <pre><code>df = (dfs.index.get_level_values(1).to_series() .groupby(dfs.index.get_level_values(0)) .agg(['min', 'first'])) print (df) min first note 1 0.5 0.5 2 0.3 0.3 </code></pre> <hr> <pre><code>df = dfs.reset_index('t'...
python|pandas|group-by
3
355,215
57,489,573
Interactive slicing of dataframe columns using Bokeh
<p>I have below function which gives me an error - "expected element of list" in Python using Bokeh.</p> <pre class="lang-py prettyprint-override"><code>data = {'Name':['A', 'B', 'C', 'D'], 'Age':[20, 21, 19, 18], 'Income':[202, 213, 194, 185]} df = pd.DataFrame(data) menu=Select(title="Columns:", value=df.columns[0...
<p><code>columns</code> should be a list of <code>TableColumn</code> objects as you can see in <a href="https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#datatable" rel="nofollow noreferrer">the docs</a>. You'll have to use CustomJS or a Bokeh server to change the displayed column in the DataT...
python|pandas|bokeh
0
355,216
57,483,923
sklearn - How to reload model with a pipeline and predict?
<p>I've saved a trained model and the testing dataset and wish to reload it just to verify I'm getting the same results for future use of the model (I don't have new data to test on at the moment). The csv I've saved does not contain the labels, it's the same test data as in the original train/test operation which work...
<p>Try substituting <code>pipe.predict(pr[pred_cols])</code> by <code>pipe.predict(X=pr[pred_cols])</code> to see if it works or if it drops you other error</p>
python|pandas|scikit-learn|pipeline
0
355,217
57,341,395
How to avoid big data problem when dealing nii.gz?
<p>I have dataset of <code>nii.gz</code> files each around <code>1G</code> including <code>4d</code> tensor. There are two ways of reading them that I am aware of as the following:</p> <pre><code>img = nib.load('fMRI.nii.gz') imgarr = np.array(img.dataobj) </code></pre> <p>or </p> <pre><code>img = nib.load('fMRI.nii...
<p>Actually you do not need to load anything of the main image <strong>data</strong> into the memory.</p> <pre><code>img = nib.load('fMRI.nii.gz') # get the first 10 slices img.slicer[0:10] #verify selection img.slicer[0:10].shape </code></pre>
python|numpy|nifti|nibabel
3
355,218
57,534,871
Can I use "model.fit()" in "for" loop to change train data in each iteration
<p>I have a large dataset and it doesn't fit in memory. So while training, SSD is being used and epochs take too much time. </p> <p>I save my dataset 9 part of <code>.npz</code> file. I choose first part (part 0) as validation part and I didn't use in training.</p> <p>I use code below, and <code>acc</code> &amp; <cod...
<p>If your model does not fit in RAM the keras documentation suggests the following (<a href="https://keras.io/getting-started/faq/#how-can-i-use-keras-with-datasets-that-dont-fit-in-memory" rel="nofollow noreferrer">https://keras.io/getting-started/faq/#how-can-i-use-keras-with-datasets-that-dont-fit-in-memory</a>):</...
python|tensorflow|machine-learning|keras
2
355,219
57,683,874
Python Pandas: How to groupby aggregate using a function that returns pd.Series
<p>I have a multiindexed dataframe on which I want to aggregate over some of the indices. If the aggregator function returns a float, things work with no problem. But I can't find how to use a function with more complex returns (e.g., a pd.Series). Using a function that returns pd.Series gives me this error: <code>Exce...
<p>Just replace <code>.agg()</code> by <code>.apply()</code>:</p> <pre><code>df.groupby('idx').apply(my_func).unstack(level=-1) </code></pre> <p>Output:</p> <pre><code> A+B A-B idx 1 161.0 1.0 2 28.5 1.5 3 32.5 4.5 </code></pre>
python|pandas|dataframe
3
355,220
57,458,330
Misunderstanding of sjoin function with geopandas
<p>I have an issue with the function <strong>sjoin</strong> of GeoPandas (0.5.1). In fact, when I try this function on the same GeoDataFrame, the result is a table that contains more results than I expected.</p> <p>I am running this little code :</p> <pre class="lang-py prettyprint-override"><code>gpd.sjoin(l.frame,...
<p>The most obvious reason would be the following - lines in dataframe intersect.</p> <p>You can check that with:</p> <pre><code>gdf.geometry.iloc[0].intersects(gdf.geometry.iloc[1]) </code></pre> <p>If that returns <code>True</code> the resulting dataframe just shows you that each line of the dataframe intersects w...
python|geopandas
0
355,221
57,687,251
What is the 'index' in TFLite interpreter.get_input_details referring to?
<p>I'm working on doing some inference with Keras/TensorFlow models but the documenation seems a little sparse so I'm trying to learn and document as much as possible as I go and not just rely on copied code examples. Examples include this line:</p> <p><code>interpreter.get_input_details()</code></p> <p>Which returns...
<p>In TFLite interpreter, all tensors are put into a tensor list (see the <code>TfLiteTensor* tensors;</code> in <a href="https://github.com/tensorflow/tensorflow/blob/r2.0/tensorflow/lite/c/c_api_internal.h#L434" rel="nofollow noreferrer">TfLiteContext</a>), the index is the index of tensor in the tensor list.</p>
tensorflow|keras|tensorflow-lite
3
355,222
57,325,687
Replace data in a data-frame with data from another data-frame
<p>I have two data-frames where <code>df1</code> looks like:</p> <pre><code>id Status Colour 1 On Blue 19 On Red 4 On Green 56 On Blue </code></pre> <p><code>df2</code> looks like</p> <pre><code>id Status 19 Off 4 Even </code></pre> <p>I am trying to replace the <code>Sta...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with replace non matched missing values by <code>fillna</code>:</p> <pre><code>df1['Status'] = df1['id'].map(df2.set_index('id')['Status']).fillna(df1['Status']) print...
python|pandas
1
355,223
57,454,529
how to assign a value to the 'Tensor' object in Keras?
<p>I want to assign value to a tensor variable in the following manner. However, I get an error saying: "'Tensor' object does not support item assignment". </p> <p>I am trying to convert these python codes to tensorflow in Keras. However, the second line gives the error</p> <pre><code>s1 = tf.zeros([5:256:256:3], tf....
<p>A TensorFlow tensor object is not assignable.<br> <a href="https://stackoverflow.com/questions/37697747/typeerror-tensor-object-does-not-support-item-assignment-in-tensorflow">This question</a> and <a href="https://stackoverflow.com/questions/47775067/how-to-assign-the-element-of-tensor-from-other-tensor-in-tensorfl...
python|tensorflow|keras
1
355,224
57,468,586
Similar to a Pivot in Pandas
<p>I have a stupid problem that I can't seem to solve. I need to take a pandas dataframe like so:</p> <pre><code>id part1 part2 part3 part4 part5 23024 xyz9 23l lk8 jkd9 298 48392 xyz10 24x 29x ef3 298 </code></pre> <p>Now, i just want to "pivot" the table so that there ar...
<p>So here are two more options <code>melt</code> and <code>wide_to_long</code> : personally I recommend second one since we do not loss any information after reshape , we still have the part number </p> <pre><code>df.melt('id') Out[167]: id variable value 0 23024 part1 xyz9 1 48392 part1 xyz10 2 2...
python|excel|pandas|numpy|pivot
3
355,225
57,512,581
Why is my .apply() function also outputting a series of 'None'?
<p>This may not be a big problem, I just haven't noticed this output of <code>None</code> before when doing .apply()</p> <p>Toy example:</p> <pre><code>mydf = pd.DataFrame({'col1':['test1',np.nan,'test3','test4'], 'col2':['test5','test6','test7','test8']}) mydf col1 col2 0 test1 test5 1 ...
<p>You should return the string instead of printing it.</p>
python|pandas
3
355,226
57,336,247
NumPy: is assignment of a scalar to a slice broadcasting?
<p>I know in Python, </p> <pre><code>[1,2,3][0:2]=7 </code></pre> <p>doesn't work because the right side must be an iterable.</p> <p>However, the same thing works for NumPy ndarrays:</p> <pre><code>a=np.array([1,2,3]) a[0:2]=9 a </code></pre> <p>Is this the same mechanism as broadcasting? On <a href="https://do...
<p>Yes, assignment follows the same rules of broadcasting because you can also assign an array to another array's items. This however requires that the second array's shape to be broadcastable to destination slice/array shape.</p> <p>This is also mentioned in <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basic...
python|numpy
1
355,227
57,475,916
How to transform some columns only with SimpleImputer or equivalent
<p>I am taking my first steps with scikit library and found myself in need of backfilling <strong>only</strong> some columns in my data frame.</p> <p>I have read carefully the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html" rel="noreferrer">documentation</a> but I still ca...
<p>There is no need to use the SimpleImputer.<br> <code>DataFrame.fillna()</code> can do the work as well<br></p> <ul> <li><p>For the second column, use</p> <p><code>column.fillna(column.mean(), inplace=True)</code></p> </li> <li><p>For the third column, use</p> <p><code>column.fillna(constant, inplace=True)</code></p>...
python|pandas|scikit-learn|data-science|imputation
14
355,228
57,501,986
Change all of one number to another number in a numpy array
<p>Suppose I have a numpy array:</p> <pre><code>[[2, 1, 1, 1], [0, 2, 1, 1], [0, 0, 2, 1]] </code></pre> <p>How do I change all of the twos to be ones?</p> <pre><code>[[1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]] </code></pre> <p>There are naive ways to do it that are <em>really</em> slow (i.e. looping through eve...
<p>I was able to do this quickly enough using a mask:</p> <pre class="lang-py prettyprint-override"><code>x[x == 2] = 1 </code></pre> <p>You can also apply more complicated masks (with <a href="https://stackoverflow.com/questions/22646463/difference-between-and-boolean-vs-bitwise-in-python-why-difference-i">bitwise p...
python|numpy-ndarray
1
355,229
57,597,074
How to add hours to pandas datetime skipping non-business hours
<p>I would like to create a running dataframe of trading data for the next four hours from the current time while skipping non-trading hours (5-6pm weekdays, Saturday-6pm Sunday). For example, at 4pm on Friday, I'd like a dataframe that runs from 4pm to 5pm on Friday and then 6pm-9pm on Sunday. </p> <p>Currently, I am...
<p>It's hard to tell from so little information. However, it seems that you're working on hour boundaries. If so, it should be straightforward to set up a look-up table (dict) keyed by each day and hour, perhaps: <code>(0,0)</code> for midnight Sun/Mon, <code>(2, 13)</code> for 1pm Wed, and so on. Then provide simpl...
python|pandas|timedelta
0
355,230
57,652,210
Is there a way to rename duplicates headers and selecting the right column python?
<p>I have a large spreadsheet file (.xlsx) that I'm processing using python pandas. I noticed there are duplicated headers and I want to rename specific columns without applying to the rest of them. </p> <pre><code>Jack | SPORT | UNI | SHOP | TOTAL | nan | Li | SPORT | UNI | SHOP | nan | JULY | 1000 | 200 | 300 | 1...
<p>You can always set columns' names by using <strong>.columns()</strong>. Example as follows:</p> <pre><code>data = {'a': [1,2,3,4], 'b': [3,2,2,1], 'c': [None, 'test', 'hi']} df = pd.DataFrame(data) a b c 0 1 3 None 1 2 2 test 2 3 2 hi 3 4 1 None df.columns = ['C1', 'C2' ,'C3'] C1 C2 ...
python|pandas|dataframe|jupyter-notebook
0
355,231
57,721,524
Overwrite checkpoint files from tf.train.Checkpoint.save
<p>In the example below, I subsequently call <code>root.save(path_to_checkpointfile)</code> and it auto-increments the filename each time. Each file is huge, and I want to just overwrite with the latest. I don't see any <code>kwarg</code> or property I can set to achieve this. Does anyone know of a way?</p> <pre><code...
<p>Using tf.train.CheckpointManager, you can specify how many checkpoints it needs to keep at any given point of time using the argument "max_to_keep". </p> <p>This keeps replacing the oldest checkpoint and saves the new one once it reaches the maximum number of checkpoints to be saved. </p> <p>Please refer below lin...
python-3.x|tensorflow
0
355,232
57,389,372
create a pandas dataframe column on the basis of another column value
<p>Hi I have a column website in pandas dataframe , which has values like expedia,MMT,Booking.com etc</p> <p>I want to add two column in dataframe.</p> <p>1) My_Site which should have site column values like 'Expedia' and 'MMT' 2)another column Cmp_site which has all values of site column except values of newly buil...
<p>If I understand correctly, you have a dataframe like this:</p> <pre><code> My_Site 0 Expedia 1 MakeMyTrip 2 Booking </code></pre> <p>You now want other sites next to each site for comparison purposes. For this, I would use <code>itertools</code> to generate the combinations. I will restrict the combi...
python|pandas
0
355,233
57,571,397
How to find if a values exists in all rows of a dataframe?
<p>I have an array of unique elements and a dataframe. I want to find out if the elements in the array exist in all the row of the dataframe. p.s- I am new to python.</p> <p>This is the piece of code I've written.</p> <pre><code>for i in uniqueArray: for index,row in newDF.iterrows(): if i in row['MKT']: ...
<p>Pandas allow you to filter a whole column like if it was Excel: </p> <pre><code>import pandas df = pandas.Dataframe(tableData) </code></pre> <p>Imagine your columns names are "Column1", "Column2"... etc</p> <pre><code>df2 = df[ df["Column1"] == "ValueToFind"] </code></pre> <p>df2 now has only the rows th...
python|pandas
0
355,234
57,302,214
Getting a confusingly complicated mysql request work
<p>I'm not an expert in SQL but I recently started using <code>sqlite3</code> module in <code>Python</code> with databases and together with <code>pandas</code> and its <code>read_sql_query()</code> they make a pretty nice tool.</p> <p>Now, say, I have a database looking something like this (I just really made this up...
<p>One approach would be to use an <code>EXISTS</code> condition in the <code>WHERE</code> clause which asserts that a given IQ value matches at least one other married record:</p> <pre><code>SELECT age, iq, married FROM People p1 WHERE EXISTS (SELECT 1 FROM People p2 WHERE p1.iq = p2.iq AND p2.married = 1); </code></...
python|mysql|sql|pandas|sqlite
3
355,235
57,609,542
How to create a random sequence excepting a set of given values
<p>I am using numpy and i want to generate an array of size <code>n</code> with random integers from <code>a</code> to <code>b</code> [upper bound exclusive] that are not in the array <code>arr</code> (if it helps, all values in <code>arr</code> are unique). I want the probability to be distributed uniformly among the ...
<p>Simplest vectorized way would be with <code>np.setdiff1d</code> + <code>np.random.choice</code> -</p> <pre><code>c = np.setdiff1d(np.arange(a,b),arr) out = np.random.choice(c,n) </code></pre> <p>Another way with <code>masking</code> -</p> <pre><code>mask = np.ones(b-a,dtype=bool) mask[arr-a] = 0 idx = np.flatnonz...
python|python-3.x|numpy|random
3
355,236
57,667,934
Appending data from excel in existing SQL Server table using python
<p>I have some CSV files with data which is recurring and therefore I need to update SQL Server by using this python script. </p> <p>I have tried updating the Microsoft driver for SQL and that doesn't help me.</p> <p>Here is my python code :</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd imp...
<p>You forgot to add <code>cursor.commit()</code> after execute. Execute command can be used only for some selects and read only queries. If you want to change something you shoud add <code>cursor.commit()</code> after.</p>
python|sql|sql-server|pandas
0
355,237
57,348,638
Average values for same key rows excluding certain columns in pandas
<p>I have a table that has a certain subset of columns as a record-key. Record keys might have duplicates e.g several rows might have same key, but different values. I want to average values for such same-key row into one row. But some columns have numbers that represent categories and I want to exclude them from avera...
<p>Here is one way </p> <pre><code>df.groupby(['k1','k2']).agg({'v1':'mean','id':lambda x : x.sample(1)}) v1 id k1 k2 1 2 4.666667 100 3 2.000000 200 </code></pre>
pandas
1
355,238
57,559,772
Removing the Timestamp from a NumPy Array
<p>I'm performing a linear regression on a dataset (Excel file) which consists of a Date column, a scores column and additional column called Predictions with NaN values which will be used to store the predicted values.</p> <p>I have found that my independent variable, X, contains timestamps which I was actually expec...
<p>Do not include the Timestamps (Date) in your creation of 'X'.</p> <p>The data set is already ordered, so do you really need the time stamps? Another option, try reassigning the index. In either case, I think, do not try to pass Timestamps as argument-data.</p> <p><strong>Implement changes at this step:</strong><...
python|numpy|timestamp
1
355,239
57,678,514
I have a dataset of 130 variables and I have to check the correlation of all variables, is there any way to check it in once
<p>I have a dataset of 130 variables and I have to check the correlation of all variables, is there any way to check it in once I am new to data science and using pandas, please suggest a way. Do I have to do hypothesis....</p>
<p><strong>You could have easily found out answer to this question elsewhere</strong> <em>but since you're new to datascience...</em></p> <pre><code># First read the dataset into a dataframe data = pd.read_excel(file_name) # Find correlation among all the columns (features / variables) # methods can be changed data.c...
python|pandas|correlation|p-value|hypothesis-test
1
355,240
57,326,545
Assigning values to parameters using read_excel from pandas in python
<p>I want to read an Excel file using pandas. I want to assign specific cells to certain parameters. </p> <p>So my Excel contains 4 columns. First columns contains locations "s", 2nd contains the time "t" in years and 3rd and 4th column are 2 different materials that are available at this certain location at a certain...
<p>I would use the <code>pivot</code> function and return the pivotized frame as a dictionaries. We need to remove the keys with empty values from the dictionary and iterate to unite the dictionaries.</p> <pre><code>df_pivot = pd.pivot_table(df, columns=['s','t'], index='Biomasse', values='KWS') lst= [{k: v for k, v i...
python|pandas|python-2.7
1
355,241
57,590,850
Memory Error while append data frames in Python
<p>I am new to Python and Data Processing with pandas data frames. I would like to handle measurement data (*.mf4). This will read in, by using the package asammdf and create a pandas data frame. </p> <p>My original attempt was to group the measurement data (single files) by the use of a dictionary. For post processin...
<p>Did you try to use the reduce_memory_usage argument? <a href="https://asammdf.readthedocs.io/en/latest/api.html#asammdf.mdf.MDF.to_dataframe" rel="nofollow noreferrer">https://asammdf.readthedocs.io/en/latest/api.html#asammdf.mdf.MDF.to_dataframe</a></p>
python|dataframe|pandas-groupby
0
355,242
57,590,374
How to insert a pandas dataframe into an existing Hive external table using Python (without PySpark)?
<p>I'm creating a connection string to Hive and running some SELECT queries on the Hive tables on that connection.</p> <p>After performing some transfomrations upon the retrieved data, I'm creating a data frame <code>df_student_credits</code> that looks as follows</p> <pre><code>NAME_STUDENT_INITIAL CREDITS_INITIA...
<p>Some pointers here before i get to the exact answer.</p> <p><strong>HDFS is nothing without partitions</strong>. In your case you haven't defined any partition. Leaving it as a default is never a good idea. It is your data and you must know how to partition that. So add a proper partition by clause.</p> <p>Let us ...
python|pandas|dataframe|hive
0
355,243
57,313,358
How do I ignore the header column and row in a csv file imported into python?
<p>I imported a csv file into python using Pandas, I am using the given matrix in csv to preform an astar algorithm. The problem is when I import the csv file it has a header column and row with 1...173 and the row of 1 1.1...1.123 and the columns and rows are continuing my code is only looking for 0s and 1s and the...
<p>use skiprows=1</p> <pre><code>df = pd.read_csv(r'C:\Users\605760\Desktop\path rec\matrix.csv',skiprows=1) </code></pre>
python|arrays|pandas|matrix|a-star
0
355,244
57,511,904
How to remove empty values from the pandas DataFrame from a column type list
<p>Just looking forward a solution to remove empty values from a column which has values as a list in a sense where we are already replacing some strings beforehand, where it's a column of string representation of lists.</p> <p>In <code>df.color</code> we are Just replacing <code>*._Blue</code> with empty string:</p> ...
<p>You can using the <code>explode</code>(pandas 0.25.0) then concat the list back </p> <pre><code> df['color'].str.replace(r'\w+_Blue\b', '').explode().loc[lambda x : x!=''].groupby(level=0).apply(list) </code></pre>
regex|python-3.x|pandas|numpy
3
355,245
57,363,146
Is any information lost by converting a fully dense array to a sparse matrix?
<p>Let's suppose that A is a (<code>scipy</code>) sparse matrix with tf-idf values and B is a (<code>numpy</code>) array with some additional features of my data.</p> <p>Each of the rows of <code>A</code> and <code>B</code> correspond to the same observation.</p> <p>I want to concatenate these matrices/arrays because...
<p>No you don't lose any information. Sparse/Dense are two different representation of the same data in this case. See <a href="https://machinelearningmastery.com/sparse-matrices-for-machine-learning/" rel="nofollow noreferrer">https://machinelearningmastery.com/sparse-matrices-for-machine-learning/</a> for more detail...
python|numpy|scikit-learn|scipy|sparse-matrix
0
355,246
57,428,430
How to select all rows from a table which match a given date/date condition?
<p>I think to fulfill the syntax requirements and already tried a lot...</p> <p>I have subsequent variables set up:</p> <pre><code>db_uri = "postgres://{}:{}@{}/{}".format(user, pwd, server, db) engine = create_engine(db_uri) con = engine.connect() </code></pre> <p>What already works:</p> <pre><code>df_sql = pd.rea...
<p>What type of syntax is this?</p> <pre><code>WHERE CAST(ts_column as date) = ts_column "2019-06-19"' </code></pre> <p>You can write this as:</p> <pre><code>WHERE CAST(ts_column as date) = '2019-06-19' </code></pre> <p>Or more colloquially in Postgres as:</p> <pre><code>WHERE ts_column::date = '2019-06-19'::date ...
python|sql|pandas|postgresql|sqlalchemy
0
355,247
57,654,372
Replace values in multiple untitled columns to 0, 1, 2 depending on column
<p>EDITED AS PER COMMENTS</p> <p><strong>Background:</strong> Here is what the current dataframe looks like. The row labels are information texts in original excel file. But I hope this small reproduction of data will be enough for a solution? Actual file has about 100 columns and 200 rows.</p> <p>Column headers and ...
<p>Here is one way to do it:</p> <ol> <li>Define a function to replace the x:</li> </ol> <pre><code>import re def replaceX(col): cond = ~((col == "x") | (col == "X")) # Check if the name of the column is undefined if not re.match(r'Unnamed: \d+', col.name): return col.where(cond, 0) else: ...
python-3.x|pandas|dataframe
1
355,248
24,128,167
Plotting Pandas DataFrames as single days on the x-axis in Python/Matplotlib
<p>I've got data like this:</p> <pre><code> col1 ;col2 2001-01-01;1 2001-01-01;2 2001-01-02;3 2001-01-03;4 2001-01-03;2 2001-01-04;2 </code></pre> <p>I'm reading it in Python/Pandas using <code>pd.read_csv(...)</code> into a DataFrame. Now I want to plot col2 on the y-axis and col1 on the x-axis day-wise. I searc...
<p>Pandas.read_csv supports parse_dates=True (default of course is False) That would save you converting the dates separately.</p> <p>Also for a simple dataframe like this, pandas plot() function works perfectly well. Example:</p> <pre><code>dates = pd.date_range('20160601',periods=4) dt = pd.DataFrame(np.random.rand...
python|numpy|matplotlib|plot|pandas
1
355,249
24,129,987
Issue with merging time series variables to create new DataFrame with arbitrary index
<p>So I am trying to merge the following columns of data which are currently indexed as daily entries (but only have points once per week). I have separated the columns into year variables but am having trouble getting them into a combined dataframe and disregard the date index so that I can build out min/max columns b...
<p>I'm not sure what your original data look like, but I don't think it's a good idea to hard-code all years. You lose re-usability. I'll setup a sequence of random integers indexed by date with one date per week.</p> <pre><code>In [65]: idx = pd.date_range ('2007-1-1','2014-12-31',freq='W') In [66]: df = pd.DataFram...
python|join|merge|pandas
0
355,250
24,413,804
calculate percentile of 2D array
<p>i have size classes and for each size class i have measured counts:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from scipy.stats import norm size_class = np.linspace(0,9,10) counts = norm.pdf(size_class, 5,1) # synthetic data counts_cumulative_normalised = np.cumsum(counts)/counts.sum() #...
<p>If you don't know if the data is normally distributed, and you want to get the percentiles based on the Empirical Cumulative Distribution Function, you can use a interpolation approach.</p> <pre><code>In [63]: plt.plot(size_class,counts_cumulative_normalised) Out[63]: [&lt;matplotlib.lines.Line2D at 0x10c72d3d0&gt...
python|numpy|scipy
1
355,251
24,398,811
Estimating confidence intervals around Kalman filter
<p>I have been working to implement a Kalman filter to search for anomalies in a two dimensional data set. Very similar to the excellent post that I found here. As a next step, I'd like to predict confidence intervals (for example 95% confidence for floor and ceiling values) for what I predict the next values will fall...
<p>The 2D generalization of the <a href="https://en.wikipedia.org/wiki/Normal_distribution#Standard_deviation_and_tolerance_intervals" rel="nofollow noreferrer">1-sigma interval</a> is the confidence ellipse which is characterized by the equation <code>(x-mx).T P^{-1}.(x-mx)==1</code>, with <code>x</code> being the par...
python|numpy|prediction|kalman-filter
4
355,252
24,419,364
Pandas if statement across list of columns
<p>I have a DataFrame with several columns that are either 0's or 1's. For example:</p> <pre><code>&gt;&gt;&gt; df=pd.DataFrame([[1,1,0], [0,0,0], [0,1,1], [0,1,0]], columns=['A', 'B', 'C']) </code></pre> <p>I want to create a new column that is populated with the value 1 if any of the list of columns <code>['A', 'B'...
<p>You can use the <code>any</code> method:</p> <pre><code>In [11]: df == 1 Out[11]: A B C 0 True True False 1 False False False 2 False True True 3 False True False In [12]: (df == 1).any(1) Out[12]: 0 True 1 False 2 True 3 True dtype: bool </code></pre> <p>You can p...
python|numpy|pandas
1
355,253
24,441,326
Dealing with dimension collapse in python arrays
<p>A recurring error I run into when using NumPy is that an attempt to index an array fails because one of the dimensions of the array was a singleton, and thus that dimension got wiped out and can't be indexed. This is especially problematic in functions designed to operate on arrays of arbitrary size. I'm looking f...
<p>There are lots of ways to avoid this behaviour.</p> <p>First, whenever you index into a dimension of an <code>np.ndarray</code> with a <code>slice</code> rather than an integer, the number of dimensions of the output will be the same as that of the input:</p> <pre><code>import numpy as np x = np.arange(12).reshap...
python|arrays|numpy|dimensions
2
355,254
43,736,901
Handling unicode names in DataFrame
<p>I want to convert all my data in a DataFrame to uppercase. When I start conversion from column names I get this error: </p> <p>Code:</p> <pre><code>xl = pd.ExcelFile(target_processed_directory + filename) # check sheet names print(xl.sheet_names[0]) # sheet to pandas dataframe df = xl.parse(xl.sheet_names[0]) # ...
<p>When using Pandas you'll want to avoid <code>for</code> loops in Python, and you'll usually want to avoid <code>map()</code> as well. Those are the slow ways to do things, and if you want to build good habits, you'll avoid them whenever you can.</p> <p>There are fast vectorized string operations available for Pand...
python|pandas|dataframe|unicode
4
355,255
43,588,646
DSX reading audio file arriving from Watson IOT to Bluemix Object storage
<p>in January I created a project in DSX that was linked to a Bluemix Object Storage. Audio file arriving from Watson IoT platform were saved in this Object Storage and they were loaded automatically in the DSX files section of the project. I'm no more able to recreate a new project with the same functionality: I'm no...
<p>Can you add a bit more detail? I don't understand what is the issue:</p> <ul> <li>You cannot create new projects in DSX associated to Object Storage?</li> <li>You wav files are not automatically showing in the DSx Project?</li> </ul>
numpy|apache-spark|object-storage|data-science-experience
0
355,256
43,623,117
Cleaner pandas/numpy code to find equivalency matrix?
<p>I have pandas DataFrame and would like to generate an equivalency matrix (or whatever it's called) where each cell has one value if the the df.Col[i] == df.Col[j] and another value when !=.</p> <p>The following code works:</p> <pre><code>df = pd.DataFrame({"Col":[1, 2, 3, 1, 2]}, index=["A","B","C","D","E"]) df ...
<pre><code>v = df.values m = v == v[:, 0] pd.DataFrame(np.where(m, 1, -1), df.index, df.index) A B C D E A 1 -1 -1 1 -1 B -1 1 -1 -1 1 C -1 -1 1 -1 -1 D 1 -1 -1 1 -1 E -1 1 -1 -1 1 </code></pre>
python|pandas|numpy
3
355,257
43,909,776
Find out the most frequency combination and add labels
<p>I have a table with my customer data like this:</p> <pre><code>Customer Price AAA 100 AAA 100 AAA 200 BBB 100 BBB 220 BBB 200 BBB 200 </code></pre> <p>What I want to do is to find out the customer with the condition <code>number of pri...
<pre><code>df.Price.ge(200).groupby(df.Customer).mean().gt(.5) Customer AAA False BBB True Name: Price, dtype: bool </code></pre> <p>Or if you insist on your format</p> <pre><code>df.Price.ge(200).groupby(df.Customer).mean().gt(.5).reset_index(name='Labels') Customer Labels 0 AAA False 1 BBB ...
python|pandas|group-by|frequency|pandas-groupby
5
355,258
43,530,065
Multiplying all values in Pandas Dataframe rows
<p>This is basically the dataframe:</p> <pre><code> col1 col2 col3 label row1 1 0 1 1 row2 0 0 0 1 row3 1 1 1 0 row4 1 2 1 0 </code></pre> <p>I basically need it to go over each row, and if label = 0, multiply all the va...
<pre><code>In [156]: df.loc[df.label==0, df.columns.drop('label')] = \ df.loc[df.label==0, df.columns.drop('label')].mul(-1) In [157]: df Out[157]: col1 col2 col3 label row1 1 0 1 1 row2 0 0 0 1 row3 -1 -1 -1 0 row4 -1 -2 -1 0 </code>...
python|pandas|numpy|dataframe
5
355,259
43,653,726
Python pandas ambiguous time index
<p>see here my pandas Dataframe:</p> <pre><code> press222 datetime 2017-03-31 14:02:04 110.854683 2017-03-31 14:02:04 110.855759 2017-03-31 14:02:04 110.855103 2017-03-31 14:02:04 110.853790 2017-03-31 14:02:05 110.854034 2017-03-31 14:02:05 110.855103 2017-03-31 14:0...
<p>You could <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> on the index and call <code>mean</code>:</p> <pre><code>In [285]: df.groupby(level=0).mean() Out[285]: press222 datetime ...
python|pandas|indexing|time|average
1
355,260
43,531,495
tiling images in a grid (i.e. with wrapround) in tensorflow
<p>The short version of what I'd like to do is take a stack of images in the format (h, w, num_images) and tile them in a grid to produce a single image that can be drawn easily, but I'd like to have them in a grid, i.e. with wrap around (and I'd like to do this in tensorflow, i.e. the graph outputs a grid image ready ...
<p>A function has been added to TensorFlow that does exactly this: <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/gan/eval/image_grid" rel="nofollow noreferrer">tf.contrib.gan.eval.image_grid</a>. It accepts as arguments an input tensor of shape <code>[batch, width, height, channels]</code>, as well as ...
python|tensorflow|conv-neural-network|convolution
3
355,261
43,831,937
Tensorflow linear classifier not training
<p>I'm trying to create a simple linear classifier for MNIST data and I can not get my loss to go down. What could be the problem? Here is my code:</p> <pre><code>import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data class LinearClassifier(object): def __init__(self): print("L...
<p>The main thing is your learning rate (0.001) is too low. I ran this after changing it to 0.5 like they did in the <a href="https://www.tensorflow.org/get_started/mnist/beginners" rel="nofollow noreferrer">mnist tensorflow tutorial</a> and I'm getting accuracy and loss more like:</p> <pre><code>Epoch: 997, Loss: 0.6...
python|tensorflow|linear-regression|mnist
3
355,262
43,804,657
dask bag foldby with numpy arrays
<p>I get a very uninformative <code>FutureWarning</code> message from <code>dask</code> / <code>numpy</code> when doing a <code>foldby</code> on a <code>dask.bag</code> that contains numpy arrays.</p> <pre><code>def binop(a, b): print('binop') return a + b[1] def combine(a, b): print('combine') return...
<p>This warning is indeed from numpy. A quick search through the code base yields <a href="https://github.com/numpy/numpy/blob/69b0c42bca27dd5d5522de306bcd7db7deccbfad/numpy/core/src/umath/ufunc_object.c#L970-L982" rel="nofollow noreferrer">these lines</a>:</p> <pre><code> if (!strcmp(ufunc_name, "equal") || ...
python|numpy|parallel-processing|mapreduce|dask
2
355,263
43,715,813
How to show numpy NxM array with dtype=float as plain gray scale image?
<p>When creating an <code>numpy</code> array with <code>dtype=float</code>, the the presentation method using <code>matplotlib.pyplot.imshow</code> appears to be dependent on the values, so a value of 0.50 is not just 50% gray.</p> <p>Using this code template:</p> <pre><code>import numpy as np import matplotlib.pyplo...
<p>You have to fix the limits of the color-scale:</p> <pre><code>plt.imshow(img, cmap='gray',clim=(0,1)) </code></pre> <p>To get a good feeling of what is going on you could include a colorbar which visualizes the conversion between colors and numerical values; for example using the following code:</p> <pre><code>fi...
python|numpy|matplotlib
4
355,264
43,701,868
TensorFlow Android Demo - How to use use ImageNet data set
<p>I have already built and executed the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android" rel="nofollow noreferrer">TensorFlow Android Demo</a> but now i would like to generate another graph. I need to train another data set first. I wanted to use <a href="http://www.image-net....
<p>According to the page you provided:</p> <blockquote> <p>Each tf.Example proto contains the ImageNet image (JPEG encoded) as well as metadata such as label and bounding box information. See parse_example_proto for details.</p> </blockquote> <p>so all the imageNet files you are downloading seems like in jpeg f...
android|tensorflow
1
355,265
43,674,766
Pandas round multiple columns with text
<p>I have this df:</p> <pre><code> A B 0 13045.0 1.0 1 13056.0 15.0 2 Mobi 2.0 3 Mobi 3.0 4 15056.0 5.0 5 15068.0 1.0 </code></pre> <p>I would to round the numeric values to 0, to end up with:</p> <pre><code> A B 0 13045 1 1 13056 15 2 Mobi ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> + <a href="http://pand...
python|pandas
1
355,266
43,557,785
How can I select a row from a SparseTensor in TensorFlow?
<p>Say, if I have two <code>SparseTensor</code>s as following:</p> <pre><code>[[1, 0, 0, 0], [2, 0, 0, 0], [1, 2, 0, 0]] </code></pre> <p>and</p> <pre><code>[[1.0, 0, 0, 0], [1.0, 0, 0, 0], [0.3, 0.7, 0, 0]] </code></pre> <p>and I want to extract the first two rows out of them. I need both indices and values of...
<p>I checked in with one of the engineers here who knows more about this area, and here's what he passed on:</p> <p>I am not sure if we have an efficient implementation of the this, but here is a not-so-optimal implementation using dynamic_partition and gather ops.</p> <pre><code>def sparse_slice(indices, values, nee...
python|tensorflow|embedding
5
355,267
43,879,595
slice and fill rows/columns pandas
<p>I have a small sample data</p> <pre><code>import pandas as pd d = { 'title': ['string1', 'string2', 'string3', 'string4', 'string5', 'string6'], 'Num/Den': ['Numerator', 'Denominator', 'Numerator', 'Denominator', 'Numerator','Denominator', 'Numerator','Denominator','Numerator', 'Denominator', 'Numer...
<p>You can replace empty string with <code>nan/None</code>, and then do a <code>ffill</code>:</p> <pre><code>df['title'] = df.title.replace("", pd.np.nan).ffill() df # Num/Den title two #0 Numerator string1 tstring1 #1 Denominator string1 tstring2 #2 Numerator string2 tstring3 #3 Denominator strin...
python|pandas
2
355,268
43,827,866
How to run a project Caffe with CPU only
<p>i'm using <code>Ubuntu 14.04</code> without GPU and i want to run this code ( <code>with CPU only</code> ). I want to run this code with CPU ( not with GPU) : <a href="https://github.com/smallcorgi/Faster-RCNN_TF" rel="nofollow noreferrer">https://github.com/smallcorgi/Faster-RCNN_TF</a> . what should I do ?</p>
<p>The Github repository you are referring to is a <strong>TensorFlow</strong> implementation of Faster-RCNN, not <strong>Caffe</strong>.</p> <p>If you want to use the <strong>Caffe</strong> implementation, you have to use this repository : <a href="https://github.com/rbgirshick/py-faster-rcnn" rel="nofollow noreferre...
tensorflow
0
355,269
43,553,149
On Windows, running “import tensorflow” generates No module named '_pywrap_tensorflow_internal' error
<p>This is a different error than <a href="https://stackoverflow.com/questions/42011070/on-windows-running-import-tensorflow-generates-no-module-named-pywrap-tenso">On Windows, running &quot;import tensorflow&quot; generates No module named &quot;_pywrap_tensorflow&quot; error</a> as it points on <code>_pywrap_tensorfl...
<p><strong>For cpu I found the solution and it worked</strong></p> <ul> <li><p>Run below command it will clear all dependencies and then update it or remove and install the latest version of tensor flow </p> <pre><code> `pip install tensorflow==1.5` </code></pre></li> </ul>
windows|tensorflow|python-import
1
355,270
43,808,714
Creating a New DataFrame Column by Using a Comparison Operator
<p>I have a DataFrame that looks like something similar to this:</p> <pre><code> 0 0 3 1 11 2 7 3 15 </code></pre> <p>And I want to add a column using two comparison operators. Something like this: </p> <pre><code>df[1] = np.where(df[1]&lt;= 10,1 &amp; df[1]&gt;10,0) </code></pre> <p>I want my return to lo...
<p><strong>Setup</strong></p> <pre><code>df = pd.DataFrame({'0': {0: 3, 1: 11, 2: 7, 3: 15}}) Out[1292]: 0 0 3 1 11 2 7 3 15 </code></pre> <p><strong>Solution</strong></p> <pre><code>#compare df['0'] to 10 and convert the results to int and assign it to df['1'] df['1'] = (df['0']&lt;10).astype(int) df Ou...
python|pandas|dataframe
1
355,271
43,481,369
Pandas Python writing to existing file and matching column values
<p>I have 2 excel sheets that I have loaded. I need to add information from one to the other one. See example below.</p> <pre><code>table 1: cust_id fname lname date_registered 1 bob holly 1/1/80 2 terri jones 2/3/90 table 2: fname lname date_registered cust_id zip la...
<p>With concat:</p> <pre><code>In [1]: import pandas as pd In [2]: table_1 = pd.DataFrame({'cust_id':[1,2], 'fname':['bob', 'teri'], 'lname':['holly', 'jones'], 'date_registered':['1/1/80', '2/3/90']}) In [3]: table_2 = pd.DataFrame({'cust_id':[3], 'fname':['lawrence'], 'lname':['fisher'], 'date_registered':['2/3/12...
python|pandas
1
355,272
43,880,238
average column size using pandas
<p>I have huge flat files for which I need to compute some metrics. Most of the metrics are simple like row count and column count and easily accomplished. The one that is giving me issues is average column size.</p> <p>For eg. here is a sample file</p> <pre><code>header1|header2|header3|header4|header5 this|is|1|12-...
<p>If by 'column size' you mean 'column width', then this should work:</p> <pre><code>df.fillna('').astype(str).apply(lambda x:x.str.len()).mean() #header1 3.0 #header2 1.0 #header3 1.5 #header4 11.0 #header5 2.5 #dtype: float64 </code></pre> <p>By the way, your file has an extra '|' at the end of ...
python|pandas
4
355,273
43,575,926
Returning a vector of class elements in numpy
<p>I can use numpy's <code>vectorize</code> function to create an array of objects of some arbitrary class:</p> <pre><code>import numpy as np class Body: """ Simple class to represent a point mass in 2D space, more to play with numpy than anything else... """ def __init__(self, position, mass, v...
<p>So, I would encourage you not to use <code>numpy</code> arrays with an <code>object</code> dtype. However, what you have here is essentially a struct, so you could use <code>numpy</code> to your advantage using a <a href="https://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow noreferrer">structured arr...
python|numpy
4
355,274
43,480,488
Visualizing filter weights in tf.layers.conv2d
<p>I am using <code>tf.layers.conv2d</code> in TensorFlow V1.0 to do convolution.</p> <p>An example is as follows :</p> <pre><code>conv1 = tf.layers.conv2d(batch_images, filters=96, kernel_size=7, strides=2, ...
<p>I managed to get the weights using the following </p> <pre><code>conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu, name='conv1') kernel = tf.get_collection(tf.GraphKeys.VARIABLES, 'conv1/kernel')[0] bias = tf.get_collection(tf.G...
tensorflow
10
355,275
43,741,869
getting the variance using numpy
<p>I want to get the variance of each column in a csv file for that I've wrote the following : </p> <pre><code>import numpy as np import csv import collections Training = 'Training.csv' inputFile = open(Training,'r',newline='') cols_values = collections.defaultdict(list) numericalValues = [] reader =...
<p>Is there a reason to not use Pandas for this?</p> <pre><code>import numpy as np import pandas as pd Training = 'Training.csv' df = pd.read_csv(Training) df.apply(np.var, axis=0) # can also use `df.var(...)` </code></pre> <p>You want to make sure that all of your columns have numerical values. You can also use...
python|numpy
1
355,276
43,579,175
arr = [a,b] choose a, x% of time
<p>I want to write a program with the following requirement. </p> <p><code>arr = ['a', 'b']</code></p> <p>How to write a python program which choose <code>a</code> from <code>arr</code> x% of time. (For example 80% of time).</p> <p>I have no idea how should I start. Please help. </p> <p>I know <code>random.choice...
<pre><code>import numpy as np np.random.choice(['a', 'b'], p=(.8, .2)) </code></pre>
python|python-3.x|numpy
6
355,277
43,826,182
How to iterate over pandas DataFrameGroupBy and select all entries per grouped variable for specific column?
<p>Let's assume, there is a table like this:</p> <pre><code>Id | Type | Guid </code></pre> <p>I perform on such a table the following operation:</p> <pre><code>df = df.groupby('Id') </code></pre> <p>Now I would like to iterate through first <code>n</code> rows and for each specific <code>Id</code> as a <code>list</...
<p>I think I would do it like this:</p> <p>Create some data for testing</p> <pre><code>df = pd.DataFrame({'Id':np.random.randint(1,10,100),'Type':np.random.choice(list('ABCD'),100),'Guid':np.random.randint(10000,99999,100)}) print(df.head() Id Type Guid 0 2 A 89247 1 4 B 39262 2 3 C 45522 3 ...
python|pandas|sqlite|sklearn-pandas
8
355,278
43,826,089
How would I find the mode (stats) of pixel values of an image?
<p>I'm using opencv and I'm able to get a pixel of an image-- a 3-dimensional tuple, via the code below. However, I'm not quite sure how to calculate the mode of the pixels values in the image. </p> <pre><code>import cv2 import numpy as np import matplotlib.pyplot as plt import numpy as np import cv2 img =cv2.imrea...
<p>From the description, it seems you are after the pixel that's occurring the most in the input image. To solve for the same, here's one efficient approach using the concept of <code>views</code> -</p> <pre><code>def get_row_view(a): void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[-1]))) a = n...
opencv|numpy|scipy
4
355,279
43,877,692
Pandas in AWS lambda gives numpy error
<p>I've been trying to run my code in AWS Lambda which imports pandas. So here is what I've done. I have a python file which contains a simple code as follows(This file has the lambda handler)</p> <pre><code>import json print('Loading function') import pandas as pd def lambda_handler(event, context): return "Welco...
<p>To include numpy in your lambda zip follow the instructions on this page in the AWS docs... </p> <p><a href="https://aws.amazon.com/premiumsupport/knowledge-center/lambda-python-package-compatible/" rel="noreferrer">How do I add Python packages with compiled binaries to my deployment package and make the package co...
python|pandas|numpy|amazon-s3|aws-lambda
13
355,280
43,854,092
Vectorizing nearest neighbor computation
<p>I have the following function which is returning an array calculating the nearest neighbor:</p> <pre><code>def p_batch(U,X,Y): return [nearest(u,X,Y) for u in U] </code></pre> <p>I would like to replace the for loop using numpy. I've been looking into numpy.vectorize() as this seems to be the right approach, b...
<p><strong>Approach #1</strong></p> <p>You could use <a href="https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>Scipy's cdist</code></a> to generate all those euclidean distances and then simply use <code>argmin</code> and index into <code>Y<...
python|arrays|numpy|vector|vectorization
2
355,281
2,142,415
Python: Analysis on CSV files 100,000 lines x 40 columns
<p>I have about a 100 csv files each 100,000 x 40 <strike>rows</strike> columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis.</p> <p>I was wondering wha...
<p>I've found that Python + CSV is probably the fastest, and simplest way to do some kinds of statistical processing. </p> <p>We do a fair amount of reformatting and correcting for odd data errors, so Python helps us.</p> <p>The availability of Python's functional programming features makes this particularly simple....
python|numpy
13
355,282
72,917,931
Discrepancy of torch shape function for 1 dimensional shaped tensor
<p>I am confused by the behavior of <code>torch</code>'s <code>shape</code> function. When a tensor <code>t</code> has shape say, <code>[3,2]</code>, then assigning <code>N, M = t.shape</code> gives <code>N = 3</code> and <code>M = 2</code>. Whereas if a tensor <code>t</code> has shape <code>[3]</code>, assigning <code...
<p>A valid point but you can also get the 3 by doing this</p> <pre><code>&gt;&gt;&gt; X, = torch.tensor([1, 1.5, 0.5]).shape &gt;&gt;&gt; X 3 </code></pre>
python|pytorch|tensor|torch
0
355,283
73,070,507
Why os.listdir() finds the excel but pd.read_excel() returns error?
<p>here is the simple version of my code:</p> <pre><code>for filename in os.listdir('excels/'): print(filename) df = pd.read_excel(filename) df.head() </code></pre> <p>Output is:</p> <pre><code>RandomExcelData.xlsx --------------------------------------------------------------------------- FileNotFoundError...
<p>You need to add the path when reading the Excel files:</p> <pre><code>for filename in os.listdir('excels/'): print(filename) df = pd.read_excel('excels/' + filename) df.head() </code></pre>
python-3.x|pandas|windows|jupyter-notebook|listdir
2
355,284
72,950,866
Add digits to the left of a value
<p>Given the following DataFrame of pandas in Python:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>code</th> <th>color</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>14563</td> <td>red</td> </tr> <tr> <td>1</td> <td>4563</td> <td>blue</td> </tr> <tr> <td>2</td> <td>1463</td>...
<p>try:</p> <pre><code>df['code'] = df['code'].str.zfill(5) </code></pre> <p>check: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html</a></p> <p>you can add astype(str) if the code column is int and not...
python|pandas|dataframe
1
355,285
72,849,420
numpy.array converts integers in my list into str_: ()
<p>I have a list of lists. Each list contains of both <code>str</code> and <code>int</code>:</p> <pre><code>[38, 'Private', 89814, 'HS-grad', 9, 'Married-civ-spouse', 'Farming-fishing', 'Husband', 'White', 'Male', 0, 0, 50, 'United-States', '&lt;=50K'] </code></pre> <p>I need to convert it into <code>ndarray</code>. I ...
<p>As @ouboros1 answered using <code>numpy.array(my_list, dtype=object)</code> helped Thanks a lot for help!!</p>
python|numpy|numpy-ndarray
1
355,286
73,059,155
dataframe groupby transform: conditional sum based on current row values
<p>I have a dataframe that lists quantities by article, shop and size: several million rows.</p> <p>The task is: If article A with size S has a non-nan quantity in shop P, then sum up <em>all</em> the sizes of article A in shop P. Show the sum in a new column, beside the quantity of size S. If the row shows NaN units, ...
<p>I just realized the simple answer:</p> <pre><code> df[&quot;Result_&quot;] = np.where(np.isnan(df[&quot;units&quot;]), np.nan, df.groupby([&quot;article&quot;, &quot;shop&quot;])[&quot;units&quot;].transform(&quot;sum&quot;)) </code></pre>
python|pandas|dataframe|lambda|transform
0
355,287
73,136,384
How to fix the input dimension from convolution flatten to feed forward layer?
<p>I am using nni framework on python to do Neural Architecture Search. In that I have defined model as:</p> <pre><code>from nni.nas.pytorch import mutables class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = mutables.LayerChoice([ nn.Conv2d(3, 32, kernel_...
<p>For <code>conv</code> with <code>kernel_zise=5</code> you need to <code>padding=2</code> and not 1.<br /> Fix:</p> <pre class="lang-py prettyprint-override"><code> self.conv1 = mutables.LayerChoice([ nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1), nn.Conv2d(3, 32, kernel_size=5, ...
python|deep-learning|pytorch|conv-neural-network|nas
1
355,288
73,146,284
pandas apply function with multiple inputs to create a new column
<p>I have a function I want to use to generate a new column</p> <pre><code> def airport_to_country(a_code,country_dict): return country_dict[a_code] </code></pre> <p>Dataframe looks like this:</p> <pre><code>Rank AirportCode 1 LAX 2 AUH 3 HBE ... . </code></pre> <p>What I want to do I create another column ...
<p>after some fiddling around I got it to work using that example:</p> <pre><code>df['country'] = df.apply(lambda x: airport_to_contry(x['a_code'],country_dict),axis = 1) </code></pre>
python|pandas|dataframe
2
355,289
72,852,923
Graphically split time history
<p>I'm trying to make a simple function allowing a user to split a time history into two parts. The user should be able to click and the x-axis value should be returned so that the output is divided into two DataFrames.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;data&quot;: np.rand...
<p>I think I have found an answer, but would love if anyone who is more expert can improve:</p> <pre><code>df = pd.DataFrame({&quot;data&quot;: np.random.rand(100)}) def split_TH(df): fig, ax = plt.subplots() df.plot(ax = ax) def onclick(event): global t t = event.xdata cid = f...
python|pandas|matplotlib|plotly
0
355,290
73,059,143
Tensorflow getting ' ValueError: Exception encountered when calling layer "normalization" Dimensions must be equal'
<p>I am following Tensorflow’s regression <a href="https://www.tensorflow.org/tutorials/keras/regression" rel="nofollow noreferrer">tutorial</a> and have created a multivariable linear regression and deep neural network however, when I am trying to collect the test set in <code>test_results</code>, I get the following ...
<p>You lost the <code>outcome</code> column in the dataframe because of pop. Try extracting that column using</p> <pre><code>train_labels = train_features['HC03'] test_labels = test_features['HC03'] </code></pre>
python|tensorflow|keras|regression
0
355,291
73,014,053
How to make a computationally expensive row-wise operation into efficient vectorized one?
<p>Fellow contributors, I have written a program that is meant to be applied on a data set of more than a million observations. At some point of the program I need to do row-wise operations on a pandas data frame where considering the number of observations it could take a while to be executed. I would like to find a m...
<p>That's exactly what the built-in pandas <code>loc</code> is made for.</p> <pre class="lang-py prettyprint-override"><code>df['C'] = 'foobar' df.loc[(df['A'] == 'Yes') &amp; (df['B'] == 'Red'), 'C'] = 'bar' df.loc[(df['A'] == 'Yes') &amp; (df['B'] == 'Blue'), 'C'] = 'foo' </code></pre>
python-3.x|pandas|dataframe
3
355,292
73,014,435
Target size (torch.Size([32, 9])) must be the same as input size (torch.Size([32, 10]))
<p>I have 10 classes. I have a model such as;</p> <pre><code>from brevitas.nn import QuantLinear, QuantReLU import torch.nn as nn # Setting seeds for reproducibility torch.manual_seed(0) model = nn.Sequential( QuantLinear(input_size, hidden1, bias=True, weight_bit_width=weight_bit_width), nn.BatchNorm1d(h...
<p>The code error is pretty straightforward - the <code>criterion</code> (that you didn't show here in the code) expects both the <code>input</code> and the <code>target</code> arguments to be the same size, but they're not.</p> <p>The problem is that you're using <code>torch.nn.functional.one_hot(target)</code> withou...
machine-learning|pytorch|conv-neural-network|size
0
355,293
73,098,217
(vectorization) loop through two dataframe cell by cell and find if one is part of the other
<p>I have a dataframe contains color and material parameters and another one contain data. I want to check cell by cell if the data dataframe have any of the data in the parameters dataframe I know that I should use vectorization but I am not sure how</p> <pre><code>parameter = pd.DataFrame({'color': ['red','blue','gre...
<p>The following code filters <code>color</code> and <code>material</code> which is able to extract color(s) and material(s).</p> <pre class="lang-py prettyprint-override"><code>data['attribute'] = data['name'].apply(lambda name: ','.join([c for c in parameter['color'].tolist() if c in name])) data['attribute2'] = data...
python|pandas
0
355,294
72,933,538
applying and assigning with lambda and struggling to resolve
<p>I have a function definition to retrieve maximum value in a column</p> <pre><code>def highestHigh(date1,ticker,allp_df): currDate= datetime.datetime.now().date() allpm_df = allp_df.loc[((allp_df['Ticker']==ticker)&amp;(allp_df['date']&gt;=date1)&amp;(allp_df['date']&lt;=currDate)),'high'] return allpm_df...
<p>I suppose the problem is <code>date1</code>. <code>date1</code> is not a scalar value like '2020-07-11' but the Series <code>allp_df['DateIdentified']</code>.</p> <p>So <code>(allp_df['date']&gt;=date1)</code> will raise an exception even if <code>init_df</code> contains only one row:</p> <pre><code>&gt;&gt;&gt; all...
python|pandas|lambda
0
355,295
72,880,176
Pandas index is sorting on its own
<p>I have a df sorted by person and time. The index is not duplicated, nor is it continuous from 0. I check the difference in time against a threshold depending on row above</p> <pre><code> person time_bought product 42 abby 2:21 fruit 12 abby 2:55 fruit 10 abby 10:35 ...
<p>Use:</p> <pre><code>df['time_bought'] = pd.to_timedelta('00:' + df['time_bought']) </code></pre> <p>Idea is not filter rows, but set <code>NaT</code> to unmatched rows:</p> <pre><code>print (df['time_bought'].where(df['product']==&quot;fruit&quot;, None)) 42 0 days 00:02:21 12 0 days 00:02:55 10 Na...
python|python-3.x|pandas|dictionary|pandas-groupby
1
355,296
72,905,444
Calculate time difference between two dates in the same column in Pandas
<p>I have a column (DATE) with multiple data times and I want to find the difference in minutes from date to date and store it into a new column (time_interval).</p> <p>This is what I have tried:</p> <p>df['time_interval'] = (df['DATE'],axis=0 - df['DATE'],axis=1) * 24 * 60</p> <p><a href="https://i.stack.imgur.com/68h...
<p>Depending on how you'd care to store the differences, either</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(data=['01-01-2006 00:53:00', '01-01-2006 01:53:00', '01-01-2006 02:53:00', '01-01-2006 03:53:00', ...
python|pandas
1
355,297
72,934,477
AttributeError: 'openvino.inference_engine.ie_api.InferRequest' object has no attribute 'outputs'
<p>I am trying to use Openvino async inference model in python. (<a href="https://docs.openvino.ai/2020.1/ie_python_api/classie__api_1_1ExecutableNetwork.html" rel="nofollow noreferrer">https://docs.openvino.ai/2020.1/ie_python_api/classie__api_1_1ExecutableNetwork.html</a>)</p> <pre class="lang-py prettyprint-override...
<p>The <em>infer_request_handle.outputs[out_blob_name]</em> has been deprecated in later OpenVINO version.</p> <p>Use <a href="https://docs.openvino.ai/2022.1/api/ie_python_api/_autosummary/openvino.inference_engine.InferRequest.html" rel="nofollow noreferrer">output_blobs</a> to get the dictionary that maps the output...
python|pytorch|openvino
0
355,298
72,859,843
Generate id of unique values from two columns in pandas
<p>I have the following data:</p> <pre><code>df = pd.DataFrame({'orig':['INOA','AFXR','GUTR','AREB'], 'dest':['AFXR','INOA','INOA','GAPR'], 'count':[100,50,1,5]}) orig dest count INOA AFXR 100 AFXR INOA 50 GUTR INOA 1 AREB GAPR 5 </code></pre> <p>For ...
<p>So first we extract the unique value for both columns, then extract again the unique value for these two array, then make a function that return the index of the x in unique array.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np unique= pd.unique(np.append(df['orig'].unique(), df['dest'].uniq...
python|pandas
3
355,299
72,926,120
spektral.datasets.citation.load_data() not found
<p>I am trying to use the CoRA dataset to train a graph neural network on tensorflow and it's my first time using Spektral.</p> <p>After some research on the internet, I learnt that there's supposed to be a useful loader function that comes with Spektral for me to load this benchmark dataset so I attempted to implement...
<p>I solved the problem myself after some more research. For Spektral version 1.1.0, I think this does the job of the loader function in terms of using the CoRA dataset:</p> <pre><code>cora_dataset = spektral.datasets.citation.Citation(name='cora') test_mask = cora_dataset.mask_te train_mask = cora_dataset.mask_tr val_...
python|tensorflow|machine-learning|graph-neural-network
2