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
11,700
57,237,906
Pickling Pandas DataFrames subclasses which include metadata
<p>The question about attaching metadata to Pandas objects, and getting that data to survive a pickle/unpickle process is a perennial one. I see some very old answers, which basically say that you can't. Hopefully, a more current answer to this question will be yes. I'm using Pandas 0.23.3.</p> <p>I've made some Pa...
<p>The comment from <a href="https://stackoverflow.com/users/3339965/root">user "root"</a> was helpful. I have confirmed that if you define a class property called _metadata inside your custom DataFrame subclass, it is the list of the instance properties you want to retain through slicing, pickling, and unpickling ope...
python|pandas|dataframe|pickle
1
11,701
46,008,030
Finding the closest matching numbers in dataframe using Pandas/Python
<p>I have a dataseries:</p> <pre><code>df = pd.DataFrame({'Values': [-0.8765, -1, -1.2, 3, 4, 5, -12.0021, 10, 11, 12, -0.982]}, index = [pd.Timestamp('20130101 09:00:00'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), ...
<p>A nice solution from <a href="https://stackoverflow.com/questions/40807475/selecting-close-matches-from-one-array-based-on-another-reference-array">this question</a> recommends using broadcasting on a <code>numpy</code> array.</p> <pre><code>pattern = [4, 5, -12.01, 10.1] thresh = 0.1 out = df[(np.abs(df.Values.va...
python|pandas|dataframe
1
11,702
45,788,049
how to make python loop faster to run pairwise association test
<p>I have a list of patient id and drug names and a list of patient id and disease names. I want to find the most indicative drug for each disease.</p> <p>To find this I want to do Fisher exact test to get the p-value for each disease/drug pair. But the loop runs very slowly, more than 10 hours. Is there a way to make...
<p>You need multiprocessing/multithreading, I have added the code.:</p> <pre><code>from multiprocessing.dummy import Pool as ThreadPool most_indicative_medication = {} rx_list = list(meps_meds.rxName.unique()) disease_list = list(meps_base_data.columns.values)[8:] def run_pairwise(i): print i rx_dict = {} ...
python|pandas|loops|statistics|associations
1
11,703
23,088,351
How can be used multiple filter in the numpy array?
<p>I am trying to filter some data out from an array</p> <pre><code> data = data[data['RotSpeed'] &lt;= ROTOR_SPEED ] data = data[data['HorWindV'] &lt;= WIND_SPEED ] </code></pre> <p>I am wondering if this can be optimized by combining the two filter?</p>
<p>You can combine the two filters with <code>&amp;</code> operator:</p> <pre><code>data = data[(data['RotSpeed'] &lt;= ROTOR_SPEED) &amp; (data['HorWindV'] &lt;= WIND_SPEED)] </code></pre> <p>It is unlikely to be much of an optimisation though. </p>
python|arrays|numpy
4
11,704
35,400,000
Add a column to pandas DataFrame based on the values of two other columns using groupby ( )
<p>I have a very large data file which can be modelled with the code below:</p> <pre><code>import pandas as pd import numpy as np import random x = pd.DataFrame({'file_name': np.repeat(['csv_1', 'csv_2'], 32), 'side': np.tile(np.repeat(['n', 'f'], 16),2), 'ten_13':np.tile(np.repeat...
<p>You <em>could</em> use <code>pandas.apply()</code> for this, but considering that you have only 4 conditions, the following is probably more efficient.</p> <pre><code>x.loc[(x['side'] == 'n') &amp; (x['ten_13'] == '10'), 'web_col'] = '1:8' ... for each condition </code></pre> <p>If you set the appropriate indexes,...
python|numpy|pandas
-1
11,705
35,514,976
numpy pad array with nan, getting strange float instead
<p>I'm trying to pad an array with <code>np.nan</code></p> <pre><code>import numpy as np print np.version.version # 1.10.2 combine = lambda real, theo: np.vstack((theo, np.pad(real, (0, theo.shape[0] - real.shape[0]), 'constant', constant_values=np.nan))) real = np.arange(20) theoretical = np.linspace(0, 20, 100) resu...
<p>The result of <code>pad</code> has the same type as the input. <code>np.nan</code> is a float</p> <pre><code>In [874]: np.pad(np.ones(2,dtype=int),1,mode='constant',constant_values=(np.nan,)) Out[874]: array([-2147483648, 1, 1, -2147483648]) In [875]: np.pad(np.ones(2,dtype=float),1,mode='cons...
python|numpy
12
11,706
11,884,195
Python Keep points in spline interpolation
<p>I wrote a code that performs a spline interpolation:</p> <pre><code>x1 = [ 0., 13.99576991, 27.99153981, 41.98730972, 55.98307963, 69.97884954, 83.97461944, 97.97038935, 111.9661593, 125.9619292, 139.9576991, 153.953469 ] y1 = [ 1., 0.88675318, 0.67899118, 0.50012243, 0.35737022, 0.27081293, 0.18486778, 0.11043095,...
<p>Right, <code>linspace</code> won't generate any of the values in <code>x</code> except the ones you pass to it (<code>x.min()</code> and <code>x.max()</code>).</p> <p>I don't have a great snappy answer, but here is one way to do it:</p> <pre><code># Interpolate the data using a cubic spline to "new_length" samples...
python|numpy|interpolation|spline
6
11,707
51,096,891
FTRL optimizer in tensorflow seems not work well
<p>Tried to training LR model on a large scale dataset via tensorflow with FTRL optimizer for a ctr task. tensorflow/sklearn auc and training/evaluation auc are OK. But performance in product is not good. I've tried to lower down the distributed level, but question can't be totally resolved. Any suggestions? </p>
<p>Found at least two reasons:</p> <p>First is the underlying implementation is not exactly the same as the original paper. I don't know why they do this, explanation needed.</p> <p>Second, the gradients used in updating weights are batch gradient, which means update the ps weights once per batch(very trivial in a mo...
tensorflow|distributed|logistic-regression
0
11,708
66,675,299
Pytorch -> [Onnx -> tensorflow] -> tflite generates lots of redundant conv2d operators
<p>I am converting efficientnet from onnx to tensorflow for further conversion to tflite. The conversion from onnx to tensorflow yields strange results</p> <p>Onnx has 1 conv2d operator</p> <p><a href="https://i.stack.imgur.com/xCLDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xCLDb.png" alt="ent...
<p>After some additional digging I've found the following</p> <ul> <li>My convs were depthwise(conv2d is depthwise in pytorch and onnx if it has groups parameter &gt; 1)</li> <li>This bunch of convs is an inefficient way of doing a depthwise conv. To do it efficiently we need to use tf.depthwiseconv</li> </ul> <p>To fi...
tensorflow|deep-learning|pytorch|tensorflow-lite|onnx
0
11,709
66,633,130
IBM tone analyzer output in pandas frame has repeated values
<p>I am doing sentiment analysis for newsapi followed by tone analysis. I am able to display output of sentiment analysis and tone analyzer in pandas frame. The issue is that the output of IBM tone analyzer has repeated values. I would want that the values should be unique in each row. Here is code and output for the s...
<p>There is multiple list of dictionaries per row, so answer is changed by flatten list comprehwension with <code>enumerate</code> for new columns names with numeric suffix:</p> <pre><code>#change f(x) to f(i) def f(i): x = ta.tone({'text': i}).get_result()['document_tone']['tones'] return pd.Series({f'{k}_{i}'...
python|pandas|ibm-watson
0
11,710
57,524,881
Pivot / invert table (but not quite) in pandas
<p>I have a problem for which I managed to write some working code, but I'd like to see if anyone here could have a simpler / more organized / less ugly / more in-built solution. Sorry for the extremely vague title, but I wasn't able to summarize the issue in one sentence.</p> <p><strong>The problem</strong></p> <p>B...
<p>You can use <a href="https://stackoverflow.com/a/44308225/2901002">argsort</a> for get top3 columns names, but then is necessary replace positions from <code>0</code> values with sorting and <code>np.where</code>:</p> <pre><code>w_columns = ['A', 'B', 'C', 'D'] w_labels = ['W1', 'W2', 'W3'] #sorting columns names ...
python|pandas|dataframe
3
11,711
57,555,217
Is there a python function I can use to group retail banking transactions?
<p>Is there perhaps another function in Python I can use to group customers' transactions? Let's say a specific word is contained in a transaction, and there are multiple transactions that have the same name, then group them together.</p> <p>I used this code, but it will be too long, because I have thousands of unique...
<p>I believe you can create a list that contains the name and use for loop to loop into each of them.</p> <pre><code>lst = ['PNP', 'JET'...] for i in lst: if df['Name'].str.contains[i]: #same as your temp df['Short_Name'] = i </code></pre> <p>If you have different name you want to give to each row, you can cr...
python|python-3.x|pandas|numpy
0
11,712
24,197,305
Error when trying to convert a column with string in Python Pandas to Float
<p>I have a column named 'market_cap_(in_us_$)' which values are like:</p> <pre><code>$5.41 $18,160.50 $9,038.20 $8,614.30 $368.50 $2,603.80 $6,701.50 $8,942.40 </code></pre> <p>My final goal is to be able to filter based on specific numeric values (for example, > 2000.00).</p> <p>By reading other questions ...
<p>The right regular expression to use is given here, as you want to remove the <code>$</code> and <code>,</code>:</p> <pre><code>In [7]: df['market_cap_(in_us_$)'].replace('[\$,]', '', regex=True).astype(float) Out[7]: 0 5.41 1 18160.50 2 9038.20 3 8614.30 4 368.50 5 2603.80 6 6701.50 ...
python|regex|python-2.7|pandas
4
11,713
43,541,030
dividing random samples to subgroups using python
<p>So I had this statistics homework and I wanted to do it with python and numpy. The question started with making of 1000 random samples which follow normal distribution. <code>random_sample=np.random.randn(1000)</code><br> Then it wanted to divided these numbers to some subgroups . for example suppose we divide them...
<p>You can get subgroup indices using <code>numpy.digitize</code>:</p> <pre><code>random_sample = 5 * np.random.randn(10) random_sample # -&gt; array([-3.99645573, 0.44242061, 8.65191515, -1.62643622, 1.40187879, # 5.31503683, -4.73614766, 2.00544974, -6.35537813, -7.2970433 ]) indices = np.digitize(ran...
python-3.x|numpy|statistics
0
11,714
43,510,022
Distributed Tensorflow: non-chief worker blocked
<p>I am trying the distributed tensorflow, and my code is shown as follow. The problem is that the chief worker can run as expected. However, non-chief worker will blocked at :</p> <blockquote> <p>sess = sv.prepare_or_wait_for_session(target, config=sess_config)</p> </blockquote> <p>Could anybody help me solve this...
<p>Sync will create a local variable which will basically create the local step variable which is a local variable. But VariableDeviceChooser doesn't tell global from local so it is not functioning until we fix the device chooser. Thanks for reporting though.</p>
tensorflow|deep-learning|distributed
0
11,715
43,769,796
How to prepare multiple RGB images as numpy array for CNN
<p>I want to use the code below with my own input images instead of the mnist images. However I am having a hard time inputting several color .jpg images into a numpy array similar to the X_train used in the code below. I have a folder called data with another folder called train that includes several images that I w...
<p>I am assuming that you are using Theano and that your jpgs have 3 bands. In addition, your jpgs should have the same input shape as the input shape that you indicate in the first convolutional model (28x28 pixels). In that case you can reshape all your jpes with the following lines:</p> <pre><code>#create random da...
python|arrays|image|numpy|keras
1
11,716
43,600,901
Copy nan values from one dataframe to another
<p>I have two dataframes <code>df1</code> and <code>df2</code> of the same size and dimensions. Is there a simple way to copy all the <code>NaN</code> values in 'df1' to 'df2' ? The example below demonstrates the output I want from <em><code>.copynans()</code></em></p> <pre><code>In: df1 Out: 10053...
<p>Either</p> <pre><code>df1.where(df2.notnull()) </code></pre> <p>Or</p> <pre><code>df1.mask(df2.isnull()) </code></pre>
python|pandas|mask
4
11,717
43,683,564
struggle trying create new series
<p>I have the following df :</p> <pre><code>             A C Date 2015-06-29   196.0  1 2015-09-18   255.0  2 2015-08-24   236.0  3 2014-11-20    39.0  4 2014-10-02  4.0  5 </code></pre> <p>How can I generate a new series that is the sum of all the previous rows of column c ?</p> <p>This would be the...
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html#pandas.Series.cumsum" rel="nofollow noreferrer"><code>cumsum</code></a> to perform this:</p> <pre><code>In [373]: df['C'].cumsum() Out[373]: Date 2015-06-29 1 2015-09-18 3 2015-08-24 6 2014-11-...
python|pandas
3
11,718
43,771,654
Pandas - Getting a Key Error when the Key Exists
<p>I'm trying to join two dataframes in Pandas. </p> <p>The first frame is called Trades and has these columns:</p> <pre><code>TRADE DATE ACCOUNT COMPANY COST CENTER CURRENCY </code></pre> <p>The second frame is called Company_Mapping and has these columns:</p> <pre><code>ACTUAL_COMPANY_ID MAPPED_COMPANY_ID </code>...
<p>Your <code>Trades</code> dataframe has a single column with all the intended column names mashed together into a single string. Check the code that parses your file.</p>
python|python-2.7|pandas
4
11,719
73,122,485
Create a dictionary from pandas dataframe modifying the structure
<p>I am pretty new with python and all of this stuff, at the moment I have a csv file uploaded inmemory with Django rest framework, so far so good at this point, now I need to insert this data into the DB so I need to get the columns accordingly my models, so I need to convert this csv to a mapping object, I am loading...
<p>You can do this by merging the three columns into a single column.</p> <pre><code>print(&quot;Dataframe reader_index=&quot;,reader_index) datasource_cols = [&quot;origin_coord&quot;, &quot;destination_coord&quot;, &quot;datetime&quot;] reader['dataSource_trips'] = reader[datasource_cols].to_dict(orient='records') r...
python|pandas|django-rest-framework
0
11,720
72,928,201
Inserting into a Cassandra DB is slow even with execute_concurrent()
<p>I am trying to insert a pandas dataframe into cassandra. I am using the execute_concurrent, but I don't see any improvement. It is taking almost 5s per row insertions. There are 14k rows so at this rate it will take more than 15 hours. I have 12 GB RAM with 2 CPU cores. How fast can I run this operation? I've tried ...
<p>Even with concurrent asynchronous requests (<code>execute_concurrent()</code>), it will still be bottlenecked on the client side because there is only so much a single client process can do even when it's multi-threaded.</p> <p>If you want to maximise the throughput of your cluster, we recommend scaling your app hor...
python|pandas|dataframe|cassandra|datastax-python-driver
0
11,721
73,072,701
python create an arbitrary score based off certain criteria
<p>I want to create a formula that will create an arbitrary score based on certain variables. For example, given a dataframe with the following columns:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Name': ['Joe', 'Bob'], 'Score': [0.75, 0.8], 'Length': [10, 20]}) </code></pre> <p>I want to...
<p>You can set up a temporary DataFrame with custom columns to sort and use its index to reorder the original:</p> <pre><code>idx = (df .assign(Length=-df['Length'].sub(10).abs(), Name=pd.Categorical(df['Name'], categories=['Joe', 'Bob'], ordered=True) ) .sort_values(by=['Length', 'Score', 'Name...
python|pandas|expression|formula
1
11,722
73,174,759
Converting list of arrays into list of lists in Python
<p>I have a list <code>I</code> which contains numpy arrays. I want to convert these arrays into lists as shown in the current and expected outputs.</p> <pre><code>import numpy as np I=[np.array([[0, 1], [0, 2], [1, 3], [4, 3], [2, 4]]), np.array([[0, 1], [0, 2], [1, 3],...
<p>You can use <code>numpy</code>:</p> <pre><code>import numpy as np I1 = np.array(I1, dtype=object).tolist() </code></pre>
python|list|numpy
1
11,723
73,034,064
How to map values to only empty rows in pandas columns?
<p>I have a column where I want to map the data from a dictionary to only empty rows.And the rows that have some value or data already in it I dont want to map any data in it.</p> <p>Expected Output:</p> <pre><code>|Column1 |Column2 | |--------|--------| |a | | | |Data | |c | | </cod...
<p>IIUC use:</p> <pre><code>for c in cols: df2.loc[df2[c].eq(''), c] = df2.x.map(er_dict) </code></pre>
python|pandas|for-loop|mapping
0
11,724
72,930,426
how to find index above threshold of each row
<p>I have numpy array in below format:</p> <pre><code>array([list([0.28552457, 0.28552457, 0.28552457, 0.28552457, 0.28552457]), list([0.71641791, 0.71641791, 0.71641791, 0.69565217, 0.69565217]), list([0.95626478, 0.95626478, 0.95513577, 0.95513577, 0.95513577]), ..., list([0.14285714, 0.14...
<p>Generating a numpy array using the following code</p> <pre class="lang-py prettyprint-override"><code>y = np.random.random(50).reshape(10, 5) </code></pre> <p>should give you something like</p> <pre class="lang-bash prettyprint-override"><code>array([[0.0992988 , 0.62179431, 0.26247934, 0.84402507, 0.05931778], ...
python|numpy
0
11,725
70,651,759
Compiling of ML Kit model on demand
<p>I want to check if it is possible to use <a href="https://developers.google.com/ml-kit/vision/pose-detection/ios" rel="nofollow noreferrer">ML Kit Pose Detection</a> without having it in the initial application bundle (to reduce application size).</p> <p>I am looking for functionality similar to one provided by Core...
<p>You can also use VNDetectHumanBodyPoseRequest, it's integrated in iOS SDK.</p> <p><a href="https://developer.apple.com/documentation/vision/detecting_human_body_poses_in_images" rel="nofollow noreferrer">https://developer.apple.com/documentation/vision/detecting_human_body_poses_in_images</a></p>
ios|tensorflow|coreml|google-mlkit
0
11,726
70,413,924
PyTorch Lightning complex-valued CNN training outputs NaN after 1 batch
<p>I have built a complex-valued CNN using <a href="https://github.com/wavefrontshaping/complexPyTorch" rel="nofollow noreferrer">ComplexPyTorch</a>, where the layers are wrapped in a <code>torch.ModuleList</code>. When running the network I get through the validation sanity check and 1 batch of the training, then my l...
<p>For anyone interested, I set <code>detect_anomaly=True</code> in <code>Trainer</code>, then was able to trace the torch function outputting NaNs during backpropagation. In my case it was <code>torch.atan2</code> so I added a tiny epsilon to its denominator and fixed it, but as a general point I've always found denom...
python|pytorch|conv-neural-network|nan|pytorch-lightning
1
11,727
70,404,562
Pandas Reversing the Dataframe and getting the first element
<p>I have two questions:</p> <ol> <li>I would like to reverse the order of the data loaded from the csv. Then get the time from the first row from the time column. After doing df = df[::-1], I expect the value 17:00:03 instead of 15:59:56. Where have I made a mistake?</li> <li>how to use Pandas to round the value 17:00...
<p>I think you need to reset the index using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer">DataFrame.reset_index</a> after reversing the order of the rows since the index doesn't get updated automatically. To round the second in the time, you can try ...
python|pandas|dataframe
1
11,728
70,643,826
Calculate Kendall's correlation in a python pandas dataframe with only one column of values
<p>Assume the following dataframe format :</p> <pre><code>qualifier tenor date return AUD 1y 2008-04-14 0.0290 AUD 1y 2008-04-15 0.1205 AUD 1y 2008-04-16 0.1300 AUD 1y 2008-04-17 0.1488 AUD 1y 2008-04-18 0.1038 AUD 2y 2008-04-14 -0.00570 AUD 2y ...
<p>Try this:</p> <pre><code>df.groupby(&quot;qualifier&quot;).apply(lambda g: g.set_index([&quot;date&quot;,&quot;tenor&quot;]).unstack(level=1).corr()) </code></pre> <p>it produces a correlation matrix between tenors for a given <code>qualifier</code></p> <pre><code> return tenor 1y 2y ...
python|pandas
1
11,729
70,456,240
How to fix 'Object arrays cannot be loaded when allow_pickle=False' in A little GUI
<p>I was running A little GUI that allows to load and look at OCT volumes stored as 3D Numpy arrays, it returned an error 'Object arrays cannot be loaded when allow_pickle=False' This is the code already used by developers in GitHub</p> <pre><code>from __future__ import print_function import sys import os. path as op ...
<p>Try changing this line in the <code>load_cube</code> function:</p> <pre><code>self.cube_original = np.load(path) </code></pre> <p>to this:</p> <pre><code>self.cube_original = np.load(path, allow_pickle=True) </code></pre>
python|numpy|view|anaconda|spyder
1
11,730
42,588,474
Numpy can't control the changing of the arrays
<pre><code>y[:,2] = np.ravel(rkf78(neq,ti,(ti-step),(step/50),tetol,x1)) </code></pre> <p>If I print <code>x1</code> before and after this line I get different results. More specifically, the value of <code>x1</code> after this line is equal to <code>y[:,2]</code></p> <pre><code>y[:,2] = np.ravel(rkf78(neq,ti,(ti-ste...
<p>Well without seeing your rkf78 function, it will be hard to see how your x1 list is being used. I'm also assuming x1 is a list or numpy array. </p> <p>The thing about lists and arrays is that when you set one equal to another, i.e.</p> <pre><code>dummy_list = x1 </code></pre> <p>where x1 is your list, any change...
python|arrays|numpy
1
11,731
42,756,696
Read multiple csv files and Add filename as new column in pandas
<p>I have several csv files in a single folder and I want to open them all in one dataframe and insert a new column with the associated filename. So far I've coded the following:</p> <pre><code>import pandas as pd import glob, os df = pd.concat(map(pd.read_csv, glob.glob(os.path.join('path/*.csv')))) df['filename']= o...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="noreferrer"><code>assign</code></a> for add new column in <code>loop</code>, also parameter <code>ignore_index=True</code> was added to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pan...
python|csv|pandas|operating-system|glob
29
11,732
42,834,853
Pandas dataframe unique values
<p>need some help with getting uniqued values from pandas dataframe</p> <p>i have :</p> <pre><code> &gt;&gt;&gt; df1 source target metric 0 acc1.yyy acx1.xxx 10000 1 acx1.xxx acc1.yyy 10000 </code></pre> <p>the goal is to remove unique values based on source+target or target+source. but i can't get ...
<p>You need first sort both columns:</p> <pre><code>df1[['source','target']] = df1[['source','target']].apply(sorted,axis=1) print (df1) source target metric 0 acc1.yyy acx1.xxx 10000 1 acc1.yyy acx1.xxx 10000 df2 = df1.drop_duplicates(subset=['source','target']) print (df2) source target me...
python|pandas
3
11,733
42,818,262
Pandas DataFrame Replace NaT with None
<p>I have been struggling with this question for a long while, and I tried different methods.</p> <p>I have a simple DataFrame as shown,</p> <p><a href="https://i.stack.imgur.com/GLWoQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GLWoQ.png" alt="enter image description here"></a></p> <p>I can use code t...
<p>Make the <code>dtype</code> <code>object</code></p> <pre><code>dfTest2 = pd.DataFrame(dict(InvoiceDate=pd.to_datetime(['2017-06-01', pd.NaT]))) dfTest2.InvoiceDate.astype(object).where(dfTest2.InvoiceDate.notnull(), None) 0 2017-06-01 00:00:00 1 None Name: InvoiceDate, dtype: object </code></...
python-2.7|pandas|dataframe
44
11,734
26,932,461
Conjugate transpose operator ".H" in numpy
<p>It is very convenient in numpy to use the <code>.T</code> attribute to get a transposed version of an <code>ndarray</code>. However, there is no similar way to get the conjugate transpose. Numpy's matrix class has the <code>.H</code> operator, but not ndarray. Because I like readable code, and because I'm too lazy...
<p>You can subclass the <code>ndarray</code> object like:</p> <pre><code>from numpy import ndarray class myarray(ndarray): @property def H(self): return self.conj().T </code></pre> <p>such that:</p> <pre><code>a = np.random.rand(3, 3).view(myarray) a.H </code></pre> <p>will give you the desired beh...
python|arrays|numpy|matrix|monkeypatching
29
11,735
26,977,476
How to pass index to function Python Pandas
<p>I am trying to pass an index from a df into my function so that my function can run through all of the rows of the df and provide the output which is a int in a new column called "TDNumber'. </p> <p>Here is the code</p> <pre><code> def createTdnumber(onedfindex): header.index maski = header.index &lt; ...
<p>Index types don't have an <code>apply</code> method, but <code>Series</code> does.</p> <p>To apply a function to your index, you can convert it to a series first, using its <code>to_series</code> method:</p> <pre><code>df['TDNumber'] = df.index.to_series().apply(createTdnumber) </code></pre>
python|pandas
1
11,736
14,564,656
Subclassing numpy.ma.MaskedArray
<p>I'm trying to subclass numpy's <code>MaskedArray</code> to add an attribute, but seem to fail getting the proper result out.</p> <p>I started out by following <a href="http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#slightly-more-realistic-example-attribute-added-to-existing-array" rel="nofollow norefe...
<p>In order for your slice to work as you wish, you may want to overload <code>__getitem__</code>:</p> <pre><code>def __getitem__(self, item): out = np.ma.MaskedArray.__getitem__(self, item) out.info = self.info return out </code></pre> <p>Ditto for <code>__setitem__</code>.</p> <p>If your <code>info</co...
python|numpy
2
11,737
30,689,063
Pandas and GeoPandas indexing and slicing
<p>I am using GeoPandas and Pandas. I have a, say, 300,000 rows Dataframe, df, with 4 columns + the index column.</p> <pre><code> id lat lon geometry 0 2009 40.711174 -73.99682 0 1 536 40.741444 -73.97536 0 2 228 40.754601 -73.97187 0 </code></pre> <p>however t...
<p>I would take the following approach:</p> <ol> <li><p>First find the unique id's and create a GeoSeries of Points for this:</p> <pre><code>unique_ids = df.groupby('id', as_index=False).first() unique_ids['geometry'] = GeoSeries([Point(x, y) for x, y in zip(unique_ids['lon'], unique_ids['lat'])]) </code></pre></li> ...
python|pandas|geopandas
3
11,738
39,068,833
Return diagonal elements of scipy sparse matrix
<p>Given a <code>scipy.sparse.csr.csr_matrix</code>, is there a quick way to return the elements on the diagonal?</p> <p>The reason I would like to do this is to compute <code>inv(D) A</code>, where <code>D</code> is a diagonal matrix whose diagonal entries agree with <code>A</code> (<code>A</code> is my sparse matrix...
<p>Use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.diagonal.html#scipy.sparse.csr_matrix.diagonal" rel="nofollow">csr_matrix.diagonal()</a>:</p> <blockquote> <p>Returns the main diagonal of the matrix</p> </blockquote> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy as...
python|numpy|matrix|scipy|diagonal
2
11,739
19,635,704
KeyError in pandas to_datetime using custom format
<p>The index of my DataFrame (TradeData) is in string format:</p> <pre><code>In [30]: TradeData.index Out[30]: Index(['09/30/2013 : 04:14 PM', '09/30/2013 : 03:53 PM', ... ], dtype=object) </code></pre> <p>And I would like it to be in Datetime. But the conversion does not seem to work:</p> <pre><code>In [31]: Trade...
<p>You can circumvent this to_datetime issue by resetting the index, manipulating the series via map/lambda/strptime, and then finally setting the index again.</p> <pre><code>In [1058]: TradeData.index Out[1058]: Index([u'09/30/2013 : 04:14 PM', u'09/30/2013 : 03:53 PM', u'09/30/2013 : 03:53 PM'], dtype=object) In [1...
python|datetime|pandas
3
11,740
12,962,705
python pandas remove duplicates in series
<p>Is there a function to enforce that the index is unique or is it only possibly to handle this in python 'itself' by converting to dict and back or something like that?</p> <p>As noted in the comments below: python pandas is a project built on numpy/scipy. </p> <p>to_dict and back works, but I bet this gets slow wh...
<p>BTW we plan on adding a <code>drop_duplicates</code> method to Series like <code>DataFrame.drop_duplicates</code> in the near future.</p>
python|pandas
7
11,741
29,292,114
Apply function row wise on pandas data frame on columns with numerical values
<p>I have the following data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]}) </code></pre> <p>Which looks like this:</p> <pre><code>In [32]: df Out[32]: AAA BBB CCC 0 w 10 100 1 x 20 50 2 y 30 -30 3 z 40 ...
<p>To select everything but the first column, you could use <code>df.iloc[:, 1:]</code>:</p> <pre><code>In [371]: df['Score'] = df.iloc[:, 1:].sum(axis=1) In [372]: df Out[372]: AAA BBB CCC Score 0 w 10 100 110 1 x 20 50 70 2 y 30 -30 0 3 z 40 -50 -10 </code></pre> <p>To app...
python|pandas
14
11,742
23,780,134
Using pandas and PyTables (3.1.1) at the same time, re-opening an already open file
<p>I use pandas and pytables (3.1.1) at once. The problem is that I already opened an HDF5 file with pytables and when I try to create a new HDF5Store with pandas</p> <pre><code>hdf5store = HDFStore(...) </code></pre> <p>I get the following error:</p> <pre><code> File "/home/travis/virtualenv/python2.7_with_system_...
<p>You need to pass <code>mode='r'</code> explicity to force an open in read-only mode. Default is to open in <code>mode='a'</code> (append mode). </p> <p>Recent versions of PyTables have become much more strict in only allowing a file to be opened in write mode ONCE ONLY, even across multiple processes/threads. This ...
python|pandas|hdf5|pytables
4
11,743
23,593,295
PSD of signal in numpy and how to scale it
<p>I am trying to compute and plot the power spectral density (PSD) of a stochastic signal. Reading the <a href="http://docs.scipy.org/doc/numpy/reference/routines.fft.html#module-numpy.fft" rel="nofollow">numpy documentation</a> for <code>np.fft.fft</code>, it mentions that if <code>A = fft(a)</code> then <code>np.abs...
<p>Oh man, the "necessary division" is a pain but you'll have to do it. Definitions are all over the place for something like a power spectral density, varying between physics and electrical engineering, etc. They vary between fields a lot, and you'll have to work out the desired prefactor yourself. Thankfully, the con...
python|numpy|scale|signal-processing|fft
4
11,744
22,819,666
Finding multiple minimums and adding new column in pandas
<p>I have a pandas df that looks like the following</p> <pre><code>df = pd.DataFrame({'Amount': [1,2,3,4,6,7], 'Name': ['person1', 'person1' ,'person2' ,'person2','person3','person3'],}) </code></pre> <p>What I am trying to do is create a third column that displays the minimum amount for each pers...
<p>The key is using <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#group-by-split-apply-combine" rel="nofollow"><code>groupby</code></a>, which is so useful that I strongly recommend reading the section of the docs linked there. You can get a <code>Series</code> with the minimum values per person:</...
python|pandas
2
11,745
22,936,168
TypeError: %d format: a number is required, not numpy.float64
<p>Trying to plot, I got the following error from <code>matplotlib</code>:</p> <pre><code>TypeError: %d format: a number is required, not numpy.float64 </code></pre> <p>This is the complete traceback (I've modified path names):</p> <pre><code>Traceback (most recent call last): File ".../plotmod.py", line 154, in _...
<p>It seems you have a NaN or infinity that you are trying to format as an integer which raises the error (there's no such thing as a NaN or Inf for the int datatype).</p> <pre><code>In [1]: import numpy as np In [2]: '%d' % np.float64(42) Out[2]: '42' In [3]: '%d' % np.float64('nan') -------------------------------...
python|date|numpy|matplotlib
4
11,746
62,439,300
Debugging Reinforcement Learning Model (MsPacman)
<p>I'm new to RL and I'm attempting to train an RL agent to play MsPacman in PyTorch. I've adapted the code from this <a href="https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html" rel="nofollow noreferrer">tutorial</a> on the PyTorch page for my problem. The DQN has the following architecture:</p> ...
<p>It would be interesting to see the episode rewards, as that is what the agent is optimising for. Is the agent getting stuck in corners from the beginning? If so, I would guess that the epsilon greedy policy (which is pretty much pure random at the beginning) is not implemented properly. I assume that the agent gets ...
python|pytorch|reinforcement-learning
0
11,747
62,193,498
groupby with visualization in python
<p>My data frame looks like -</p> <pre><code>state material bihar a wb b ap a bihar a bihar d ap b </code></pre> <p>I want data frame looks like -</p> <pre><code>state state_contribution material_a material_b material_c material_d bih...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>df.groupby</code></a> with <a href="https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferr...
python|python-3.x|pandas|pandas-groupby
1
11,748
62,043,469
pandas.read_sql_query - how to write correctly WHERE condition if both the column name and searched value contain space
<p>I write the SQL query like this</p> <pre><code>df = pd.read_sql_query('SELECT * FROM hr_dataset WHERE "Performance Score" = "Needs Improvement";', conn) </code></pre> <pre><code>hr_dataset - table Performance Score - column Needs Improvement - searched value </code></pre> <p>Both column name and searched value co...
<p>if it is SQL Server</p> <pre><code>SELECT * FROM hr_dataset WHERE [Performance Score] like '%Needs Improvement%' </code></pre> <p>if it is MySQL </p> <pre><code>SELECT * FROM hr_dataset WHERE `Performance Score` like '%Needs Improvement%' </code></pre> <p>if it is PostgresSQL, try</p> <pre><code>SELECT * FROM h...
python|sql|pandas|psycopg2
0
11,749
62,296,015
Pandas group by and perform calculations on multiple columns
<p>I have a real estate data</p> <pre><code>Reg Area Price A 20 356 B 30 98 A 50 900 </code></pre> <p>and I want to get </p> <pre><code>Reg Area Price AvgUnitPrice A 20 356 17.9 B 30 98 3.26 A 50 900 17.9 </code></pre> <p>For each region get all properties and ...
<p>One more approach</p> <pre><code>a = (df.groupby('Reg', sort=False)['Price'].sum()/df.groupby('Reg',sort=False)['Area'].sum()).reset_index(name='AuP') df.merge(a, on= 'Reg',sort=False) </code></pre> <p><strong>(Output</strong></p> <pre><code>Reg Area Price AuP A 20 356 17.942857 A 50 900 ...
python|pandas
2
11,750
51,242,967
How to write in excel no more than 1 million records from python data-frame
<p>I have a python data frame with more than 50 million records. I want to write them into a excel sheet where each sheet should have no more than 1 million records in them.</p>
<p>You can use <code>.iloc</code> to access certain rows of your data, and then dump them to Excel. Here's an example where 1000 rows are posted per sheet, the same basic idea will apply when you up it to 1000000:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Val': [i for i in range(5000)]}) GROUP_LENGTH = ...
python|pandas
2
11,751
51,255,249
Python Append leaving last entry in dataframe only
<p>I have created a function which connects through a DB system and then passes the values through in the below image:</p> <p><a href="https://i.stack.imgur.com/IhE90.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IhE90.png" alt="Example"></a></p> <p>Next, I have used my function and iterated thro...
<p>If you're trying to grab a list and append it to the end of a dataframe, why not initialize df_tmp with the data, like this:</p> <pre><code>df_master = pd.DataFrame([]) for i in PI_tags: df_tmp = pd.DataFrame(ReadPiValues(i, interval, start_date, end_date)) df_master = df_master.append(df_tmp) </code></pre...
python|pandas
1
11,752
48,343,179
how to optimize iteration on exponential in numpy
<p>Say I have the following <code>numpy array</code></p> <pre><code>n = 50 a = np.array(range(1, 1000)) / 1000. </code></pre> <p>I would like to execute this line of code</p> <pre><code>%timeit v = [a ** k for k in range(0, n)] 1000 loops, best of 3: 2.01 ms per loop </code></pre> <p>However, this line of code will...
<p>In quick tests <code>cumprod</code> seems to be faster.</p> <pre><code>In [225]: timeit v = np.array([a ** k for k in range(0, n)]) 2.76 ms ± 1.62 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [228]: %%timeit ...: A=np.broadcast_to(a[:,None],(len(a),50)) ...: v1=np.cumprod(A,axis=1) ....
loops|numpy|exponential|exponent
1
11,753
48,258,678
How to connect Conv3D output to MaxPooling2D in Keras?
<p>I'm using Keras to implement CNN. People often use Conv2D to do classification tasks. However, I want to get relationships between two images, then I decide to try Conv3D. However, I couldn't manage the dimension output from Conv3D and match the following layers.</p> <p>More specifically, I want to apply (5,5,2)...
<p>Stack both the images (remember to stack acc. to the backend you are using, theano is <code>channels_first</code> and tensorflow is <code>channels_last</code>) and pass 2 as the number of channels in <code>Conv2D</code>.</p> <p>Or if you have many channels for each images, then again stack them up and pass the tota...
tensorflow|keras|convolution
1
11,754
48,768,206
How to use dataset.shard in tensorflow?
<p>Recently I am looking into the dataset API in Tensorflow, and there is a method <code>dataset.shard()</code> which is for distributed computations.</p> <p>This is what's stated in Tensorflow's documentation:</p> <pre><code>Creates a Dataset that includes only 1/num_shards of this dataset. d = tf.data.TFRecordData...
<p>You should take a look at the <a href="https://www.tensorflow.org/deploy/distributed" rel="noreferrer">tutorial on Distributed TensorFlow</a> first to better understand how it works.</p> <p>You have multiple workers, that each run the same code but with a small difference: each worker will have a different <code>FL...
tensorflow|tensorflow-datasets
12
11,755
48,809,240
unique values with count of each value for each column in Pandas dataframe
<p>How can I get unique values with count of each value for each column in a pandas dataframe using for loop:</p> <p>Following code gives me count of each unique value for each column but I want the values as well.</p> <pre><code>import pprint col_uni_val={} for i in data.columns: col_uni_val[i] = len(data[i].un...
<p>Demo:</p> <pre><code>In [351]: d Out[351]: A B 0 1 4 1 1 4 2 2 6 3 2 6 4 2 6 5 3 6 In [352]: res = {col:d[col].value_counts() for col in d.columns} In [353]: res['A'] Out[353]: 2 3 1 2 3 1 Name: A, dtype: int64 In [354]: res['B'] Out[354]: 6 4 4 2 Name: B, dtype: int64 </code></pre...
python|pandas|dataframe
1
11,756
48,512,393
Pandas dropping columns end with number
<p>I have a df with the following column names:</p> <p>Name, xyz, ijk, 1, 2, 3, val1, val2, test1, test2 I want to drop all the columns whose name end with number but I still want to keep columns that only has number. How can this be done? </p> <p>The result would be: Name, xyz, ijk, 1, 2, 3</p> <p>Thanks!</p>
<p>Setup - </p> <pre><code>df = pd.DataFrame(columns=['xyz', 'ijk', '1', '2', '3', 'val1', 'test1', 'test2']) df Empty DataFrame Columns: [xyz, ijk, 1, 2, 3, val1, test1, test2] Index: [] </code></pre> <p>The fundamental assumption here is <em>all</em> your column names are <em>strings</em>. Let's use <code>filter</...
python|pandas
2
11,757
48,547,818
How to get to last record of large dataframe in Spyder window?
<p>I want to be able to open a dataframe in a Spyder (Python IDE) window and quickly scroll down to the last record of a relatively large pandas dataframe (134,890 records in table). It's frustrating because Spyder only loads a certain number of records from large tables, and scrolling down takes a while. </p> <p>Does...
<p>I think I figured it out. I must keep pulling down on the scroll bar and wiggle it left and right until Spyder has loaded all the records. The key is not to let go of the scroll bar until Spyder has finished loading all the records. If I let go, Spyder will stop loading new records. </p>
python|pandas|dataframe|spyder
1
11,758
70,770,949
Formatting and replacing the date format in a pandas dataframe column with month
<p>I am trying to replace the date format if present in a pandas dataframe with month in string format but getting error during the process</p> <p><strong>Code</strong></p> <pre><code>def date_format(url_link): match = re.compile(r'[\d]{2,4}[/|-][\d]{1,2}[/|-][\d]{2,4}') mo = match.search(url_link) mo = mo....
<p>Use <code>str.replace</code>:</p> <pre><code># Because my locale is french # import locale # locale.setlocale(locale.LC_TIME, 'en_US.UTF-8') # Add capture group -v-------------------------------------v match = re.compile(r'([\d]{2,4}[/|-][\d]{1,2}[/|-][\d]{2,4})') # Replace values date_to_month = lambda x: pd.to_d...
python|pandas|python-re
1
11,759
71,054,498
Why is pd.to_datetime() only changing type if utc is True?
<p>After loading my csv file into my notebook in VS Code i wanted to change the columns type from <code>object</code> to <code>datetime</code> for some columns. So i did the following:</p> <h2>object values of columns</h2> <p>These are example values in the columns.</p> <pre><code>my_col_1 -&gt; 2022-02-07 20:19:04+01:...
<p>So here is my Solution. Converting it with <code>dt.tz_convert('Europe/Berlin')</code> does the job. So i guess there is no way around to just take the already given <code>+01:00</code> value. Turn the Column with <code>to_datetime</code> to UTC <code>+00:00</code>and afterwards you have to convert it to your Timezo...
python|pandas|jupyter-notebook|jupyter
1
11,760
51,710,566
python arrays: averaging slope and intercept of datasets
<p>I am having some difficulties achieving the following. Let's say I have two sets of data obtained from a test: </p> <pre><code> import numpy as np a = np.array([[0.0, 1.0, 2.0, 3.0], [0.0, 2.0, 4.0, 6.0]]).T b = np.array([[0.5, 1.5, 2.5, 3.5], [0.5, 1.5, 2.5, 3.5]]).T </code></pre> <p>where the data in ...
<p>You can get the coefficients (slope and intercept) of each dataset, obtain the mean, and fit that data to a new array of x values.</p> <h1>Step by Step:</h1> <p>Fit deg-1 polynomial to each array <code>a</code>, and <code>b</code> using <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.polyf...
python|python-3.x|numpy
2
11,761
51,889,928
pandas: Set zero values of rows to the max value of that row of dataframe
<p>I'm working on a solution for modifying a dataframe using pandas. I have a dataframe like below which I need to change zero values of a row to maximum value of that row:</p> <pre><code> a b c 0 0 0 0.10 1 2.1 0 0 2 0 1.9 0 3 0 7.8 6.5 </code></pre> <p>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow noreferrer"><code>DataFrame.max</code></a>:</p> <pre><...
python-3.x|pandas|dataframe
2
11,762
51,805,352
Pandas: convert series of time YYYY-MM-DD hh:mm:ss.0 keeping the YYYY-MM-DD format only
<p>Pandas: convert series of time YYYY-MM-DD hh:mm:ss.0 keeping the YYYY-MM-DD format only</p> <p>python 3.6, pandas 0.19.0</p> <pre><code> timestamp 0 2013-01-14 21:19:42.0 1 2013-01-16 09:04:37.0 2 2013-03-20 12:50:49.0 3 2013-01-03 17:02:53.0 4 2013-04-13 16:44:20.0 </code></pre> <p>I tried:</p...
<p>it may satisfy your demand</p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d') </code></pre>
python-3.x|pandas|time
1
11,763
41,927,279
Python and associated Legendre polynomials
<p>I have been searching for a python implementation of the associated Legendre polynomials quite a long time and have found nothing satisfying me. There is an implementation in <code>scipy.special</code>, but it is not vectorized. I have found a solution to use <code>pygsl</code> interface with <code>gsl</code> librar...
<p><a href="https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.special.lpmv.html" rel="nofollow noreferrer">scipy.special.lpmv</a> is vectorized.</p>
python|numpy|scipy|scientific-computing
3
11,764
64,344,943
How do you switch single quotes to double quotes using to_tsv() when dealing with a column of lists?
<p>If I have a dataframe</p> <pre><code>df = pd.DataFrame({0: &quot;text&quot;, 1: [[&quot;foo&quot;, &quot;bar&quot;]]}) df 0 1 0 text [foo, bar] </code></pre> <p>And I write the df out to a tsv file like this</p> <pre><code>df.to_csv('test.tsv',sep=&quot;\t&quot;,index=False,header=None, doublequote...
<p>Try with <code>json.dumps</code></p> <pre><code>import json df[1]=df[1].map(json.dumps) </code></pre> <p>Then</p> <pre><code>df.to_csv('test.tsv', sep=&quot;\t&quot;, index=False, header=None, doublequote=True, quoting=csv.QUOTE_NONE) </code></pre>
python|pandas
1
11,765
49,245,392
Pandas merge: combining column values & merging new column values to the same row
<p>I'm uncertain whether one method, or even the practice of merging dataframes, can achieve my intentions below- or whether I need to resort to writing my own functions using for loops. </p> <p>I want to progressively build up a master dataframe comprising all possible column values from a number of smaller dataframe...
<p>Let's try <code>concat</code> + <code>groupby</code> + <code>agg</code>:</p> <pre><code>df = pd.concat( [df_master, df_lunch, df_ingredients, df_breakfast] ) g = df.groupby('Names', sort=False, as_index=False).agg(lambda x: ','.join(x.dropna())) g['Age'] = df_lunch['Age'] Names Breakfast Dinner Hair ...
python|pandas|merge
2
11,766
49,135,606
Transpose only one level of a pandas MultiIndex dataFrame
<p>I am trying to reformat a DataFrame, turning values in a row into columns. I tried using melt but just got errors. Transpose seemed to get me part of the way there, but gave weird output (because the input was a grouped DataFrame I think) </p> <pre><code>d = {'name':['bil','bil','bil','jim'], 'col2': ['acct',...
<p>You can use <code>first</code> directly. Also, you'll need <code>unstack</code> with a custom <code>fill_value</code>:</p> <pre><code>(df2.groupby(['name', 'col2'])['col3'] .first() .unstack(fill_value='') .rename_axis(None, 1)) acct acct2 law name bil 1 3 2 jim ...
python|pandas|dataframe|multi-index
3
11,767
58,892,390
How do you create a new column whose values are the hex strings of an existing ByteArray column?
<p>I have a dataframe that currently looks like this: </p> <pre><code>Date ByteArray 1/2/2019 bytearray([21,24,120,3,32,32,0,215]) 2/1/2019 bytearray([24,22,115,4,35,31,0,216]) </code></pre> <p>My goal is to get to get a dataframe that looks like this:</p> <pre><code>Date ByteArray ...
<p>There might be a better (faster) way using built-in Pandas functions that I'm not aware of, but with <code>apply</code>, you can apply an arbitrary Python function to your data. The code below simply applies the code snippet you provided to each element in your column:</p> <pre><code>df['Hex String'] = df['ByteArra...
python|pandas
3
11,768
58,907,121
Is there a way to make my attributes using tensorflow?
<p>I wonder if there is a way for me to make my attributes (or attribute) using tensorflow model. For an example, if I want to generate following attributes array using tensorflow model </p> <ul> <li>Input : An Image</li> <li>Output : Attribute Array [image mean, image std, image entropy, sum of image edge values] </...
<pre><code>I found the answer myself. Answering it as I now understand the question was confusing Machine learning algorithms require well-designed attributes. Their performance highly depend on the attributes. Normally we must write some code to read an input &amp; calculate an attribute. My question was whether this...
tensorflow|attributes
0
11,769
58,924,758
Python 3.6: Creating a pivot table summarizing counts of values for multiple columns in dataframe
<p>I have the following data frame:</p> <pre><code>df = pd.DataFrame({'X': ['Agree', 'Disagree', 'Agree', 'Neutral', 'Agree','Neutral'], 'Y': ['Disagree', 'Neutral', 'Agree', 'Disagree', 'Agree', 'Neutral'], 'Z': ['Agree', 'Neutral', 'Neutral', 'Disagree', 'Neutral','Neutral']}) </code><...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> + <code>pd.value_counts</code>:</p> <pre><code>new_df=df.apply(pd.value_counts) print(new_df) X Y Z Agree 3 2 1 Disagree 1 2 1 ...
python|pandas|dataframe|pivot-table|python-3.6
1
11,770
58,826,572
Numpy library not resolving in Pycharm
<p>I'm using PyCharm: </p> <pre><code>PyCharm 2019.2.4 (Community Edition) Build #PC-192.7142.42, built on October 31, 2019 Runtime version: 11.0.4+10-b304.77 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o macOS 10.15.1 </code></pre> <p>And I'm having troubles to import numpy library.</p> <pre><code>import n...
<p>A gray import in PyCharm is usually just an import you're not using in your code. If that's the only line of code using <code>np</code>, no errors (exit code 0) actually means the import was a success</p> <p>Hovering over marked code (gray or underlined) with your mouse, will show you what it means</p>
python|numpy|pycharm
2
11,771
58,730,460
Freeze sublayers in tensorflow 2
<p>I have a model which is composed of custom layers. Each custom layer contains many tf.keras.layers. The problem is that if I want to freeze those layers after defining my model, the loop:</p> <pre><code>for i, layer in enumerate(model.layers): print(i, layer.name) </code></pre> <p>only prints the "outer" custo...
<p>You can use keras callbacks. If you want to freeze your first layer after some certain amount of epochs, add this callback</p> <pre class="lang-py prettyprint-override"><code> class FreezeCallback(tf.keras.callbacks.Callback): def __init__(self, n_epochs=10): super().__init__() self.n_epochs = n...
tensorflow|keras|keras-layer|tf.keras
1
11,772
70,116,617
Is there a way to pivot a datetime column in a dataframe into columns with the months with Python?
<p>I have the next problem with a dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Product</th> <th>Arrive Time</th> </tr> </thead> <tbody> <tr> <td>00001</td> <td>2021-1-25</td> </tr> <tr> <td>00002</td> <td>2021-2-25</td> </tr> <tr> <td>00003</td> <td>2021-3-25</td> </tr> <tr> <t...
<p>Use <code>crosstab</code>:</p> <pre><code>&gt;&gt;&gt; pd.crosstab(df['Product'], df['Arrive Time'].dt.strftime('%B')) \ .astype(bool).replace({True: 'Yes', False: 'na'}) Arrive Time April February January March Product 1 Yes na Yes na 2 Ye...
python|pandas
1
11,773
70,176,218
python pandas how to multiply columns by other values in different dataframe
<p>I have 2 DataFrames:</p> <p><code>df1</code> (original has about 3000 rows x 200 columns: 190 to add and multiply, rest has some other information):</p> <pre><code> tag A35 A37 A38 ITEM B1 SAS 8.0 3.0 1.0 B2 HTW 1.0 3.0 3.0 B3 ASD 0.0 8.0 0.0 B4 ...
<p>Use <code>dot</code> for the multiplication and <code>join</code> to <code>df1</code>:</p> <pre><code>#set indices if needed df1 = df1.set_index(&quot;ITEM&quot;) df2 = df2.set_index(&quot;prices&quot;) output = df1.join(df1.drop(&quot;tag&quot;, axis=1).dot(df2).add_suffix(&quot;_price&quot;)) &gt;&gt;&gt; output...
python|pandas|dataframe
5
11,774
70,333,362
Acess a dataframe in dictionaries
<p>Morning,</p> <p>I have a dictionary that contains pairs of 1 keys and 2 values, at those values are dataframes</p> <pre><code>dictionary = {'key_1' : [df_1, df_2], 'key_2' : [df_3, df_4], ....} </code></pre> <p>I want to create a new data frame (named using the key) that merges the two values of each ke...
<p>Not certain I'm understanding the question correctly, but I think you may want to do something like this.</p> <pre><code>merged_df_list = [] for key in dictionary.keys(): df1, df2 = dictionary[key][0], dictionary[key][1] key = pd.merge(left = df1, right = df2, how = &quot;left&quot;, on = &quot;column_name&q...
python|pandas|loops|dictionary|merge
1
11,775
56,348,561
How to merge a grouped and aggregated df?
<p>I have grouped and aggregated transactions per account number (to calculate monthly statisitics) and now I want to merge the output with another dataframe on account numbers. The account numbers are however no longer in the index/columns.</p> <h1>Group transactions per account and month and perform aggregated calcul...
<p>You need to keep account number in your df1 because without it you can not join.</p> <p>If you don't need it in your final df you can drop it with</p> <pre><code>df3 = df3.drop("AcctNr", axis=1) </code></pre>
pandas-groupby
0
11,776
56,013,696
numpy - broadcasting an operation over dimensions on which two arrays match
<p>I have two arrays, <code>x</code> and <code>y</code>, where <code>x.shape == (n, d)</code> and <code>y.shape == (k, d)</code>.</p> <p>I'd like to produce an array z where <code>z.shape == (n, k)</code> and <code>z[i][j] = np.linalg.norm(x[i] - y[j])</code>. </p> <p>Is there any reasonable, vectorized way to do thi...
<p>You can use <code>np.linalg.norm(np.expand_dims(x, 1) - y, axis=-1)</code>.</p> <p>For example,</p> <pre><code>In [15]: d = 2 In [16]: n = 3 In [17]: k =...
python|arrays|python-3.x|numpy|vectorization
1
11,777
56,113,588
Datetime plotting traceback uninformative
<p>I was using PyCharm's SciView plotter (I think it is an matplotlib backend), but as it does not enable zooming panning and other functions, I disabled it. Now I get the following error thrown:</p> <pre><code>ValueError: view limit minimum -1.0 is less than 1 and is an invalid Matplotlib date value. This often happe...
<p>The traceback does show the line that causes the interpreter error, even if it is not in your source. Stepping through your code to reveal an error-causing state is how you find the problem. </p> <p>The PyCharm debugger makes this less tedious. Use the "step into" function with your variables as watches until you r...
python|pandas|matplotlib|seaborn
0
11,778
55,682,792
Aggregation on id and append different values in different columns pandas
<p>I have a pandas dataframe like below:</p> <pre><code>id c1 c2 c3 1 5 text1 -4 2 8 text2 -1 1 4 text1 0 2 7 text2 -8 3 2 text3 -5 1 2 text1 -8 ... </code></pre> <p>then, this is my desire output:</p> <pre><code>id c2 c3 c4 c5 1 text1 -4 ...
<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> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFr...
python|pandas
2
11,779
55,693,103
iterate over df and output dictionary with list of values
<p>I need to convert a dataframe to a dictionary but can't get all of the values from the dataframe to appear within the dictionary. </p> <p><strong>dataframe:</strong> </p> <pre><code>id| region | Num | --|--------|-----| 2 | NYC |2344 | 3 | NYC |3243 | 4 | NYC |3253 | 5 | NYC |2345 | 6 | CHI |8756 |...
<p>Use <code>groupby.apply(list)</code> then <code>.to_dict</code></p> <pre><code>df.groupby('region')['Num'].apply(list).to_dict() </code></pre> <p>[out]</p> <pre><code>{'ATL': [1234], 'CHI': [8756, 9786, 7674, 6678], 'NYC': [2344, 3243, 3253, 2345]} </code></pre>
python|pandas|dictionary
5
11,780
55,747,344
pandas pivot_table() puts an unwanted column in my dataframe when I write it to excel why?
<p>I am making a pivot table from an excel sheet with dozens of columns. I get a 3rd column from the excel sheet even though it's not in my code anywhere.</p> <p>Data looks like this</p> <p>Source IP, Destination IP,Zones,Connections,P/D,Comments,Location, Hours,BACKUP,DATACOURCE<p> 1.1.1.1,2.2.2.2,DATACENTER,3,P,Dec...
<p>If you can add some more source data to get us to expected results that may be helpful. My guess is that what you're getting is because you're not excluding the &quot;connections&quot; column anywhere. Read Excel will pull all columns by default, if that column is in your dataframe the pivot_table is most likely d...
python|python-3.x|pandas|pivot-table
2
11,781
64,876,434
Need to access the index of my excel using pandas python, I wanna print who and how much sold the most
<p>so... I have this excel sheet, I have 4 employees with certain amounts of sells, I know how to print the biggest number, but I also wanna print who achieved it.</p> <pre><code> Employee Total Sells 0 Carlos 205301 1 Fernanda 204982 2 Theo 272816 3 Raquel 172700 </code></pre> <p>Alright, wh...
<p>Use -</p> <pre><code>sheet.loc[sheet['Total Sells'].idxmax(), 'Employee'] </code></pre> <p><strong>Output</strong></p> <pre><code>'Theo' </code></pre> <p>To print the entire row, just use -</p> <pre><code>sheet.loc[sheet['Total Sells'].idxmax(), :] </code></pre>
python|python-3.x|pandas|dataframe|data-science
0
11,782
64,637,206
BeautifulSoup4 and Pandas, follow links in table to download another table, concatenate tables into one Dataframe
<blockquote> <p>Note: The question and code has been heavily edited as there were errors in my original posting and I tried the suggested answer but all the values were placed in one column of a dataframe.</p> </blockquote> <p>I followed this answer: <a href="https://stackoverflow.com/a/64636320/13865853">https://stack...
<p>in the last line of your first solution instead of printing the list create dataframe from the list:</p> <pre><code>df = pd.DataFrame(en_stuff) </code></pre>
python|pandas|beautifulsoup
0
11,783
64,626,087
Using numpy, how do you calculate snowfall per month?
<p>I have a data set with snowfall records per day for one year. Date variable is in YYYYMMDD form.</p> <pre><code>Date Snow 20010101 0 20010102 10 20010103 5 20010104 3 20010105 0 ... 20011231 0 </code></pre> <p>The actual data is here</p> <p><a href="https://github.com/emily737373/emily737373/blob/master/C...
<p>I hope you can use some built-in packages, such as <code>datetime</code>, cause it's useful when working with datetime objects.</p> <pre><code>import numpy as np import datetime as dt df = np.genfromtxt('test_files/COX_SNOW-1.csv', delimiter=',', skip_header=1, dtype=str) date = np.array([dt.datetime.strptime(d, &...
python|arrays|numpy|snow
2
11,784
64,867,781
Pytorch BiDirectional RNN not working: RuntimeError: Expected hidden[0] size (2, 76, 6), got (2, 500, 6)
<pre><code>class BiLSTMnetwork(nn.Module): def __init__(self, in_features, hidden_sz=6, p=0.5, out_features=2): #def __init__(self, embedding_dim, hidden_dim, vocab_size, target_size): super(BiLSTMnetwork, self).__init__() self.hidden_sz = hidden_sz self.in_features = in_features ...
<p>for BiLSTM , got to set batch_first = False. Many thanks even though I don't know exactly why.</p>
python|pytorch|recurrent-neural-network
0
11,785
65,023,408
creating nested loop with dict data type
<p>I'm running a loop to calculate <code>abs(x-y)</code> for <code>n</code> trials</p> <p>my code:</p> <pre><code>for i in P0: answer = (i['x']-i['y']) A = (abs(answer)) </code></pre> <p>returns the values for <code>P0</code></p> <p><code>P0</code> is the positions data for the first trial (<code>P0 = T0['pos...
<p>in your case <code>i</code> (the first one) is actually <code>Ti</code> you are searching for. try this:</p> <pre><code>for Ti in T: Pi = Ti['positions'] for i in Pi: answer = (i['x']-i['y']) A = (abs(answer)) </code></pre>
python|numpy|for-loop|statistics|nested-loops
0
11,786
39,939,723
Sum data points from individual pandas dataframes in a summary dataframe based on custom (and possibly overlapping) bins
<p>I have many dataframes with individual counts (e.g. <code>df_boston</code> below). Each row defines a data point that is uniquely identified by its <code>marker</code> and its <code>point</code>. I have a summary dataframe (<code>df_inventory_master</code>) that has custom bins (the <code>point</code>s above map to ...
<p>Here is how I approached it, basically a *sql style left join * using the pandas merge operation, then apply() across the row axis, with a lambda to decide if the individual records are in the band or not, finally groupby and sum: </p> <pre><code>df_merged = df_inventory_master.merge(df_boston, on=['Marker'],how...
python|python-3.x|pandas|dataframe
1
11,787
44,112,360
tranpose of multidimension with permute the axes
<p>For higher dimensional arrays, transpose will accept a tuple of axis numbers to permute the axes (for extra mind bending):</p> <pre><code>In [115]: arr = np.arange(16).reshape((2, 2, 4)) In [116]: arr Out[116]: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]]) In [117]: arr.transpose((...
<p>The default transpose is to reverse the axes, so an <code>A x B</code> matrix becomes <code>B x A</code>. For 3D, the default would be to transpose <code>A x B x C</code> to <code>C x B x A</code>.</p> <p>In your example, <code>transpose(1, 0, 2)</code>, it will transpose <code>A x B x C</code> to <code>B x A x C<...
python|numpy|transpose
1
11,788
69,453,613
Scale an array with zero values in numpy python
<p>I have an array like this:</p> <pre><code>[[1 2 3 4] [9 8 7 6]] </code></pre> <p>and want to upscale like this:</p> <pre><code>[[1 0 0 2 0 0 3 0 0 4 0 0] [0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0] [9 0 0 8 0 0 7 0 0 6 0 0] [0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0]] </code></pre> <p>Try with...
<p>You can just use assignment here. If <code>n</code> might be different for width and height, just index using <code>result[::h, ::w]</code>.</p> <pre><code>n = 3 result = np.zeros(np.array(a.shape) * n, dtype=int) result[::n, ::n] = a </code></pre> <hr /> <pre><code>array([[1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0], ...
python|numpy
4
11,789
41,156,460
tensorflow doing gradients on sparse variable
<p>I am trying to train a sparse variable in tensorflow, As far as I know current tensorflow doesn't allow for sparse variable. </p> <p>I found two threads discussing similar issue: <a href="https://stackoverflow.com/questions/37001686/using-sparsetensor-as-a-trainable-variable">using-sparsetensor-as-a-trainable-varia...
<p>I'm not familiar with IndexedSlices or sparse variables, but what I gather is that you are trying to only apply a gradient update to certain slices of a Variable. If that is what you are doing, then there is an easy workaround: extract a copy of the Variable with</p> <pre><code>weights_copy = tf.Variable(weights_va...
tensorflow|sparse-matrix
1
11,790
66,174,756
calculating sum of specific rows in excel sheet using pandas
<p>hi:) i'm a newbie at python and would like to ask for help to calculaate the sum of specific rows in an excel worksheet. i've tried searching for help online however, all examples given were different to my situation, so i found it difficult to modify the code to my needs. this is the code i've used. (need to calcul...
<p>You could do this:</p> <pre><code>df[df[&quot;country&quot;] == &quot;Malta&quot;][&quot;AirPollutionLevel&quot;].sum() </code></pre> <p>Steps in the code above:</p> <ul> <li>Grab all the rows where country equals Malta</li> <li>Grab the AirPollutionLevel column of this subset</li> <li>Sum it!</li> </ul>
python|excel|pandas
1
11,791
52,779,736
TFDV Tensorflow Data Validation: how can I save/load the protobuf schema to/from a file
<p>TFDV generates schema as a Schema protocol buffer. However it seems that there is no helper function to write/read schema to/from a file.</p> <pre><code>schema = tfdv.infer_schema(stats) </code></pre> <p>How can I save it/load it ?</p>
<p>You can use the following methods to write/load the schema to/from a file. </p> <pre><code>from google.protobuf import text_format from tensorflow.python.lib.io import file_io from tensorflow_metadata.proto.v0 import schema_pb2 def write_schema(schema, output_path): schema_text = text_format.MessageToString(sche...
python|tensorflow|protocol-buffers|tensorflow-data-validation
6
11,792
52,500,199
Indexing numpy matrix
<p>So lets say I have a <code>(4,10)</code> array initialized to zeros, and I have an input array in the form <code>[2,7,0,3]</code>. The input array will modify the zeros matrix to look like this:</p> <pre><code>[[0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1,0,0], [1,0,0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0,0]] </code></p...
<p>You only wish to update one column for each row. Therefore, with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">advanced indexing</a> you must explicitly provide those row identifiers:</p> <pre><code>A = np.zeros((4, 10)) A[np.arange(A.sh...
python|arrays|python-3.x|numpy|matrix
1
11,793
58,579,476
Extracting specific rows in numpy array using Numba
<p>I have the following array:</p> <pre><code>import numpy as np from numba import njit test_array = np.random.rand(4, 10) </code></pre> <p>I create a "jitted" function that slices the array and does some operations afterwards:</p> <pre><code>@njit(fastmath = True) def test_function(array): test_array_sliced ...
<p>I think it will work (it seems to suggest so <a href="https://numba.pydata.org/numba-doc/dev/reference/numpysupported.html#array-access" rel="nofollow noreferrer">in the docs</a>) if you index with an array instead of a list:</p> <pre><code>test_array_sliced = array[np.array([0,1,3])] </code></pre> <p>(I changed t...
python|numpy|numba
2
11,794
69,131,598
how to solve "If using all scalar values, you must pass an index" problem pandas
<p>Following my previous <a href="https://stackoverflow.com/questions/68962900/how-to-put-data-into-excel-table-with-for-loop-pandas">question</a> , all is working well but when the list it's long it's showing this erreur, This is a simple of d :</p> <pre><code>['Houda Golf &amp; Aquapark Novostar Monastir ', &quot; {...
<p>Try to convert the values of dictionary to <code>list</code> if they are scalars:</p> <pre class="lang-py prettyprint-override"><code>from ast import literal_eval vals = literal_eval(d[1].strip()) df = pd.DataFrame( {k: v if isinstance(v, (list, tuple)) else [v] for k, v in vals.items()} ) print(df) </code></p...
python|pandas|web-scraping|indexing|scalar
1
11,795
69,259,998
Share X axis of two pandas series' plots
<p>I have two pandas series. I need to plot them with shared X axis stacked on each other. I tried the code below but instead of stacking them it rather puts the two lines on the same plot. Why is that? How can I stack them?</p> <pre><code>n=10 x = pd.Series(data = np.random.randint(0,10, n), index=pd.date_range(pd.to_...
<p>Use <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer"><code>subplots</code></a> to create shared axis:</p> <pre><code>fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) x.plot(ax=ax1) y.plot(ax=ax2) plt.show() </code></pre>
python|pandas|matplotlib|plot
1
11,796
68,981,831
Tensorflow 2.0 syntax change
<p>I have the following lines of codes that i would like to run and it's written based on the tensorflow 1.0 syntax:</p> <pre><code>import tensorflow as tf a = tf.constant(5) b = tf.constant(2) c = tf.constant(3) d = tf.multiply(a,b) e = tf.add(b,c) f = tf.subtract(d,e) with tf.Session() as sess: fetches = [a,b,c,...
<p>try to use <code>tf.compat.v1.Session</code> inplace of <code>Session</code> other than this for more doubts you can refer to tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session</a></p>
python|tensorflow|tensorflow2.0
1
11,797
69,072,625
Dataframe did not insert into DB but throws DPI Not connected error
<p>I need to insert a dataframe into oracle sql and fastest method I could found was sqlalchemy but this doesn't seem to work in my favor.</p> <p>My code :</p> <pre><code>import pandas as pd from sqlalchemy.engine import create_engine from sqlalchemy import types import cx_Oracle DIALECT = 'oracle' SQL_DRIVER = 'cx_o...
<p>By default, <code>cx_oracle</code> rollbacks any transaction without explicit commit.</p> <blockquote> <p><strong>Autocommitting mode</strong></p> <p>The Connection object has an attribute called <strong>autocommit</strong> that allows you to commit the transaction automatically. By default, its value sets to False....
python|pandas|oracle|dataframe|sqlalchemy
1
11,798
44,557,427
Translational equivariance and its relationship with convolutonal layer and spatial pooling layer
<p>In the context of convolutional neural network model, I once heard a statement that:</p> <blockquote> <p>One desirable property of convolutions is that they are translationally equivariant; and the introduction of spatial pooling can corrupt the property of translationally equivalent.</p> </blockquote> <p>W...
<p>Most probably you heard it from <a href="http://www.deeplearningbook.org/" rel="nofollow noreferrer">Bengio's book</a>. I will try to give you my explanation.</p> <hr> <p>In a rough sense, two transformations are equivariant if <code>f(g(x)) = g(f(x))</code>. In your case of convolutions and translations means tha...
math|machine-learning|tensorflow|computer-vision|deep-learning
4
11,799
61,128,502
Troubles with bazel and building tensorflow on ubuntu
<p>I'm trying to build tensorflow on ubuntu using bazel, I failed using bazelisk and bazel. There is some silly bug with the installer. I'm really having hard time because of the awful documentation of building tensorflow from source found <a href="https://www.tensorflow.org/install/source" rel="nofollow noreferrer">he...
<p>Your checkout of the Tensorflow source code requires Bazel 2.0.0, because of the use of the <code>--experimental_repo_remote_exec</code> flag. </p> <p>Also see <a href="https://github.com/tensorflow/tensorflow/issues/37474" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/37474</a></p> <p>...
tensorflow|build|bazel
1