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
10,800
72,783,690
Multiple parallel image-encoders in pytorch
<p>I have an image encoder which can generate output features. I want to split my image into several patches (around <em>16</em>) and feed each patch to a separate image encoder (the parameters for each encoder are different). Initially, it's like:</p> <p><code>Input -&gt; Encoder -&gt; Output</code></p> <p>I want to c...
<p>You need to use a <a href="https://pytorch.org/docs/stable/generated/torch.nn.ModuleList.html" rel="nofollow noreferrer"><code>nn.ModuleList</code></a> in order to properly register the list of <code>Patch</code> modules inside <code>Model</code> <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.htm...
python|pytorch
0
10,801
72,808,606
PANDAS - Inserting additional columns and Values based off another column
<p>I have a Dataframe, with a &quot;time in seconds&quot; column. Which looks like the following:</p> <pre><code> Number Seconds Col[2] Col[3] ... Col[n] 0 1 57047.9293 v2 v3 ... vn 1 2 57048.9824 -- -- -- ... m </code></pre> <p>I am attempting to insert additio...
<p>The function <code>convertSecondsto_</code> takes a float value as argument. But it's receiving a series from the insert method. You need to change the function to convert every value in the series and produce a list that can be inserted in the dataframe.</p> <pre><code>def convertSecondsto_(time, value): conver...
python|python-3.x|pandas|dataframe
1
10,802
72,777,822
After a Pandas Dataframe merge headers gain an "_x"
<p>I have a list of csvs, seven for every month, they all have the same structure. I'm trying to merge them into monthly datasets using concat monthly, then merge them so that I get fields like JAN_COUNT, FEB_COUNT, MAR_COUNT etc.. based on a id number. The first part of my code produces tables like I would expect. Eac...
<p>with merge, when the left and the right DF have the same column-name, these are suffixed with &quot;_x&quot; for left, and &quot;_y&quot; for right.</p> <p>You can overwrite it by changing the suffixes</p> <p>suffixes=()</p> <p>refer to documentation here <a href="https://pandas.pydata.org/pandas-docs/stable/referen...
python|pandas
1
10,803
59,577,183
Adding new column with the header containing date at the beginning of CSV file
<p>I was looking on Stackoverflow for this thing but I didn't find exactly what I wanted. I would like to open csv file on Python and add new column with header "Date" and until end of the file add today's date. How can I do it? I was trying to do it with pandas but I only know how to append to the end. </p> <p>I was ...
<p>Try this:</p> <pre><code>import pandas as pd import datetime df = pd.read_csv("my.csv") df.insert(0, 'Date', datetime.datetime.today().strftime('%Y-%m-%d')) df.to_csv("my_withDate.csv", index=False) </code></pre> <p>PS: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html" r...
python|pandas|csv
3
10,804
40,535,688
Flipping along two axis in a multidimensional numpy array
<p>So I'm trying to perform some numerical calculations and in it, I have to flip the first and second dimensions of a multidimensional array. I tried it with two methods and I noticed that the first one gives the wrong output and the second method gives the correct output. Here is the code for both:</p> <pre><code>fo...
<p>Look at the code for the flip functions. They just apply the ::-1 indexing to different dimensions</p> <pre><code>def fliplr m = asanyarray(m) if m.ndim &lt; 2: raise ValueError("Input must be &gt;= 2-d.") return m[:, ::-1] # ud: m[::-1, ...] </code></pre> <p>So anything they can do, you ca...
python|arrays|numpy|multidimensional-array
2
10,805
18,401,417
How do I add a column to a 2d array with specific dtype?
<p>Here is the code I wrote. The 'guteliste25.txt' contains a data table with a header where the names of the colums are specified.</p> <pre><code>import numpy as np d = 'guteliste25.txt' CNS = np.genfromtxt(d, dtype = None, names = True) dt = np.dtype([('R','&lt;f8')]) test = np.ones(len(CNS),dtype=dt) klaus = np.co...
<p>Its probably best to create a structured array from scratch and fill it:</p> <p>The two examples begin with:</p> <pre><code>import numpy as np from numpy.lib import recfunctions ints = np.ones(5,dtype=np.int) floats = np.ones(5,dtype=np.float) strings = np.array(['A']*5) </code></pre> <p>To create an empty struc...
python|numpy
0
10,806
18,293,186
Plotting moving average with numpy and csv
<p>I need help plotting a moving average on top of the data I am already able to plot (see below)</p> <p>I am trying to make m (my moving average) equal to the length of y (my data) and then within my 'for' loop, I seem to have the right math for my moving average.</p> <p>What works: plotting x and y</p> <p>What doe...
<p>The problem here lives in your computation of the moving average -- you just have a couple of off-by-one problems in the indexing !</p> <pre><code>y = value m = np.zeros(y.shape) for i in range(10, y.shape[0]): m[i-10] = y[i-10:1].mean() </code></pre> <p>Here you've got everything right except for the <code>:1]...
arrays|numpy|matplotlib|plot|average
1
10,807
61,730,340
How can I build a relation between columns in pandas?
<p>I have a data frame from the LASTFM dataset with columns: <strong>user_id | friend_id</strong> like so:</p> <pre><code>uid | fid 346 | 23 355 | 48 </code></pre> <p>and I would like to have a relation between users as a third columns (kind of an adjacency vector), such as:</p> <pre><code>uid1 | uid2 | friends 23 ...
<p>The strategy here is two step. First create the UID cross product dataset, then attach the friends indicator:</p> <p>Create the UID cross product by first taking the union of pairs from original dataset, along with their inverses. We'll create an intermediate dataset, <code>friends</code>, which we'll use later in ...
python|pandas|python-3.7|last.fm|knowledge-graph
1
10,808
34,302,229
Concatenating two series with None value (pandas DataFrame)?
<p>I am trying to concatenating two columns in pandas DataFrame. The problem is when there is None value exist in either series, the result is NaN. Since the real data is very large and there is value to keep original None values for later reference, I hope not to change the original value in the columns. Is there a ...
<p>Call <code>fillna</code> on each column to set the Nones to <code>''</code>, which is the identity element under string concatenation.</p> <pre><code>f['new_str'] = f.xx.fillna('') + f.yy.fillna('') </code></pre> <p>This gives a new column formatted the way you wanted:</p> <pre><code>&gt;&gt;&gt; f xx yy ...
python|pandas|dataframe
6
10,809
34,401,714
Is tensorflow lazy?
<p>Let's say you have some piece of code like this</p> <pre><code>import tensorflow as tf ... f = h*y + z*t #Just some expression involving other tensors. e = ... # some expression that does not involve f. result = tf.select(b, e, f) sess.run(result) </code></pre> <p>b is a boolean tensor of the same shape as e an...
<p><strong>TL;DR:</strong> TensorFlow is strict, so both <code>e</code> and <code>f</code> will be evaluated before the <code>tf.select()</code> node executes.</p> <p>This has caused some confusion. TensorFlow first prunes the dataflow graph based on which operations are <em>statically</em> required to produce the val...
tensorflow
15
10,810
34,027,499
Concatenate two columns in CSV: Python
<pre><code>AuthorID CityArrival CountryArrival Departure CountryDeparture DateDeparture DateArrival 1922 Paris France New York UnitedState 2008-03-10 2001-02-02 1002 LosAngeles UnitedState California UnitedState 2008-03-10 2008-12-01 1901 Paris France Lagos Nigeria 2001-03-05 2001-02...
<pre><code>import pandas as pd df = pd.read_csv(path) df['Arrival'] = df.CityArrival + ' ' + df.CountryArrival </code></pre>
python|csv|pandas
2
10,811
34,366,618
Transform pandas Timestamp to end of current month
<p>This is a follow-up to a <a href="https://stackoverflow.com/questions/18233107/pandas-convert-datetime-to-end-of-month">this question</a>, which was asked a few years ago. The output I'm getting makes me think date offsets in pandas have changed during that time.</p> <p>I have dates, and I want to move them to the ...
<p>Here are few alternatives:</p> <pre><code>import numpy as np import pandas as pd import pandas.tseries.offsets as offsets ONE_MONTH = np.array([1], dtype='timedelta64[M]') ONE_DAY = np.array([1], dtype='timedelta64[D]') df = pd.DataFrame(pd.to_datetime(['2014-01-15', '2014-01-31', '2014-02-01']), ...
python|pandas
4
10,812
37,113,531
Prevent Pandas from unpacking a tuple when creating a dataframe from dict
<p>When creating a DataFrame in Pandas from a dictionary, a tuple is automatically expanded, i.e.</p> <pre><code>import pandas d = {'a': 1, 'b': 2, 'c': (3,4)} df = pandas.DataFrame.from_dict(d) print(df) </code></pre> <p>returns</p> <pre><code> a b c 0 1 2 3 1 1 2 4 </code></pre> <p>Apart from converting...
<p>Try add <code>[]</code>, so value in <code>dictionary</code> with key <code>c</code> is <code>list</code> of <code>tuple</code>:</p> <pre><code>import pandas d = {'a': 1, 'b': 2, 'c': [(3,4)]} df = pandas.DataFrame.from_dict(d) print(df) a b c 0 1 2 (3, 4) </code></pre>
python|pandas
4
10,813
36,805,395
need to use different type of interpolation? numpy interp1d
<p>I have 2 columns of information. The 2nd column is time in seconds. The first column is error at that time. I need to make a vector that contains the value of error in seconds for 2.5s intervals. there should be 172 of them. Here is my data: <strong>col 0 = error, col 1 = time in seconds</strong></p> <pre><code> ar...
<p>I'd usually do this without interpolation, just using the most recent value (so no sampling from future data):</p> <pre><code>times = np.arange(orig[0,1], orig[-1,1], 2.5) indexes = np.searchsorted(orig[:,1], times, side='right') - 1 np.column_stack((orig[indexes,0], times)) </code></pre> <p>This gives you two col...
python|numpy|interpolation|linear-interpolation
2
10,814
36,923,494
Pandas DataFrame use previous row value for complicated 'if' conditions to determine current value
<p>I want to know if there is any faster way to do the following loop? Maybe use apply or rolling apply function to realize this Basically, I need to access previous row's value to determine current cell value.</p> <pre><code>df.ix[0] = (np.abs(df.ix[0]) &gt;= So) * np.sign(df.ix[0]) for i in range(1, len(df)): fo...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="noreferrer">.shift()</a> function for accessing <em>previous</em> or <em>next</em> values:</p> <p>previous value for <code>col</code> column:</p> <pre><code>df['col'].shift() </code></pre> <p>next value fo...
python|pandas|dataframe|apply
54
10,815
49,617,712
Select the first condition per group iteration
<pre><code> A B C D 0 01:00:00 2002-01-16 10 3 1 01:30:00 2002-01-16 10 -12 2 02:00:00 2002-01-16 10 7 3 01:00:00 2002-01-17 20 33 4 01:30:00 2002-01-17 20 -27 5 02:00:00 2002-01-17 20 12 results = {} </code></pre> <p>I want to select one row per each <code>A</code> grou...
<p>More or less what you have but using <code>groupby.apply</code>, also from your desired output it doesn't seem you prioritize the first condition, in which case, you need to combine the two conditions with <em>or</em> <code>|</code>:</p> <pre><code>def first_last(g): # this is used at multiple places, cache the...
python|pandas|conditional
2
10,816
28,087,429
SettingWithCopyWarning in pandas: how to set the first value in a column?
<p>When running my code I get the following message:</p> <pre><code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy df['detect'][df.index[0]] = df[...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow"><code>ix</code></a> to perform the index label selection:</p> <pre><code>In [102]: df = pd.DataFrame({'detect':np.random.randn(5), 'event':np.arange(5)}) df Out[102]: detect event 0 -0.815105 0 1 -0.656923 1 2 -1...
python|pandas|compatibility
1
10,817
73,283,413
Huggingface Transformers FAISS index scores
<p>Huggingface transformers library has a pretty awesome feature: it can create a FAISS index on embeddings dataset which allows searching for the nearest neighbors.<br></p> <pre><code>train_ds['train'].add_faiss_index(&quot;embedding&quot;) scores, sample = train_ds.get_nearest_examples(&quot;embedding&quot;, query_em...
<p>FAISS uses binning and PQ (Product Quantization) to yield approximate answers quickly and requiring considerably less memory. So the score might bounce around because of this approximation. It's not even guaranteed to find all KNN because of the approximation (due to sampling of only some bins, I think).</p> <p>So y...
huggingface-transformers|cosine-similarity|faiss
0
10,818
73,191,344
How to combine/reduce multiple rows from a dataframe that share the same ID based on a business rule?
<p>I have a dataframe that looks like this:</p> <pre><code> A B C. ID 0. 1. 0. 1. 1 1. 0. 0. 1. 2 2. 1. 1 0. 1 3. 0 1. 0. 3 ..... </code></pre> <p>I want to reduce the dataframe so that only unique ID's remain. The business rule I want to apply is that if user <code>n</code> has multiple rows then th...
<pre><code>pd.DataFrame( { 'A': {0: 1, 1: 0, 2: 1, 3: 0}, 'B': {0: 0, 1: 0, 2: 1, 3: 1}, 'C': {0: 1, 1: 1, 2: 0, 3: 0}, 'ID': {0: 1, 1: 2, 2: 1, 3: 3} } ).groupby('ID').max() </code></pre> <p>Output:</p> <pre><code> A B C ID 1 1 1 1 2 0 0 1 3 0 1 0 </cod...
python|pandas
1
10,819
73,352,538
check if values are between two values pandas
<p>I have a two values that are being found in a for loop like so:</p> <pre><code>for i in range(df_zones.shape[0]): filter_max = df_labels[df_labels['Labels'] == i].sort_values(by='level').iloc[-1] filter_min = df_labels[df_labels['Labels'] == i].sort_values(by='level').iloc[0] </code></pre> <p>I have another d...
<p>You can solve this with <code>apply</code> and pandas' <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.between.html" rel="nofollow noreferrer">between</a>:</p> <pre><code>df_zones['Flag'] = df_zones.apply(lambda x: 1 if x.between(filter_min,filter_max).any() else 0,axis=1) </code></pre> <p>How ab...
python|pandas|for-loop|boolean
1
10,820
35,257,786
Join two pandas dataframes based on line order
<p>I have two dataframes df1 and df2 I want to join. Their indexes are not the same and they don't have any common columns. What I want is to join them based on the order of the rows, i.e. join the first row of df1 with the first row of df2, the second row of df1 with the second row of df2, etc.</p> <p>Example:</p> <...
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>pd.concat([df1.reset_index(), df2.reset_index()], axis=1) </code></pre> <p>The <code>reset_index</code>() calls make the indices the same, then, <code>concat</code> with <co...
join|pandas|concatenation
2
10,821
67,540,087
How to remove special characters from a string before specific character?
<p>I have a <code>df</code> that has a column called <code>EMAIL</code>, which contains various email addresses. I want to remove all the special characters, specifically ., -, and _ that come before @ and append a new column <code>NEW_EMAIL</code>. For example, if <code>df['EMAIL'] = 'ab_cd_123@email.com'</code>, I w...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>df['NEW_EMAIL'] = df['EMAIL'].str.replace(r'[._-](?=[^@]*@)', '', regex=True) </code></pre> <p>See the <a href="https://regex101.com/r/oBjOvF/1" rel="nofollow noreferrer">regex demo</a>. <em>Details</em>:</p> <ul> <li><code>[._-]</code> - a <code>.</cod...
python|regex|pandas|special-characters|str-replace
4
10,822
67,555,365
How to Split Pandas DataFrames Based on a Status Column
<p>I have a DataFrame that looks somehow like the following one:</p> <pre><code> time status A 0 0 2 20 1 1 2 21 2 2 2 20 3 3 2 19 4 4 10 18 5 5 2 17 6 6 2 18 7 7 2 19 8 8 2 18 9 9 ...
<p>Input data:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df time status A 0 0 2 20 # group 1 1 1 2 21 # 1 2 2 2 20 # 1 3 3 2 19 # 1 4 4 10 18 # group 2 5 5 2 17 # group 3 6 6 2 18 # 3 7 7 2 19 # 3...
python|pandas|dataframe|split|slice
1
10,823
67,530,442
how to use collate_fn properly in the code below?
<p>My code is:</p> <pre class="lang-py prettyprint-override"><code>model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) dataset = PennFudanDataset('PennFudanPed', get_transform(train=True)) data_loader = torch.utils.data.DataLoader( dataset, batch_size=2, shuffle=True, num_workers=4, collate_fn...
<p>Ok so I read the tutorial and it seems that it wants you to use the helper files in this repository: <a href="https://github.com/pytorch/vision/tree/master/references/detection" rel="nofollow noreferrer">https://github.com/pytorch/vision/tree/master/references/detection</a> .</p> <p>In there is the <code>utils.py</c...
python|machine-learning|pytorch|pytorch-dataloader
1
10,824
34,738,010
Turn a non-symmetric 3 dimensional list into a 2 dimensional list of lists in python
<p>I have a list that takes the shape</p> <pre><code>[[1,1],[2,2,2]],[[3,3],[4,4],[5,5,5]] </code></pre> <p>which when turned into a numpy array becomes</p> <pre><code>[[1 1],[2 2 2]], [[3 3 3],[4 4],[5 5 5]] </code></pre> <p>so to be clear, i have a list made up of 2 lists and each of those lists are made up of li...
<p>You could simply use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.concatenate.html" rel="nofollow"><code>np.concatenate</code></a> -</p> <pre><code>np.concatenate(input_list) </code></pre> <p>Sample run -</p> <pre><code>In [19]: input_list = [[1,1],[2,2,2]],[[3,3],[4,4],[5,5,5]] In [...
python|arrays|list|numpy
3
10,825
60,031,321
Python - Plotting two 3D graphs with a contour map
<p>I am trying to plot a figure in Python with two 3D graphs (same function, different angles) and a 2D contour map of the same function and I'm not sure why but the two first figures are okay and the contour map is weird, it appears at the bottom of the two first figures and the sizing is all weird (see the picture at...
<p>Got it:</p> <pre><code>import numpy as np import matplotlib.pylab as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D x = np.arange(-5, 5, 0.01) y = np.arange(-5, 5, 0.01) X, Y = np.meshgrid(x, y) Z = 5 + (10 * X**2 + 20 * Y**2) * np.exp((-X**2)-(Y**2)) + 3 *np.sin(X) - np.sin(Y) fig = plt....
python|numpy|matplotlib|3d
0
10,826
59,968,955
Adding background color to panda dataframe
<p>I have a pivot table created using Pandas looks like below: <a href="https://i.stack.imgur.com/E1Eqt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1Eqt.png" alt="enter image description here"></a></p> <p>How can I achieve this?</p>
<p>You can create DataFrame of styles with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>Styler.apply</code></a> and set rows by index value with <code>loc</code>:</p> <pre><code>df = df.reset_index() def color(x): c1 ...
python|pandas|pivot-table
1
10,827
60,236,598
Read_Csv() not giving expected output ,After If i update any cell in csv
<p>1) Creation of DF</p> <pre><code>import pandas as pd li=[["10","Data","String","01249","0199"],["10","Data","String","",""]] df=pd.DataFrame(li) df.to_csv("Dummy.csv") </code></pre> <p>2)Dummy.csv Looks like</p> <pre><code> 0 1 2 3 4 0 10 Data String 1249 199 1 10 Data String </code></pre> <p>3) T...
<p>It is an Excel issue as opposed to python.</p> <p>Change the type of the whole column (by clicking on the column letter) to <strong>text</strong> instead of general. General means that you are allowing Excel to guess the datatype, and since these are numbers it omits the leading zero.</p>
python|pandas|csv
0
10,828
59,963,431
Efficient way of tracking Ordinal data movement over time
<p>I have some ordinal data column in my dataframe and would like to track how these category goes up or down in the hierarchy over time.</p> <p>For instance if my dataframe looks like:</p> <pre><code>Date Animal OrdinalCategory Mar A Good Mar B Worse Jun A Bad Jun B Worse Jun ...
<p>Dealt with this in a slightly different way.</p> <pre><code>ordered_categpry = ['NA', 'Good', 'Bad', 'Worse'] df.OrdinalCategory.astype("category", ordered=True, categories=ordered_categpry ).cat.codes </code></pre> <p>And for the Entry Exit prob, created two columns to indicate when the animal entered first a...
python|pandas
0
10,829
65,089,750
How to merge multiple CSV files with different languages into one CSV file?
<p>I have a lot of CSV files and I want to merge them into one CSV file. The thing is that the CSV files contain data in different languages like Russian, English, Croatian, Spanish, etc. Some of the CSV files even have their data written in multiple languages.</p> <p>When I open the CSV files, the data looks perfectly...
<p>When you force the input encoding to Latin-1, you are basically wrecking any input files which are not actually Latin-1. For example, a Russian text file containing the text <code>привет</code> in code page 1251 will silently be translated to <code>ïðèâåò</code>. (The same text in the UTF-8 encoding would map to t...
python|pandas|csv|encoding
2
10,830
65,118,810
how to get a list of stock tickers by entering a sector name
<p>I am trying to write a code to return a list of stock tickers when entering a sector name.</p> <p>for example, MSFT is in the technology sector in yfinance and I want the remaining companies that belong to this particular sector.</p> <pre><code>import yfinance as yf msft= yf.Ticker(&quot;MSFT&quot;) print(msft.info...
<p>That data can be retrieved pretty easily with a package called <a href="https://yahooquery.dpguthrie.com/guide/screener/#get_screeners" rel="nofollow noreferrer">yahooquery</a>. Disclaimer: I am the author of the package.</p> <p>To get stocks in the technology sector, you can do the following:</p> <pre><code>from ...
python|pandas|dataframe|finance|yfinance
2
10,831
65,241,301
Split single dataframe into multiple dataframe
<p>I'm trying to split a single dataframe into multiple dataframes as follows:</p> <ol> <li>this is my df:</li> </ol> <pre><code>Date Attributes Symbols value 11/12/2019 Adj Close AALR3.SA 18.001.112 11/12/2019 Adj Close ABCB4.SA 18.298.676 11/12/2019 Adj Close ABEV3.SA 17.977.827 12/...
<blockquote> <p>I'm trying to separate it into multiple data frames to get this..</p> </blockquote> <p>It's a bit unclear why you are trying to replace the <code>.SA</code> string, but based on the input and the expected output that you mention here is what you can do.</p> <p>You can iterate over the data frames create...
python|pandas|dataframe|for-loop
0
10,832
65,134,556
Compute cumulative euclidean distances between subsequent pairwise coordinates
<p>I have the following 2 arrays:</p> <pre><code>X = array([37., 42., 31., 27., 37.]) Y = array([52., 57., 62., 68., 69.]) </code></pre> <p>I could alternatively combine them as follows with this:</p> <pre><code>XY = np.array((X, Y)).T </code></pre> <p>which produces</p> <pre><code> ([[37., 52.], [42., 57.], [31...
<p>You can do it completely vectorized one-liner with ANY loops as the following with broadcasting -</p> <ol> <li>First, <code>(5,1,2) broadcasted with (1,5,2) -&gt; (5,5,2)</code></li> <li>Subtract with this broadcast to get <code>(5,5,2)</code></li> <li>Then square each element in the <code>(5,5,2)</code></li> <li>Su...
python|numpy|scipy|vectorization|distance
3
10,833
50,150,694
Assigning states of Hidden Markov Models by idealized values intensity values.
<p>I'm running the pomegranate HMM (<a href="http://pomegranate.readthedocs.io/en/latest/HiddenMarkovModel.html" rel="nofollow noreferrer">http://pomegranate.readthedocs.io/en/latest/HiddenMarkovModel.html</a>) on my data, and I load the results into a Pandas DF, and define the idealized intensity as the median of all ...
<p>It looks like you just need to define a sorted HMM state like this:</p> <pre><code>state_orders = {v: i for i, v in enumerate(sorted(df.hmm_idealized.unique()))} df['sorted_state'] = df.hmm_idealized.map(state_orders) </code></pre> <p>Then you can continue as you did in the question, but taking a diff on this colu...
python|pandas|hidden-markov-models
2
10,834
50,012,399
string split and assign unique ids to Pandas DataFrame
<p>I have following dataframe</p> <pre><code>MESSAGE DOCUMENT_ID 0 @Zuora wants to help @Network4Good with Hurricane and hurriacane... 263403828328665088 1 @ztrip please help spread the good word on hello and hello... 264142543883739136 2 #ZSwaggers @Zendaya9...
<p>use <code>nltk</code> to segment the <code>MESSAGE</code>, then make Cartesian product with document_id and words, and then use <code>groupby</code> and <code>count</code>.</p> <pre><code>import nltk from itertools import product from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) df[...
regex|python-3.x|pandas|numpy
0
10,835
50,060,320
how to match the column value from one file to another using pandas dataframe
<p>I need to insert data from excel then match it to another excel data using vc_no column and Type (Secondary, Primary) as my key to put the data to respective column. here's an example:</p> <h1>First excel file</h1> <pre><code> secondary pairs primary pair vc_no stat vc_no1 c_re...
<p>Several methods are possible, here one example if I understand well your question. I created my input with only necessary columns in <code>df_first</code> and <code>df_source</code> but if you get other columns when you read excel, no problem normally.</p> <pre><code>import pandas as pd # Create both DF with used d...
python|pandas|dataframe
1
10,836
63,914,656
How can I round each entry (which is a tuple) of a pandas dataframe in Python?
<pre class="lang-py prettyprint-override"><code>import pandas as pd D = {&quot;a&quot;:[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)], &quot;b&quot;:[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)], &quot;c&quot;:[(1.0411070751196425, 1.0...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>DataFrame.applymap</code></a> for elementwise processing with generator comprehension and tuples:</p> <pre><code>D = D.applymap(lambda x: tuple(round(y,4) for y in x)) print (D) ...
python|pandas|decimal|rounding
4
10,837
64,083,185
Problem with dataframe using beautiful soup
<p>I create a dataframe using beautiful soup scraping the data. However, there have 2 problems.</p> <ol> <li>Why does the for loop run 2 times?</li> <li>How to remove the brackets on the data frame?</li> </ol> <p>import urllib.request as req</p> <pre><code>from bs4 import BeautifulSoup import bs4 import requests import...
<p>To get information about the company, you don't have to loop over the <code>soup</code>, just extract necessary information directly. To get rid of <code>[..]</code> brackets, use <code>.text</code> property:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://finance.yahoo.com/quote/BF-B/p...
python|pandas|dataframe|beautifulsoup
0
10,838
64,008,893
Create a distance matrix from Pandas Dataframe using a bespoke distance function
<p>I have a Pandas dataframe with two columns, &quot;id&quot; (a unique identifier) and &quot;date&quot;, that looks as follows:</p> <pre class="lang-none prettyprint-override"><code>test_df.head() id date 0 N1 2020-01-31 1 N2 2020-02-28 2 N3 2020-03-10 </code></pre> <p>I have created a custom Python fun...
<p>Let us try <a href="https://docs.scipy.org/doc/scipy-0.17.0/reference/generated/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer"><code>pdist</code></a> + <a href="https://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.spatial.distance.squareform.html#scipy.spatial.distance.squareform...
python-3.x|pandas|matrix|distance|adjacency-matrix
2
10,839
63,833,354
python pandas how to get data every n and every nth rows?
<p>This question is not same as pandas every nth row or every n row,please don't delete it.</p> <p>Following are some rows of my table:</p> <pre><code>open high low close volume datetime 277.14 277.51 276.71 276.8799 968908 2020-04-13 08:31:00.000 245.3 246.06 245.2 246.01 1094537 2020-04-13 08:32...
<p>Use generator with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> to select the desire rows:</p> <pre><code>def rows_generator(df): i = 0 while (i+3) &lt;= df.shape[0]: yield df.iloc[i:(i+3):1, :] ...
python|python-3.x|pandas
2
10,840
63,807,765
Get sentiment score of emoji #Python
<pre><code>df 0 NaN 1 NaN 2 3 NaN 4 ❤ ... 26368 NaN 26369 NaN 26370 NaN 26371 26372 NaN Name: emojis, Length: 26373, dtype: object </code></pre> <p>From the df above, I would like to calculate the sentiment score of the emojis in each row. If NaN, then re...
<p>From your error, I'm guessing <code>get_emoji_sentiment_rank(text)[&quot;sentiment_score&quot;]</code> fails if text is <code>NaN</code>, so you can either apply the function and assign the update only to the rows that re non-nan (preferable, but you first need to crate the column <code>emoji_sentiment</code> with a...
python|pandas|emoji|sentiment-analysis
0
10,841
63,781,846
Best way to split multi values of columns into multiple rows in python
<p>This is how my data looks,</p> <pre><code>emp_id col1 col2 col3 1234,abc|de,2020|2011,89 5639,ma,2010|2019,90 </code></pre> <p>This is how data need to be changed and saved into the file</p> <pre><code> emp_id col1 col2 col3 1234 abc 2020 89 1234 abc 2011 89 1234 de 2020 89 1234 de ...
<p>I don't think I have the easiest way but the following code works on your example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # read your example df = pd.read_csv( io.StringIO( r&quot;&quot;&quot;emp_id,col1,col2,col3 1234,abc|de,2020|2011,89 5639,ma,2010|2019,90&quot;&quot;&...
python-3.x|pandas
0
10,842
46,648,536
Tensorflow initialize certain scope only
<p>He there,</p> <p>I have a question regarding control over which variable scope is initialized, or at least, which variable scope is used during the run.</p> <p>Take for example this easy piece of code</p> <pre><code>import numpy as np import tensorflow as tf with tf.variable_scope('0') as scope: place_holder...
<p>Try this:</p> <pre><code>import numpy as np import tensorflow as tf g1 = tf.Graph() with g1.as_default() as g: with tf.variable_scope('0') as scope: place_holder_batch_x = tf.Variable(np.random.rand(11,6), dtype=tf.float64) place_holder_batch_y = tf.Variable(np.random.rand(8,5), dtype=tf.float...
python|tensorflow
1
10,843
47,003,784
Using condition in function while generating values for dataframe
<p>I have to create a dataframe having columns start_date and end_date where <code>end_date &gt; start_date</code> using a function which randomly generates date values.</p> <p>I tried something like this:</p> <pre><code>Project = pd.DataFrame({'Name': np.random.choice(['Starbucks','Macdonalds', 'KFC', 'Maruti', ...
<p>Idea is generate random <code>end time</code> from <code>start time</code> by adding random <code>timedelta</code>:</p> <pre><code>N = 10 shift_end_date = 20 def gen_datetime(min_year=2017, max_year=datetime.now().year): start = date(min_year, 10, 28) years = max_year - min_year + 1 end = start + timede...
python-3.x|pandas|numpy
1
10,844
46,840,960
IndexError: At least one sheet must be visible
<pre><code> def multiple_dfs(sheet, row=2): writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl') f1 = { 'user': ['Bob', 'Jane', 'Alice'], 'income': [40000, 50000, 42000], } f2 = { 'amount': ['Chest', 'Bras', 'Braa'], 'income': [40000, 50000, 42000] } f...
<p>Alternatively, if you don't need to load a workbook, you can merely use xlsxwriter instead of openpyxl; it hasn't this problem. You can also create a workbook with the regular </p> <pre><code>from openpyxl import Workbook #... wb= Workbook() ws=wb.active with pd.ExcelWriter(output_filepath, engine="openpyxl") as wr...
python|pandas
14
10,845
33,047,379
Summarize a column in pandas data frame based on other columns
<p>I have a small data frame tbl: </p> <pre><code> CatAreaSqKm CatMean CatPctFull CatCount CatSum COMID 1861888 0.2439 0.0000 0.000000 0 0.000000 1862004 0.4050 27.9765 18.222222 82 2294.072964 ...
<p>Dividing by zero results in a NaN value. You could use <code>fillna(0)</code> to replace the NaNs with zeros:</p> <pre><code>tbl['WsMean'] = ((tbl.CatSum + tbl.UpCatSum)/(tbl.CatCount + tbl.UpCatCount)).fillna(0) </code></pre>
python|pandas
3
10,846
32,679,403
Python: dangers of temporarily changing the random seed using a context manager?
<p>When aiming for reproducibility in Python code using random number generators, the recommended approach seems to be to construct separate RandomState objects. Unfortunately, some essential packages like scipy.stats cannot (to the best of my knowledge) be set to use a specific RandomState and will just use the curren...
<p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.set_state.html#numpy.random.set_state" rel="nofollow">numpy documentation</a> claims:</p> <blockquote> <p>set_state and get_state are not needed to work with any of the random distributions in NumPy. If the internal state is manually ...
python|numpy|random|contextmanager|random-seed
4
10,847
32,851,388
Attribute error float object has no attribute 'append'
<p>I try to make this code to open LAS files make a change and then save the result in a new LAS file. The las file contains points which have coordinates (X and Y) and values (like Z for elevation). Unfortunately the code works if I don't put the saving part into it, but when I do like below, I got the following error...
<p>You set <code>p</code> to a <code>float</code> at the start of your outer <code>while</code> loop:</p> <pre><code>p=0.1 </code></pre> <p>That masks the <code>numpy</code> import at the top:</p> <pre><code>import numpy as p </code></pre> <p>so within the <code>while</code> loop <code>p</code> is no longer the mo...
python|numpy|lidar
5
10,848
38,650,482
Tensorflow from source master gives a syntax error from import
<p>I tried compiling tensorflow from sources (master) and follow the <a href="https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#create-the-pip-package-and-install" rel="nofollow noreferrer">tensorflow instructions</a> using <code>python3</code> instead of <code>python2</code> (and <code>pip</code> defa...
<p>It looks like the installed <code>dateutil</code> package (which TensorFlow depends on via <code>dask</code> and <code>pandas</code>) is incompatible with Python 3, using backticks as a synonym for <code>repr()</code>, which was removed in 3.0. The particular line from <code>dateutil/parser.py</code> where the error...
tensorflow|python-3.5|ubuntu-16.04
6
10,849
38,704,648
How to fix Numpy REFS_OK flag error?
<p>I have the following code:</p> <pre><code>import cv2 import numpy as np image = cv2.imread('pic1.png', cv2.IMREAD_GRAYSCALE) height = 0 count = 0 it = np.nditer(image) for(x) in it: count += 1 if count == 80: count = 0 height += 1 if x &gt; 400: print("Heigh...
<p>Check that the returned <code>image</code> variable isn't <code>None</code>. Perhaps the image is not in the path your script is run from. OpenCV doesn't raise an exception when it can't read/load the image, but, rather, returns <code>None</code>, in which case weird exceptions you will meet, when you try to operate...
python|opencv|numpy
0
10,850
38,581,263
regarding printing the shape of tensor
<p>I test the following code script</p> <pre><code>import tensorflow as tf a, b, c = 2, 3, 4 x = tf.Variable(tf.random_normal([a, b, c], mean=0.0, stddev=1.0, dtype=tf.float32)) s = tf.shape(x) print(s) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) print(sess.run(s)) </code></pre> <p>Ru...
<p>The call to <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#shape" rel="nofollow"><code>s = tf.shape(x)</code></a> defines a symbolic (but very simple) TensorFlow computation that only executes when you call <code>sess.run(s)</code>.</p> <p>When you execute <code>print(s)</code> Pyt...
tensorflow
1
10,851
63,186,507
pandas find median after group by
<p><a href="https://i.stack.imgur.com/oDsug.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oDsug.png" alt="enter image description here" /></a></p> <p>df.head(10).to_clipboard(sep=';', index=True)</p> <p>I have a dataframe as above and I have the following column descriptions</p> <pre><code>• Id -...
<p>Here is how I would do to display required figures:</p> <pre class="lang-py prettyprint-override"><code># Subset dataframe to only have the desired plan_id sub_Tx = Tx[Tx['plan_id'] == '869BB6FB-.....'] # median of deliveries per route in the given plan sub_df = sub_Tx[['plan_id', 'route_id']] sub_df['count_deliver...
python|pandas|pandas-groupby
0
10,852
62,998,785
Comparing two lists and add a new column with the results
<p>Comparing two lists and add a new column with findKB different</p> <pre><code>df = pd.DataFrame({'A': [['10', '20', '30', '40'],['50', '60', '70', '80']], 'B': [['a', 'b'],['c','d']]}) findKBs = ['10','90'] A B 0 [10, 20, 30, 40] [a, b] 1 [50, 60, 70, 80] [c, d] </code><...
<p>We can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>np.isin</code></a></p> <pre><code>df['C'] = [find_kb[~np.isin(find_kb, a)] for a, find_kb in zip(df['A'], np.array([findKBs] * len(df)))] print(df) A B C ...
python|pandas
4
10,853
63,128,654
Groupby agg mean and count incl. datetime values
<p>Main_df</p> <pre><code>product_id viewed_date viewed_storeA viewed_storeB viewed_storeA_first time_delta 323224 2019-04-01 2019-04-01 08:01 2019-04-01 08:20 True 00:19:00 942234 2019-04-01 2019-04-01 08:13 2019-04-01 08:43 True 00:30:00 424244 2019-04-01 2...
<ul> <li>Currently, your <code>time_delta</code> column is a <code>timedelta64</code> datatype, but to perform aggregation functions, it needs to be an integer</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'product_id': [323224, 942234, 424244, 749249, 224345], 'viewed_...
python|pandas
0
10,854
63,270,075
Group by range of row numbers in a dataframe
<p>I have a dataframe with 5000 rows, I want to split it into multiple dataframes based on the row value.</p> <pre class="lang-py prettyprint-override"><code>object result 1200 1 1201 0 1202 1 1203 0 1204 0 ...
<p>You could do it using division.</p> <pre><code>df['groupObject'] = df['object'].div(50).round().astype(int) </code></pre> <p>Now, you want to split the individual ints in the dataframe. Here are all our groups:</p> <pre><code>groups = df['groupObject'].unique().values.tolist() dfs = [] for group in groups: dfs.a...
python|pandas|dataframe|split|pandas-groupby
0
10,855
62,924,866
does Numpy have any dictionary and tuple same as python?
<p>is there any built-in function in <code>NumPy</code> that I can keep both value and array in it? something like <code>x = [1,3,[3,4,2],4,[2,6]]</code>. I try <code>numpy.array</code> <code>append</code> method but it returns something like <code>x=[1,3,3,4,2,4,2,6]</code> is there something like tuple or dictionary ...
<p>In numpy, you cannot have a non rectangular array of objects. Therefore, you need to store your inner lists as single objects (either list or array).</p> <p>If you want your elements to be lists:</p> <pre><code>x = np.array([1,3,[3,4,2],4,[2,6]]) #[1 3 list([3, 4, 2]) 4 list([2, 6])] </code></pre> <p>and if you want...
python|arrays|numpy|numpy-ndarray
0
10,856
68,018,701
Python: Pandas read_excel cannot open .xls file, ValueError: File is not a recognized excel file
<p><strong>Problem:</strong></p> <p>I got an error when I tried to open a <code>product.xls</code> with <code>pd.read_excel</code> (&quot;NDC database file - Excel version (zip format)&quot; downloaded from <a href="https://www.fda.gov/drugs/drug-approvals-and-databases/national-drug-code-directory" rel="nofollow nore...
<p>I had a similar issue, where I had to read and combine a bunch of .xls files in a folder into one single dataframe. Turns out the error arose because .txt files were forcibly saved as .xls files. This also generated an error in excel upon attempting to open the file, which said</p> <blockquote> <p>&quot;The file for...
python|excel|pandas|openpyxl|xlrd
3
10,857
31,776,014
Pandas: Convert DataFrame to Mean and Standard Deviation of Each Cell
<p>I have an unconventional DataFrame (which was read in from a csv). It looks like this:</p> <pre><code>SubjAns a1 a2 demog S1A1 "1,2,3" "4,6" A S1A2 "101,1" NaN B </code></pre> <p>For each cell, I first need to convert the string to a list of floats (Is there a way for pandas to ...
<p>One way, is to write a mini parse-then-stat function</p> <pre><code>In [270]: df Out[270]: SubjAns a1 a2 demog 0 S1A1 1,2,3 4,6 A 1 S1A2 101,1 NaN B </code></pre> <p>This, creates a float list, then numpy array and returns mean and std</p> <pre><code>In [271]: def split_stat(x): .......
python|csv|pandas|scikit-learn|dataframe
4
10,858
41,610,667
ValueError in rank method in pandas without more explanation
<p>I have a pandas Dataframe like this :</p> <pre><code> year week city avg_rank 0 2016 52 Paris 1 1 2016 52 Gif-sur-Yvette 2 2 2016 52 Paris 1 3 2017 1 Paris 4 4 2016 52 Paris 3 5 2016 ...
<p>Since my DataFrame came from several files, I noticed that some indexes were duplicated.</p> <p>With</p> <pre><code>df.index = np.arange(df.shape[0]) </code></pre> <p>just after loading the data, it now works.</p> <p>Indeed, my hypothesis is that in some groups in the groupby there were sometimes rows with same ...
python|pandas
9
10,859
41,473,476
Why does a numpy array with dtype=object result in a much smaller file size than dtype=int?
<p>Here an example:</p> <pre><code>import numpy as np randoms = np.random.randint(0, 20, 10000000) a = randoms.astype(np.int) b = randoms.astype(np.object) np.save('d:/dtype=int.npy', a) #39 mb np.save('d:/dtype=object.npy', b) #19 mb! </code></pre> <p>You can see that the file with dtype=object is about half...
<p>With a non-object dtype, most of the npy file format consists of a dump of the raw bytes of the array's data. That'd be either 4 or 8 bytes per element here, depending on whether your NumPy defaults to 4- or 8-byte integers. From the file size, it looks like 4 bytes per element.</p> <p>With an object dtype, most of...
python|numpy
7
10,860
27,686,726
Importing a module under a module (pandas.io.data)
<p>I've just encountered something that bothers me.<br> I always thought that importing a 'parent' module should import everything under it.<br> But, when running:<br></p> <pre><code>import pandas pandas.io.data </code></pre> <p>I get an error: <code>AttributeError: 'module' object has no attribute 'data'</code>.</p>...
<p>The reason for this is that <code>pandas.io</code> is a submodule of the <code>pandas</code> package. Subpackages or submodules are not imported automatically, although you can do this in the <code>__init__.py</code> of your module if you wish to (usually you don't want to do this).</p> <p><a href="https://docs.pyt...
python|pandas|import|module
2
10,861
61,390,019
Removing some characters in a DataFrame
<p>I have a problem on replacing this value "..." by NaN. Here is my code</p> <pre><code> import pandas as pd import numpy as np energy = pd.read_excel('Energy Indicators.xls') del energy['Unnamed: 0'] del energy['Unnamed: 1'] energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capi...
<p>Your problem is that replace returns a DataFrame by defaulft (see <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">doc</a>). To solve this you can either</p> <pre class="lang-py prettyprint-override"><code>energy = energy.replace("...", np....
python|pandas
1
10,862
61,296,707
subtract x columns in one df from x columns in another and maintain other columns
<p>I have three string columns and three value columns in two separate dfs. I am trying to subtract the values in the one df from the values in the other while maintaining the string columns. If an entry is in one df but not the other, I need to keep it and and subtract 0 or vice versa. Code below simplified, but in my...
<p>If you set the same index on both <code>DataFrame</code>s then you can use normal arithmetic.</p> <pre><code>keys = ['lvl1', 'lvl2', 'lvl3'] df1 = df1.set_index(keys) df2 = df2.set_index(keys) df2 - df1 # val1 val2 val3 # lvl1 lvl2 lvl3 # a b c 7.0 7.0 7.0 # d ...
python|python-3.x|pandas
2
10,863
61,323,621
How to understand hidden_states of the returns in BertModel?(huggingface-transformers)
<blockquote> <p>Returns last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)): Sequence of hidden-states at the output of the last layer of the model.</p> <p>pooler_output (torch.FloatTensor: of shape (batch_size, hidden_size)): Last layer hidden-state of the first token...
<blockquote> <p>hidden_states (tuple(torch.FloatTensor), optional, returned when config.output_hidden_states=True): Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).</p> </blockquote> <blockquote> <p>Hidden-states of...
nlp|pytorch|huggingface-transformers|bert-language-model|electrate
15
10,864
61,229,102
How can I change the data types of multiple dataframe columns based on a condition in python?
<p>I have a data frame with 80 columns, for some columns data types should be integers but python sees them as float. Rather than manually changing the data types I am trying to write a loop that identifies the datatype that a column contains and changes the data type accordingly. I have tried the following options but...
<p>Use:</p> <pre><code>df = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5.,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1.8,3.3,5,7,1,0], 'E':[5.0,3,6,9,2,4], 'F':list('aaabbb') }) print (df) A B C D E F 0 a 4.0 7 1.8 5.0 a 1 b 5.0 8 3.3 3.0 a 2 c 4.0...
python|pandas|dataframe
2
10,865
61,303,821
Filling up dataframe columns based on condition in pandas
<p>I have two dataframes , like below </p> <pre><code> df_input df_output id POLL_X POLL_Y POLL_Z .. id Pass_01 Pass_02 Pass_03 ..... 110101 1 2 4 110101 110102 2 1 3 110102 </code></pre> <p>and ...
<p>I assume that at the start you have <em>df_output</em> with proper column names (as they should be after filling).</p> <p>To do your task:</p> <ol> <li><p><code>import re</code> (will be used in a moment).</p></li> <li><p>Define the following function generating an outpu row, based on a source row:</p> <pre><code...
python|python-3.x|pandas|python-2.7|dataframe
1
10,866
68,545,007
Formula that maps the index of a numpy array to the corresponding index in the flattened vector?
<p>As in the title, what is the formula that maps the index of a numpy array to the corresponding index in the flattened vector?</p> <p>As a concrete example:</p> <pre><code>np.random.seed(2021) X = np.random.normal(size=(5,4,3)) x = X.flatten(order='C') ix = (1,2,2) </code></pre> <p>What is the formula to calculate th...
<p>You can create a function that retunes partial index based on the relative position of the value in <code>X</code> buy multiplying the number of arrays and rows with the values in <code>ix</code></p> <pre><code>def calculate_index(x, i): return x[0].size * i np.random.seed(2021) X = np.random.normal(size=(5, 4,...
python|arrays|numpy|tensor
1
10,867
68,503,388
Pandas grouped aggregation with multiple columns as inputs to a user defined function
<p>I am still trying to learn pandas. I have a custom user defined function which will require two columns as input. It is an aggregation function so it needs to be done by group.</p> <p>This is my question: How can I get a grouped aggregation with multiple columns as inputs to a user defined function?</p> <p>Here is m...
<p>I think this does what you are looking for</p> <pre><code>import pandas as pd import numpy as np def first_b_over_avg_c(group): first_b = group['b'].iloc[0] avg_c = np.mean(group['c']) return first_b / avg_c np.random.seed(42) df = pd.DataFrame( { &quot;a&quot;: [&quot;one&quot;, ...
python|pandas|dataframe
0
10,868
36,384,760
Transforming a row vector into a column vector in Numpy
<p>Let's say I have a row vector of the shape (1, 256). I want to transform it into a column vector of the shape (256, 1) instead. How would you do it in Numpy?</p>
<p>you can use the <strong><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.transpose.html" rel="noreferrer">transpose</a></strong> operation to do this:</p> <p>Example:</p> <pre><code>In [2]: a = np.array([[1,2], [3,4], [5,6]]) In [5]: a.shape Out[5]: (3, 2) In [6]: a_trans = a.T #or: np.tra...
python|numpy|multidimensional-array|linear-algebra|numpy-ndarray
30
10,869
36,670,530
Sorting a pandas data frame by a series
<p>Pandas data frames can be sorted by values of its columns, but I wanted to sort a data frame by values of a series that I don't want to add to the data frame - although it has the same indexes.</p> <p>I got my data frame sorted by adding the series to the data frame (as a column), sorting, and removing the column a...
<p><code>sort_values</code> returns the sorted series, so take the index of this and name it <code>idx</code>. Because the index of <code>s</code> corresponds to that of <code>df</code>, you can use <code>loc</code> together with <code>idx</code> to then rearrange the rows based on the sorted value of `s.</p> <pre><c...
pandas
3
10,870
53,324,376
Get a sample of aggregated row values with pandas
<p>I need a function that given a data frame and a number <code>num</code> constructs a data frame with <code>num</code> rows such that every row has the following value: - for columns with string values we sample a value from a column in original table - for columns with floats or ints we find mean value</p> <p>Here ...
<p>One error seems that the condition <code>column.dtype != np.number</code> does not work. Then there is a problem with index alignment when you do <code>pd.concat([row, item], axis=1)</code>, <code>item</code> contains an index number that is not always the same and this add rows with <code>Nan</code> in <code>row</c...
python|pandas
1
10,871
65,750,458
CNN Model Training Problem (%16 Accuracy)
<p>I have a homework about Neural Networks. I need to develop a flower recognition application.</p> <p>First of all, i tried to learn how to classify cat-dog photos from <a href="https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/" rel="nofollow noreferr...
<p>You have 5 classes. Therefore you are no longer doing binary classification. Here are the things you need to change</p> <pre><code>In train_it and test_it change class_mode to 'categorical' code model.add(Dense(1,activation='sigmoid')) should be changed to model.add(Dense(5,activation='softmax')) code model.compil...
python|tensorflow|keras|neural-network|conv-neural-network
1
10,872
65,636,233
seaborn heatmap color map
<p>I have a dataframe <code>df</code> with values from 0 to x (x is integer and no fixed value), in my example is x=10</p> <p>I want to map the heatmap with cmap 'Reds', however where value 0 is should not be white but green '#009933'</p> <pre><code>import seaborn as sns # matplotlib inline import random data = [] for...
<p>As an alternative to the <a href="https://stackoverflow.com/a/65636565/3944322">accepted answer</a> you could also set <code>vmin</code> to slightly above <code>0</code> and define the color for out-of-range values with <a href="https://matplotlib.org/api/_as_gen/matplotlib.colors.Colormap.html?highlight=set_under#m...
python|pandas|numpy|seaborn
4
10,873
65,522,147
Convert seconds to date and time in python
<p>I have a DataFrame with a column containing seconds and I would like to convert the column to date and time and save the file with a column containing the date and time .I Have a column like this in seconds</p> <pre><code>time 2384798300 1500353475 7006557825 1239779541 1237529231 </code></pre> <p>I was able to...
<p>Use <code>df.apply</code>:</p> <pre><code>In [200]: from datetime import datetime In [203]: df['time'] = df['time'].apply(lambda x: datetime.fromtimestamp(x).strftime(&quot;%A, %B %d, %Y %I:%M:%S&quot;)) In [204]: df Out[204]: time 0 Friday, July 28, 2045 01:28:20 1 ...
python|pandas|dataframe
0
10,874
65,797,718
Pandas check that a list is is_monotonic_increasing but with specific step
<p>Lets say that we have these columns in a df:</p> <pre><code> A B C 0 1 0 1 1 2 2 2 2 3 4 4 3 4 6 6 4 5 8 8 </code></pre> <p>I know that I can check that every specific columns with monotonic_increasing like that</p> <pre><code>df['A'].is_monotonic_increasing. </code></pre> <p>I was wondering if th...
<p>I don't think there's a function for that. We can build a two-line function:</p> <pre><code>def step_incr(series, step=1): tmp = np.arange(len(series)) * step return series.eq(series.iloc[0]+tmp).all() step_incr(df['A'], step=1) # True step_incr(df['B'], step=1) # False </code></pre> <p>Another way to chec...
pandas|dataframe
2
10,875
65,779,183
How to import data from CSV file containing certain words?
<p>I have a CSV file containing daily data on yields of different government bonds of varying maturities. The headers are formatted as by the country followed by the maturity of the bond, for eg UK 10Y. What I would like to do is just import all the yields for one government bond at all maturities for one date, so for ...
<p>You can try:</p> <pre><code>import time import datetime col_to_check = &quot;UK government bond yields&quot; get_after = &quot;07/01/2021&quot; get_after = time.mktime(datetime.datetime.strptime(get_after, &quot;%d/%m/%Y&quot;).timetuple()) with open(&quot;yourfile.csv&quot;, &quot;r&quot;) as msg: data = ms...
python|pandas
0
10,876
65,864,729
Newlines not preserved when copying / pasting from Apache Zeppelin
<p>I'm printing CSVs in Zeppelin (MacOS 10.14.6, Google Chrome, pyspark, Python 3.6.8) using the pandas <code>to_csv()</code> function, and when I copy and paste the results to another application (e.g. Excel, Google Sheets, Apple Notes), it all appears on a single line. I've tried updating the newline character using ...
<p>try this</p> <pre class="lang-py prettyprint-override"><code>with open(file_path, mode='w', newline='\r\n') as f: data_frame.to_csv(f, index=False) </code></pre>
pandas|vim|newline|apache-zeppelin
0
10,877
21,167,478
Pandas: Product of specific columns
<p>Finding the product of all columns in a dataframe is easy:</p> <pre><code>df['Product'] = df.product(axis=1) </code></pre> <p>How can I specify which <strong>column names</strong> (not column numbers) to include in the product operation?</p> <p>From the help page for <a href="http://pandas.pydata.org/pandas-docs/...
<p>You can use the <code>df[[colname1, colname2, colname3...]]</code> syntax to select the columns you want and then call <code>.product</code> on that:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"A": [2,2], "B": [3,3], "C": [5,5]}) &gt;&gt;&gt; df A B C 0 2 3 5 1 2 3 5 [2 rows x 3 columns] &gt;&gt;&gt...
python|pandas|product
12
10,878
63,521,468
Using if function on data frame
<p>I am trying to use panda for data management. So python scans a .tsv with some data in it and using panda convert it into df using headers. I currently have a data frame(df) let's say 'x', of the length 50. I want to know how many numbers in the df are lesser than 5. For this I used:</p> <pre><code>if(len (df1(df1['...
<p>To find total elements in column x that are less than 5:</p> <pre><code>(df['x'] &lt; 5).sum() </code></pre> <p>To find index of element which are less than 5 in column x:</p> <pre><code>df[df['x'] &lt; 5].index </code></pre> <p>or Using numpy:</p> <pre><code>list(np.where(df['x'] &lt; 5]) </code></pre>
python|pandas|dataframe
0
10,879
63,360,462
How to replace different values in each column with NAN values?
<p>Please let me know if anyone knows of a better way to do about the following. I am trying to replace some values in numpy array. Replace condition is differ in each columns. Suppose I have a numpy array and list of nodata values like:</p> <pre><code>import numpy as np array = np.array([[ 1, 2, 3], ...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>np.isin</code></a> to create boolean index &amp; broadcast.</p> <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html" rel="nofollow noreferrer"><code>astype</code></a> to a...
python|arrays|numpy
1
10,880
21,887,625
Python Empirical distribution function (ecdf) implementation
<p>I am aware of <a href="http://statsmodels.sourceforge.net/stable/generated/statsmodels.tools.tools.ECDF.html" rel="noreferrer">statsmodels.tools.tools.ECDF</a> but since the calculation of an empricial cumulative distribution function (ECDF) is pretty straight-forward and I want to minimise dependencies in my projec...
<p>Since you are already using <code>pandas</code> I think it will be silly not to use some of its features:</p> <pre><code>In [15]: import numpy as np from numpy import * sq=ser.value_counts() sq.sort_index().cumsum()*1./len(sq) Out[15]: 2.083520e-12 0.058824 1.283440e-09 0.117647 8.517870e-09 0.176471 4.282...
python|numpy|pandas|ecdf
12
10,881
29,913,034
How to compare two arrays and find the optimal match in Python?
<p>I have two arrays X and Y, X is the base array and Y is operated in a loop. As the loop runs I want to compare the arrays to find the nearest value of Y to X or in other words where is Y most close to X. As an example I have attached the reproducible code:</p> <pre><code>from __future__ import division import numpy...
<p>You can compute the Euclidean distance between the two matrices:</p> <pre><code>import numpy as np import scipy.spatial.distance import matplotlib.pyplot as plt x = np.array([[0.12, 0.11, 0.1, 0.09, 0.08], [0.13, 0.12, 0.11, 0.1, 0.09], [0.15, 0.14, 0.12, 0.11, 0.1], [0.17, 0.15, 0.14, 0.12, 0.11], [0.1...
python|arrays|numpy|scipy
3
10,882
53,685,906
Choropleth map in Plotly: colours not showing correctly
<p>Trying to make a choropleth map in plotly using some data I have in a csv file. Have created the following map:</p> <p><a href="https://i.stack.imgur.com/QqtnI.png" rel="nofollow noreferrer">my choromap</a></p> <p>This isn't a correct display of the data however. Here is an excerpt of my csv file:</p> <pre><code>...
<p>per your comment I would make sure that china is indeed 2447 and not something like 244. I would also follow the <a href="https://plot.ly/python/choropleth-maps/" rel="nofollow noreferrer">plotly documentation</a> although you example code works.</p> <pre><code>import plotly.plotly as py import pandas as pd df = p...
python|pandas|plotly|data-visualization|choropleth
0
10,883
53,605,193
Dask.dataframe or Alternative: Scalable way of dropping rows of low frequency items
<p>I am looking for a way to remove rows from a dataframe that contain low frequency items. I adapted the following snippet from <a href="https://stackoverflow.com/questions/32511061/remove-low-frequency-values-from-pandas-dataframe">this</a> post:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFra...
<p>Not sure if this will help you out, but it's too big for a comment:</p> <pre><code>df = pd.DataFrame(np.random.randint(0, high=20, size=(30,2)), columns = ['A', 'B']) unique, counts = np.unique(df.values.ravel(), return_counts=True) d = dict(zip(unique, counts)) threshold = 10 to_remove = [k for k, v in d.items() i...
python|pandas|dask
1
10,884
53,443,941
Structuring of messy data using python
<p>I have a set of data which is not tab or comma delimited. When open in Notepad, it looks very structured as shown below but when open with Excel, It is not structured properly</p> <pre class="lang-none prettyprint-override"><code>Tuesday 19-April-2010 00:01 CC 11 PQ 1.1 PS1.1 CS# 111 +1 RS113' SC 183 ZA 71 IFJ...
<p>I would suggest you use a script to first convert your data into a suitable CSV format that could then be loaded without problem using Pandas. </p> <p>Most of the data appears to be in a fixed width format, as such the column locations could be hard coded, and <code>strip()</code> applied to remove any whitespace. ...
python|pandas|dataframe
1
10,885
12,621,272
Python: gridding point X,Y, and Z in order to extract statistical attribute
<p>Sorry for the easy question but I am new in Python and i need same help.</p> <p>My data are in point format: X,Y,Z. Where X and Y are coordinates, and z the value.</p> <p>My problem is: create a raster (in TIF or ASCII) with 0.5 m by 0.5 m (or 1 by 1 m) where the value of each pixel is the avarage of Z. In case wh...
<p>A way to go:</p> <ul> <li>define your grid <code>spacing</code> (a floating point number), which is the distance between two pixel/voxel midpoints in the same dimension</li> <li>figure out the size of the grid you need, i.e. the number of grid points in <code>x</code> and <code>y</code> dimension, <code>N_x</code>,...
python|numpy|geospatial|raster|gdal
6
10,886
71,919,125
fastapi using ORM not able to convert to pandas
<p>I've been developing a fastapi way to query my database, instead of directly using SQL with pg.</p> <p>For some reason, I'm having issues converting the ORM query returned values into something usable, within a pandas dataframe.</p> <p>for example,</p> <pre><code>def sentimentDataframe(db: Session, user_id: str): ...
<p>To load data from sql</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_sql(query.statement, query.session.bind) </code></pre> <p>from pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html" rel="nofollow noreferrer">docs</a></p> <pre class="lang-py prettyprint...
python|pandas|sqlalchemy|fastapi
1
10,887
71,849,638
Add dict as value to dataframe
<p>I want to add a dict to a dataframe and the appended dict has dicts or list as value.</p> <p>Example:</p> <pre class="lang-python prettyprint-override"><code>abc = {'id': 'niceId', 'category': {'sport':'tennis', 'land': 'USA' }, 'date': '2022-04-12T23:33:21+02:...
<p>Your question is not very clear in terms of what your expected output is. But assuming you want to create a dataframe where the columns should be <em>id</em>, <em>category</em>, <em>date</em> and <em>numbers</em> (just added to show the list case) in which each cell in the <em>category</em> column keeps a dictionary...
python|pandas|dictionary
0
10,888
16,755,780
Python pandas an efficient way to see which column contains a value and use its coordinates as an offset
<p>As part of trying to learn pandas I'm trying to reshape a spreadsheet. After removing non zero values I need to get some data from a single column.</p> <p>For the sample columns below, I want to find the most effective way of finding the row and column index of the <code>cell</code> that contains the value <code>da...
<p>This really just reformats a lot of the iteration you are doing to make it clearer and take advantage of pandas ability to easily select, etc.</p> <p>First, we need a dummy dataframe (with date in the last row and explicitly ordered the way you have in your setup)</p> <pre><code>import pandas as pd df = pd.DataFra...
python|pandas
3
10,889
55,386,621
Create an array with a letter repeated a given number of times given by another array
<p>I have an array <code>a</code> and i want to create another array <code>b</code> with a certain string repeated the number of times specified by <code>a</code></p> <pre><code>a = np.array([1,2,3]) s = 'a' </code></pre> <p>i want the <code>b</code> to be <code>np.array(['a','aa','aaa'])</code>. What would be the nu...
<p>There is a built-in method:</p> <pre><code>output = np.core.defchararray.multiply(s,a) </code></pre>
python|numpy
6
10,890
55,170,552
Cannot find tag value in element
<p>I'm trying to parse an XML file to a pandas Dataframe. My root element is <code>&lt;Games&gt;</code> which contains one element <code>&lt;Game&gt;</code>. I want to retrieve the tag values inside the <code>&lt;Event&gt;</code> element. </p> <p>I thought it was straight-forward with the <code>find()</code> function ...
<p>This seems to work:</p> <pre><code>import xml.etree.ElementTree as ET xml = '''&lt;Games timestamp="2016-12-02T09:06:51"&gt; &lt;Game id="853139" away_team_id="143" away_team_name="Lyon" competition_id="24" competition_name="French Ligue 1" game_date="2016-08-14T14:00:00" home_team_id="148" home_team_name="Nancy...
python|xml|pandas
1
10,891
55,482,151
How to fix the openCV error with cv2.CascadeClassifier?
<p>I am creating a car recognition program.</p> <pre><code>import cv2 import numpy as np car_cascade = cv2.CascadeClassifier('cars.xml') </code></pre> <p>This error is being thrown:</p> <pre><code>cv2.error: OpenCV(4.0.0) C:\build\master_winpack-build-win64-vc14\opencv\modules\core\src\persistence.cpp:722: error:...
<p>This is happening because the .xml file exists, but the contents are corrupt. I just spent way too long trying to figure this out only to realize that I didn't download the xml file properly. If you are 100% sure the file is correct, god help you.</p>
python-3.x|numpy|opencv
4
10,892
55,508,539
How to concatenate every two csv file from a single folder in to one csv file each?
<p>I have a folder with files in the format <strong>p1_1001.csv, p1_1002csv, p2_1001.csv, p2_1002.csv...</strong></p> <p>They are part1 and part 2 data for a single candidates <strong>1001,1002...</strong></p> <p>I want to combine p1 and p2 for each candidate. That is, generate a single csv file for each candidate.. ...
<p>I've tried it using <strong>glob</strong> and it should work fine.</p> <pre><code>import pandas as pd import glob _candidates = ['1001', '1002'] # All candidates _candidate_files = [(candidate, glob.glob('./*{}.csv'.format(candidate))) for candidate in _candidates] for candidate in _candidate_files: df = [] ...
python|database|pandas|dataframe|concatenation
1
10,893
9,763,471
audioop.rms() - why does it differ from normal RMS?
<p>I am writing a python function to return the loudness of a .wav file. RMS seems to be best the metric for this, <a href="https://stackoverflow.com/questions/2668442/detect-and-record-a-sound-with-python">Detect and record a sound with python</a>. <code>audioop.rms()</code> does the trick, but I'd like to avoid audi...
<p>Perform calculations using <code>double</code> as in <a href="http://hg.python.org/cpython/file/2.7/Modules/audioop.c#l410"><code>audioop.rms()</code> code</a>:</p> <pre><code>d = np.frombuffer(data, np.int16).astype(np.float) </code></pre> <h3>Example</h3> <pre><code>&gt;&gt;&gt; import audioop, numpy as np &gt;...
python|numpy
16
10,894
7,448,554
Replicating the indices result of Matlab's ISMEMBER function in NumPy?
<p>I have been racking my brain for a solution that is along the lines of this <a href="https://stackoverflow.com/questions/4287078/equivalent-of-matlab-ismember-in-numpy-python">older question</a>. I have been trying to find a Python code pattern that replicates the indices result. For example:</p> <pre><code>A = [...
<pre><code>import numpy as np A = np.array([3,4,4,3,6]) B = np.array([2,5,2,6,3,6,2,2,5]) def ismember(a, b): # tf = np.in1d(a,b) # for newer versions of numpy tf = np.array([i in b for i in a]) u = np.unique(a[tf]) index = np.array([(np.where(b == i))[0][-1] if t else 0 for i,t in zip(a,tf)]) ret...
python|matlab|numpy
5
10,895
7,447,184
Numpy product or tensor product question
<p>How can I calculate this product without a loop? I think I need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>numpy.tensordot</code></a> but I can't seem to set it up correctly. Here's the loop version:</p> <pre><code>import numpy as np a = np.random....
<p>I've lost the plot. The answer is simply</p> <pre><code>c = a * b c = np.sum(c,axis=3) c = np.sum(c,axis=2) </code></pre> <p>or on one line</p> <pre><code>c = np.sum(np.sum(a*b,axis=2),axis=2) </code></pre>
python|matrix|numpy|linear-algebra
3
10,896
56,835,149
Remove row with spesific value in pandas dataframe
<p>I have a dataframe like this:</p> <pre><code>value1 value2 aa7bbc aaaa ss ss0 qqq wwww nn77 qqee </code></pre> <p>I want to remove the row that :</p> <ul> <li>has digit in value</li> <li>begin with <code>nn</code></li> <li>has less than two characters</li> </ul> <p>I've tri...
<p>you just need to refine your regex with OR to match any of the conditions.</p> <p><code>r'(\d)|(^nn)|(^.?$)'</code></p> <p>this is:</p> <p><code>\d</code> for a contained digit</p> <p>OR</p> <p><code>^nn</code> for begin with nn</p> <p>OR</p> <p><code>^.?$</code> for 0-1 chars (less than two characters).</p> ...
python|python-3.x|pandas|dataframe
1
10,897
56,741,189
Exploding Dataframes based on cell values
<p>I have a data frame that looks something like:</p> <pre><code>import pandas as pd import numpy as np f = {'business':['#','FX','IR'], 'AL':['A','L','#'], 'Company':['207','#','1']} filterr = pd.DataFrame(data=f) filterr </code></pre> <p>Whenever there is a '#' present in the dataframe, I need the rows to repeat...
<p>Here is one method , I am not sure about the efficient part </p> <pre><code>filterr.mask(filterr.eq('#')).fillna(d).stack().str.split(',').apply(pd.Series).stack().unstack(1).ffill() Out[804]: business AL Company 0 0 FX A 207 1 IR A 207 2 CR A 207 1 0 FX L 1 ...
python|pandas
3
10,898
56,678,240
Pandas error on unix datetime conversation -- OutOfBoundsDatetime: cannot convert input with unit 's'
<p>I am getting this error </p> <pre><code> File "pandas/_libs/tslib.pyx", line 356, in pandas._libs.tslib.array_with_unit_to_datetime pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: cannot convert input with unit 's' </code></pre> <p>when trying to convert pandas column to datetime format. </p> <p>I checked t...
<p>It works if you add the <code>origin='unix'</code> parameter:</p> <pre><code>pd.to_datetime(df['date'], origin='unix', unit='s') 0 2015-01-01 07:20:00 1 2015-01-01 07:20:00 2 2015-01-01 07:25:00 3 2015-01-01 07:25:00 4 2015-01-01 07:30:00 </code></pre>
python|pandas
4
10,899
56,686,913
add axis titles to 3d surface plot cufflinks & plotly
<p>Would anyone be able to give me a tip on how to add x,y,z axis titles to the 3 surface plot created with plotly &amp; cufflinks?</p> <p>Im using Jupyter notebooks Anaconda 3.7</p> <pre><code>import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import iplot, init_notebook_mode # Using plotl...
<p>There you go:</p> <pre><code>import plotly import plotly.graph_objs as go plotly.offline.init_notebook_mode(connected=True) import pandas as pd # creating dataframe with three axes data = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[10, 20, 30, 20, 10], 'z':[5, 4, 3, 2, 1]}) ...
python|pandas|plotly
0