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
375,100
69,661,091
X axis label and minor tick labels do not show on Pandas scatter plot
<p>I have created a new environment with Python 3.8.12 and installed the following packages:</p> <ul> <li><code>matplotlib</code> (3.4.3)</li> <li><code>pandas</code> (1.3.3)</li> <li><code>scikit-learn</code> (0.24.2)</li> </ul> <p>I am running the code in a Jupyter notebook.</p> <p>I am using code from two examples i...
<p>This is a known and open issue with Pandas when using the matplotlib backend in Jupyter (noteboooks).</p> <blockquote> <p>This issue was reported and resolved in #10611 but returned with 0.24.0.</p> </blockquote> <p>see <a href="https://github.com/pandas-dev/pandas/issues/36064" rel="nofollow noreferrer">BUG: Scatte...
python|pandas|plot
0
375,101
69,342,255
How to use recursion to record all routes in a parent child hierarchy?
<p>I am trying to go through a hierarchy dataframe and record every possible routes into another dataframe. These routes can have variable depth.</p> <p>Original dataframe (df). The highest column means that the value in the parent column is not a child of any:</p> <div class="s-table-container"> <table class="s-table"...
<p>You can use <a href="https://networkx.org/" rel="nofollow noreferrer"><code>networkx</code></a> to solve the problem. Note if you use <code>networkx</code> you don't need the <code>highest</code> columns. The main function to find all paths is <a href="https://networkx.org/documentation/stable/reference/algorithms/g...
python|pandas|dataframe|recursion|hierarchy
4
375,102
69,474,172
How can I use pandas explode on string?
<p>I have the following dataFrame in pandas</p> <pre><code>df=pd.DataFrame({'questionId':[1, 2],'answer':['[&quot;Trustful&quot;, &quot;Curious&quot;, &quot;Nervous&quot;]', &quot;very good&quot;]}) df.explode('answer') </code></pre> <p>The actual answer:</p> <pre><code>questionId answer 0 1 [&quot;Trustful&quot;,...
<p>Try with <code>str.findall</code></p> <pre><code>s = df.answer.str.findall('&quot;([^&quot;]*)&quot;') out = df.assign(answer = np.where(s.astype(bool),s,df.answer)).explode('answer') out questionId answer 0 1 Trustful 0 1 Curious 0 1 Nervous 1 2 very good </co...
python|pandas
1
375,103
69,415,715
Pandas Pivot/Reshape/... GroupyBy rows to Columns
<p>[First off, these are my first &quot;real&quot; experiments with pandas, so the terminology in this question might be off.]</p> <p>I am working with the GHCN weather data (<a href="https://www.ncei.noaa.gov/data/global-historical-climatology-network-daily/" rel="nofollow noreferrer">https://www.ncei.noaa.gov/data/gl...
<p>You have the right terminology, and looking for <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.pivot.html" rel="nofollow noreferrer">pivot</a> in the docs would probably have led you straight to using:</p> <pre><code>&gt;&gt;&gt; df.pivot(index=['station', 'date'], columns='measure...
pandas|dataframe|pandas-groupby
1
375,104
69,306,245
How to find rows with duplicate values using pd.duplicated() and a date within +- 2 days Pandas Dataframe
<p>I have a pandas dataframe such as:</p> <pre><code> number GENDER DOB Code 0 500401081 M 1994-08-01 AP 1 500401094 F 1998-05-04 CB 2 500401081 M 1994-08-03 AP 3 500401096 M 1998-05-06 AP </code></pre> <p>I want all rows that have the ...
<p>You can sort the data by &quot;DOB&quot;, compute then difference between successive &quot;DOB&quot; per group and construct a mask if the difference is lower of equal 2 days:</p> <pre><code># group per number/GENDER group = df.groupby(['number', 'GENDER']).ngroup() # compute first mask mask = df.sort_values(by='DO...
python|pandas|duplicates
1
375,105
69,607,902
How to transform the following dataset for time series analysis?
<p><a href="https://i.stack.imgur.com/IDugj.jpg" rel="nofollow noreferrer">This is the dataset, I want to transform for time series forecasting. Here, the column names contains the store number.</a></p> <p>df=</p> <pre><code>| Date | store_1 |store_2 |store_3 |:---- |:------:| -----:|-----:| | 1-1-21 | 0.5 | 0.2 | ...
<p>Use <code>melt</code>:</p> <pre><code>out = df.melt(id_vars=['Date'], var_name='Store_number', value_name='Value') out['Store_number'] = out['Store_number'].str.extract(r'store_(\d+)') print(out) # Output: Date Store_number Value 0 1-1-21 1 0.5 1 1-2-21 1 0.3 2 1-3-21 ...
python|pandas|dataframe|time-series
2
375,106
69,316,778
How to create rows from pandas dataframe column value
<p>I want to create Dataframe rows using the value in the Dataframe column(<strong>Race, TGR1</strong>). I still have additional columns aside from <strong>Race, TGR1</strong> but the number of column values are the same. I can't think of the best possible way to achieve this.</p> <p>Any help would be greatly appreciat...
<p>You can use <code>apply</code>+<code>pd.Series.explode</code>. You first need to set aside the columns not to be exploded using <code>set_index</code>, then bring them back as columns with <code>reset_index</code>.</p> <pre><code>(df.assign(Race=df['Race'].str.split(','), TGR1=df['TGR1'].str.split(',')) ...
python|pandas|dataframe
1
375,107
69,390,591
mixing two sensors data in a dataframe regarding timestamp condition
<p>I would like to merge some data from different sensors regardin the Timestamp.</p> <p>I can be done by iterating the dataframe with an if condition on the timestamp, but it's not very efficient.. Does somebody have a better idea ?</p> <p>Here is a simple example with the result I expect :</p> <p>The sensor 1 worked ...
<p>why not filter by the index?</p> <pre><code>idx = pd.date_range(&quot;2018-01-01&quot;, periods=6, freq=&quot;H&quot;) df = pd.DataFrame(data={ 'sensor 1' :[5.4,5,5.2,3,2,2], 'sensor 2' : [-1,-2,-3,5.5,5.4,5.6]}, index=idx) date = datetime.datetime(2018, 1, 1,02) sens_1_data = df.loc[df.index &lt;= dat...
python|pandas|dataframe
1
375,108
69,589,226
TensorFlow Probability: Different log probabilities for Sequential vs Named JointDistributions?
<p>I'm fairly new to Bayesian estimation with TensorFlow. I was trying to set up a very simple regression of height on weight (using McElreath's <a href="https://github.com/rmcelreath/rethinking/blob/master/data/Howell1.csv" rel="nofollow noreferrer">Howell data</a>) to familiarize myself with the machinery in TensorFl...
<p>JDSequential &quot;pops&quot; distributions off a stack, so you need to reference them in reverse order. <a href="https://colab.research.google.com/gist/brianwa84/a47f4f43b1e58b9ac24ed34766478679/so69589226.ipynb" rel="nofollow noreferrer">https://colab.research.google.com/gist/brianwa84/a47f4f43b1e58b9ac24ed3476647...
python|tensorflow-probability|probability-distribution
0
375,109
69,613,766
ref() of tensor not equal in dataset. Why?
<p>I am very confused by the following behavior. Take this program:</p> <pre><code>import tensorflow_datasets as tfds # %% Train dataset (ds_train_original, ds_test_original), ds_info = tfds.load( &quot;mnist&quot;, split=[&quot;train&quot;, &quot;test&quot;], shuffle_files=True, as_supervised=True, ...
<p>After posting an <a href="https://github.com/tensorflow/tensorflow/issues/52537" rel="nofollow noreferrer">issue</a> on Github, it seems like the only viable solution is to compare the samples values, since only <a href="https://docs.python.org/3/library/weakref.html" rel="nofollow noreferrer">weakrefs</a> are creat...
tensorflow|tensorflow-datasets
0
375,110
69,361,063
Normalization of samples based on the controls when we have several groups
<p>Let's say we have the following DataFrame:</p> <pre><code>data = {'Compounds': ['Drug_A', 'Drug_A', 'Drug_A', 'Drug_A', 'Drug_A', 'Drug_A', 'Drug_B', 'Drug_B', 'Drug_B','Drug_B','Drug_B','Drug_B','Drug_B','Drug_B','Drug_B','Drug_B','Drug_B','Drug_B', 'Drug_C', 'Drug_C','Drug_C',...
<p>Is this what you're looking for?</p> <pre><code>df.groupby(by=['identifier']).mean() Out: values identifier Control 30.384615 Sample 24.285714 </code></pre> <p>and then:</p> <pre><code>df.groupby(by=['identifier', 'Experiment']).mean() Out: values identi...
python|pandas|normalization
1
375,111
69,452,108
Save multiple dataframes into the environment in Python
<p>I have a similar problem with <a href="https://stackoverflow.com/questions/57452403/how-to-split-pandas-dataframe-into-multiple-dataframes-based-on-unique-string-va">this question</a> but the original question was to make multiple csv output. In my case, I am wondering if there's a way to make the multiple dataframe...
<p>You could use the same code as the link posted, but save the different dfs into a dictionary:</p> <pre><code>codes = ['US', 'MX', 'CA', 'AU'] result_dict = {} for code in codes: temp = df.query(f'country_code.str.match(&quot;{code}&quot;)') result_dict[code] = temp </code></pre>
python|pandas|f-string
1
375,112
69,311,721
Counting number of events on each user in two dataframe
<p>I'm attempting to count the number of events that occurred in the past for each user in a table. Actually, I have two dataframe, one for each user at a specific point 'T' in time and one for each event that also occur in time.</p> <p>This is the exemple of the user table:</p> <pre><code> ID_CLIENT START_DATE 0 ...
<p>I guess the slow exection is caused by <code>pd.apply(axis=1)</code>, which is explained <a href="https://towardsdatascience.com/avoiding-apply-ing-yourself-in-pandas-a6ade4569b7f" rel="nofollow noreferrer">here</a>.</p> <p>I estimate that you can improve the execution time by using functions that are not applied ro...
python|pandas
0
375,113
69,472,596
BCELoss().backward throws Runtime Error or doesn't train with Requires_grad
<p>I'm new to PyTorch and am running into an error with optimizing an <code>nn.Embedding</code> matrix.</p> <p>My code below, with given variables <code>embedding_dim</code>, <code>num_node</code>, <code>train_label</code> and <code>train_edge</code>:</p> <pre><code>emb = nn.Embedding(num_node, embedding_dim) optimizer...
<p>The error raises clearly due to <code>res</code> not having <code>.requires_grad</code> on.</p> <p>Since you are making a Tensor from a list of Tensors, its better to use <code>torch.cat</code> and not <code>torch.FloatTensor</code>. The latter is for <em>constructing</em> a tensor and do not have <code>.requires_gr...
python|pytorch
0
375,114
69,400,936
How to find the last date of the month from current month (excel version of EOMONTH) in PYTHON?
<p>my df currently consists of only date column</p> <pre><code>date 28/09/1995 30/10/1993 26/02/2021 04/04/2020 </code></pre> <p>I want to create 2 new columns called &quot;end of month&quot; which gives the last day of the month &amp; &quot;end of quarter&quot; which gives last day of quarter</p> <pre><code>date ...
<p>Try this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'date':['28/09/1995', '30/10/1993', '26/02/2021', '04/04/2020']}) df['date'] = pd.to_datetime(df['date'], dayfirst=True) df['end of month'] = df['date'] + pd.offsets.MonthEnd(1) df['end of quarter'] = df['date'] + pd.offsets.QuarterEnd(1) date...
python|pandas|date|datetime|data-manipulation
1
375,115
69,660,627
Finding first occurrence of negative value in a row
<p>Say I have the following DataFrame:</p> <pre><code>df = pd.DataFrame({'a': [12, 34, -45], 'b':[-24, 36, 48], 'c':[28, -14, 68]}) </code></pre> <p>df:</p> <pre><code> a b c 12 -24 28 34 36 -14 -45 48 68 </code></pre> <p>I am looking to return the index(+1) of the first column to contain a n...
<p>If always exist at least one negative value use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmax.html" rel="nofollow noreferrer"><code>numpy.argmax</code></a> for first negative value less like <code>0</code>:</p> <pre><code>df['first_neg_col'] = np.argmax(df.lt(0).to_numpy(), axis=1) + 1 print...
python|pandas
1
375,116
69,568,271
Pandas how to squeeze duplicate rows into one row
<p>I have following dataframe</p> <pre><code>| name | value | | name_1 | A | | name_1 | B | | name_1 | C | </code></pre> <p>How to reshape dataframe to looks like</p> <pre><code>| name | value | | name_1 | A,B,C | </code></pre> <p>or</p> <pre><code> | name | value | | name_1 | [A,B,C] | </...
<p>Use <code>groupby.agg</code>:</p> <pre><code>&gt;&gt;&gt; df.groupby('name').agg(list) value name name_1 [A, B, C] &gt;&gt;&gt; </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; df.groupby('name').agg(', '.join) value name name_1 A, B, C &gt;&gt;&gt; </code></pre>
python|pandas
1
375,117
69,454,217
Op type not registered \'IO>BigQueryClient\' with BigQuery connector on AI platform
<p>I'm trying to parallelize the training step of my model with tensorflow <code>ParameterServerStrategy</code>. I work with GCP <code>AI Platform</code> to create the cluster and launch the task. As my dataset is huge, I use the bigquery tensorflow connector included in <code>tensorflow-io</code>.</p> <p>My script is ...
<p>I think this is due to lazy loading of libtensorflow_io.so. <a href="https://github.com/tensorflow/io/commit/85d018ee59ceccfae06914ec2a2f6d6583775ff7" rel="nofollow noreferrer">https://github.com/tensorflow/io/commit/85d018ee59ceccfae06914ec2a2f6d6583775ff7</a></p> <p>Can you try adding something like this to your c...
tensorflow|google-cloud-ml|google-cloud-ai
2
375,118
69,630,736
How to use Model Parallelism with a custom Tensorflow 2.0 model on TPUs?
<p>To replicate <a href="https://arxiv.org/abs/2106.13884" rel="nofollow noreferrer">Multimodal Few-Shot Learning with Frozen Language Models</a>, I am trying to train a ~7B parameter subclassed TF2 model on a TPUv3-32. Out of the 7B parameters, roughly 6B parameters are frozen.</p> <p>I want to use model and data para...
<p>According to the cloud TPU documents, there is no official support:</p> <blockquote> <p>Does Cloud TPU support model parallelism?</p> <p>Model parallelism (or executing non-identical programs on the multiple cores within a single Cloud TPU device) is not currently supported.</p> </blockquote> <p><a href="https://clo...
tensorflow|machine-learning|google-cloud-platform|deep-learning|tpu
2
375,119
69,563,301
How to group data by customized date logic?
<p>I have a dataframe that looks like this:</p> <pre><code>Date | Apples | Bananas etc 2020-01-01 | 2 | 5 2020-02-01 | 12 | 44 2020-03-01 | 4 | 45 </code></pre> <p>I want to create a grouping logic by date but the date must be transformed to the following:</p> <p>If the Date is on or after February ...
<p>You could use <code>np.where</code> to do a conditional date offset.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Date': ['2020-01-01', '2020-02-01', '2020-03-01'], 'Apples': [2, 12, 4], 'Bananas': [5, 44, 45]}) df['Date'] = pd.to_datetime(df['Date']) # Add a year if the month is gre...
python|pandas
0
375,120
69,402,510
How to combine lists(first three columns) to generate output shown in last column in python
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>List1</th> <th>List2</th> <th>List3</th> <th><strong>output</strong></th> </tr> </thead> <tbody> <tr> <td>MAN</td> <td>TH</td> <td>ESE</td> <td>MAN-TH-ESE</td> </tr> <tr> <td></td> <td></td> <td>PA</td> <td>MAN-TH-PA</td> </tr> <tr> <td>PWP</td> <...
<p>Replace empty space by missing values, forward filling them and last join together:</p> <pre><code>df['output'] = df[['List1','List2','List3']].replace('',np.nan).ffill().apply('-'.join, 1) </code></pre> <p>If need join all columns:</p> <pre><code>df['output'] = df.replace('',np.nan).ffill().apply('-'.join, 1) </cod...
python|pandas|dataframe|loops|conditional-statements
1
375,121
69,356,473
split strings in a cell into different row, pandas
<p>I need to split this cell in different rows in pandas dataframe, basically splitting strings but ignoring the comma inside quotes.</p> <pre><code>'one two three', 'don't split, this' </code></pre> <p>output would be like:</p> <pre><code>'one two three' 'don't split, this' </code></pre> <p>Thanks in advance</p>
<p>Why not just use:</p> <pre><code>df['col'].str.split(r&quot;(?&lt;=')[,(\s|)](?=')&quot;) </code></pre> <p>Or if there always be a space after the comma, do:</p> <pre><code>s.str.split(r&quot;(?&lt;='), (?=')&quot;) </code></pre>
python|regex|pandas
0
375,122
69,581,447
Inconsistent behaviour with numpy broadcasting while creating array of array
<p>If I'm trying to execute :</p> <pre><code>a = np.ones((1, 2)) b = np.ones((1, 3)) np.array([a, b], dtype=np.ndarray) </code></pre> <p>I get the following error :</p> <pre><code>ValueError: could not broadcast input array from shape (2,) into shape (1,) </code></pre> <p>But I'm would like to get :</p> <pre><code>arr...
<p>Based on @hpaulh comments, this works:</p> <pre><code>import numpy as np a = np.ones((1, 2)) b = np.ones((1, 3)) test = np.empty((2,), dtype=np.ndarray) test[0] = a test[1] = b </code></pre> <p>returns</p> <pre><code>array([array([[1., 1.]]), array([[1., 1., 1.]])], dtype=object) </code></pre>
python|numpy|numpy-ndarray
1
375,123
69,343,401
Is it possible to convert numbers in an array to tuple enumerating with python?
<p>I have an example array:</p> <pre><code>&gt;&gt;&gt; arr = np.array([[2, 4, 1], [3, 4, 2], [3, 6, 1]]) &gt;&gt;&gt; arr array([[2, 4, 1], [3, 4, 2], [3, 6, 1]]) </code></pre> <p>Desired output:</p> <pre><code> array([[(0, 2), (1, 4), (2, 1)], [(0, 3), (1, 4), (2, 2)], [(0, 3), ...
<p>Usually you don't have tuples in a numpy array. Your output is basically what you desire but as lists and not as tuples. You can use a workaround like shown <a href="https://stackoverflow.com/questions/47389447/how-convert-a-list-of-tupes-to-a-numpy-array-of-tuples">here</a>:</p> <pre><code>import numpy as np def r...
python|arrays|numpy
3
375,124
69,467,339
What is the purpose of the view() method in numpy
<p><strong>Code 1</strong></p> <pre><code>arr = np.array([1, 2, 3]) arr2 = arr.view() </code></pre> <p><strong>Code 2</strong></p> <pre><code>arr = np.array([1, 2, 3]) arr2 = arr </code></pre> <p>Both of these snippets have the same functionality, so why do we actually need the <code>view</code> method in NumPy if we c...
<p>Even without using the things <code>view</code> lets you do, the semantics are different.</p> <pre><code>arr2 = arr </code></pre> <p>This assigns a reference to the original array to a different name. Any change you make to <code>arr2</code> short of reassignment will show up when you access <code>arr</code>.</p> <p...
python|numpy
2
375,125
69,566,433
Export final data from numpy to excel
<p>here I used panda for export my data which is located in numpy array. but there is a problem that I cant export my data and also there is a erroe that you can see below.</p> <p>valueError: Must pass 2-d input</p> <p>this is my main variable AccZONE=c.T and The type of that is Array Of float64, and the size Of That i...
<p>From the error it looks like the array is 3 dimensions, you need to change it to 2 dimensions, it would be nice if you could provide some code.</p> <p>You can try <code>np.reshape(arr,(-1,1))</code> or <code>np.ravel(arr)</code>.</p>
python|numpy
0
375,126
69,353,179
Can one add the output of a function in Python as a column to a dataframe
<p>I have an array of countries. I would like to run this array through a function and append the output of the function as a column to a dataframe.</p> <p>I used the <code>apply</code> method but keep getting a <code>KeyError</code>. I am not sure what I am doing wrong.</p> <p><strong>Code</strong></p> <pre><code>impo...
<p>Yes, you can use a function. You were almost there. If your function takes a single argument, and you are applying to a column, there's no need to add the argument. If you want to use multiple args, you can combine apply and lambda.</p> <p>No need for lambda in your case, This should solve it:</p> <pre><code>data = ...
python|pandas|dataframe|apply|pycountry-convert
1
375,127
69,325,728
Using a loop to select multiple columns from a pandas dataframe
<p>I am trying to create a <code>DataFrame</code> that only has certain columns from a previously created dataframe using a loop.</p> <p>I have the following dataframe:</p> <pre><code> Time Amount Amount i=2 Amount i=3 Amount i=4 0 20 10 20 20 20 1 10 5 10 ...
<p>You can do something like this if you want to use a loop</p> <pre><code>df1 = df[['Time','Amount'] + ['Amount i={}'.format(i) for i in range(2,4)]] </code></pre>
python|pandas|loops
2
375,128
69,413,567
filename as key in dictionary - pandas
<p>I have around 100 .csv files in a folder.<br/> They are named like AA.csv, BB.csv, CC.csv.....<br/></p> <p>I have used the below command to load all the files into the dataframe</p> <pre><code>import pandas as pd import glob df = pd.concat(map(pd.read_csv, glob.glob('/Users/redman/stock-data/*.csv'))) </code></pre>...
<p>We can use a dictionary comprehension:</p> <pre><code>import glob import pandas as pd d = {f: pd.read_csv(f) for f in glob.glob('/Users/redman/stock-data/*.csv')} </code></pre> <p>We can use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem" rel="nofollow noreferrer"><code>Path.ste...
python|pandas|dataframe
4
375,129
69,322,880
Bokeh remove gaps in datatime axis when date is mising
<p>I trying to plot chandlestick with the OHLC data that I have. The data come from 5 minute timeframe resample to 4 hour timeframe, so there will be huge gap on weekends.</p> <pre class="lang-py prettyprint-override"><code># Load data subdata = pd.read_csv( 'data/M5/EURUSD.csv', header = None, skiprows = 0, se...
<p>After trial and error, I finally found the root of the problem. When changing xaxis to <code>enumerate(subdata.index)</code> it means xaxis uses numbers instead of datetime. But i still use datetime to make plots that are supposed to use numbers, and here comes the weird thing. Why is bokeh still receiving xaxis dat...
python|pandas|bokeh
1
375,130
69,360,657
Date extraction without "T00:00:00" and formated as %d/%m/%Y
<p>I have been working on a huge text file. Where I want to read and cut it with pandas.</p> <p>Here is a sample of the raw file:</p> <pre><code>Date;Time;GHI;DNI;DIF;flagR;SE;SA;TEMP;AP;RH;WS;WD;PWAT 01.01.1994;00:07;0;0;0;0;-41.92;-19.43;14.3;1004.4;93.4;0.3;189;17.7 01.01.1994;00:22;0;0;0;0;-40.65;-23.70;14.3;1004.4...
<p>That's how VScode Data Viewer views date, it doesn't mean it's this way actually.</p> <p>So, you can change the format of your <code>Date</code> column by replacing it with this:</p> <pre><code>file[&quot;Date&quot;] = pd.to_datetime(file['Date'], format='%d.%M.%Y').dt.strftime('%d/%m/%Y') # write dataframe to CSV...
python|pandas|datetime|visual-studio-code
1
375,131
69,497,328
Why are torch.version.cuda and deviceQuery reporting different versions?
<p>I have a doubt about the CUDA version installed on my system and being effectively used by my software. I have done some research online but could not find a solution to my doubt. The issue which helped me a bit in my understanding and is the most related to what I will ask below is <a href="https://stackoverflow.co...
<p>PyTorch doesn't use the system's CUDA library. When you install PyTorch using the precompiled binaries using either pip or conda it is shipped with a copy of the specified version of the CUDA library which is installed locally in your environment. In fact, you don't even need to install CUDA on your system to use Py...
python|linux|pytorch|cuda|virtual-environment
5
375,132
69,523,275
How to efficiently filter two-dimensional np array by values given in a list (by many values)
<p>I have a two-dimensional np array and I need to efficiently filter it by values given in a list.</p> <pre><code>b = np.array([['a', 'b', 'c', 'd'], ['b', 'a', 'c', 'd'], ['c', 'b', 'a', 'd'], ['a', 'd', 'c', 'b']]) values_to_stay_in_b = ['a', 'b'] </code></pre> <p>I found solution with using set difference, but the ...
<p>Using pure numpy, so atleast removing for loops.</p> <p>For each entry in b, compare it with each entry in values_to_stay_in_b and get a mask list. This is done adding extra axis and comapring using broadcasting</p> <p>Any one in this need to be true.</p> <p>Since you clarify that after filtering each row has same c...
python|arrays|numpy
0
375,133
69,526,947
Confidence Interval 3 dimensional plot
<p>I have a 3-dimensional plot and I am able to plot it with the code written below.</p> <p>Considering that my point distribution is represented by a 100x100 matrix, is it possible to plot a confidence interval on my data? In the code below, my data are called &quot;result&quot;, while the upper bound and lower bound ...
<p>Check out this 3d surface plot using plotly graph objects:</p> <pre><code>import plotly.graph_objects as go import numpy as np x = np.arange(0.1,1.1,0.01) y = np.linspace(-np.pi,np.pi,100) X,Y = np.meshgrid(x,y) result = [] for i,j in zip(X,Y): result.append(np.log(i)+np.sin(j)) upper_bound = np.array(result)...
python|numpy|matplotlib|multidimensional-array|numpy-ndarray
1
375,134
69,327,200
Speed Up Python Function that Extracts Text from PDF
<p>I am currently working on a program that scrapes text from tens of thousands of PDFs of court opinions. I am relatively new to Python and am trying to make this code as efficient as possible. I have gathered from <em>many</em> posts on this site and elsewhere that I should be trying to vectorize my code, but I have ...
<p>I took the advice in the comments. I did not use pandas, used list comprehension, and rewrote this as:</p> <pre><code>def pdftotext(path): args = r'pdftotext -layout -q Temporary_Opinion.pdf Opinion_Text.txt' cp = sp.run( args, stdout=sp.PIPE, stderr=sp.DEVNULL, check=True, text=True ) re...
python|pandas|vectorization|coding-efficiency|pdftotext
0
375,135
69,444,086
Running loop for frequency calculation in Python
<p>I have the data as shown in the table. I want to use Python. For all the fruits that exist in the year 2016 and 2017, I want the frequencies of country in 2015 for those fruits.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Country</th> <th>Fruit</th> <th>Year</th> </tr> </thead> <tbod...
<p>Try:</p> <pre><code>df_2015 = df[df['Year'] == 2015] pd.crosstab(df_2015['Fruit'], df_2015['Country']).reindex(df['Fruit'].unique(), fill_value=0) </code></pre> <p>Output:</p> <pre><code>Country France Germany Spain Fruit Apple 2 1 1 Banana 1 1 0 Gr...
python|pandas|loops|dummy-variable
2
375,136
69,623,839
How to pass a pandas dataframe from main class to another class?
<p>There are lots of widgets in the original code and that is why I need to open the file in the main window. Therefore, I need to pass a dataframe (data_df) that comes from a csv file open in the main menu (main class) to 'MyApp' class. I will use the dataframe (input_df) to perform calculations down the road.</p> <p...
<p>You can pass the data from one another through the <code>__init__</code> method using something like this on your main window class:</p> <pre><code>class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.init_ui() def goToOtherWindo...
python|pandas|pyqt5
0
375,137
69,586,002
How to convert a pandas dataframe into a format (similar to one hot encoding) taking an amount-column into account
<p>What is the most convenient way to convert a pandas dataframe (entailing date, amount, category) into a one hot endocing format which takes the amount-column into account. Please see the example below.</p> <p><a href="https://i.stack.imgur.com/h6sVw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>You can just loop over the database and use the values for each entry for indexing the new database. See example below:</p> <pre><code>import pandas as pd # create the example databases d1 = {'value' : [100,200,300], 'char': ['a' , 'b', 'c']} d2 = {'a' : [None, None, None], 'b': [None, None, None], 'c': [None, Non...
python|pandas
0
375,138
69,592,003
Why is meshgrid changing (x, y, z) order to (y, x, z)?
<p>I have 3 vectors:</p> <pre><code>u = np.array([0, 100, 200, 300]) #hundreds v = np.array([0, 10, 20]) #tens w = np.array([0, 1]) #units </code></pre> <p>Then I used <code>np.meshgrid</code> to sum <code>u[i]+v[j],w[k]</code>:</p> <pre><code>x, y, z = np.meshgrid(u, v, w) func1 = x + y + z </code></pre> <p>So, when (...
<p>From the <code>meshgrid</code> docs:</p> <pre><code>Notes ----- This function supports both indexing conventions through the indexing keyword argument. Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N...
python|numpy
1
375,139
69,352,013
Convert string to multidimensional array in Python
<p>I'm having a problem managing some data that are saved in a really awful format.</p> <p>I have <a href="https://filebin.net/mfqrxtphkno5kbw0" rel="nofollow noreferrer">data for points</a> that correspond to the edges of a polygon. The data for each polygon is separated by the string <code>&gt;</code>, while the <cod...
<p>You can use regex to match decimal numbers.</p> <pre><code>import re PATH = &lt;path_to_file&gt; coords = [] with open(PATH) as f: for line in f: nums = re.findall('-?\d+\.\d+', line) if len(nums) &gt;0: coords.append(nums) print(coords) </code></pre> <p><strong>Note:</strong> this so...
python|arrays|string|numpy|multidimensional-array
0
375,140
69,354,179
How to get the classes from a Binary Image Classification model with Keras?
<p>Currently I am working on a binary classification model using Keras(version '2.6.0'). And I build simple model with three Blocks of 2D Convolution (Conv2D + ReLU + Pooling), then a finale blocks contain a Flatten, Dropout and two Dense layers. I have a small dataset of images in my disk and they are organized in a m...
<p>Try this :</p> <pre><code>ImagePath = &quot;YourImagePath&quot; img = keras.preprocessing.image.load_img( ImagePath, target_size=image_size ) img_array = keras.preprocessing.image.img_to_array(img) img_array = tf.expand_dims(img_array, 0) # Create batch axis predictions = model.predict(img_array) score = pred...
python|tensorflow|keras
0
375,141
40,916,388
Python Pandas Bokeh Indexerror: list index out of range - why?
<p>I'm having trouble with the code below:</p> <pre><code>from bokeh.plotting import figure, output_file, show, save from bokeh.models import ColumnDataSource from bokeh.models import Range1d, LinearAxis import pandas as pd from pandas import HDFStore from bokeh.palettes import Spectral9 store = pd.HDFStore('&lt;hdf ...
<p>The following lines appear towards the top of your code.</p> <pre><code>#the number of colums is the number of lines that we will make numlines = len(df.columns) #import colour pallet mypalette = Spectral9[0:numlines] </code></pre> <p>In the first line, you set numlines equal to the number of columns you have. Yo...
python|pandas|range|bokeh|index-error
2
375,142
41,225,041
Dataframe complex reformating
<p>I would like to transform this dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame.from_items([('a', [13,'F','RD',0,0,1,0,1]), ('b', [45,'M','RD',1,1,0,1,0]), ('c', [67,'F','AN',0,0,1,0,1]), ('d', [23,'M','AN',1,...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>, <a href="...
python|pandas|dataframe|formatting
0
375,143
41,071,446
Merging back new calculations in original pandas dataframe
<p>Say I have a Pandas dataframe named 'df' and seen below:</p> <pre><code> X Y Z 0 -3 6 -7 1 -4 -10 -1 2 9 -10 -9 3 5 0 -8 4 -2 1 -8 </code></pre> <p>And I want to create a new frame out of some of the rows in df:</p> <pre><code>new_df = df.loc[(df['X'] == -3) &amp; (df['X'] == 9)] </code></pre> <p>A...
<p>If you want to replace values with conditions, you can do it in one step, i.e. specify the row and column conditions and assign values, and you can avoid merging the new data frame with the original data frame:</p> <pre><code>df.loc[(df['X'] == -3) | (df['X'] == 9), "Y"] = 150 # I assume you mean or instead of an...
python|pandas
2
375,144
41,007,797
Pandas: find most frequent values in columns of lists
<pre><code> x animal 0 5 [dog, cat] 1 6 [dog] 2 8 [elephant] </code></pre> <p>I have dataframe like this. How can i find most frequent animals contained in all lists of column.</p> <p>Method value_counts() consider list as one element and i can't use it. </p>
<p>something along these lines?</p> <pre><code>import pandas as pd df = pd.DataFrame({'x' : [5,6,8], 'animal' : [['dog', 'cat'], ['elephant'], ['dog']]}) x = sum(df.animal, []) #x #Out[15]: ['dog', 'cat', 'elephant', 'dog'] from collections import Counter c = Counter(x) c.most_common(1) #Out[17]: [('dog', 2)] </code>...
pandas
4
375,145
40,837,066
Numpy: convert 2D array of indices to 1D array for intersection calculation
<p>I have a situation where I need to do the intersection of two binary image arrays in python. Ideally, I do this pretty quickly. </p> <hr> <p>Numpy has the <code>intersect1d</code> function that will do the job, if I can turn my coordinates into single elements. </p> <p>Right now (since I know the dimensions of...
<p>Two approaches could be suggested -</p> <pre><code>255*(~((A==0) &amp; (B==0))).astype(A.dtype) 255*(((A!=0) | (B!=0))).astype(A.dtype) </code></pre>
python|arrays|numpy
1
375,146
40,888,274
How to loop list value of a specific column in pandas?
<p>I have a pandas dataframe, which the first column are list values. I want to loop each str value of each list, and the values of next columns will be in included together.</p> <p>For example:</p> <pre><code>tm = pd.DataFrame({'author':[['author_a1','author_a2','author_a3'],['author_b1','author_b2'],['author_c1','a...
<p>I think you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> for repeat values by legths by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>str.le...
python|loops|pandas
2
375,147
41,225,604
Concat list of pandas data frame, but ignoring column name
<p>Sub-title: Dumb it down pandas, stop trying to be clever.</p> <p>I've a list (<code>res</code>) of single-column pandas data frames, each containing the same kind of numeric data, but each with a different column name. The row indices have no meaning. I want to put them into a single, very long, single-column data ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>:</p> <pre><code>prin...
python|pandas|rbind
5
375,148
41,085,803
tensorflow slim fix bias, train weights
<p>What is the best way to create a slim fully connected layer with fixed biases? Currently I have:</p> <pre><code>fc = slim.fully_connected(inputs, num_outputs = 10) </code></pre> <p>but the fully_connected function only allows fixing both the weights and biases at the same time.</p>
<p>It turns out that if you pass in an identity normalizer_fn, no biases are created and this is good enough for me:</p> <pre><code>fc = slim.fully_connected(normed, num_outputs = self.nInternalUnits, normalizer_fn=lambda x: x ) </code></pre>
tensorflow
0
375,149
41,011,469
Improving performance of Python for loop?
<p>I am trying to write a code to construct dataFrame which consists of cointegrating pairs of portfolios (stock price is cointegrating). In this case, stocks in a portfolio are selected from S&amp;P500 and they have the equal weights. </p> <p>Also, for some economical issue, the portfolios must include the same secto...
<p>I dont know what computer you have, but i would advise you to use some kind of multiprocessing for the loop. I haven't looked really hard into your code, but as far as i see <code>res</code> and <code>sec</code> can be moved into shared memory objects, and the individual loops paralleled with <code>multiprocessing</...
python|python-3.x|pandas|dataframe
2
375,150
41,176,033
ConvNet : Validation Loss not strongly decreasing but accuracy is improving
<p>Using <code>TensorFlow</code> I've build a simple <code>CNN</code> for classification. It has the following definition:</p> <pre><code>Input Tensor : 32,32,1 Grayscale Image 1 Conv Layer 3x3x32 Relu Activated 2x2 Max Pooled 128 FC1 43 FC2 # 43 classes </code></pre> <p>Full code can be found on this <a href="https...
<p>This is a classic mistake in TensorFlow: you shouldn't apply a softmax on your output and then <code>tf.nn.softmax_cross_entropy_with_logits</code>.</p> <p>The operation <code>tf.nn.softmax_cross_entropy_with_logits</code> expects unscaled logits (i.e. without softmax). From the <a href="https://www.tensorflow.org/...
tensorflow|conv-neural-network|multilabel-classification
1
375,151
40,978,859
Creating simple Android app using android studio and tensorflow
<p><strong>Update 1</strong></p> <p>I have installed the official WIN package located at PyPi repository </p> <p>Just to make sure I did not miss anything, I downloaded the .whl file manually, renamed it to .zip, opened and listed all the files and directories inside this package. There is nothing related to android....
<p>My guess is the Android example, originally targeted for Linux, has not been updated to work on Windows. The TensorFlow update that supports Windows was just released last week.</p>
android|windows|tensorflow
0
375,152
40,852,729
Permanently Inject Constant into Tensorflow Graph for Inference
<p>I train a model with a placeholder for <code>is_training</code>:</p> <pre><code>is_training_ph = tf.placeholder(tf.bool) </code></pre> <p>however once training and validation are done, I would like to permanently inject a constant of <code>false</code> in for this value and then "re-optimize" the graph (ie using <...
<p>One possibility is to use the <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#import_graph_def" rel="noreferrer"><code>tf.import_graph_def()</code></a> function and its <code>input_map</code> argument to rewrite the value of that tensor in the graph. For example, you could structure...
tensorflow|tensorflow-serving
7
375,153
40,855,591
pandas select subset of pivot_table
<p>There are a few questions here on this topic, but none seem to be helpful in my case. Here's a dumbed down version of what I want:</p> <p>This is the csv file of interest: <a href="http://pastebin.com/rP7tPDse" rel="nofollow noreferrer">http://pastebin.com/rP7tPDse</a></p> <p>I'm creating the pivot table as:</p> ...
<p>When I copied dataframe, the columns were strings and rows were floats.<br> To get the columns as float</p> <pre><code>df.columns = df.columns.astype(float) </code></pre> <p>Now you can <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow noreferrer"><code>pd.IndexSlice</code></a></p> ...
python|pandas|pivot-table
2
375,154
41,004,155
Parse Salesforce report in Pandas DataFrame using Beatbox
<p>Has anybody tried parsing SalesForce report into Pandas DataFrame using Beatbox? There are couple of examples on SO but none of them have provided comprehensive solution or at least what I have perceived it hasn't.</p> <pre><code>#!/usr/bin/env python3 import beatbox import pandas as pd sf = beatbox._tPartnerNS ...
<p>Report data can be retrieved by <a href="https://resources.docs.salesforce.com/sfdc/pdf/salesforce_analytics_rest_api.pdf" rel="nofollow noreferrer">Salesforce Reports and Dashboards REST API</a>. This works in Salesforce since Summer'15 (ver 34.0).</p> <p>I wrote an example with package <a href="https://github.com/...
pandas|salesforce|beatbox
3
375,155
41,044,374
Reshaping dataframe in Pandas
<p>Is there a quick pythonic way to transform this table </p> <pre><code>index = pd.date_range('2000-1-1', periods=36, freq='M') df = pd.DataFrame(np.random.randn(36,4), index=index, columns=list('ABCD')) In[1]: df Out[1]: A B C D 2000-01-31 H 1.368795 0.106294 ...
<p>For easier check, I've created dataframe of the same shape but with integers as values.</p> <p>The core of the solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html" rel="nofollow noreferrer"><code>pandas.DataFrame.transpose</code></a>, but you need to use <code>...
python|pandas|dataframe|time-series
6
375,156
41,003,463
Create column in a pandas DataFrame based on whether value exists in a different DataFrame column
<p>I would like to add a column to dfA based on whether or not the job title (and its matching State) exists in dfB.</p> <p>dfA=</p> <pre><code>Title State Income Cashier WY 15000 Cashier WY 20000 Cashier WY 15000 Manager WY 25000 Cashier CO 15000 </code></pre> <p>dfB=<...
<p>You can <code>merge</code> the two DataFrames A and B to create the new DataFrame:</p> <pre><code>&gt;&gt;&gt; dfA.merge(dfB, on=['Title', 'State'], how='left') Title State Income MostFreqIncome 0 Cashier WY 15000 15000.0 1 Cashier WY 20000 15000.0 2 Cashier WY 15000 ...
python|pandas|dataframe
2
375,157
40,910,857
How to interpret increase in both loss and accuracy
<p>I have run deep learning models(CNN's) using tensorflow. Many times during the epoch, i have observed that both loss and accuracy have increased, or both have decreased. My understanding was that both are always inversely related. What could be scenario where both increase or decrease simultaneously.</p>
<p>The loss decreases as the training process goes on, except for some fluctuation introduced by the mini-batch gradient descent and/or regularization techniques like dropout (that introduces random noise).</p> <p>If the loss decreases, the training process is going well.</p> <p>The (validation I suppose) accuracy, i...
tensorflow|deep-learning|loss
58
375,158
41,202,025
Find where array values increase monotonically over some value
<p>I'm trying to find the locations in an array where the values increase monotonically such that the total change in value is greater than k. Ie for <code>k = 5</code> and <code>data = [1, 4, 5, 7, 10, 9, 6, 14, 3, 4]</code> I would want to return:</p> <pre><code>[4, 7] </code></pre> <p>In general the array would be...
<p>Here's a vectorized approach -</p> <pre><code>d = a[1:] - a[:-1] mask = np.concatenate(( [False], d &gt; 0, [False] )) start = np.flatnonzero(mask[1:] &gt; mask[:-1]) stop = np.flatnonzero(mask[1:] &lt; mask[:-1]) count = np.bincount(np.repeat(np.arange(start.size) ,stop - start), d[mask[1:-1]]) out = stop[count &g...
python|performance|numpy|vectorization
2
375,159
41,049,567
How to convert a series object in to data frame using string cleaning
<p>I have a series object of strings where there is a specific characters i can go along with. For instance, the one with the end character of <code>[]</code> will be corresponded to those with end character of <code>()</code></p> <pre><code>s = pd.Series(['September[jk]', 'firember hfh(start)','secmber(end)','Last da...
<p>I don't think there's any magic here, so I recommend parsing the list yourself before creating the dataframe:</p> <pre><code>import re import pandas as pd l = ['September[jk]', 'firember hfh(start)','secmber(end)','Last day(hjh)', 'October[jk]','firober fhfh (start)','thber(marg)','lasber(sth)', ...
python-3.x|pandas
0
375,160
40,887,409
Numpy matrix determinant precision problems
<p>I am trying to write a script on python to determine a matrix determinant using Gauss method. It works correctly, but the precision isn't enough for me. My code is:</p> <pre><code>import scipy.linalg as sla import numpy as np def my_det(X): n = len(X) s = 0 if n != len(X[0]): return ValueError ...
<p>The reason why the code fails the test condition, <code>abs(my_det(X) - sla.det(X)) &lt; 1e-6</code>, is not due to lack of precision but rather the change in sign brought about the unintended side-effect of <code>my_det</code> mutating <code>X</code>:</p> <pre><code>X[i][k], X[maxRow][k] = X[maxRow][k], X[i][k] </...
python|numpy|algebra
1
375,161
40,855,047
np.argsort with support for ties
<p>Say we define a function for doing <code>argsort</code> with support for ties <a href="https://stackoverflow.com/a/20199459/1732769">as described in this solution</a>:</p> <pre><code>def argsort_with_support_for_ties(a): rnd_array = np.random.random(a.size) return np.lexsort((rnd_array,a)) </code></pre> <p>We ...
<p>I understand that you want to rank the elements so that the tiebreaking is random. For this you just need to invert the permutation that you got from <code>lexsort</code>:</p> <pre><code>output = np.argsort(np.lexsort((rnd_array,a))) </code></pre> <p>My output (which is not identical to yours because of randomness...
python-3.x|sorting|numpy
1
375,162
40,848,809
How to Find a Point within a Polygon?
<p>I am trying to find a point within polygons of a shapefile. </p> <p>I need to write a loop that can loop over the polygons and return the index of the polygon in which the point is located. </p> <p>How would I write a loop to find out which polygon the point is in? </p> <p>Here's what I have written so far: </p>...
<p>I solved it in one line of code. No loop necessary.</p> <p>Posting for anyone else that may be interested: </p> <pre><code># Setting the coordinates for the point CUSP = shapely.geometry.Point((-73.986403, 40.693217,)) # Longitude &amp; Latitude # Printing a list of the coords to ensure iterable list(CUSP.coor...
python|pandas|geometry|shapely|geopandas
1
375,163
41,051,492
Add attribute to edge in projected graph
<p>I have a DataFrame that resembles an affiliation matrix. I have a person, an event and the year of the event.</p> <pre><code>d = {'person' : ['1', '2', '3', '1', '4', '3', '4', '1', '2'], 'event' : ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'], 'year' : [1995, 1995, 1995, 1996, 1996, 2000, 2000, 2001, 2001]...
<p>I'm not familiar enough with NetworkX to help you with the problem of adding edge attributes, but this method does identify the first meeting of individuals.</p> <pre><code>import pandas as pd import itertools # initial data d = {'person' : ['1', '2', '3', '1', '4', '3', '4', '1', '2'], 'event' : ['A', 'A', '...
python|pandas|networkx
0
375,164
40,788,391
Attribute prediction with CNN and cross entropy loss (negative values for absent attributes)
<p>I am building a neural net (CNN) which predict 100 attributes of an image. The training data is as follows-</p> <p><code>image_name image_attributes</code></p> <p><code>img/img001.jpg -1, 1, -1 , 1, 0 .......-1 , 1</code></p> <p>So the attributes which are present have value <code>1</code>, and <code>-1</code> if...
<p>So to make it clear you should see your result out of the classifier as three nodes having their result whatever it is. which they are (y0,y1,y2) and then by applying softmax on these results you'll have a new values representing the answer in a probability range between 0 and 1 </p> <p><a href="https://i.stack.img...
machine-learning|computer-vision|tensorflow|deep-learning
1
375,165
53,859,920
Filling a pandas column based on another column
<p>I would like to fill each row of a column of my dataframe based on the entries in another column, in particular I want to fill each row with the corresponding name of the corresponding ticker for that stock, like so</p> <pre><code>dict1 = [{'ticker': 'AAPL','Name': 'Apple Inc.'}, {'ticker': 'MSFT','Name': 'Microso...
<p>You can first create a series mapping:</p> <pre><code>ticker_name_map = get_nasdaq_symbols()['Security Name'].str[:-15] </code></pre> <p>Then use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>pd.Series.map</code></a><sup>1</sup>:</p> <pre><...
python|pandas|apply
2
375,166
54,183,920
Append any further columns to the first three columns AND indicate the triple column it comes from
<p>This is a follow-up question to <a href="https://stackoverflow.com/questions/54182470/append-any-further-columns-to-the-first-three-columns/54182646">Append any further columns to the first three columns</a>.</p> <p>I start out with about 120 columns. It is always three columns that belong to each other. Instead of...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> for remove only first level, second level of <code>MultiIndex</code> convert to column:</p> <pre><code>arr = np.arange(len(df.columns)) df.columns = [arr // 3,...
python|pandas
1
375,167
53,814,772
Copying data from one tensor to another using bit masking
<pre><code>import numpy as np import torch a = torch.zeros(5) b = torch.tensor(tuple((0,1,0,1,0)),dtype=torch.uint8) c= torch.tensor([7.,9.]) print(a[b].size()) a[b]=c print(a) </code></pre> <blockquote> <p>torch.Size([2])<br>tensor([0., 7., 0., 9., 0.])</p> </blockquote> <p>I am struggling to understand how this w...
<p>Indexing with arrays works the same as in numpy and most other vectorized math packages I am aware of. There are two cases:</p> <ol> <li><p>When <code>b</code> is of type <code>uint8</code> (think boolean, pytorch doesn't distinguish <code>bool</code> from <code>uint8</code>), <code>a[b]</code> is a 1-d array conta...
pytorch
2
375,168
53,830,057
Update Column based on another column and Delete data from the other
<p>Lets assume the df looks like:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'fname':['Anky','Anky','Tom','Harry','Harry','Harry'],'lname':['sur1','sur1','sur2','sur3','sur3','sur3'],'role':['','abc','def','ghi','','ijk'],'mobile':['08511663451212','+4471123456','0851166346','','0851166347',''],'Pmobil...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a> to shift the columns left do this:</p> <pre><code>In[50]: df.loc[df['Pmobile'].str.startswith(('08','8','+353'),na=False), ['mobile','Pmobile']] = df[['mobile','P...
python-3.x|pandas|dataframe
2
375,169
54,031,493
How to Create Tensorflow Session with nvlink GPU
<p>I am trying to run inference with Tensorflow. I have 2 Quadro GV100's connected via nvlink and another GPU for display on my desktop.</p> <p>When I create the SessionOptions object, I need to call the following to set which GPU to use:</p> <pre><code>auto options = SessionOptions(); options.config.mutable_gpu_opt...
<p>The short answer is yes, Tensorflow is able to take advantage of the NVLINK technology. But, as mentioned <a href="https://www.pugetsystems.com/labs/hpc/NVLINK-on-RTX-2080-TensorFlow-and-Peer-to-Peer-Performance-with-Linux-1262/?utm_source=youtube&amp;utm_campaign=smarter#tensorflow-performance-with-2-rtx-2080-gpus-...
c++|tensorflow|nvidia
2
375,170
53,953,087
How to Assign Data after Groupby and Concat in pandas
<p>Iam newbie in python. I have huge a <code>dataframe</code> with millions of rows and id. my data looks like this:</p> <pre><code>Time ID X Y 8:00 A 23 100 9:00 B 24 110 10:00 B 25 120 11:00 C 26 130 12:00 C 27 140 13:00 A 28 150 14:00 A 29 160 15:00 D 30 170 16:00 C...
<p>No need <code>groupby</code> using <code>drop_duplicates</code>after you sort </p> <pre><code>df=pd.concat([df.drop_duplicates(['ID']).assign(sign='first'),df.drop_duplicates(['ID'],keep='last').assign(sign='last')]).sort_values('ID') df Time ID X Y sign 0 8:00 A 23 100 first 4 20:00 A 35 22...
pandas|dataframe|group-by|concat
3
375,171
53,921,570
accessing to a specific cell value in excel with pandas
<p>i want to store a specific value of some cell in a variable which have my condition. i am trying on <a href="https://www.dataquest.io/blog/large_files/movies.xls" rel="nofollow noreferrer">IMDB movie dataset</a>.</p> <pre><code>import pandas as pd file='movies.xls' sorted=pd.read_excel(file,index_col='Language') pr...
<p>this code do what i want...</p> <pre><code>import pandas as pd file='movies.xls' sorted=pd.read_excel(file,sheet_name=0,index_col='Title') var=sorted[sorted['Language'].str.contains("German")] print(var.head()) </code></pre>
python|excel|pandas
1
375,172
54,191,326
Moving pandas series value by switching column name?
<p>I have a DF, however the last value of some series should be placed in a different one. This happened due to column names not being standardized - i.e., some are "Wx_y_x_PRED" and some are "Wx_x_y_PRED". I'm having difficulty writing a function that will simply find the columns with >= 225 NaN's and changing the col...
<p>Doing with <code>split</code> before <code>frozenset</code>(will return the order list), then we do <code>join</code>: Notice this solution can be implemented to more columns </p> <pre><code>df.columns=df.columns.str.split('_').map(frozenset).map('_'.join) df.mask(df=='NaN').groupby(level=0,axis=1).first() # groupb...
python|pandas
1
375,173
53,885,868
Is it Possible to classify dataset using DNN classifier based on Different label values of type String?
<p>I have a network traffic as CSV file and inside that file all required features and class column (Label Column). But the problem is with the class column of type String and it contents with in the following labels: </p> <p>'normal','icmp-echo','tcp-syn','udp-flood','httpFlood','slowloris','slowpost','bruteForce</p>...
<p>Yes you can do classification using DNN. Here is an <a href="http://vprusso.github.io/blog/2016/tensor-flow-neural-net-breast-cancer/" rel="nofollow noreferrer">example</a> to do breast cancer classification using DNN.</p> <p>As far as the <strong>String labels</strong> are concerned, you need to do <a href="https:/...
python|tensorflow|deep-learning
2
375,174
54,089,396
Threshold numpy array, find windows
<p>Input data is a 2D array (timestamp, value) pairs, ordered by timestamp:</p> <pre><code>np.array([[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66], [ 2, 3, 5, 6, 4, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3]]) </code></pre> <p>I want to find time windows where the value excee...
<p>Here's one way:</p> <pre><code># Create a mask In [42]: mask = (a[1] &gt;= 4) # find indice of start and end of the threshold In [43]: ind = np.where(np.diff(mask))[0] # add 1 to starting indices In [44]: ind[::2] += 1 # find and reshape the result In [45]: result = a[0][ind].reshape(-1, 2) In [46]: result Out[46...
python|arrays|numpy
6
375,175
53,820,131
How to create a dataframe from numpy arrays?
<p>I am trying to create a matrix / DataFrame with the numbers stored in 2 variables</p> <pre><code>x = np.linspace(0,50) y = np.exp(x) </code></pre> <p>and I would like them to look like this:</p> <pre><code>x | y ___________________ 0 | 1.0... 1 | 2.77... 2 | 7.6... ...
<p>With <code>pandas</code>:</p> <p>You can issue</p> <pre><code>&gt;&gt;&gt; xs = np.arange(51) &gt;&gt;&gt; ys = np.exp(xs) </code></pre> <p>to get the x and y values and then build your dataframe with</p> <pre><code...
python|pandas|numpy|dataframe
4
375,176
53,979,153
Error when plotting contour with matplotlib
<p>I am trying to plot such a function. However, the following code will cause an error. I think that the cause is that a scalar value is returned in <code>norm ()</code>, but how can it be solved?<a href="https://i.stack.imgur.com/JLzB7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JLzB7.png" alt=...
<p>The problem is that your current <code>Z</code> is not of same dimension as your <code>X</code> and <code>Y</code>. This could be verified by printing the shape of X, Y and Z. The reason is that you did not provide an <code>axis</code> while computing the <code>norm</code> in your equation and hence you were getting...
python|numpy|matplotlib
1
375,177
54,093,244
Shape of data and LSTM Input for varying timesteps
<p>For my master thesis, I want to predict the price of a stock in the next hour using a LSTM model. My X data contains 30.000 rows with 6 dimensions (= 6 features), my Y data contains 30.000 rows and only 1 dimension (=target variable). For my first LSTM model, I reshaped the X data to (30.000x1x6), the Y data to (30....
<p>You are on the right track but confusing the number of units with timesteps. The <code>units</code> is a hyper-parameter that controls the output dimension of the LSTM. It is the dimension of the LSTM output vector, so if input is <code>(1,6)</code> and you have 32 units you will get <code>(32,)</code> as in the LST...
python|tensorflow|keras|neural-network|lstm
1
375,178
54,140,523
Retain order when taking unique rows in a NumPy array
<p>I have three 2D arrays <code>a1</code>, <code>a2</code>, and <code>a3</code></p> <pre><code>In [165]: a1 Out[165]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) In [166]: a2 Out[166]: array([[ 9, 10, 11], [15, 16, 17], [18, 19, 20]]) In [167]: a3 Out[167]: ...
<p>Using <code>return_index</code></p> <pre><code>_,idx=np.unique(stacked, axis=0,return_index=True) stacked[np.sort(idx)] array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [15, 16, 17], [18, 19, 20], [ 4, 5, 5]]) </code></pre>
python|numpy|multidimensional-array|unique|size-reduction
9
375,179
53,921,175
Not able to import tensorflow on anaconda with python 3.6 version on 64bit system with 64bit anaconda
<p>When I import tensorflow it gives me this error:</p> <blockquote> <blockquote> <blockquote> <blockquote> <p>Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap...
<p>I just solved this same issue with my system (Win 10, 64 bit). Following are the details of how I resolved this issue:</p> <ol> <li>Install <strong>VS 2017</strong>, tensorflow doesn't use it but having it helps in the smooth installation of CUDA toolkit. </li> <li>Update <strong>NVDIA driver from windows device ma...
python|python-3.x|tensorflow
0
375,180
54,122,400
Efficient way of getting average area in numpy
<p>Is there a more efficient way in determining the averages of a certain area in a given numpy array? For simplicity, lets say I have a 5x5 array:</p> <pre><code>values = np.array([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], ...
<p>This solution is less efficient (slower) than yours but is just an example using <a href="https://www.numpy.org/devdocs/reference/maskedarray.generic.html" rel="nofollow noreferrer"><code>numpy.ma</code></a> module.</p> <p>Required libraries:</p> <pre><code>import numpy as np import numpy.ma as ma </code></pre> <...
python|numpy|vectorization
0
375,181
54,168,946
Adding text annotations to a map
<p>I'm using geoplotlib to siplay points on a map and i would like to add names to the points displayed in my map, like text annotations. But can't figure out how after googling it for a while and looking in the github documentation site. Here's the code to create the map:</p> <pre><code>import pandas as pd # Datafra...
<p>The <a href="https://andrea-cuttone.github.io/geoplotlib/api.html#geoplotlib.dot" rel="nofollow noreferrer">geoplotlib API reference for the geoplotlib.dot()</a> function provides an argument <code>f_tooltip</code> which accepts a <em>function</em> to generate a tooltip string for a point.</p> <p>In your code, you ...
python|pandas|python-2.7|google-maps|dataframe
1
375,182
53,995,570
Fetch DB tables blueprint like "describe table_name" commande from redshift and DB2 from python
<p>I want to fetch data using my python code like we do with <code>describe [tableName] statement</code>. I want to do that on Redshift and DB2. </p> <p>I tried to do that using Pandas and cursors, I tried the following chunks of commands:</p> <ol> <li><p><code>"set search_path to SCHEMA; select * from pg_table_def w...
<p>A lot of this data is included in the <code>SVV_COLUMNS</code> system view. You can query that table using the <code>table_name</code> and <code>table_schema</code> columns.</p> <p><a href="https://docs.aws.amazon.com/redshift/latest/dg/r_SVV_COLUMNS.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/redsh...
python|pandas|db2|cursor|amazon-redshift
0
375,183
54,081,213
Flatten Dataset of multiple files tensorflow
<p>I'm trying to read the CIFAR-10 dataset from 6 .bin files, and then create a initializable_iterator. <a href="https://www.cs.toronto.edu/~kriz/cifar.html" rel="nofollow noreferrer">This</a> is the site I downloaded the data from, and it also contains a description of the structure of the binary files. Each file cont...
<p>I am not sure how your bin file is structured. I am assuming 32*32*3 = 3072 points per image is present in each file. So the data present in each file is a multiple of 3072. However for any other structure, the kind of operations would be similar, so this can still serve as a guide for that. You could do a series of...
python|tensorflow|tensorflow-datasets
1
375,184
54,139,851
Using Pandas Dataframe within a SQL Join
<p>I'm trying to perform a SQL join on the the contents of a dataframe with an external table I have in a Postgres Database.</p> <p>This is what the Dataframe looks like:</p> <pre><code>&gt;&gt;&gt; df name author count 0 a b 10 1 c d 5 2 e f 2 </code></pre> <p>I need to join it...
<p>I managed to do this without having to convert the dataframe to a temp table or without reading SQL into a dataframe from the blog table. </p> <p>For anyone else facing the same issue, this is achieved using a virtual table of sorts.</p> <p>This is what my final sql query looks like this:</p> <pre><code>&gt;&gt;&...
python|sql|postgresql|pandas
7
375,185
54,063,466
Shift elements above the diagonal to the start of the row
<p>I have a matrix that was generated as a pivot table. I have included the data below. I need to turn the diagonal into the first column, which effectively re-orients the matrix so that the cell in the diagonal becomes the cell in the first column, for each row. </p> <p>This is the matrix as rendered in Pandas</p> <...
<p>Before filling or resetting the index, you can justify NaNs using Divakar's <a href="https://stackoverflow.com/a/44559180/4909087"><code>justify</code></a> function.</p> <pre><code>pivot = df.pivot_table(values='exposure', index='due_date', columns='repaid_date', ...
python|pandas|dataframe
1
375,186
53,968,639
How to create a columns from another column in a pandas dataframe like below
<p>I have a dataframe which contains duplicate records with columns x,y,z,A </p> <pre><code>X Y Z A a US 88 2016 a IND 88 2016 a IND 88 2017 a RSA 45 2017 a RSA 45 2018 b US 65 2017 b RSA 58 2018 c RSA 58 2016 </code></pre> <p>I want to create columns from the values of colu...
<p>You can use <code>pivot_table</code>:</p> <pre><code>df.pivot_table('Y',['X','Z'],'A',aggfunc='count', fill_value=0).reset_index() </code></pre> <p>Output:</p> <pre><code>A X Z 2016 2017 2018 0 a 45 0 1 1 1 a 88 2 1 0 2 b 58 0 0 1 3 b 65 0 1 0 4 c 58...
python|pandas|pandas-groupby|data-science
0
375,187
53,951,351
return indexes of filtered dataframe as values
<p>I have a dataframe like the input dataframe below. I would like to create a new dataframe, where I filter my original data frame to only return the indexes of every column value above 0.66. I know I could filter the whold dataframe like </p> <pre><code>df[df&gt;0.66] </code></pre> <p>which would give me NaN valu...
<p>Just using <code>mul</code> with Boolean dataframe </p> <pre><code>(df&gt;0.66).mul(df.index.values,0) </code></pre>
python-3.x|pandas|numpy
1
375,188
54,042,674
Lambda Apply on Pandas values taking the average of row before and after
<p>I have a price time-series where I wish cleanse the data-set. How I plan to do it is to set 'incorrect' jump in prices to the average of the 'before' and 'after' price.</p> <p>I have a panda frame name df, with price as 'mid'. I set the prx_chg as per below.</p> <pre><code>df['prx_chg'] = df['mid'].pct_change(peri...
<p>IIUC, you might use <code>np.where</code> and <code>shift</code> in this case;</p> <pre><code>df['mid'] = np.where((df['prx_chg'].shift(1) &gt;= 10) | (df['prx_chg'].shift(1) &lt;= -10), (df['mid'].shift(-1) + df['mid'].shift(1)) / 2, df['mid']) df mid prx_chg 0 1.00 0.100000 1 1.10 -0.090909 2 1....
python-3.x|pandas|lambda
1
375,189
53,904,175
python nested lists and arrays
<p>I have an output from a code where coordinates of several rectangles (four corners x,y) are provided in a list of arrays containing nested lists, which looks as follows: </p> <pre><code>[array([[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]], dtype=float32), ... array([[[x1, y1], [x2, y2]...
<p>Here is one way of doing it using list comprehensions. </p> <p><strong>Explanation:</strong> You loop over the combination of two lists (<code>coords</code> and <code>ids</code>) since they map one to one. <code>i[0]</code> gives you the index and <code>j.flatten()</code> converts each array of your <code>coords</c...
python|arrays|list|numpy|nested
4
375,190
53,841,760
Python pandas concatenate columns csv
<p>I have a huge list of <code>Users_id</code> that I want to concatenate. I know how to do it in excel but the file is much too large.</p> <pre><code>Users ID 101 101 102 101,102 103 101,102,103 104 101,102,103,104 </code></pre> <p>Here is what I want to achieve. Here is what I have so far.</p> <pre><code>impo...
<p>This is an unusual operation since your input is numeric, while your output is a sequence of comma-separated strings. One solution is to use <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow noreferrer"><code>itertools.accumulate</code></a> with f-strings (Python 3.6; <a h...
python|pandas|csv|concatenation
1
375,191
54,120,583
tf-serving abnormal exit without error message
<p>tf-serving abnormal exit without error message</p> <h3>System information</h3> <p>OS Platform and Distribution (e.g., Linux Ubuntu 16.04): ReaHat EL6</p> <p>TensorFlow Serving installed from (source or binary): source using bazel 0.18.0</p> <p>TensorFlow Serving version: 1.12.0</p> <h3>Describe the problem</h3>...
<p>It is not an abnormal exit. It is an indication that the <strong>Server is ready to receive the Inference Requests.</strong> </p> <p>For clarification, please find the below explanation:</p> <pre><code>docker run --runtime=nvidia -p 8501:8501 \ --mount type=bind,\ source=/tmp/tfserving/serving/tensorflow_serving...
tensorflow-serving
0
375,192
54,050,581
Installed Keras with pip3, but getting the "No Module Named keras" error
<p>I am Creating a leaf Identification Classifier using the CNN, the Keras and the Tensorflow backends on Windows. I have installed Anaconda, Tensorflow, numpy, scipy and keras.</p> <p>I installed keras using pip3:</p> <pre><code>C:\&gt; pip3 list | grep -i keras Keras 2.2.4 Keras-Applications 1.0.6 Ke...
<p>Installing Anaconda and then install packages with pip seams like confusing the goal of Anaconda(or any other package management tools)</p> <p>Anaconda is there to help you organize your environments and their dependences.</p> <p>Assuming you have conda on your system path, Do:</p> <p>Update conda</p> <pre><cod...
python|windows|tensorflow|keras|keras-2
6
375,193
53,861,726
Inserting zeros in numpy array
<p>A function that takes in a <strong>vector</strong> and returns a new vector where every element is separated by 4 consecutive zeros. </p> <p>Example: </p> <pre><code>[4, 2, 1] --&gt; [4,0,0,0,0,2,0,0,0,0,1] </code></pre>
<p><strong><em>Setup</em></strong></p> <pre><code>a = np.array([4, 2, 1]) </code></pre> <hr> <p>Using slice assignment:</p> <pre><code>s = a.shape[0] v = s + (4 * (s - 1)) f = np.zeros(v) f[::5] = a </code></pre> <p></p> <pre><code>array([4., 0., 0., 0., 0., 2., 0., 0., 0., 0., 1.]) </code></pre>
python|numpy
3
375,194
53,983,083
Linear regression with defined intercept
<p>I have a DataFrame (df) with two columns and three rows. </p> <p>Column X = [137,270,344] Column Y = [51, 121, 136]</p> <p>I want to get the slope of the linear regression considering the intercept = 0. </p> <p>I have tried to add a point (0,0) but it doesn´t work.</p> <p>EX. Column X = [0, 137,270,344] Column ...
<p>In standard linear regression, all data points implicitly have a weight of 1.0. In any software that allows linear regression using weights, the regression can effectively be made to pass through any single point - such as the origin - by assigning that data point an extremely large weight. Numpy's polyfit() allows ...
python|pandas|dataframe|linear-regression
0
375,195
54,084,310
How to prevent multi value dictionary object from splitting each word into individual letter strings?
<p>I have a dictionary object that looks like this:</p> <pre><code>my_dict = {123456789123: ('a', 'category'), 123456789456:('bc','subcategory'),123456789678:('c_d','subcategory')} </code></pre> <p>The below code extracts and compares a integer in column headers in a df to the key in the dictionary and cre...
<p><code>list(new_df[value][0])</code> breaks a string into a list of characters, that's why you get the individual characters.</p> <p><code>list(new_df[value][0])</code> must be <code>[new_df[value][0]]</code>. Or, better, <code>list(new_df[value][0]) + [key]</code> must be <code>[new_df[value][0], key]</code>. </p>
python|python-3.x|string|pandas
2
375,196
54,065,097
Is there any way to remove column and rows numbers from DataFrame.from_dict?
<p>So, I have a problem with my dataframe from dictionary - python actually "names" my rows and columns with numbers. Here's my code:</p> <pre><code>a = dict() dfList = [x for x in df['Marka'].tolist() if str(x) != 'nan'] dfSet = set(dfList) dfList123 = list(dfSet) for i in range(len(dfList123)): number = dfList.c...
<h3><code>index</code> and <code>columns</code> are properties of your dataframe</h3> <p>As long as <code>len(df.index) &gt; 0</code> and <code>len(df.columns) &gt; 0</code>, i.e. your dataframe has nonzero rows and nonzero columns, you cannot get rid of the labels from your <code>pd.DataFrame</code> object. Whether t...
python|python-3.x|pandas|dataframe|series
1
375,197
53,896,749
Understanding peaked/curved results in mAP and Loss during object detector training
<p>I am working on training the object detector with a custom dataset designed to detect the head of a plant. I am using the "Faster R-CNN with Resnet-101 (v1)" that was originally designed for the pet dataset. </p> <p>I modified the config file to match my dataset (1875 training/375 eval) of images that 275x550 in si...
<p>This is a standard case of overfitting: your model is memorizing the training data and lost its ability to generalize on unseen data.</p> <p>For cases like this one you have two options:</p> <ul> <li>early stopping: monitor the validation metrics and as soon as the metrics become constants and/or starts decreasing...
tensorflow|deep-learning|object-detection-api
-1
375,198
54,124,828
Python pandas multiplying 4 columns with decimal values
<p>I have a pandas dataframe with 4 columns containing decimal values which I have to multiply to create a 5 column with the answer. For example</p> <pre><code>col1 col2 col3 col4 0.03 0.02 0.01 0.05 0.12 0.32 0.05 0.03 </code></pre> <p>I tried multiplying using the following code:</p> <pre><code>...
<p>You can modify pandas option to display the number of decimals you want :</p> <pre><code>df = pd.DataFrame(np.random.randn(5,5)) print(df) pd.set_option('precision',10) print(df) </code></pre>
python|pandas|multiplication
1
375,199
54,202,579
Type error when trying to modify values using .loc
<p>Trying to modify all values in the column of a dataframe where values in another column is equal to something specific. </p> <p>I'm using a dataframe <code>df</code>, with columns a,b,c,d. I first duplicated column d using </p> <p>df["e"] = df["d"]</p> <p>Then, using <code>.loc</code>, I went for:</p> <pre><code...
<pre><code>import pandas as pd data = [['2334','00001','50','Unknown'],['6754','00001','80','Unknown']] df = pd.DataFrame(data, columns = ['a','b','c','d']) df['e'] = df['d'] df.loc[df['d'] == 'Unknown', 'e'] = 'Not Unknown!' </code></pre> <p>Completely works for me.</p>
python-3.x|pandas
0