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
1,300
68,811,534
Several problems when packaging with pyinstaller
<p>I was packaging my python program with PyInstaller, and several problems occurred. Here's my code below:</p> <pre><code>#!/usr/bin/python # -*- coding: UTF-8 -*- from spleeter import separator import tkinter as TKT from tkinter import ttk from tkinter import messagebox import tensorflow window = TKT.Tk() screen_w...
<p>You need to exclude the PyQt5 Library in the pyinstaller command. Adding the command below, in the pyinstaller command.</p> <pre><code>--exclude-module &quot;PyQt5&quot; </code></pre> <p>You can use the auto-py-to-exe application to create an exe. This application use the pyinstaller library. It's really easy to han...
python|python-3.x|tensorflow|pyinstaller
1
1,301
68,671,394
Add New Values ​to Dataframe according to predictions
<p>I have the following dataframe called &quot;lastDays&quot;:</p> <pre><code> Units Date 2021-06-01 00:00:00 3 2021-06-01 01:00:00 4 2021-06-01 02:00:00 1 2021-06-01 03:00:00 2 2021-06-01 04:00:00 8 2021-06-01 05:00:00 9 2021-06-01 06:00:00 3 2021-06-01 07:00:00 5 2021-0...
<p>I was able to find the solution that was the following:</p> <p>Apply <code>pd.date-range</code> to create a new column of dates in the created dataframe &quot;nextMonth&quot; and reflect the forecasts. The applied function <code>nextMonth['Date'] = pd.date_range (start = lastDays.index [-1], period = len (lastDays),...
python|pandas|dataframe|datetime
0
1,302
68,494,337
Split rows of pandas textual dataframe
<p>I have a pandas textual dataframe which looks like this:</p> <pre><code>+-----------------------------------+ | text | +-----------------------------------+ | A very long sentence | +-----------------------------------+ | Another very long sentence | +----------------...
<p>you can try via <code>str.split()</code>+<code>str.join()</code> if the sentence are seperated by <code>' '</code> :</p> <pre><code>df['text']=df['text'].str.split().str[:512].str.join(' ') </code></pre> <p>Now For checking the length(after running the above code) you can do:</p> <pre><code>df['text_len']=df['text']...
python|pandas|dataframe|text
0
1,303
68,641,777
Excel file only opens with pandas in Python after being resaved
<p>I have some Excel files with measurements taken from National Instruments' LabView. I'm trying to use Pandas to be able to edit the data but when using read_excel on those Excel files I get the error <code>TypeError: expected &lt;class 'openpyxl.styles.fills.Fill'&gt;</code>.</p> <p>The strange part is that if I ope...
<p>Seems like the source file is corrupt to the point that a standard method of opening the file is not possible (e.g., <code>pd.read_excel()</code> or <code>pd.ExcelFile()</code>. If there are too many files to open manually and save...Try a non-standard way of opening the file.</p> <p>One idea is using the code from...
python|excel|pandas
1
1,304
68,449,166
pandas rolling apply return np.nan
<p>I would like to apply a custom skewness function to rolling apply, but got np.nan instead.</p> <pre><code>import pandas as pd import numpy as np def _get_skewness(col, q=(0.05, 0.95)): if q[0] &gt; 0: quantiles = col.quantile(q) col.loc[(col&lt;quantiles[q[0]]) | (col &gt; quantiles[q[1]])] = np...
<p>By using <code>loc</code> on <code>col</code> the actual DataFrame is being modified in each iteration. The introduction of <code>NaN</code> in the column eventually means the window becomes all <code>NaN</code>. The easiest fix (without understanding more about how the skewness is to be applied) would be to create ...
python|pandas
1
1,305
68,649,384
Pandas Dataframe remove rows depending on two columns with equal values
<p>basically i have a dataframe where is a lot of columns, but the main are ITEM_ID and PRICE.</p> <p>For example:</p> <pre><code>ID ITEM_ID ITEM PRICE 1 1 potato 20 2 1 potato 20 3 1 potato 25 4 2 tomato 50 5 2 tomato 55 </code></pre> <p>And I wa...
<p>Solution to this problem is:</p> <pre><code>df.drop_duplicates(subset=['item_id', 'price'], inplace=True) </code></pre>
python|pandas|dataframe|duplicates
2
1,306
36,458,573
Torch/Lua equivalent function to MATLAB or Numpy 'Unique'
<p>In Python one can do the following to get the unique values in a vector/matrix/tensor:</p> <pre><code>import numpy as np a = np.unique([1, 1, 2, 2, 3, 3]) # Now a = array([1, 2, 3]) </code></pre> <p>There is a similar function in MATLAB as well:</p> <pre><code>A = [9 2 9 5]; C = unique(A) %Now C = [9, 2, 9] </co...
<p>Nope, there is no such a standard function in stock Lua and/or Torch.</p> <p>Considering using some implementation of <code>set</code> data structure, rolling Your own implementation of <code>unique()</code> or redesigning Your application not to require this kind of functionality.</p> <p>Example 11-liner:</p> <p...
python|matlab|numpy|lua|torch
1
1,307
53,216,162
How to train Tensorflow Object Detection images that do not contain objects?
<p>I am training an object detection network using Tensorflow's object detection,</p> <p><a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="noreferrer">https://github.com/tensorflow/models/tree/master/research/object_detection</a></p> <p>I can successfully train a network based ...
<p>An Object Detection CNN can learn what is not an object, simply by letting it see examples of images without any labels.</p> <p>There are two main architecture types: </p> <ol> <li>two-stages, with first stage object/region proposal (RPN), and second - classification and bounding box fine-tuning; </li> <li>one-sta...
python|tensorflow|deep-learning|object-detection|object-detection-api
8
1,308
52,939,153
Creating new dataframe based on maximum element
<p>I have two dataframes-</p> <pre><code>cols = ['A','B'] data = [[-1,2],[0,2],[5,1]] data = np.asarray(data) indices = np.arange(0,len(data)) df = pd.DataFrame(data, index=indices, columns=cols) cols = ['A','B'] data2 = [[-13,2],[-1,2],[0,4],[2,1],[5,0]] data2 = np.asarray(data2) indices = np.arange(0,len(data2)) ...
<p>Using <code>drop_duplicates</code></p> <pre><code>pd.concat([df2,df]).sort_values('B').drop_duplicates('A',keep='last') Out[80]: A B 3 2 1 2 5 1 0 -13 2 0 -1 2 2 0 4 </code></pre>
python|pandas
4
1,309
65,495,533
Getting an error when trying to get pandas to read my json file
<p>I'm getting <code>ValueError: Expected object or value</code> when trying to get pandas to read my json file.</p> <p>Here is the code I'm using:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import json dataframe = pd.read_json(r'C:\Users\stans\WFH Project\data.json') </code></pre> <p>This ...
<pre><code>import json import panda as pd f = open('C:/Users/stans/WFH Project/data.json',) data = json.load(f) df = pd.DataFrame(data) f.close() </code></pre>
python|json|pandas
0
1,310
65,816,766
How do I save a file in f4 format using numpy in python
<p>I have generated a coupling file and save it like this, <br></p> <p>np.save('J', Jindep,)</p> <p>This saves in J.npy format. How do I convert it in 'f4'format?</p>
<p>You can use open function to create files.</p> <pre><code>numpy_array = [] f = open('j.f4','w') f.write(numpy_array) f.close() </code></pre>
python|numpy
0
1,311
65,797,608
Most efficient way to iterate over large vector?
<p>I have an input ndarray, <code>pointsCount</code>, with shape (4000000, 1). I have another ndarray, <code>clusters</code>, with shape (2,1). I then want to perform the following:</p> <pre><code>distances = np.zeros((pointsCount, n_clusters)) for x in range(len(trainPoints)): for c in range(len(clusters)): ...
<p>All you need to do is transpose <code>clusters</code>. For example, given initial arrays:</p> <pre><code>&gt;&gt;&gt; pointsCount # I have considered 4 instead of 4 mil array([[2], [4], [7], [6]]) &gt;&gt;&gt; clusters array([[2], [3]]) # Your code: &gt;&gt;&gt; np.array([(x-cluster).T...
python|numpy
1
1,312
63,585,285
Why is history storing auc and val_auc with incrementing integers (auc_2, auc_4, ...)?
<p>I am beginner with keras and today I bumped into this sort of issue I don't know how to handle. The values for <code>auc</code> and <code>val_auc</code> are being stored in <code>history</code> with the first even integers, like <code>auc</code>, <code>auc_2</code>, <code>auc_4</code>, <code>auc_6</code>... and so o...
<p>Use tf.keras.backend.clear_session()</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/backend/clear_session" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/backend/clear_session</a></p>
python|tensorflow|keras|deep-learning
1
1,313
63,398,403
Replace date "/" tobe "-" in existing column .csv pandas
<p>I have data in wind.csv format :</p> <pre><code>Date,Time,Wind 13/08/2020,12.00z, 13020knot 14/08/2020,12.00z, 14004knot 15/08/2020,12.00z, 10005knot </code></pre> <p>I want to replace the sign &quot;/&quot; to &quot;-&quot;, the Date Data.</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv(&quo...
<p>Here is my solution. It gets the result that you want but I don't know if it fit your desire.</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;Date.csv&quot;) df[&quot;Date&quot;] = df[&quot;Date&quot;].str.replace(&quot;/&quot;,&quot;-&quot;) </code></pre> <p>This one work but take long line of code</p> <p...
python|pandas
0
1,314
63,369,555
Google Cloud Function Build timeout - all requirements have been loaded
<p>I have the following code on my cloud function -</p> <pre><code>import os import numpy as np import requests import torch from torch import nn from torch.nn import functional as F import math from torch.nn import BCEWithLogitsLoss from torch.utils.data import TensorDataset from transformers import AdamW, XLNetToke...
<p>It might be due to the <code>torch</code> import, as this causes you to import the PyTorch lib that contains CUDA and hence requires a GPU, which isn't available on Cloud Functions.</p> <p>Instead, you can use a direct link to the cpu only version in your requirements.txt, like this:</p> <pre><code>certifi==2020.6.2...
python|google-cloud-functions|pytorch|cloud|requirements.txt
1
1,315
24,884,399
How to perform a simple signal backtest in python pandas
<p>I want to perform a simple and quick backtest in pandas by providing buy signals as DatetimeIndex to check against ohlc quotes DataFrame (adjusted close price) and am not sure if I am doing this right.</p> <p>To be clear I want to calculate the cummulated returns of all swapping buy signals (and stock returns as we...
<p>You don't have enough information to run a backtest. Your "strategy" currently just has True or False. When it's True, how much do you want to buy? If it's True twice in a row, does that mean buy-and-hold or buy at both times? Does False mean liquidate or not to buy?</p> <p>You need to:</p> <ol> <li>Translate your...
python|numpy|pandas|finance|quantitative-finance
2
1,316
53,459,046
Pandas dataframe change all value if greater than 0
<p>I have a dataframe</p> <pre><code>df= A B C 1 2 55 0 44 0 0 0 0 </code></pre> <p>and I want to change values to 1 if the value is >0.</p> <p>Is this the right approach: df.loc[df>0,]=1</p> <pre><code>to give: A B C 1 1 1 0 1 0 0 0 0 </code></pre>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.clip_upper.html" rel="nofollow noreferrer"><code>clip_upper</code></a>:</p> <pre><code>df = df.clip_upper(1) print (df) A B C 0 1 1 1 1 0 1 0 2 0 0 0 </code></pre> <p>Numpy alternative:</p> <pre><code>df = pd.DataFra...
pandas|dataframe
6
1,317
17,387,219
Sorting numpy matrix for a given column
<p>I've tried to use Ned Batchelder code to sort in human order a <code>NumPy</code> matrix, as it was proposed in this following post:</p> <p><a href="https://stackoverflow.com/q/7638738">Sort numpy string array with negative numbers?</a></p> <p>The code runs on a one-dimensional array, the command being:</p> <pre>...
<p>If you have a <code>np.matrix</code>, called <code>m</code>:</p> <pre><code>col = 1 m[np.array(m[:,col].argsort(axis=0).tolist()).ravel()] </code></pre> <p>If you have a <code>np.ndarray</code>, called <code>a</code>:</p> <pre><code>col = 1 a[a[:,col].argsort(axis=0)] </code></pre> <p>If you have a structured ar...
python|numpy|sorting|matrix
5
1,318
17,451,425
Hist in matplotlib: Bins are not centered and proportions not correct on the axis
<p>take a look at this example:</p> <pre><code> import matplotlib.pyplot as plt l = [3,3,3,2,1,4,4,5,5,5,5,5,5,5,5,5] plt.hist(l,normed=True) plt.show() </code></pre> <p>The output is posted as a picture. I have two questions:</p> <p>a) Why are only the 4 and 5 bins centered around its value? Shouldn't the others...
<p>You should adjust the keyword arguments of the <code>plt.hist</code> function. There are many of them and the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist" rel="noreferrer">documentation</a> can help you answer many of these questions.</p> <p>a. ) You can pass the keywords <code>bins=ra...
python|numpy|matplotlib
16
1,319
71,988,044
Financial performance and risk analysis statistics from sample DataFrame
<p>How do I output detailed financial performance and risk analysis statistics from this sample pandas DataFrame?</p> <p>Can anyone show how this could be done with Quantstats, Pyfolio or another similar approach?</p> <p><strong>Code</strong></p> <pre><code>start_amount = 100000 np.random.seed(8) win_loss_df = pd.Data...
<p>We will use the profit column and use <a href="https://github.com/ranaroussi/quantstats" rel="nofollow noreferrer">quantstats</a> to generate reports.</p> <h4>Code</h4> <pre><code>import quantstats as qs import numpy as np import pandas as pd start_amount = 100000 np.random.seed(8) win_loss_df = pd.DataFrame( ...
python|pandas|finance
1
1,320
71,950,486
I have unlabelled data and I want to make it into labelled into three category 1.Refilling 2. theft 3. sloshing
<pre><code>timestamp vehicle_speed fuel_in_lit 2022-01-01 00:00:03 0 61 2022-01-01 00:00:23 2 60 2022-01-01 00:00:33 0 59 2022-01-01 00:00:43 0 58 2022-01-01 00:00:53 0 56...
<p>IIUC, you can use a set of masks and <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p> <pre><code>diff = df['fuel_in_lit'].diff() # speed is 0 m1 = df['vehicle_speed'].eq(0) # fuel is increasing m2 = diff.gt(0) # fuel is decreasi...
python|pandas|dataframe|numpy
-1
1,321
72,031,917
How to compare two dataframes' structures
<p>I have two pandas dataframes and I want to compare their structures only. I tried to do this:</p> <pre><code>df0Info = df0.info() df1Info = df1.info() if df0Info == df1Info: print(&quot;They are same&quot;) else: print(&quot;They are diff&quot;) </code></pre> <p>I found the result always is same whether the ...
<p><code>pandas.DataFrame.info</code> prints a summary of a DataFrame and returns <code>None</code>, so comparing outputs to one another will always be True because you're essentially testing <code>None == None</code>.</p>
python|pandas
0
1,322
72,046,021
Save multiple dataframes to the same file, one after the other
<p>Lets say I have three dfs</p> <pre><code>x,y,z 0,1,1,1 1,2,2,2 2,3,3,3 a,b,c 0,4,4,4 1,5,5,5 2,6,6,6 d,e,f 0,7,7,7 1,8,8,8 2,9,9,9 </code></pre> <p>How can I stick them all together so that i get:</p> <pre><code>x,y,z 0,1,1,1 1,2,2,2 2,3,3,3 a,b,c 0,4,4,4 1,5,5,5 2,6,6,6 d,e,f 0,7,7,7 1,8,8,8 2,9,9,9 </code></pre>...
<p>If you want to save all your dataframes in the <strong>same file</strong> one after the other, use a simple loop with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>to_csv</code></a> and use the file append mode (<strong>a</strong>):</p> <pre class...
python|pandas|dataframe
2
1,323
19,071,199
Drop columns whose name contains a specific string from pandas DataFrame
<p>I have a pandas dataframe with the following column names:</p> <p>Result1, Test1, Result2, Test2, Result3, Test3, etc...</p> <p>I want to drop all the columns whose name contains the word "Test". The numbers of such columns is not static but depends on a previous function.</p> <p>How can I do that?</p>
<p>Here is one way to do this:</p> <pre><code>df = df[df.columns.drop(list(df.filter(regex='Test')))] </code></pre>
python|pandas|dataframe
283
1,324
17,833,119
Lowpass Filter in python
<p>I am trying to convert a Matlab code to Python. I want to implement <code>fdesign.lowpass()</code> of Matlab in Python. What will be the exact substitute of this Matlab code using <code>scipy.signal.firwin()</code>:</p> <pre><code>demod_1_a = mod_noisy * 2.*cos(2*pi*Fc*t+phi); d = fdesign.lowpass('N,Fc', 10, 40, 16...
<p>A very basic approach would be to invoke</p> <pre><code># spell out the args that were passed to the Matlab function N = 10 Fc = 40 Fs = 1600 # provide them to firwin h = scipy.signal.firwin(numtaps=N, cutoff=40, nyq=Fs/2) # 'x' is the time-series data you are filtering y = scipy.signal.lfilter(h, 1.0, x) </code></...
python|numpy|filter|scipy
6
1,325
55,272,152
Pandas - Calculate average of columns with condition based on values in other columns
<p>I struggle to create a new column in my data frame, which would be the result of going through each row a data frame and calculating the average based on some conditions. That is how the data frame looks like</p> <pre><code>ID, 1_a, 1_b, 1_c, 2_a, 2_b, 2_c, 3_a, 3_b, 3_c 0, 0, 145, 0.8, 0, 555, 0.7, 1, 335, 0.7 1...
<p>If your columns are in a similar range for both '_a' and '_c', you can simply loop through them;</p> <pre><code>r = range(1,4) for i in r: df.loc[df["{}_a".format(i)] != 1, "{}_c".format(i)] = np.NaN df['NEW'] = df[['{}_c'.format(i) for i in r]].mean(axis=1) </code></pre>
python|pandas|if-statement|iteration
1
1,326
55,159,061
store values from a list into an array after each iteration consists of specified column of files in python
<p>For a file in files:</p> <p>This is my list which consists of values from 3 files after each iteration. </p> <pre><code>import pandas ...
<p>Your question is very general. Try to provide a minimal complete verifiable example otherwise it is difficult to help you.</p> <p>What is in the files? Is each line a number? Too few information.</p> <p>In Python you can use multiple iteration variables. </p> <pre><code>#open the files first f1 = open("file1", "r...
python|pandas|numpy
0
1,327
55,193,810
Binary Image classification using TensorFlow
<p>I am writing a code to classify between dogs and cats in python(Tensorflow) but the code is displaying this error:</p> <p><strong>IndexError: index 0 is out of bounds for axis 0 with size 0</strong></p> <p>I am stuck here. Any help is appreciated. </p> <p>Also can you please help me I cant figure out here how One...
<blockquote> <p>IndexError: index 0 is out of bounds for axis 0 with size 0</p> </blockquote> <p>It means you don't have the index you are trying to reference. </p> <p>Since this is a binary classification problem, you don't required one_hot encoding for pre-processing labels. if you have more than two labels then ...
tensorflow|deep-learning|classification|conv-neural-network
0
1,328
56,695,811
Is it possible to calculate accuracy and ROC-AUC score at the same time with GridSearchCV?
<pre><code>rf = RandomForestClassifier(random_state=0) parameters = {'bootstrap': [True, False], 'min_samples_split':[2,3,4], 'criterion':['entropy', 'gini'], 'n_estimators':[100, 200] } grid_search = GridSearchCV(estimator=rf, param_grid=parameters, scoring='accuracy', cv=10, n_jobs=-1) </code></pre> <p...
<p>Per the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html" rel="nofollow noreferrer">docs</a>, you can pass a <code>list</code> of strings. In this specific case, <code>scoring=['accuracy', 'roc_auc']</code> would be what you want.</p>
python|pandas|numpy|cross-validation|grid-search
0
1,329
56,850,868
How do I add numbers to a column based on another column? (dictionary)
<p>I have a dictionary with values that I need to add to a column in a dataframe. The dictionary looks like this:</p> <pre><code>{1:123, 2:345, 3:678} </code></pre> <p>and the column of the dataframe looks like this:</p> <pre><code>col1 1 2 3 </code></pre> <p>and I want this result:</p> <pre><code>col1 1123...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a> to cast as <code>str</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Serie...
python|pandas|dataframe
2
1,330
56,455,555
Adding weights to edges in networkx automatically depending of the number of connections form pandas dataframe
<p>I am trying to create out of a pandas dataframe a directed graph right now with networkx, so far i can use:</p> <pre><code>nx.from_pandas_edgelist(df, 'Activity', 'Activity followed', create_using=nx.DiGraph()) </code></pre> <p>which shows me all the nodes and edges from Activity --> Activity followed.</p> <p>In ...
<p>You could try adding the <code>weight</code> attribute as a column, using <a href="http://OutEdgeDataView([(&#39;Lunch&#39;,%20&#39;Dinner&#39;,%20%7B&#39;weight&#39;:%202%7D),%20(&#39;Breakfast&#39;,%20&#39;Lunch&#39;,%20%7B&#39;weight&#39;:%201%7D)])" rel="noreferrer"><code>groupby.transform</code></a>, then pass ...
python|pandas|networkx
5
1,331
56,775,346
Numpy 2d array, clipping each index of each row to the minimum of that index and a specific column
<p>Given a 2d array, I want to take a specific column of that array.</p> <p>I then want to take every value of each row in the array, and change that value to whatever the minimum is between its current value, and the value in the specified column <em>for that row</em> is.</p> <p>What is an efficient way to do this? ...
<p>Use <code>numpy.minimum</code>. You need to broadcast to keep the dimensions of the column so you aren't comparing row-wise with the entire column.</p> <pre><code>np.minimum(a, a[:, col, None]) </code></pre> <hr> <p><strong><em>MCVE</em></strong></p> <pre><code>a = np.array([[1, 3, 1, 9, 4], [2, 3...
python|numpy
2
1,332
56,601,817
Conditional Cumulative Sums in Pandas
<p>I am a former Excel power user repenting for his sins. I need help recreating a common calculation for me.</p> <p>I am trying to calculate the performance of a loan portfolio. In the numerator, I am calculating the cumulative total of losses. In the denominator, I need the original balance of the loans included ...
<p>You use a complex conditions depending on variables. It is easy to find a vectorized way for simple cumulative sums, but I cannot imagine a nice way for the Cumulative NCO.</p> <p>So I would revert to Python comprehensions:</p> <pre><code>data = [ { 'Reference Age': ref, 'Outstanding Balance': df.loc[df....
python|pandas|pandas-groupby
2
1,333
56,611,648
CUMSUM addition as below
<p>i have to calculate the cumsum addition in the below. A should be blank. B should be as it, c should 31 + 30 = 61, previous item and addition of present item, D = 61 + 31 = 92 and so on. </p> <p>data: </p> <pre><code> 0 1 cumsum 1 A 31 2 B 31 31 3 C 30 61 4 D 31 92 5 E 30 122 6 ...
<p>I think you need </p> <pre><code>df['1'].shift(-1).cumsum().shift(1) 1 NaN 2 31.0 3 61.0 4 92.0 5 122.0 6 153.0 7 184.0 8 214.0 9 245.0 10 275.0 Name: 1, dtype: float64 </code></pre>
python|pandas|python-2.7
3
1,334
25,596,639
Get the expected array with SciPy's Fisher exact test?
<p>SciPy allows you to conduct both chi square tests and Fisher exact tests. While the output of the chi square test includes the expected array, the Fisher exact does not. </p> <p>e.g.:</p> <pre><code>from scipy import stats import numpy as np obs = np.array( [[1100,6848], [11860,75292]]) stats.chi2_continge...
<p>Fisher's exact test (<a href="http://en.wikipedia.org/wiki/Fisher%27s_exact_test" rel="nofollow">http://en.wikipedia.org/wiki/Fisher%27s_exact_test</a>) doesn't involve computing an expected array. That's why <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html" rel="nofollow">...
python|numpy|scipy
2
1,335
25,936,899
Select a subset of a Pandas DataFrame based on a list of criteria built from another DataFrame
<p>Suppose we have the following DataFrame</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df_org = pd.DataFrame({'A' : [1,2,3,4,5,6], 'B' : [1,1,1,1,2,2], 'C' : [1,2,3,4,1,2]}) A B C 0 1 1 1 1 2 1 2 2 3 1 3 3 4 1 4 4 5 2 1 5 6 ...
<p>A simple inner merge would work:</p> <pre><code>In [285]: df_org.merge(df_criteria, on=['B','C']) Out[285]: A B C 0 1 1 1 1 5 2 1 </code></pre>
python|pandas|dataframe
7
1,336
26,390,895
Why isn't pip updating my numpy and scipy?
<p>My problem is that pip won't update my Python Packages, even though there are no errors. </p> <p>It is similar to <a href="https://stackoverflow.com/questions/21473600/matplotlib-version">this one</a>, but I am still now sure what to do. Basically, ALL my packages for python appear to be ridiculously outdated, even...
<p>In OS X 10.9, Apple's Python comes with a bunch of pre-installed extra packages, in a directory named <code>/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python</code>. Including <code>numpy</code>.</p> <p>And the way they're installed (as if by using <code>easy_install</code> with an ancient ...
python|macos|numpy|pip|package-managers
14
1,337
66,829,674
Can't create pandas DataFrame with MultiIndex columns from dicts with tuples as columns
<p>I have this Python data structure:</p> <pre><code>a = [ { ('Temperature', 'C'): 25, ('Temperature', 'F'): 77 }, { ('Temperature', 'C'): 30, ('Temperature', 'F'): 86 } ] </code></pre> <p>I try to convert this data structure to a tab separated string like this, having 2 ...
<p>How about using <code>MultiIndex.from_tuples</code></p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(a) df.columns = pd.MultiIndex.from_tuples(df.columns) </code></pre> <p><code>df</code> is now:</p> <pre><code> Temperature C F 0 25 77 1 30 86 </code></pre> <pr...
python|pandas
2
1,338
67,113,949
make pandas recognize a list containing column names the same of of the columns in its dataframe?
<p>Let's say I have a list called x</p> <pre><code>x = ['Sales', 'Total', 'Quantity'] </code></pre> <p>and I have an excel dataframe with columns named 'Employee', 'Age', 'Sex', 'Sales' , 'Quantity' and 'Total'. How do I make pandas only pick the columns of the dataframe that have the same name as of those in the list?...
<p>Just do:</p> <pre><code>x = ['Sales', 'Total', 'Quantity'] df = df[x] </code></pre> <p>Since <code>x</code> is already a list of columns, use it inside <code>single-brackets</code> to subset the dataframe.</p> <p><strong>OR</strong> use <code>Index.intersection</code>:</p> <pre><code>df = df[df.columns.intersection...
python|pandas
2
1,339
67,128,738
Sort and Filter Pandas Dataframe in the most efficient manner
<p>I want to filter by the column name 'duration' and then display values greater than 200. This is just a snippet of the dataset. I have a very huge dataset. I can use df[df.duration &gt; 200]. However, this runs on the entire dataframe. Is there any way in which I can specifically target the column duration and then ...
<p>Using pandas, I think <code>df[df.duration &gt; 200]</code> would be among the best choices, but eager to compare with any alternatives.</p>
python|pandas
0
1,340
10,907,917
Python numpy addition error
<p>I'm getting a very odd error using a basic shortcut method in python. It seems, unless I'm being very stupid, I get different values for A = A + B, and A += B. Here is my code:</p> <pre><code>def variance(phi,sigma,numberOfIterations): variance = sigma for k in range(1,numberOfIterations): phik = np...
<p>The culprit is:</p> <pre><code>variance = sigma </code></pre> <p>If you change that to:</p> <pre><code>variance = sigma.copy() </code></pre> <p>You'll see the correct result.</p> <p>This is because <code>+=</code> actually performs a (more efficient) in-place addition… And since both <code>variance</code> and <...
python|numpy
7
1,341
68,441,433
Get time data was submitted from Yfinance
<p>I am working on a project using the Yfinance module to get information from the stock market. My problem is, I need the date/time that the data was submitted, and I don't know how to access it. There is nothing about this that I can find on the documentation, but i know it is there because when i run:</p> <pre><code...
<p>you can store the datetime data in a list</p> <pre><code>from os import pardir import yfinance as yf data = yf.download(tickers='UBER', period='5d', interval='5m') stored_datetime = data.index print(stored_datetime) </code></pre> <p>Output:</p> <pre><code>DatetimeIndex(['2021-07-16 09:30:00-04:00', '2021-07-16 09:3...
python|pandas|datetime|yfinance
0
1,342
59,273,860
How can I change my code so that string is NOT changed to float
<p>I am trying to write a code that detects fake news. Unfortunately, I keep getting the same error message. Please could someone explain where I've gone wrong? I have got some lines of codes from <a href="https://data-flair.training/blogs/advanced-python-project-detecting-fake-news/" rel="nofollow noreferrer">https://...
<p>I imagine you have text data in <code>df['headline']</code> column, you need a few steps to first convert the text data to a number based format, then pass it to machine learning models to handle. </p> <p>You might want to refer to sklearn's <code>CountVectorizer</code> and <code>TfidfTransformer</code> <a href="ht...
python|pandas|numpy|scikit-learn
1
1,343
44,991,076
One line solution for editing a numpy array of counts? (python)
<p>I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:</p> <pre><code>a = np.array([[1,2,3], [3,2,1], [2,1,3], [1,1,1]]) </code></pre> <p>I want to get back an array like so:</p> <pre><code...
<p>IIUC, you could take advantage of broadcasting:</p> <pre><code>In [93]: ((a[:, None] - 1) == np.arange(3)[:, None]).swapaxes(2, 1).astype(int) Out[93]: array([[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, 0, 1], [0, 1, 0], [1, 0, 0]], [[0, 1, 0], [1, 0, 0], ...
python|arrays|numpy
3
1,344
45,126,821
Saving confusion matrix
<p>Is there any possibility to save the confusion matrix which is generated by <code>sklearn.metrics</code>? </p> <p>I would like to save multiple results of different classification algorithms in an array or maybe a pandas data frame so I can show which algorithm works best.</p> <pre><code>print('Neural net: \n',con...
<p>First getting to array not defined problem. In python list is declared as :</p> <pre><code>array=[] </code></pre> <p>Since size of list is not given during declaration, no space is allocated. Hence we can't assign values the place which is not allocated.</p> <pre><code>array[i]=some value, but no space is allocat...
python|pandas|dataframe|confusion-matrix
1
1,345
45,255,167
Use numpy.argwhere to obtain the matching values in an np.array
<p>I'd like to use <code>np.argwhere()</code> to obtain the values in an <code>np.array</code>.</p> <p>For example:</p> <pre><code>z = np.arange(9).reshape(3,3) [[0 1 2] [3 4 5] [6 7 8]] zi = np.argwhere(z % 3 == 0) [[0 0] [1 0] [2 0]] </code></pre> <p>I want this array: <code>[0, 3, 6]</code> and did this:</...
<p>Why not simply use masking here:</p> <pre><code>z<b>[z % 3 == 0]</b></code></pre> <p>For your sample matrix, this will generate:</p> <pre><code>&gt;&gt;&gt; z[z % 3 == 0] array([0, 3, 6]) </code></pre> <p>If you pass a matrix with the same dimensions with booleans as indices, you get an array with the elements o...
python|numpy
14
1,346
44,874,061
Comparing cell values with a integer in pandas giving typeerror
<p>I have been trying to compare values of each cell in a row with an integer like so:</p> <pre><code>df.loc[df['A'] &lt;= 14, 'A'] </code></pre> <p>All rows whose values are less than or equal to 14, but it shows an error like:</p> <blockquote> <pre><code>TypeError : '&lt;=' is not supported between instances of st...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>replace</code></a> <code>,</code> to empty space and convert to <code>int</code>:</p> <pre><code>df = pd.DataFrame({'A':['1,473','1,473','1,4', '1,2'], 'B':[2,4,...
python|pandas
1
1,347
56,896,712
How to represent the Null class in Multilabel Classification with Convolutional Neural Nets?
<p>I'm trying to label images with the various categories that they belong to with a convolutional neural net. For my problem, the image can be in a single category, multiple categories, or zero categories. Is it standard practice to set the zero category as all zeroes or should I add an additional null class neuron to...
<p>Yes, the "null" category should be represented as just zeros. In the end multi-label classification is a set of C binary classification problems, where C is the number of classes, and if all C problems output "no class", then you get a vector of just zeros.</p>
python|tensorflow|machine-learning|keras
5
1,348
57,279,754
What are the Tensorflow qint8, quint8, qint32, qint16, and quint16 datatypes?
<p>I'm looking at the Tensorflow tf.nn.quantized_conv2d function and I'm wondering what exactly the qint8, etc. dataypes are, particularly if they are the datatypes used for the "fake quantization nodes" in tf.contrib.quantize or are actually stored using 8 bits (for qint8) in memory.</p> <p>I know that they are defin...
<p>These are the data types of the <code>output Tensor</code> of the function, <code>tf.quantization.quantize()</code>. This corresponds to the Argument, <code>T</code> of the function.</p> <p>Mentioned below is the underlying code, which converts/quantizes a Tensor from one Data Type (e.g. <code>float32</code>) to an...
python|tensorflow|neural-network|tensorflow-lite|quantization
6
1,349
57,037,252
Updating column in for loop using merge
<p>Hi, </p> <p>I have two dataframes and I want to loop through subsets of my first DF and merge values to my second DF. </p> <p>My data looks like: </p> <pre><code> DF1 product survey_id X1 survey_1 x2 survey_1 x3 survey_2 x4 survey_3 x5 survey_3 ...
<p>This is based on assumption: </p> <p><strong>for all product xi, we require survey_j such that j is maximum.</strong></p> <pre><code>&gt;&gt;&gt; data = {'product':['x1','x1','x2','x2','x2'], 'survey_id':['survey_1','survey_2','survey_1', 'survey_2', 'survey_3'] } &gt;&gt;&gt; df = pd.DataFrame(data) &gt;&gt;&gt;...
python|sql|pandas|numpy|merge
0
1,350
56,942,827
How do I style a subset of a pandas dataframe?
<p>I previously asked <a href="https://stackoverflow.com/questions/56942320/how-do-i-style-only-the-last-row-of-a-pandas-dataframe">How do I style only the last row of a pandas dataframe?</a> and got a perfect answer to the toy problem that I gave. </p> <p>Turns out I should have made the toy problem a bit closer to m...
<p>Using a <code>tuple</code> for <code>subset</code> worked for me, but not sure if it is the most elegant solution:</p> <pre><code>df.style.background_gradient(cmap=cm, subset=(df.index[-1], df.select_dtypes(float).columns)) </code></pre> <p>Output:</p> <p><a href="https://i.stack.img...
python|pandas|dataframe
10
1,351
57,060,655
Error com_error: (-2147221005, 'Invalid class string', None, None) while writing dataframe into excel binary notebook
<p>I am trying to write a data frame into excel sheet(xlsb), which is having formulas, using xlwing library:</p> <pre><code>app = xw.App() book = xw.Book('ABC.xlsb') sheet = book.sheets('SL Dump') sheet.range('A1').values=final_merge_dataframe </code></pre> <p>After running the above code, I am getting this error:...
<p>I use to have the same problem,</p> <pre><code>dispatch = pythoncom.CoCreateInstanceEx( pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) </code></pre> <p>After installing MS Office into my machine the error was resolved, it seems <em>xlwings</em> requires some packages or files from the MS Off...
python|pandas
0
1,352
57,255,266
Search excel columns for matching text value, print row #s
<p>Here I grab the name and zip values from a different document; and store in variables: (works fine)</p> <pre><code> Name = find_name.group(0) </code></pre> <p><strong>Then I simply want to search my excel file to find a match; where the <code>Name</code> text value is found, get row number(s):</strong>...
<p>I do not have your excel file, so I setup the following code:</p> <pre><code>import pandas as pd names = [&quot;RHONDA GILBERT&quot;, &quot;FRED FLINTSTONE&quot;, &quot;FRED FLINTSTONE&quot;, &quot;BARNEY RUBLE&quot;, &quot;RHONDA GILBERT&quot;] add1 = [&quot;123 Elm St&quot;, &quot;254 Pine Ave&quot;, &quot;254 Pin...
python|regex|excel|pandas|python-3.7
1
1,353
45,978,058
Return NaN from indexing operation on a pandas series
<pre><code>a = pd.Series([0.1,0.2,0.3,0.4]) &gt;&gt;&gt; a.loc[[0,1,2]] 0 0.1 1 0.2 2 0.3 dtype: float64 </code></pre> <p>When a non existent index is added to the request along with existing ones, it returns NaN (which is what I need).</p> <pre><code>&gt;&gt;&gt; a.loc[[0,1,2, 5]] 0 0.1 1 0.2 2 0.3...
<p>Try <code>pd.Series.reindex</code> instead.</p> <pre><code>out = a.reindex([0,1,2, 5]) print(out) 0 0.1 1 0.2 2 0.3 5 NaN dtype: float64 </code></pre> <hr> <pre><code>out = a.reindex([5]) print(out) 5 NaN dtype: float64 </code></pre>
python|pandas|indexing|nan|series
5
1,354
45,927,399
Memory error when initializing Xception using Keras
<p>I am having difficulty implementing the pre-trained Xception model for binary classification over new set of classes. The model is successfully returned from the following function:</p> <pre><code>#adapted from: #https://github.com/fchollet/keras/issues/4465 from keras.applications.xception import Xception from ke...
<p>Per Yu-Yang, the simplest solution was to reduce the batch size, everything ran fine after that!</p>
tensorflow|out-of-memory|keras|gpu
0
1,355
46,045,512
h5py - HDF5 database randomly returning NaNs and near very small data with multiple readers?
<p>I have an HDF5 dataset and I'm using a framework which is creating multiple processes to read from it (PyTorch's DataLoader, but this framework shouldn't be important). I'm indexing the first dimension of a 3D float array randomly, and to debug what was going on, I have been summing the slice from the indexing. Ever...
<p>I encountered the very same issue, and after spending a day trying to marry PyTorch DataParallel loader wrapper with HDF5 via h5py, I discovered that it is crucial to open <code>h5py.File</code> inside the new process, rather than having it opened in the main process and hope it gets inherited by the underlying mult...
python|numpy|hdf5|h5py
7
1,356
35,700,389
How to use numpy where for several possible values?
<p>Consider a numpy ndarray called <code>picks_user</code> with shape <code>picks_user.shape = (2016,3)</code>. The 'columns' represent the variables user, item and count in that order. The 'rows' represent observations.</p> <p>When performing:</p> <p><code>target_users = picks_user[np.where(picks_user[:,1]== 2711)][...
<p>You can use <code>np.in1d</code> as:</p> <pre><code>&gt;&gt;&gt; picks_user = np.random.randint(0,10, (10,3)) &gt;&gt;&gt; picks_user array([[7, 8, 7], [6, 0, 9], [5, 6, 7], [6, 7, 3], [0, 1, 3], [8, 7, 5], [2, 6, 6], [7, 9, 8], [1, 7, 1], [9, 8, 4]]) &...
python|numpy|vectorization
3
1,357
35,495,543
pandas DataFrame cumulative value
<p>I have the following pandas dataframe:</p> <pre><code>&gt;&gt;&gt; df Category Year Costs 0 A 1 20.00 1 A 2 30.00 2 A 3 40.00 3 B 1 15.00 4 B 2 25.00 5 B 3 35.00 </code></pre> ...
<p>This works in pandas 0.17.0 Thanks to @DSM in the comments for the terser solution.</p> <pre><code>df['Cumulative Costs'] = df.groupby(['Category'])['Costs'].cumsum() &gt;&gt;&gt; df Category Year Costs Cumulative Costs 0 A 1 20 20 1 A 2 30 50 2 ...
python|pandas|dataframe
2
1,358
35,695,259
pandas read_sql convers column names to lower case - is there a workaroud?
<p>related: <a href="https://stackoverflow.com/questions/28318722/pandas-read-sql-drops-dot-in-column-names">pandas read_sql drops dot in column names</a></p> <p>I use pandas.read_sql to create a data frame from an sql query from a postgres database. some column aliases\names use mixed case, and I want it to propagat...
<p>Postgres normalizes unquoted column names to lower case. If you have such a table:</p> <pre><code>create table foo ("Id" integer, "PointInTime" timestamp); </code></pre> <p>PostgreSQL will obey the case, but you will <strong>have to</strong> specify table names quoted as such:</p> <pre><code>select "Id", "PointIn...
postgresql|pandas|sqlalchemy
4
1,359
11,718,852
sum over values in python dict except one
<p>Is there a way to sum over all values in a python dict except one by using a selector in </p> <pre><code>&gt;&gt;&gt; x = dict(a=1, b=2, c=3) &gt;&gt;&gt; np.sum(x.values()) 6 </code></pre> <p>? My current solution is a loop based one:</p> <pre><code>&gt;&gt;&gt; x = dict(a=1, b=2, c=3) &gt;&gt;&gt; y = 0 &gt;&gt...
<p>You could loop over the dict to create a generator for the <code>sum</code> method:</p> <pre><code>np.sum(value for key, value in x.iteritems() if key != 'a') </code></pre>
python|dictionary|numpy|sum
8
1,360
11,687,953
Operations on rows in scipy sparse matrix of csr format
<p>I would like to multiply single rows of a csr matrix with a scalar. In numpy I would do</p> <pre><code>matrix[indices,:] = x * matrix[indices,:] </code></pre> <p>For csr this raises an exception in scipy.</p> <p>Is there a way to do this similarily with csr matrixes?</p>
<p>No, there's no way to this directly, because although you can compute <code>row * x</code>, you can't assign to a row in a CSR matrix. You can either convert to DOK format and back, or work on the innards of the CSR matrix directly. The <code>i</code>'th row of a CSR matrix <code>X</code> is the slice</p> <pre><cod...
python|numpy|scipy
12
1,361
28,863,853
Minimum element from the matrix column
<p>I need to find minimum over all elements from the column which has the maximum column sum. I do the following things:</p> <p>Create random matrix</p> <pre><code>from numpy import * a = random.rand(5,4) </code></pre> <p>Then calculate sum of each column and find index of the maximum element</p> <pre><code>c = a.s...
<p>You can extract the minimum value of a column as follows (using the variables you have indicated):</p> <pre><code>e=a[:,d].min() </code></pre> <p>Note that using</p> <pre><code>a=min(a[:,d]) </code></pre> <p>will break you out of Numpy, slowing things down (thanks for pointing this out @SaulloCastro).</p>
python|numpy|matrix|minimum
5
1,362
50,905,520
Using pd.ExcelWriter to write many dataframes to a single Excel workbook for VBA manipulation
<p>I have over 60 dataframes to write to an excel template. My intention is to paste all these to various named ranges via vba once all df's are exported. </p> <pre><code>excel_writer = pd.ExcelWriter('test.xlsx') df['state'].value_counts().to_excel(excel_writer, sheet_name='Sheet1', startrow=5, startcol=0, na_rep=0, ...
<p><code>df_Shape</code> is a shape of <code>df</code><br> <code>df_Start_Date</code> is a time</p> <p>They're not <code>pd.DataFrame</code> objects, thus they don't have method <code>.to_excel</code></p> <p><strong>EDIT</strong>:<br> You can create new dataframe with necessary statistics and write it to the same she...
python|pandas|dataframe
2
1,363
50,932,129
Pandas: groupby column and set it as index
<p>If I have a dataframe such as this:</p> <pre><code>df1 = pd.DataFrame({'A':[1,2,3,4,5,6,7,8], 'B':['a','b','c','d','e','f','g','h'], 'C':['u1','u2','u4','u3','u1','u1','u2','u4']}) </code></pre> <p>And would like it to be as such, with u1 to u4 as the indices.</p> <pre><code> A ...
<p>You can set C as an index and then sort it : </p> <pre><code>df1.set_index('C').sort_index(axis=0) </code></pre>
python|pandas
2
1,364
50,955,960
How can I map 2 numpy arrays with same indices
<p>I am trying to map 2 numpy arrays as [x, y] similar to what zip does for lists and tuples.</p> <p>I have 2 numpy arrays as follows:</p> <pre><code>arr1 = [1, 2, 3, 4] arr2 = [5, 6, 7, 8] </code></pre> <p>I am looking for an <code>output as np.array([[[1, 5], [2, 6], [3, 7], [4, 8]]])</code></p> <p>I tried this b...
<p>You are looking for <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dstack.html" rel="nofollow noreferrer"><strong><code>np.dstack</code></strong></a></p> <blockquote> <p>Stack arrays in sequence depth wise (along third axis).</p> </blockquote> <pre><code>np.dstack([arr1, arr2]) array...
python|numpy
2
1,365
50,941,409
Quote marks in bash file created in Python
<p>I'm using Python and Pandas to write multiple bash scripts. I have a pandas.Series containing the script. Simplified::</p> <pre><code>script = pd.Series([ '#!/bin/bash', '#SBATCH --output "/home/path/output_filename.out"' ]) </code></pre> <p>I then use <code>script.to_csv('script_file.bat',index=False)</code> to c...
<p>It's possible to explicitly specify quoting for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>df.to_csv</code></a>:</p> <pre><code>import csv pd.DataFrame(script).to_csv("test.sh", index=False, header=False, ...
python|string|bash|pandas|quotes
1
1,366
50,698,834
How can I remove sharp jumps in data?
<p>I have some skin temperature data (collected at 1Hz) which I intend to analyse. </p> <p>However, the sensors were not always in contact with the skin. So I have a challenge of removing this non-skin temperature data, whilst preserving the actual skin temperature data. I have about 100 files to analyse, so I need to...
<p>Try the code below (I used a tangent function to generate data). I used the second order difference idea from Mad Physicist in the comments.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame() df[0] = np.arange(0,10,0.005) df[1] = np.tan(df[0]) #the following...
python|python-3.x|pandas|dataframe|filtering
3
1,367
33,226,017
Pandas Aggregating a GroupBy object using UDF
<p>Suppose that I have the following. I group by "happy" and then sum over each group. It works great.</p> <pre><code>import pandas as pd testdf = pd.DataFrame({"happy": [1, 2, 1, 3], "sad": [4, 5, 6, 7], \ "cool":[1, 99, 0, -5]}) testgb = testdf.groupby(["happy"]) testgb.sum() </code></pre> <p>...
<p>I'm assuming that you want to pass the list of values from other column, e.g. <code>sad</code>. You can use the <code>agg</code> function</p> <pre><code>testdf = pd.DataFrame({"happy": [1, 2, 1, 3], "sad": [4, 5, 6, 7], "cool":[1, 99, 0, -5]}) testgb = testdf.groupby(["happy"]).agg({'sad': lambda x: max(x)}) </code...
python|pandas
1
1,368
33,460,209
How to get the union of two MultiIndex DataFrames?
<p>How do I merge two MultiIndexed DataFrames? </p> <p>For example, let's say I have:</p> <pre><code>index1 = pd.MultiIndex.from_tuples([('2010-01-01', 'Jim'), ('2010-01-01', 'Mike'), ('2010-01-02', 'Sam')]) index2 = pd.MultiIndex.from_tuples([(...
<p>Try:</p> <pre><code>df3 = df1.join(df2, how='outer', lsuffix='1', rsuffix='2') </code></pre> <p>Or</p> <pre><code>df3 = pd.merge(df1, df2, how='outer', left_index=True, right_index=True) </code></pre>
python|pandas
1
1,369
66,569,033
How to fill one column in a csv by comparing values to three different columns in another csv file?
<p>As I am completely new to pandas, I would like to ask.</p> <p>I have two CSV files.</p> <p>One of them has all the colors of different languages in one column:</p> <p>I have color blue in three rows here: azul, bleu all means blue in different languages, so they should be in the same group 1. rouge and rojo means re...
<p>You can use <code>map</code></p> <p>Using <code>df2</code> you can create a dict <code>d</code> and then map the name values to their corresponding group.</p> <pre><code>d = dict(zip(df2.T.values[3], df2.values[:,:3].tolist())) df1['group'] = df1.name.map(lambda x: [k for k in d if x in d[k]][0]) </code></pre> <hr /...
python-3.x|pandas|dataframe|csv
1
1,370
66,721,047
Pandas: compute average and standard deviation by clock time
<p>I have a DataFrame like this:</p> <pre><code> date time value 0 2019-04-18 07:00:10 100.8 1 2019-04-18 07:00:20 95.6 2 2019-04-18 07:00:30 87.6 3 2019-04-18 07:00:40 94.2 </code></pre> <p>The DataFrame contains value recor...
<p>We can <code>split</code> the <code>time</code> column around the delimiter <code>:</code>, then slice the <code>hour</code> component using <code>str[0]</code>, finally <code>group</code> the dataframe on <code>date</code> along with <code>hour</code> component and aggregate column <code>value</code> with <code>mea...
python|pandas|dataframe
4
1,371
16,574,470
Out of memory when using numpy's multivariate_normal random sampliing
<p>I tried to use numpy.random.multivariate_normal to do random samplings on some 30000+ variables, while it always took all of my memory (32G) and then terminated. Actually, the correlation is spherical and every variable is correlated to about only 2500 other variables. Is there another way to specify the spherical c...
<p>If your correlation is spherical, that is the same as saying that the value along each dimension is uncorrelated to the other dimensions, and that the variance along every dimension is the same. You don't need to build the covariance matrix at all, drawing one sample from your 30,000-D multivariate normal is the sam...
python|memory|numpy
1
1,372
57,403,472
How do I add a new feature column to a tf.data.Dataset object?
<p>I am building an input pipeline for proprietary data using Tensorflow 2.0's data module and using the tf.data.Dataset object to store my features. Here is my issue - the data source is a CSV file that has only 3 columns, a label column and then two columns which just hold strings referring to JSON files where that d...
<p>Wow, this is embarassing, but I have found the solution and it's simplicity literally makes me feel like an idiot for asking this. But I will leave the answer up just in case anyone else is ever facing this issue.</p> <p>You first create a new tf.data.Dataset object using any function that returns a Dataset, such a...
tensorflow|dataset|tensorflow-datasets
15
1,373
57,478,251
Maximum of an array constituting a pandas dataframe cell
<p>I have a pandas dataframe in which a column is formed by arrays. So every cell is an array.</p> <p>Say there is a column A in dataframe df, such that</p> <pre><code>A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ... ] </code></pre> <p>I want to operate in each array and get, e.g. the maximum of each a...
<p>Here is one way without apply:</p> <pre><code>df['B']=np.max(df['A'].values.tolist(),axis=1) </code></pre> <hr> <pre><code> A B 0 [1, 2, 3] 3 1 [4, 5, 6] 6 2 [7, 8, 9] 9 </code></pre>
python|arrays|pandas|data-analysis
1
1,374
43,549,885
Trying to replace all values matching a pattern in a pandas dataframe with the matched capture groups reversed
<p>Been trying to replace all values matching a pattern in a pandas dataframe with the matched capture groups reversed. So <code>Mouse, Mickey</code> would be replaced with <code>Mickey Mouse</code></p> <p>Dataframe looks like:</p> <pre><code>+---+---------------+------+------+------+------+------+------+------+-----...
<p>You need to specify <code>regex=True</code>; By default, <em>DataFrame.replace</em> method replaces values literally:</p> <pre><code>df = pd.DataFrame({"A": ["Mouse, Mickey", "Duck, Donald"]}) df.replace(r'(.*),\s+(.*)', r'\2 \1', inplace=True, regex=True) df # A #0 Mickey Mouse #1 Donald Duck </co...
python|regex|python-3.x|pandas|dataframe
2
1,375
43,524,953
Find index where elements change value pandas dataframe
<p>Regaring to <a href="https://stackoverflow.com/questions/19125661/find-index-where-elements-change-value-numpy">this question/answer</a>, is there a way to accomplish the same function for a pandas dataframe structure without casting it as a numpy array?</p>
<h3>Update: we can use this per @LorenzoMeneghetti</h3> <pre><code>s[s.diff() != 0].index.tolist() </code></pre> <p>Output:</p> <pre><code>[0, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16] </code></pre> <hr /> <pre><code>s = pd.Series([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5]) print(s.diff()[s.diff() != 0].inde...
python|pandas
13
1,376
43,547,754
How to Import data through Panda for several years but specifc months?
<p>I want to import data from panda for 10 years. But I need each season to be imported separately. for example all the data during Spring from 2000 to 2010.</p> <p>I have following code but this does not separate the season. </p> <pre><code>import pandas_datareader.data as web import datetime start = datetime.dateti...
<p>Assuming that you are targeting Spring months (maybe January 1st through April 30th, subject to change), you can create a <code>list</code> of date <code>tuples</code> where each <code>tuple</code> holds the <code>start</code> and <code>end</code> dates for a given <code>year</code>. For instance, the first element ...
python|python-2.7|python-3.x|pandas-datareader
2
1,377
43,668,993
How to select rows that not consist of only NaN values and 0s
<p>This is my dataframe:</p> <pre><code>cols = ['Country', 'Year', 'Orange', 'Apple', 'Plump'] data = [['US', 2008, 17, 29, 19], ['US', 2009, 11, 12, 16], ['US', 2010, 14, 16, 38], ['Spain', 2008, 11, None, 33], ['Spain', 2009, 12, 19, 17], ['France', 2008, 17, 19, 21], ...
<pre><code>In [307]: df[~df[['Orange','Apple','Plump']].fillna(0).eq(0).all(1)] Out[307]: Country Year Orange Apple Plump 0 US 2008 17.0 29.0 19.0 1 US 2009 11.0 12.0 16.0 2 US 2010 14.0 16.0 38.0 3 Spain 2008 11.0 NaN 33.0 4 Spain 2009 12.0 19.0 1...
python|pandas
6
1,378
43,643,663
Merge serval models (LSTMs) in TensorFlow
<p>I know how to merge different models into one in Keras.</p> <pre><code>first_model = Sequential() first_model.add(LSTM(output_dim, input_shape=(m, input_dim))) second_model = Sequential() second_model.add(LSTM(output_dim, input_shape=(n-m, input_dim))) model = Sequential() model.add(Merge([first_model, second_mod...
<p>As was said in the comment, I believe the simplest way to do this is just to concatenate the outputs. The only complication that I've found is that, at least how I made my LSTM layers, they ended up with the exact same names for their weight tensors. This led to an error because TensorFlow thought the weights were a...
deep-learning|tensorflow|keras
3
1,379
1,664,917
Automatic string length in recarray
<p>If I create a recarray in this way:</p> <pre><code>In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b']) </code></pre> <p>The result looks fine:</p> <pre><code>Out[29]: rec.array([(1, 'hello'), (2, 'world')], dtype=[('a', '&lt;i8'), ('b', '|S5')]) </code></pre> <p>But if I want to specif...
<p>If you don't need to manipulate the strings as bytes, you may use the object data-type to represent them. This essentially stores a pointer instead of the actual bytes:</p> <pre><code>In [38]: np.array(data, dtype=[('a', np.uint8), ('b', np.object)]) Out[38]: array([(1, 'hello'), (2, 'world')], dtype=[('a'...
python|numpy
2
1,380
72,907,661
Creating a Multiple Dictionaries from a CSV File
<p>I am currently importing a file as so:</p> <pre><code>df= pd.read_csv(r&quot;Test.csv&quot;) </code></pre> <p>And the output looks like</p> <pre><code> Type Value 0 Food_Place_1 1 1 Food_Place_2 2 2 Car_Type_1 3 3 Car_Type_2 4 </code></pre> <p>I would like to iterate through this df and dep...
<p>Create category for possible aggregate lists for nested dictionary:</p> <pre><code>#If category is set by remove digits cat = df['Type'].str.replace('\d','') #If category is set by first letter #cat = df['Type'].str[0] d = df.rename(columns={'Type':'Component'}).groupby(cat).agg(list).to_dict('index') print (d) {'...
python|pandas
2
1,381
73,022,079
Turning Python Keras Machine Learning model into repeatable function that can take as input multiple X and y data sets
<p>I am currently building various machine learning models, each of the models takes in X and Y data that represent different stock prices e.g. there's an X and y data frame for each stock e.g. Apple, Microsoft.</p> <p>I am trying to produce these models so that they are repeatable, modular, functions that I can quickl...
<p>Try providing default values for your <code>LSTM_regressor</code> function.</p> <p><code>def LSTM_regressor(X_train=X_tr, X_test=X_te, y_train=y_tr, y_test=y_te):</code></p> <p>From the docs:</p> <blockquote> <p>sk_params takes both model parameters and fitting parameters. Legal model parameters are the arguments of...
python|function|tensorflow|machine-learning|keras
1
1,382
72,952,488
Pandas Scipy mannwhitneyu in this type of data table
<p>I have a data table similar to this one (but huge), many types and more &quot;Spot&quot; cells for each &quot;Color&quot;:</p> <pre><code>Type Color Spots A Blue 792 A Blue 56 A Blue 2726 A Blue 780 A Blue 591 A Blue 2867 A Blue 193 A Green 134 A Green 631 A Green ...
<p>Your questions might be leaving a lot that is obvious to you implied for people who are not as familiar with the sort of statistical analysis you are interested in. That might be making it difficult to help you along, but by trying to cover all my bases, I think I might be able to help you regardless.</p> <p>The fir...
python|pandas|scipy|statistics
-1
1,383
72,990,835
How to send emails for each person in a excel file
<p>So i have a file em.xlsx where i have Name &amp; Email columns, i want to send email when Name matchs the the filename in a directory</p> <p>How can i do that ? so far i have this code below, but it actualy return nothing</p> <pre><code>import glob import pandas as pd import smtplib from email.mime.text import MIMET...
<p>Following code passed my test. Hope it can help you. I'm not sure what's <code>while name == os.path:</code> for, so I just ignore it.</p> <pre><code>import glob import pandas as pd import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import M...
python|pandas|email|path|smtplib
0
1,384
72,845,550
Python Pandas. Endless cycle
<p>Why does this part of the code have an infinite loop? It can't be so, because where I stop this part of code (in Jupyter Notebook), all 99999 values have changed to oil_mean_by_year[data.loc[i]['year']]</p> <pre><code>for i in data.index: if data.loc[i]['dcoilwtico'] == 99999: data.loc[i, 'dcoilwtico'] ...
<p>Use merge to align the oil mean of a year with the given row:</p> <p>Merge on <code>data['year']</code> vs <code>oil_mean_by_year</code>'s index</p> <pre><code>data_with_oil_mean = pd.merge(data, oil_mean_by_year.rename(&quot;oil_mean&quot;), left_on=&quot;year&quot;, right_index=True, ...
python|pandas
0
1,385
70,622,976
pytest: use fixture with pandas dataframe for parametrization
<p>I have a fixture, which returns a <code>pd.DataFrame</code>. I need to insert the individual columns (<code>pd.Series</code>) into a unit test and I would like to use <code>parametrize</code>.</p> <p>Here's a toy example without <code>parametrize</code>. Every column of the dataframe will be tested individually. How...
<p>If you try to generate multiple data from a fixture based on another fixture you will get the <code>yield_fixture function has more than one 'yield'</code> error message.</p> <p>One solution is to use <a href="https://docs.pytest.org/en/6.2.x/fixture.html#parametrizing-fixtures" rel="nofollow noreferrer">fixture par...
python|pandas|pytest|fixtures|parametrized-testing
1
1,386
70,688,556
What is the equivalent of PyTorch's BoolTensor in Tensorflow 2.x?
<p>Is there an equivalent of BoolTensor from Pytorch in Tensorflow assuming I have the below usage in Pytorch that I want to migrate to Tensorflow</p> <pre><code>done_mask = torch.BoolTensor(dones.values).to(device) next_state_values[done_mask] = 0.0 </code></pre>
<p>What is <code>dones</code>? Assuming it's a 0/1 tensor, you can convert it to a Bool tensor like this:</p> <pre><code>tf.cast(dones,tf.bool) </code></pre> <p>However, if you want to assign values to a tensor, you can't do it that way.</p> <p>A way, which I recommend, is to multiply by a matrix of 1/0:</p> <pre><code...
python-3.x|tensorflow|pytorch|tensorflow2.0|tf.keras
1
1,387
70,498,489
Create multiple dataframes with for loop in python
<p>I need to compile grades from 10 files named quiz2, quiz3 [...], quiz11.</p> <p>I have the following transformation:</p> <ul> <li>Import the xls to df with pandas</li> <li>Get only the 4 renamed columns</li> <li>Keep only the highest grade if there is multiple values for the same ID</li> </ul> <p>The code for one da...
<p>You could generate the file name dynamically by looping through a range of numbers from 1 to 11 and concatenating the number to the file name and suffix.</p> <pre><code>#create an empty dataframe for collecting loop results cumulative_df = pd.DataFrame(columns = ['a']) #loop through a range of numbers from 1 to 11 ...
python|pandas|dataframe|loops|file
-1
1,388
70,415,426
Allocator ran out of memory - how to clear GPU memory from TensorFlow dataset?
<p>Assuming a Numpy array <code>X_train</code> of shape <code>(4559552, 13, 22)</code>, the following code:</p> <pre class="lang-py prettyprint-override"><code>train_dataset = tf.data.Dataset \ .from_tensor_slices((X_train, y_train)) \ .shuffle(buffer_size=len(X_train) // 10) \ .batch(batch_size) </code></p...
<p>Try setting a hard limit on the total GPU memory as shown in <a href="https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth" rel="nofollow noreferrer">here</a></p> <pre><code>import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0],...
python|tensorflow|gpu|out-of-memory
1
1,389
70,407,722
Using one excel column on two places JSON
<p>I have Excel file which I am converting to JSON and merge with existing JSON file. The case is that In Excel I have column &quot;ja&quot; and values in it. IS there a way to add values from that column in JSON, on two places: &quot;ja&quot; and &quot;ja-jpn&quot; Expected output:</p> <pre><code>&quot;ja&quot;:{ ...
<p>Before you convert your dataframe to JSON, just duplicate the column, like this:</p> <pre><code>if 'ja' in new_data.columns: new_data['ja-jpn'] = new_data['ja'] </code></pre>
python|json|excel|pandas|localization
0
1,390
70,567,173
Pandas - how to convert objects to float values?
<p>I am working with a pandas dataframe of football players. There is a column with the value of each player. The problem is the type of this column is an object and I want to convert it to float64. How can I do it? The variable is <code>Release clause</code>.</p> <pre><code>df_fifa['Release Clause'] 0 €226.5M 1...
<p>Convert your symbol <code>€</code>, <code>K</code> and <code>M</code> to <code>''</code>, <code> * 1e3</code> and <code> * 1e6</code> and evaluate your expression with <code>pd.eval</code>:</p> <pre><code>mapping = {'€': '', 'K': ' * 1e3', 'M': ' * 1e6'} df_fifa['Release Clause'] = \ pd.eval(df_fifa['Release Cl...
python|pandas|dataframe|variables
2
1,391
70,527,526
When using df1[~df1.isin(df2)].dropna() Question
<p>I have a data set filled with invoices columns including:</p> <ul> <li>CaseID</li> <li>Customer</li> <li>Supplier</li> <li>Part Number</li> <li>Cost.</li> </ul> <p>This data set includes Charges and Credits. I want to remove the Credits and the Charges they credited from DataFrame. I'd like to remove the rows in ori...
<p>Try this:</p> <pre><code>invoices = pd.DataFrame([['111', '2g', 53], ['112', '7g', 25], ['112', '7g', 25], ['113', '8g', 20], ['113', '8g', -20], ['114', '9g', 15], ['...
python|pandas|dataframe
1
1,392
70,441,819
In a pandas string column, eliminate the text preceding a substring
<p>For example I have a Pandas DataFrame with a string column in which I would like to delete the <code>**bold**</code> text before a substring:</p> <pre><code>Column1 **Yon-RM-**CT 500M **Abib-RM-**CT 500M **Wal-RM-**CT 500M **Sopxc-RM-**CT 1000M </code></pre> <p>Notice that the bold text could have different length b...
<p>Assuming all you want is CT 500M, and all follow the same format, apply a lambda function that splits by &quot;-&quot;, and get the third index</p> <pre><code> df[&quot;Column1&quot;] = df.apply(lambda x: x[&quot;Column1&quot;].split(&quot;-&quot;)[2], axis=1) </code></pre> <p>You could also split by &quot;RM&quot;<...
python|pandas|substring
0
1,393
42,914,747
Setting value to a copy of a slice of a DataFrame
<p>I am setting up the following example which is similar to my situation and data:</p> <p>Say, I have the following DataFrame: </p> <pre><code>df = pd.DataFrame ({'ID' : [1,2,3,4], 'price' : [25,30,34,40], 'Category' : ['small', 'medium','medium','small']}) </code></pre> <p><br></p> <pre>...
<p>One approach with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> -</p> <pre><code>mask = df.Category.values=='small' df['Discount'] = np.where(mask,df.price*0.01, df.price*0.02) </code></pre> <p>Another way to put things a bit dif...
python|pandas|numpy|dataframe
8
1,394
42,956,997
Stripping and testing against Month component of a date
<p>I have a dataset that looks like this:</p> <pre><code>import numpy as np import pandas as pd raw_data = {'Series_Date':['2017-03-10','2017-04-13','2017-05-14','2017-05-15','2017-06-01']} df = pd.DataFrame(raw_data,columns=['Series_Date']) print df </code></pre> <p>I would like to pass in a date parameter as a stri...
<p>convert your column to <code>Timestamp</code></p> <pre><code>df.Series_Date = pd.to_datetime(df.Series_Date) date = pd.to_datetime('2017-03-01') </code></pre> <p>Then</p> <pre><code>df[ (df.Series_Date.dt.year - date.year) * 12 + df.Series_Date.dt.month - date.month == 3 ] Series_Date 4 2017-06-01 <...
python|python-2.7|pandas
0
1,395
42,605,840
Automatic extraction of recent nine months data in python
<p>I have a data frame which consists of data aggregated over certain time span with 'date'as one of the columns. Now every day a new data with exactly same columns is added to this aggregated data. Now I want to apply a filter on this aggregated data, that post appending new daily data I want only recent nine months d...
<p>You can dynamically generate 6 months old date</p> <pre><code>from datetime import date from dateutil.relativedelta import relativedelta six_months_old = date.today() + relativedelta(months=-6) six_months_old #datetime.date(2016, 9, 5) </code></pre> <p>now use this value to filter your dataframe</p> <pre><code>...
python|pandas|datetime
2
1,396
42,955,746
Process to build our own model for image detection
<p>Currently, I am working on deep neural network for image detection and I founded a model called YOLO Network, and it's very powerful to make objects detections, but I have a question:</p> <ul> <li>How can we design and concept our own model? Do we use a brut force for that, for example "I use 2 convolutional and 1...
<p>There are a couple of papers addressing this issue. For example in <a href="http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Szegedy_Rethinking_the_Inception_CVPR_2016_paper.pdf" rel="nofollow noreferrer">http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Szegedy_Rethinking_the_Inceptio...
tensorflow|deep-learning|object-detection
2
1,397
27,100,799
how to do 3d matrix to 3d multiplication in python without loops?
<p>I am doing segmentation part in my project, where I need to multiply a 3 dimensional mask to a color image. </p> <p>What am doing now:</p> <pre><code>maskedFrame=np.zeros((rgbFrame.shape)) maskedHsvFrame=np.zeros((rgbFrame.shape)) for color in range(0,3): maskedFrame[:,:,color]=rgbFrame[:,:,color]*biscuitMask ...
<p>AFAIK, numpy can <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">braodcast</a> <code>biscuitMask</code> along the color dimension to fit the shape of the frame.<br> This broadcasting is done automatically. Thus,</p> <pre><code>maskedFrame = rgbFrame * biscuitMask maskedHsvFram...
python|image-processing|numpy|image-segmentation
0
1,398
14,398,188
Numpy import in PyCharm yields "Cannot locate working compiler"
<p>I am new to Python and PyCharm, installed PyCharm 2.6 (on Mac OSX) and tried to import NumPy for Python 3.3. JetBrains support file tells me to install Cython which also yields "Cannot locate working compiler"</p> <p>How and which compiler do I need to install?</p> <p>Thanks!</p>
<p>Check whether the 'gcc' command works. If it's there, try setting the CC environment variable to 'gcc'.</p>
compiler-construction|numpy|python-3.x|pycharm
0
1,399
25,275,009
Pandas Series.filter.values returning different type than numpy array
<p>I am trying to run the <code>scipy.stats.entropy</code> function on two arrays. It is being run on each row of a Pandas DataFrame via the apply function:</p> <pre><code>def calculate_H(row): pk = np.histogram(row.filter(regex='stuff'), bins=16)[0] qk = row.filter(regex='other').values stats.entropy(pk, ...
<p>I suspect <code>qk</code> is an <code>object</code> array and not an array of integers. In <code>calculate_H</code>, try this:</p> <pre><code>qk = row.filter(regex='other').values.astype(int) </code></pre> <p>(i.e. cast the values to an array of integers).</p>
python|numpy|pandas|scipy
2