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
359,000
66,679,177
Using Styleframe to pull styles of individual cells from Excel
<p>I'm trying to write a script that merges two excel files together. One has been has been hand processed and has a bunch custom formatting done to it, and the other is an auto-generated file. Doing the merge in pandas is simple enough, but preserving the formatting is proving troublesome. I found the styleframe libra...
<p>Figured it out. I rejiggered my dataframe so that I could just us a <code>.at</code> instead of a <code>.loc</code> lookup. This, coupled with the <code>apply_style_by_indexes</code> method got me where I needed to be:</p> <pre><code>for index, row in orig_excel.iterrows(): for column, value in row.iteritems():...
python|pandas|styleframe
1
359,001
66,487,171
ValueError related to Size of X Dataset Array in Jupyter
<p>I'm relatively new to tensorflow and I'm experiencing an error I don't know how to fix.</p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import cifar10 from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.models import Sequential ...
<p>I've resolved the issue. The X values were 3 times as expected because 1 value was expected, but the images were in color, not grayscale, thus having 3 values instead of the expected 1.</p>
python|tensorflow|jupyter-lab|valueerror|image-classification
0
359,002
16,171,658
How to install external libraries with Portable Python?
<p>I can't install Python on my machine due to administrator privileges, but I did download/open Portable Python successfully. I am on a Windows 7 64-bit machine. How would I be able to use the external libraries from before, such as Numpy or Gmpy?</p>
<p>easy_install is trying to install from source. gmpy and gmpy2 are C extensions and require the presence of a compatible C compiler and other libraries (GMP; and MPFR and MPC for gmpy2). Installing from source is frequently difficult on Windows. The installers include a precompiled version of the extension.</p> <p>O...
python|numpy|installation|portability
4
359,003
57,724,300
Compairing 4 graph in one graph
<p>I have 4 dataframe with value count of number of occurance per month. I want to compare all 4 value counts in one graph, so i can see visual difference between every month on these four years. Like below <a href="https://i.stack.imgur.com/02FH9.png" rel="nofollow noreferrer">i like to have output like this image wit...
<p>Create dictionary of <code>DataFrame</code>s and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> together, then use <code>plot</code>:</p> <pre><code>dfs = {2015:newdf2015, 2016:newdf2016, 2017:newdf2017, 2018:newdf2018} df = ...
python-3.x|pandas|dataframe|matplotlib
0
359,004
57,572,342
How to add the columns after subseting?
<p>I have the following data frame:</p> <pre><code>import pandas as pd import numpy as np dic = { "ID": [1, 2, 3, 4, 5], "Age": [18, 20, 18, 30, 30], "Car": ["BMW", "Benz", "BMW", "porsche", "porsche"], "Salary": [1000, 2000, 3000, 1200, 4000] } dt = pd.DataFrame(dic) </code></pre> <p>I need to omit...
<p>Use <code>drop_duplicates</code> like this:</p> <pre><code>dt.drop_duplicates(['Age', 'Car'], keep = 'first') </code></pre> <p>Output:</p> <pre><code> ID Age Car Salary 0 1 18 BMW 1000 1 2 20 Benz 2000 3 4 30 porsche 1200 </code></pre>
python|pandas|numpy
1
359,005
57,683,973
Generate new data frame column based on content of current column using lamdas
<p>I have a simple data frame with a columns labeled 'Vehicles', 'Red', 'Blue'. The 'Vehicles' column has a list that includes items like 'Red Car', 'Blue truck' and so on. I would like to populate the Red and Blue columns with a True or False dependant on the content of the 'Vehicle' column. My poor attempt so far:...
<p>I am think this is more like a <code>get_dummies</code> problem </p> <pre><code>s=df.Vehicles.str.extract('(Red|Blue|Green)')[0].str.get_dummies() df=pd.concat([df,s],axis=1) df Vehicles Blue Green Red 0 Red Truck 0 0 1 1 Blue Car 1 0 0 2 Red Car 0 0 1 3 Green Van ...
python|pandas
2
359,006
57,442,989
How can I merge multiple xls sheets in python?
<p>I am working on a social media project and the excel file I have has multiple sheets. How do I merge the sheets to create a single df?</p> <p>My machine is running Python v3 in Anaconda. Please see the code below:</p> <pre><code>import pandas as pd xls = pd.ExcelFile('Digital Metrics Platforms_Clean.xlsx') df1 ...
<p>I discovered that my sheets did not have the same number of columns, so ensuring that the data was in the same shape solved the problem</p>
python-3.x|pandas|dataframe|concat
0
359,007
57,305,288
How can i make a matrix filled with a sequence for the rows and columns
<p>I want to create a matrix with an complex part and a real part. The values from the colums should go from [-2.0 -> 1.0] with 300 steps The values from the rows should go from [-1.5 -> 1.5] with steps of 300, this is also the complex part.</p> <p>I can make a matrix of 301 X 301 and fill this with zeros. But then i ...
<p>You can make an <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ogrid.html" rel="nofollow noreferrer">open grid</a> and sum it:</p> <pre><code>sum(np.ogrid[1.5j:-1.5j:301j,-2:1:301j]) </code></pre>
python|python-3.x|numpy|matrix
1
359,008
57,364,080
Compare columns from two different dataframes pandas
<p>I am querying AD for a list of machines. I filter this list with pandas by last log on date. When I am done with this data I have one column in a dataframe. </p> <p>I have another report that has a list of machines that a product we use is installed. I clean this data and I am left with the devices that I want to ...
<h1><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer">DataFrame.isin</a></h1> <p>this is a simple check to see if one value is in another, you do this in a multitude of ways, this is probably one of the simpliest.</p> <p>I'm providing some dummy ...
python|python-3.x|pandas
0
359,009
57,704,092
how do I sum each column based on condition of another column without iterating over the columns in pandas datframe
<p>I have a data frame as below:</p> <pre><code> Preg Glucose BloodPressure SkinThickness Insulin Outcome 0 1.0 85.0 66.0 29.0 0.0 0.0 1 8.0 183.0 64.0 0.0 0.0 0.0 2 1.0 89.0 66.0 23.0 94.0 1.0 3 ...
<p>Here is a solution to get the expected output:</p> <pre><code>sum_df = df.loc[df.Outcome == 1.0].sum().to_frame().T sum_df.Outcome = 0.0 </code></pre> <p>Output:</p> <pre><code> Preg Glucose BloodPressure SkinThickness Insulin Outcome 0 6.0 342.0 180.0 58.0 262.0 0.0 </code>...
pandas|dataframe|sum
2
359,010
57,494,188
pandas reshape multi key value dataframe colums to rows
<p>I have a dataframe like: <a href="https://i.stack.imgur.com/JHGDn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JHGDn.png" alt="enter image description here"></a></p> <p>How can it be reshaped that the columns (0 => 1, 2=> 3) are stored as records? I.e. columns <code>metric_name</code> and <cod...
<p>If only 4 columns you can flatten values and create DataFrame by constructor:</p> <pre><code>a = df[[0, 2]].values.ravel() b = df[[1, 3]].values.ravel() df = pd.DataFrame({'A':a, 'B':b}) print (df) A B 0 Model: Logit 1 Pseudo R-squared: ...
python|pandas|reshape
1
359,011
57,447,937
How to use tft.compute_and_apply_vocabulary and tft.tfidf correctly?
<p>I try to use tft.compute_and_apply_vocabulary and tft.tfidf to compute tfidf in my jupyter notebook. However I always get the following error:</p> <pre><code>tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'compute_and_apply_vocabulary/vocabulary/Placeholde...
<p>We can't use the Operations of <code>Tensorflow Transform</code> like <code>tft.compute_and_apply_vocabulary</code> directly, unlike <code>Tensorflow</code> Operations, which can be used directly in a <code>Session</code>.</p> <p>For us to use the Operations of <code>Tensorflow Transform</code>, we must run them in...
python|tensorflow|tf-idf|tensorflow-transform
2
359,012
57,362,206
Pandas fill missing values with groupby
<p>I have a table of various indicators grouped by Date and Code. I am trying to fill missing values with the previous day's data OR if not available - with the next day's data for each Code.</p> <p>The problem is when I group by 'Code' and 'Date', nothing happens</p> <pre class="lang-py prettyprint-override"><code>d...
<p>You need:</p> <pre><code>df.groupby(['Code']).apply(lambda x: x.ffill().bfill()) </code></pre> <p>Output:</p> <pre><code> Code Date Price Volume ATM 0 APL 2019-05-01 15951.0 303.0 49.0 1 APL 2019-05-02 16075.0 301.0 46.0 2 APL 2019-05-03 16075.0 300.0 45.0 3 APL 2019-05-04 15868.0 29...
pandas|fillna
3
359,013
57,555,948
Find first three closest points from other dataframe
<p>Having original pandas dataframe containing 2 coordinates x_1 and x_2 without values:</p> <pre><code> x_1 x_2 0 0.0 0.0 1 1.0 0.0 2 2.0 0.2 3 2.5 1.5 4 1.5 2.0 5 -2.0 -2.0 </code></pre> <p>and other "calibration" dataframe that contains coordinate points with values:</p> <pre><code> x_1 x_2 val...
<p>If two datasets are not too big to calculate pairwise distance, you could outer merge two datasets, calculate the distance for each pair, rank them in each group. see code below (assuming <code>df1</code> is <code>df</code> and <code>df2</code> is <code>calibration</code>,</p> <pre><code>result = (df1.reset_index(...
python|pandas
1
359,014
57,557,231
Broadcasting only with specific dimensions of ndarray in python
<p>Consider a <code>TxFxM</code> ndarray. I wish to multiply it with its conjugate, only for the <code>M</code> dimension while keeping the other dimensions the same as presented in the following code: </p> <pre><code>import numpy as np T=2 F=3 M=4 x=np.random.rand(T,F,M) result=np.zeros((T,F,M,M)) for i in range(...
<p>The array you need can be computed with broadcasting if you inject singleton dimensions in two different places for <code>x</code> and <code>x.conj()</code>. If <code>x</code> has shape <code>(T,F,M)</code> then arrays of shape <code>(T,F,M,1)</code> and <code>(T,F,1,M)</code> will broadcast to <code>(T,F,M,M)</code...
python|numpy|vectorization|simd|array-broadcasting
0
359,015
57,517,702
Having trouble converting code from Python to c#
<p>SOLVED: I'm working on detecting the MRZ of a passport. I've got a strategy but due to lack of documentation I haven't been able to convert the following lines of code. My project is using OpenCvSharp and NumSharp which is a port of numpy to c#. Any help would be much appreciated.</p> <p>Python Code: </p> <pre>...
<p>Here is the solution to my original problem:</p> <pre><code>// compute the Scharr gradient of the blackhat image and scale the // result into the range [0, 255] Cv2.Sobel(blackhat, gradX, MatType.CV_32F, 1, 0, -1, 1, 0); //(minVal, maxVal) = (np.min(gradX), np.max(gradX)) double minVal, maxVal; gradX.MinMaxLoc(out...
python|c#|numpy|opencv
1
359,016
57,375,664
Pandas - how to merge dataframes on datetime column of different format?
<p>I have two dataframes that I need to merge based on date. The first dataframe looks like:</p> <pre><code> Time Stamp HP_1H_mean Coolant1_1H_mean Extreme_1H_mean 0 2019-07-26 07:00:00 410.637966 414.607081 0.0 1 2019-07-26 08:00:00 403.521735 424.787366 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> with sorted both DataFrames by datetimes:</p> <pre><code>#if necessary df1['Time Stamp'] = pd.to_datetime(df1['Time Stamp']) df2['Time Stamp'] = pd.to_datetime(df2['Ti...
python|pandas|merge|timestamp
2
359,017
57,588,828
Seaborn pairplot not working fine using anaconda and pycharm. getting Degrees of freedom warning
<p>I am very new to using python data science libraries. I am using PyCharm as IDE and Anaconda Python 3.7 Interpreter. </p> <p>I have Anaconda3 and I'm using Jupyter Notebook. I have a csv file named smartphones.csv which has the details in the picture below and I imported all necessary libraries.</p> <p><a href="ht...
<p>It seems like an error would occur if you don't specify the <code>diag_kind</code> argument; here is the <a href="https://github.com/mwaskom/seaborn/issues/1627" rel="nofollow noreferrer">issue</a> you could read on.</p> <pre class="lang-py prettyprint-override"><code># diag_kind : {'auto', 'hist', 'kde'} sb.pairpl...
python|pandas|matplotlib|anaconda|seaborn
2
359,018
57,439,094
Get band values when using seaborn lineplot with ci parameter
<p>I want to get the bounding values when I use seaborn lineplot with the parameter <code>ci</code> set to <code>sd</code> e.g. </p> <pre><code>import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") ax = sns.lineplot(x="timepoint", y="signal", ci="sd", data=fmri) </code></pre>...
<p><code>sns.lineplot()</code> is plotting the mean of <code>fmri.signal</code> at each value of <code>fmri.timepoint</code> and adding confidence intervals by standard deviation. You can get the mean and standard deviation with native Pandas:</p> <pre><code>fmri.groupby('timepoint')['signal'].mean() fmri.groupby('tim...
python|pandas|seaborn
1
359,019
57,597,738
How can multiple groups of data be put in a single bar chart?
<p>I have a simple DataFrame of nutrition values for each meal time:</p> <pre><code>import pandas as pd import seaborn as sns df = pd.DataFrame( [ [ 0.0367354, 0.0484153 , 0.0894831 , -0.131245 , -0.0961374, -0.049433 , 0.142161 , 0.0884946, 'breakfast'], [-0.06033...
<p>Can be done with <code>transpose</code> after setting the index</p> <pre><code>df.set_index('mealtime').T.plot(kind='bar') </code></pre> <p><a href="https://i.stack.imgur.com/4qidJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4qidJ.png" alt="enter image description here"></a></p>
pandas|dataframe|bar-chart|seaborn
1
359,020
57,612,703
Could not import PIL.Image even if Pillow already installed?
<p>I'm going through chapter 5 of the book Deep Learning with R (<a href="https://livebook.manning.com/book/deep-learning-with-r/chapter-5/112" rel="nofollow noreferrer">https://livebook.manning.com/book/deep-learning-with-r/chapter-5/112</a>). </p> <p>When running the code below, the following error appears: <code>Er...
<p>The problem is that Keras for R creates its own virtual environment, called <code>r-reticulate</code>, and pillow is missing in there. You also have to find out whether it used conda or virtualenv to create such environment. Then, activate it and install pillow and scipy. Finally, restart the R session.</p> <p>In m...
python|r|tensorflow|keras|deep-learning
0
359,021
57,658,802
How do I split a single dataframe into multiple dataframes by the range of a column value?
<p>First off, I realize that this question has been asked a ton of times in many different forms, but a lot of the answers just give code that solves the problem without explaining what the code actually does or why it works. </p> <p>I have an enormous data set of phone numbers and area codes that I have loaded into a...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a> to <code>bin</code> the <code>area</code> column , then use the labels to group the data and store in a dictionary. Finally print each key to see the dataframe:</p> ...
python|python-3.x|pandas
2
359,022
57,604,810
How to set Seaborn/Matlplotlib scatterplot markers to corresponding images/photos?
<p>I'm trying to create a scatterplot with Seaborn that would have small thumbnail images as markers instead of the default markers (circles, crosses, squares etc.). Each image is different and must follow unique IDs that run through my entire Pandas dataframe.</p> <p>I can create the plots just fine with normal marke...
<p>**I think it's markers not maker.</p> <p>you can create a dictionary where each X value is associated with path.and in makrker you can give path of that dict. </p> <p>like this==></p> <pre><code> data = { "3.4":"C:\Images\imageid1.jpg",..........} sns.scatterplot(...... ...
python|pandas|image|matplotlib|seaborn
-2
359,023
57,310,861
How to stack numpy arrays alternately/slicewise along a specific axis?
<p>How can I stack arrays in an alternating fashion? Consider the following example with three arrays:</p> <pre><code>import numpy as np one = np.ones((5, 2, 2)) two = np.ones((5, 2, 2))*2 three = np.ones((5, 2, 2))*3 </code></pre> <p>I would like to create a new array <code>result</code> with shape <code>(15, 2, 2)...
<p>You may wanne take a look at <code>np.stack()</code> i.e.:</p> <pre><code>np.stack([one, two, three], axis=1).reshape(15, 2, 2) </code></pre>
python|arrays|numpy
2
359,024
57,310,263
Flatten triple-nested JSON with normalize
<p>I am trying to flatten the following but it only works for a non triple-nested JSON.</p> <p>Working code:</p> <p>import json </p> <pre><code>import pandas as pd from pandas.io.json import json_normalize data = [{'masterName': 'AAAAAAAAAAA', 'shortname': 'AA', 'info': { 'name': 'r...
<p>As suggested by @Aayush Mahajan in the comments, it might be simpler to define your own function. Here is one working with <code>data2</code>:</p> <pre><code>out = [] data2 = data2[0] # Remove first level for main in data2["mainNames"]: # Iterate "mainNames" ...
python|json|pandas|python-2.7
0
359,025
57,530,795
Question on offsetting when resampling a dataframe
<p>I am trying to resample a dataset for every 3 hours with a 1 hour offset. When I attempt it, the time is offset by 1 hour and set for every 3 hours as desired, but the values are only resampled and not taking into account the offset</p> <p>My attempt has looked like this</p> <pre class="lang-py prettyprint-overrid...
<p>You need to use parameter <code>base</code> instead of <code>loffset</code> which only adjust the labels.</p> <p>Try:</p> <pre><code>thirdly = df.resample('3H', base = 1, on='TIME').mean() </code></pre>
python|pandas|dataframe|datetime
0
359,026
57,682,485
Tensorflow classifier.evaluate running indefinitely?
<p>I've started trying out some of the Tensorflow API's. I am using the iris data set to experiment with Tensorflows Estimator's. I'm loosely following this tutorial except that I load my data in a little differently: <a href="https://www.tensorflow.org/guide/premade_estimators#top_of_page" rel="nofollow noreferrer">ht...
<p>Had to switch a lot of things up but finally got the estimator working on the IRIS data set. Here is the code below for any who may find it useful in the future. Cheers.</p> <pre><code>#First we want to import what we need. Typically this will be some combination of: import tensorflow as tf import pandas as pd impo...
python-3.x|tensorflow
0
359,027
57,487,087
C51 reinforcement learning algorithm extremely slow
<p>I am applying reinforcement learning on a time series prediction problem. Until now, I have implemented a dueling DDQN algorithm with LSTM which seems to give some pretty good results, though sometimes slow to converge depending on the exact problem. I have then used C51 distributional reinforcement learning to comp...
<p><strong>If there is anything wrong with your GPU, then Tensorflow will notify you with a Warning, when you first run the script.</strong></p> <p>Generally, C51-DQN algorithm is slower than DQN. This is because It takes <strong>longer time</strong> to compute the distribution of the reward of an action, rather than t...
python|tensorflow|machine-learning|reinforcement-learning|q-learning
0
359,028
57,581,257
Pandas: How to check if any of a list in a dataframe column is present in a range in another dataframe?
<p>I'm trying to compare two bioinformatic DataFrames (one with transcription start and end genomic locations, and one with expression data). I need to check if any of a list of locations in one DataFrame is present within ranges defined by the start and end locations in the other DataFrame, returning rows/ids where t...
<p>Based on a comment below, I tried playing with <code>merge_asof</code>:</p> <pre class="lang-py prettyprint-override"><code>pd.merge_asof(tss_df,exp_df,left_on='locs',right_on='start') </code></pre> <p>This gave me an incompatible merge keys error, I suspect because I'm comparing a list to integer; so I split out ...
python|pandas
1
359,029
57,461,893
Cannot manually load kears imbd dataset
<p>following this instruction: <a href="https://stackoverflow.com/questions/40690203/the-alternative-to-from-keras-datasets-import-mnist/51632839">the alternative to from keras.datasets import mnist</a></p> <p>I am able to load the mnist dataset, with the following lines:</p> <pre><code>f = gzip.open('C:/.../Datasets...
<p>Since you are behind a proxy, there are alternatives to download the dataset:</p> <ul> <li>Download the file at <a href="https://s3.amazonaws.com/text-datasets/imdb.npz" rel="nofollow noreferrer">https://s3.amazonaws.com/text-datasets/imdb.npz</a></li> <li>Put the downloaded file inside <code>C:\Users\&lt;your_user...
python|tensorflow|keras
2
359,030
57,383,430
Ideas on filling each shape in triangle mesh with values
<p>I'm trying to write python code that creates a 2D NumPy array (e.g. 128x128) containing a mesh of raster triangles in which each triangle has a random value.</p> <p>Does anyone know of any python package that could do this?</p> <p>I tried using this triangle package (<a href="https://rufat.be/triangle/examples.htm...
<p>Generate <em>k</em> random points inside the rectangle (0,0,128,128) and generate the <a href="https://en.wikipedia.org/wiki/Delaunay_triangulation" rel="nofollow noreferrer">Delaunay Triangulation</a> of the set of the points plus the four corners of the rectangle. </p> <p>Construct the NumPy array from the list o...
python|numpy
1
359,031
57,532,092
How to speed up calculating variance among sparse matrix
<p>Thank you for your help. Let me explain my question more clearly.</p> <p>I have several coo_matrix M with same shape. Indexes of each matrix represent a journal pair. Each element represents the frequency of a journal pair. For example, for all matrices, [1,2] gives the frequency of journal pair 1-2; [2,1] gives th...
<p>If I understand correctly (correct me if I'm wrong) you are hoping to compute the elementwise variance across a list of sparse matrices all of which have the same shape. For example, you could have 100 sparse matrices each of size 200 by 300 as below.</p> <pre class="lang-py prettyprint-override"><code>from scipy i...
python|pandas|numpy|sparse-matrix
0
359,032
57,494,770
Pandas Correlation GroupBy with several columns
<p>Assuming I have a dataframe similar to the one below, how can I get the correlation between all the columns using <code>groupby</code>?</p> <p>What I have:</p> <pre><code>DAY Val1 Val2 Val3 1 4 3 4 1 3 8 6 1 2 3 4 2 4 3 4 2 3 ...
<p>First, you get the results with:</p> <pre><code>df.groupby('DAY')[['Val1','Val2', 'Val3']].corr() </code></pre> <p>Though, you still need to format the results to get the desired output; something like:</p> <pre><code>(df[~df['Val1'].eq(1)] .reset_index(1, drop=True)['Val1'] .rename('CorrVal1-...
python|pandas|group-by|correlation
-1
359,033
57,498,478
Python function to get a column name based on element
<p>I have a given DataFrame, that has unique column names but has duplicates in the single element'S values within the dataframe. - My dataframe is About 10*2000</p> <pre><code>df = DataFrame({"R1": [1,2,3], "R2": [4,2,6], "R3": [7,8,2]}) </code></pre> <p>Example #1:</p> <blockquote> <p>Input: 1<br> Output: "R1"...
<p>I am not aware of a build in function, however, the following should be reasonably fast:</p> <pre><code>input = your_input # iterate over all your columns for x in list(df.columns.values): # if the colums contains the desired value, print it/do whatever you want with it if input in df[x].values: pri...
python|pandas
0
359,034
57,410,576
My Dataframe all have NaN except the last column
<p>I'm trying to loop over multiple JSON data and then for each value in list add it to the DataFrame. For each JSON data, I create a column header. I seem to always only get the data for the last column, so there is clearly something wrong with the way I append the data I believe.</p> <pre><code>from pycoingecko impo...
<p>Ok I think I found the issue. </p> <p>The problem is you append data structures row by row that contained only one column to the frame, so all the other columns were filled with <code>NaN</code>. What i <em>think</em> you want is to join the columns by their timestamp. This is what i did in my example below. Let me...
python|json|pandas|loops
1
359,035
57,551,081
How to format datetime values in columns without to_datetime functions in pandas?
<p>I have a dataframe as shown below</p> <pre><code>df1_new = pd.DataFrame({'person_id': [1, 1, 3, 3, 5, 5],'obs_date': ['7/23/2377 12:00:00 AM', 'NA-NA-NA NA:NA:NA', 'NA-NA-NA NA:NA:NA', '7/27/2277 12:00:00 AM', '7/13/2077 12:00:00 AM', 'NA-NA-NA NA:NA:NA']}) </code></pre> <p><a href="https://i.stack.imgur.com/ih...
<p>Convert the string date to datetime and then back to the format you want. Example below:</p> <pre><code>from datetime import datetime d = "7/23/2377 12:00:00 AM" datetime.strptime(d, "%m/%d/%Y %I:%M:%S %p").strftime("%Y-%m-%d %H:%M:%S %p") #output &gt;&gt;&gt;'2377-07-23 00:00:00 AM' </code></pre>
python|python-3.x|pandas|dataframe|datetime
1
359,036
57,538,174
How can I share memory between numpy arrays?
<p>I have a large numpy array of size 100x100. Among these 10000 values, there are only about 50 unique values. So I want to create a second array of length 50, containing these unique values, and then somehow map the large array to the smaller array. Effectively, I want to store just 50 values in my system instead of ...
<p>In general it is not possible to save memory in this way. The reason is that your data consists of 64-bit integers, and pointers are also 64-bit integers, so if you try to store each value exactly once in some auxiliary array and then point at those values, you will end up using basically the same amount of space.<...
python|numpy|memory
0
359,037
57,330,054
Why is pandas data frame returning everything as a string?
<p>I have a pandas data frame read from a csv. It has mixed data types, strings and floats (can be integers; it doesn't matter which for my data processing).</p> <p>When I am trying to access the rows of integers, however, I am getting a string return rather than a list of floats. Even the '[' at the ends are counted ...
<p>I came up with a solution facilitating easier access to your data.</p> <p>For demonstration purpose, I took a fragment of your source file (title and just 2 columns, with limited length of included lists):</p> <pre><code>Title,Tissue: area 24,Tissue: area 9 Activation path,"[0.0, 4.0, 7.0]","[0.0, 4.0, 7.0]" Inhib...
python|pandas|csv|types
1
359,038
57,315,352
how to filter dataframe using a function?
<p>i would like to use the following function to filter a dataframa</p> <pre class="lang-py prettyprint-override"><code>def isInRadius(position): latCheck = False lonCheck = False if position.lat &lt; 0: latCheck = position.lat &lt;= upperLat and position.lat &gt;= lowerLat else: latChe...
<p>Just use the <code>.apply</code> functionality of pandas dataframes</p> <pre><code>df[df.apply(isInRadius, 1)] </code></pre>
python|pandas|dataframe
4
359,039
57,297,296
TypeError: object of type 'Conv2DTranspose' has no len()
<p>I'm coding an autoencoder using Keras and I keep getting the below error. I think it's related to adding the arg <code>keras_initializer</code> since I got this error before for Conv2D, added the initializer and Conv2D had length. Although, since I'm using <code>tf.keras.layers.reshape</code>, this isn't a valid ar...
<p>You are mixing <code>tf.keras</code> and <code>keras</code> imports, and <strong>this is not supported</strong> and it will not work. You need to choose one implementation and import all modules/classes from it.</p>
tensorflow|keras
9
359,040
57,454,973
Parsing a text file with tweets to csv with '|' delimiter
<p>I have a .txt file containing geotagged tweets. The information is delimited by '|' character. The information (which can be perceived as columns) are datetime, latitude, longitude and tweet_text. </p> <pre><code>Date_time|latitude|longitude|tweet_text Mon Jan 01 09:09:57 +0000 2018|-37.8140362|144.9644232|terima k...
<p>So it was just a matter of specifying the number of columns by specifying the column names.</p> <pre><code>data = pd.read_csv('MelbCBD_scs2018_new.txt', sep="|", names = ["Date_time", "latitude", "longitude","tweet_text"], header=None, quoting=csv.QUOTE_NONE,error_bad_lines=False) </code></pre> <p>Now, this return...
python|pandas|csv|parsing|text
1
359,041
57,521,410
Generate positive only distribution based on array
<p>I have an array of data, for example:</p> <pre><code>[1000,800,700,650,630,500,370,350,310,250,210,180,150,100,80,50,30,20,15,12,10,8,6,3] </code></pre> <p>From this data, I want to generate random numbers that fit the same distribution.</p> <p>I can generate a random number using code like the following:</p> <p...
<p>As broadly suggested in the comments by Hilbert's Drinking Problem, the real solution was to find a better distribution that fit the parameters. In my case Chi-Squared, which fit both the shape of the curve, and also the fact that it only took positive values.</p> <p>However in the comments Stelios made the good su...
python-3.x|numpy|scipy
0
359,042
57,597,557
How can I get the information from a dataframe containing dictionaries or lists in every column?
<p>I have this information and I can't get the values of the columns <code>serviceTypes</code> and <code>crowding</code>:</p> <pre class="lang-none prettyprint-override"><code>id name modeName disruptions lineStatuses serviceTypes crowding 0 piccadilly Piccadilly tube [] [] [{'$type': 'Tfl.Api.Pr...
<p>You can pull a pandas column into a list like so:</p> <pre><code>service_types = dflines['serviceTypes'] </code></pre> <p>The first value is now the the first value in the list service_types.</p> <pre><code>first_value = service_types[0] </code></pre> <p>Pandas works differently than a dictionary. I think you mi...
python|pandas|dataframe
0
359,043
57,367,856
Plotting Specific Regions
<p>I am new to python. The problem is that, assume that we have two parameters, x and y, and four functions f_1, f_2, f_3 and f_4. Suppose that we know that:</p> <ol> <li>If (x &lt; 5 &lt; y &lt; 5+x) or (5 &lt;= y &lt; x) or (x= 5 and 5 &lt; y &lt; 10) then function f_1 is the maximum function.</li> <li>If (5 &lt; x ...
<p>When you set the initial array to -9999.99 you now have to make sure you only contour the values that you want which is between 1-3. Since that value is so much bigger in magnitude it does not get included in your plot. Set your contour levels for your plot using this:</p> <pre><code>plt.contourf(x,y,maxf,[0,1,2,3]...
python|python-3.x|numpy|matplotlib
1
359,044
57,410,493
Is this example data cleaning code updating the pandas dataframe?
<p>In <a href="https://viblo.asia/p/predict-independent-values-with-text-data-using-linear-regression-aWj5314eZ6m" rel="nofollow noreferrer">this article on predicting values with linear regression</a> there's a cleaning step</p> <pre><code># For beginning, transform train['FullDescription'] to lowercase using text.lo...
<p>The right way to apply these transformations would be...</p> <p><code>df.loc[:, 'FullDescription'] = ...</code></p> <p>More informations about this would be <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#why-does-assignment-fail-when-using-chained-indexing" rel="nofollow noreferrer"...
python-3.x|pandas|data-cleaning
0
359,045
24,428,856
Panda group dataframes into user specified time period
<p>Probably related: <a href="https://stackoverflow.com/questions/17764619/pandas-dataframe-group-year-index-by-decade">pandas dataframe group year index by decade</a></p> <p>For example if I have data as follows</p> <pre><code> status bytes_sent upstream_cache_status \ timestamp ...
<p><code>df.groupby(pd.Grouper(freq='30S', level=0))</code> should do; for example </p> <pre><code>&gt;&gt;&gt; aggr = lambda df: df.apply(tuple) &gt;&gt;&gt; df.groupby(pd.Grouper(freq='30S', level=0)).aggregate(aggr) status bytes_...
python|pandas
1
359,046
24,262,766
How to force pandas DataFrame use the desired dtypes when it is constructed?
<p>For example:</p> <pre><code>raw = {'x':[1,2,3,4], 'y':[None,]*4, 'z':[datetime.now()] *4, 'e':[1,2,3,4]} a = pd.DataFrame(raw, dtype={'x':float, 'y':float, 'z':object, 'e':int}) </code></pre> <p>This doesn't work.</p> <p>Currently I have to do:</p> <pre><code>a = pd.DataFrame(raw, dtype=object) a['x'] = a['x']....
<p>The constructor will infer non-ambiguous types correctly. You cannot specify a compound dtype mapping ATM, issue is <a href="https://github.com/pydata/pandas/issues/4464" rel="nofollow">here</a>, pull-requests are welcome to implement this.</p> <ul> <li>Don't use <code>None</code>, instead use <code>np.nan</code> (...
python|pandas
3
359,047
24,097,266
matplotlib changing barplot xtick labels and sorting the order of bars
<p>I have a dataset that i'm trying to plot, this is how I plot it:</p> <pre><code> for i in range(0,5): plt.subplot2grid((1,5),(0,i)) df.Survived[df.SibSp == i].value_counts().plot(kind='bar') title(str(i)) </code></pre> <p>the values in X (survived) are 0 or 1 and i'm plotting the value count of them....
<p>I am not sure how your data looks like, but I assume 1 means survived and 0 means dead, and there are no other values other than 0 and 1. If so, you need a few small changes:</p> <pre><code>for i in range(0,5): plt.subplot2grid((1,5),(0,i)) ax=df.Survived[df.SibSp == i].value_counts().ix[[0,1]].plot(kind='b...
python|pandas
2
359,048
24,082,784
pandas dataframe groupby datetime month
<p>Consider a csv file:</p> <pre><code>string,date,number a string,2/5/11 9:16am,1.0 a string,3/5/11 10:44pm,2.0 a string,4/22/11 12:07pm,3.0 a string,4/22/11 12:10pm,4.0 a string,4/29/11 11:59am,1.0 a string,5/2/11 1:41pm,2.0 a string,5/2/11 2:02pm,3.0 a string,5/2/11 2:56pm,4.0 a string,5/2/11 3:00pm,5.0 a string,5/...
<p>Managed to do it:</p> <pre><code>b = pd.read_csv('b.dat') b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p') b.groupby(by=[b.index.month, b.index.year]) </code></pre> <p>Or </p> <pre><code>b.groupby(pd.Grouper(freq='M')) # update for v0.21+ </code></pre>
python|pandas|datetime|pandas-groupby
242
359,049
24,334,683
how do I add error bars to a grouped bar chart with python pandas?
<p>I know there is <a href="https://stackoverflow.com/questions/23000418/adding-error-bars-to-grouped-bar-plot-in-pandas">a very related question here</a>. However, the solution there works for that example, but it is giving me an error still. </p> <p>Here is my fairly simple code:</p> <p>I am trying to add error bar...
<p>apparently there was an issue with Pandas 0.13. This was solved in 0.14. Thanks to @chrisb for confirming and sorting. </p>
python|matplotlib|pandas
0
359,050
23,990,217
scipy optimization error for logistic regression with regularization
<p>i get the following error while i try to minimize the following function using CG:</p> <pre><code>def costFunctionReg(theta, X, y, labda): import numpy as np import sigmoid as sg grad=np.zeros((28,1),dtype=float) #setting predictions m=len(y) #calculating predictions using the sigmoid func...
<p>Try <code>return J, grad.flatten()</code> rather than <code>return J, grad</code></p>
python|numpy|scipy
1
359,051
24,417,951
Access single cell of pandas dataframe?
<p>I have the following data with some missing holes. I've looked over the 'how to handle missing data' but can't find anything that applies in this situation. Here is the data:</p> <pre><code> Species GearUsed AverageFishWeight(lbs) NormalRange(lbs) Caught 0 BlackBullhead Gillnet 0....
<p>Do you want to fill the missing values in other rows as well? Seems to be what <code>fillna()</code> is for:</p> <pre><code>In [83]: print df.fillna(method='pad') Species GearUsed AverageFishWeight(lbs) NormalRange(lbs) Caught 0 BlackBullhead Gillnet 0.11 0.8-7.7 0.18 ...
python|numpy|pandas
1
359,052
24,380,635
Pandas optimization
<p>I wrote a function to process data with pandas. Profiling log using <code>%prun</code> of my function is posted at bottom (only a top few lines). I want to optimize my code because I need call this function I wrote more than 4,000 times. And it took 37.7 s to run this function once.</p> <p>It seems the most time co...
<p>The df.ix[] is a little unpredictable in that is primarily label-based but has an integer-position fallback. You should try using .loc[] instead. If you just pass a single label it will return a series of the row at that index label. You can also slice by passing a range. So instead of:</p> <pre><code>df.ix[begin_d...
python|numpy|pandas
0
359,053
23,963,997
python child process crashes on numpy dot if PySide is imported
<p>I've got this very peculiar hanging happening on my machine when using pytnon multiprocessing Pool with numpy and PySide imported. This is the most entangled bug I have seen in my life so far:) The following code:</p> <pre><code>import numpy as np import PySide def hang(): import multiprocessing pool = mu...
<p>this is a general issue with some BLAS libraries used by numpy for <code>dot</code>.</p> <p>Apple Accelerate and OpenBlas built with GNU Openmp are known to not be safe to use on both sides of a fork (the parent and the child process multiprocessing create). They will deadlock.</p> <p>This cannot be fixed by numpy...
python|numpy|multiprocessing|pyside
8
359,054
43,662,364
Conda Runtime error when installing PyTorch using anaconda
<p>When installing pytorch using anaconda I am continiously getting Conda Runtime Error </p> <pre><code>Traceback (most recent call last): File "/home/codehead/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 479, in conda_exception_handler return_value = func(*args, **kwargs) File "/home/codeh...
<pre><code>HTTPSConnectionPool(host='binstar-cio-packages-prod.s3.amazonaws.com', port=443): Read timed out. </code></pre> <p>This is an HTTP timeout, most likely due to a flakey internet connection. From the stack trace, I'm guessing you're running conda 4.2. Conda 4.3 has longer timeouts, and they're also now conf...
python|anaconda|pytorch
0
359,055
43,531,017
How to verify the actual data in Tensorflow slim dataset
<p>I have encoded my data into tfrecord files. For each image, I encode multiple bounding boxes with multiple labels with it. Now, I want to verify whether my data have been correctly decoded by the Tensorflow/slim dataset type. I write a following test:</p> <pre><code>def test2(sess): labels_to_class = read_label_f...
<p>You probably need to start queue runners for the image and label to be evaluated.</p>
tensorflow|dataset
1
359,056
43,886,157
Parse a very large CSV dataset
<p>I have a very large CSV dataset (900M records) that consists of the following format:</p> <pre><code>URL | IP | ActivityId </code></pre> <p>Example data:</p> <pre><code>http://google.com/ | 127.0.0.1 | 2 http://google.com/ | 12.3.3.1 | 2 </code></pre> <p>For this format, I wish to get all the unique activities p...
<p>I'm assuming that you have in fact already loaded the dataset into memory (let's say it's stored in a variable named <code>df</code>), and run into trouble when you tried to "get all the unique activities per URL".</p> <p>If you just want the number of unique activities per URL, use the <code>.groupby()</code> meth...
python|python-2.7|csv|pandas|scikit-learn
0
359,057
43,764,947
merge dataframe memory efficiency issue pandas
<p>I am trying to use this exact command for my code</p> <p><a href="https://stackoverflow.com/questions/17457142/merging-files-based-on-column-coordinates-of-two-files-in-python">merging files based on column coordinates of two files in python</a></p> <p>but my system would just freeze (may be because i have ~315,00...
<p>Simply use <code>new_df</code> fields. Your logic uses fields in the original <code>df</code> that was previously merged. Carefully, look at your linked question. Such logic across dataframes would be tough to run!</p> <pre><code>new_df = new_df[(new_df.start_x &gt;= new_df.start_y) &amp; (new_df.end_x &lt;= new_df...
python|pandas|optimization
1
359,058
43,485,607
Creating extra rows based on string formatting in a DataFrame
<p>I am looking to perform the following operation on a <code>DataFrame</code> efficiently. There <code>DataFrame</code> has a special column, containing strings, where some rows have a formatting problem. Naemly, in my case it has a <code>+</code> sign seperating what should be entries of two separate columns.</p> <p...
<p>One way would be to combine <code>.str.split</code> with <code>stack</code> and then <code>join</code>:</p> <pre><code>s = df[0].str.split("+", expand=True).stack() s.index = s.index.droplevel(1) result = s.to_frame().join(df.drop(0, axis=1)).reset_index(drop=True) </code></pre> <p>gives me</p> <pre><code>In [18]...
python|pandas|dataframe|string-formatting|apply
3
359,059
43,896,459
Inconsistency of control_dependencies in distributed TensorFlow
<p>I wrote a simple test code to test <code>tf.control_dependencies()</code> between two machines. I think the code always have to return the same result, but the result is not consistent.</p> <h3>Code</h3> <p>There are two hosts and each has its own variable. One of them update its variable via SGD, and when it ends...
<p>I suspect your issue is that <code>tf.Variable</code> takes cached snapshots of variables. This is an optimization that minimizes transfers in distributed training, but can have some surprising implications.</p> <p>Try using <code>tf.Variable.read_value()</code> to grab the latest copy.</p> <p>See the documentatio...
tensorflow
1
359,060
43,696,774
Pandas bitwise comparisons throws exception when using multiple conditions
<p>I am working with a large data, and I want to extract a subset. In SQL representation this is what I want to achieve. I would like to do this using pandas/numpy. </p> <pre><code>select * from Data where cpty_type = 'INTERBRANCH' and (settlementDate &gt;= '2017-04-18 00:00:00.000' or settlementDate = '1899-12-30 00...
<p>In Python, bitwise operations like <code>|</code>, <code>&amp;</code>, and <code>^</code> have higher precedence than comparison operations like <code>&lt;</code>, <code>&gt;</code>, <code>==</code>, etc. You need to use parentheses in your expressions to force the correct evaluation order.</p> <p>For example, if y...
python|pandas
4
359,061
43,744,910
Timeseries plot from CSV data (Timestamp and events): x-label constant
<p>(This question can be read alone, but is a sequel to: <a href="https://stackoverflow.com/questions/43735396/timeseries-from-csv-data-timestamp-and-events">Timeseries from CSV data (Timestamp and events)</a>)</p> <p>I would like to visualize CSV data (from 2 files) as shown below, by a timeseries representation, usi...
<p>Making the example reproducible, we can create the following text file (<code>data/timestamp01.csv</code>):</p> <pre><code>TIMESTAMP;eventid 2017-03-20 02:38:24;1 2017-03-21 05:59:41;1 2017-03-23 12:59:58;1 2017-03-24 01:00:07;1 2017-03-27 03:00:13;1 </code></pre> <p>(same for <code>data/timestamp00.csv</code>). W...
python|pandas|matplotlib|dataframe|time-series
7
359,062
43,558,145
SyntaxNet to process a large number of sentences, do GPUs increase performance?
<p>I have a large dataset of sentences (i.e., ~5.000.000) in raw text which I want to process using SyntaxNet already trained for English. That is, I just want to process the sentences using a SyntaxNet model, I don't want to train any new model. </p> <p>Setting up a processing environment with GPUs will have any effe...
<p>You still need to do a lot of tensor operations on the graph to predict something. So GPU still provides performance improvement for inference. Take a look at this <a href="https://www.nvidia.com/content/tegra/embedded-systems/pdf/jetson_tx1_whitepaper.pdf" rel="nofollow noreferrer">nvidia paper</a>, they have not t...
syntax|tensorflow|nlp|gpu
3
359,063
43,922,198
How to rotate a 3D image by a random angle in python
<p>I'm using a set of 32x32x32 grayscale images and I want to apply random rotations on the images as a part of data augmentation while training a CNN by tflearn + tensorflow. I was using the following code to do so:</p> <pre><code> # Real-time data preprocessing img_prep = ImagePreprocessing() img_prep.add...
<pre><code>def random_rotation_3d(batch, max_angle): """ Randomly rotate an image by a random angle (-max_angle, max_angle). Arguments: max_angle: `float`. The maximum rotation angle. Returns: batch of rotated 3D images """ size = batch.shape batch = np.squeeze(batch) batch_rot = n...
python|image|tensorflow|deep-learning|tflearn
11
359,064
43,563,530
Boxplot Pandas data
<p>DataFrame is as follows:</p> <pre><code> ID1 ID2 0 00:00:01.002 00:00:01.002 1 00:00:01.001 00:00:01.006 2 00:00:01.004 00:00:01.011 3 00:00:00.998 00:00:01.012 4 NaT 00:00:01.000 ... 20 NaT 00:00:00.998 </code></pre> <p>What I am t...
<p>I am not sure how this works in <code>0.14.0</code> version, because last is <code>0.19.2</code> - I recommend upgrade if possible:</p> <pre><code>#sample data np.random.seed(180) dates = pd.date_range('2017-01-01 10:11:20', periods=10, freq='T') cols = ['ID1','ID2'] df = pd.DataFrame(np.random.choice(dates, size=(...
python|pandas|dataframe|boxplot
1
359,065
43,579,465
How to go through the same dataset several times on tensorflow with queues
<p>I have a dataset. In order to train on it, I want to put it through an optimizer several times. How can I do this with a queue mechanism? Are there any standard methods of doing so?</p>
<p>A queue-based TensorFlow input pipeline typically begins with some kind of "input producer" stage, such as a <a href="https://www.tensorflow.org/api_docs/python/tf/train/string_input_producer" rel="nofollow noreferrer"><code>tf.train.string_input_producer()</code></a>, <a href="https://www.tensorflow.org/api_docs/py...
tensorflow
1
359,066
43,749,076
Numpy: Select row multiple times using different indices array
<p>Suppose I have the following array.</p> <pre><code>l = np.asarray([1,3,5,7]) Out[552]: array([1, 3, 5, 7]) </code></pre> <p>I can select the row twice using a index array <code>np.asarray([[0,1],[1,2]])</code>:</p> <pre><code>l[np.asarray([[0,1],[1,2]])] Out[553]: array([[1, 3], [3, 5]]) </code></pre> <...
<p>I think this is the closest I can get.</p> <pre><code>import numpy as np l = np.asarray([1, 3, 5, 7]) idx = [[1,3],[1,2,3]] output = np.array([np.array(l[i]) for i in idx]) print output </code></pre> <p>Result:</p> <pre><code>[array([3, 7]) array([3, 5, 7])] </code></pre>
python|arrays|numpy
1
359,067
43,730,635
ValueError: Input to `.fit()` should have rank 4. Got array with shape: (10, 20, 50, 50, 1)
<p>My model </p> <pre><code>model.add(Conv3D(nb_filters[0], kernel_dim1=nb_conv[0], kernel_dim2=nb_conv[0], kernel_dim3=nb_conv[0], input_shape=(20, 50, 50,1), activation='relu')) model.add(MaxPooling3D(pool_size=(nb_pool[0], nb_pool[0], nb_pool[0]))) model.add(Conv3D(nb_filters[1], kernel_dim1=nb_conv[0], kernel_di...
<p>For image data generator, image shape should be set with rank 4. So, I think your reshape command should be altered (my suggestion). For reshape <code>-1</code>, this actually means &quot;convert the multi-dimension into one dimension&quot;.</p>
python-3.x|numpy|image-processing|keras|conv-neural-network
0
359,068
43,706,181
summing dataframe values based on unique grouping of column in pandas
<p>i want to aggregate values from this pandas table after grouping by <code>name</code>:</p> <pre><code>name id c john a1 10 john a1 10 bob a2 20 mary a3 30 </code></pre> <p>specifically i want to sum the values of <code>c</code>, grouped by <code>name</code>, but only for instances where <code>id</c...
<p>This should work.</p> <pre><code>df.drop_duplicates(['name', 'id'], keep='first', inplace=True) df = df.groupby('name').sum().reset_index() </code></pre>
python|pandas|numpy
2
359,069
43,868,745
Convert and check array datatype
<p>For a python course I would like your help for an assignment.</p> <p>Define a function check_conversion which takes as imput two parameters: an array and a data type. The function should return a boolean value that indicate if all elements in the initial array can be losslessly converted to the specificed data type...
<p>Does this suits you ?</p> <pre><code>import numpy def check_conversion(x, d_type): xb = numpy.array(x, dtype= d_type) print x, xb if numpy.array_equal(x, xb): return d_type, True return d_type, False a = numpy.array([3., 3.2, 1]) data_type_a = "int" print(check_conversion(a, data_type_a)) ...
python|arrays|numpy|type-conversion
0
359,070
43,788,518
Indexing/matching the Date in a DataFrame (Python Pandas) conditional on another one?
<p>I've got two DataFrames (df_small and df_large) with a DatetimeIndex and a similar amount of rows. However, the timestamps (ns granularity) aren't identical and lets say df_large covers a much larger time period than df_small, however it entails df_small's timeperiod.</p> <p>How can I match the time period so I can...
<p>I like to generate an index that is the union of the two and use <code>interpolate</code> to fill in the gaps. Mind to use the <code>'index'</code> option as it will interpolate based on the index values.</p> <pre><code>uidx = df_small.index.union(df_large.index) df = pd.concat([ df_small.Price.reindex(uid...
python|pandas
1
359,071
43,924,280
Pair plot with heat maps (possibly logarithmic)?
<p>How to create a pair plot in Python like the following: <a href="https://i.stack.imgur.com/uotUg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uotUg.png" alt="enter image description here"></a> but with <em>heat maps</em> instead of points (or instead of a "hex bin" plot)? Having the possibility...
<p>The key to your answer is the matplotlib function <code>plt.hist2d</code>, which plots counts within rectangular bins using a color scale (a "heatmap"). Its API is almost compatible with <code>PairGrid</code>, but not quite, because it doesn't know how to handle a <code>color=</code> kwarg. This is easily solved by ...
python|pandas|matplotlib|seaborn
12
359,072
43,761,607
Pandas: how to read csv with multiple lines on the same cell?
<p>I have a <code>csv</code> that I am not able to read using <code>read_csv</code> Opening the <code>csv</code> with sublime text shows something like:</p> <pre><code>col1,col2,col3 text,2,3 more text,3,4 HELLO THIS IS FUN ,3,4 </code></pre> <p>As you can see, the text <code>HELLO THIS IS FUN</code> takes three lin...
<p>It looks like you'll have to preprocess the data manually:</p> <pre><code>with open('data.csv','r') as f: lines = f.read().splitlines() processed = [] cum_c = 0 buffer = '' for line in lines: buffer += line # Append the current line to a buffer c = buffer.count(',') if cum_c == 2: processed....
python|csv|pandas
1
359,073
43,756,234
How to create array in C++ similar to Python's numpy array?
<p>I am converting <code>Python program to C++</code> format.</p> <p>Python has an array in the following format.</p> <pre><code>boxes = np.zeros((1, 300, 4, 5, 1), dtype = np.float) </code></pre> <p>What could be the best way to create a <code>C++</code> array functioning similar to that <code>boxes</code> array?</...
<p>In fact, numpy allocates a contiguous array storage and the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html" rel="nofollow noreferrer">strides</a> are used to compute memory offset based on a multi-dimensional index. To achieve similar results in C++, you can write something ...
python|c++|c++11|numpy
4
359,074
1,634,555
least square solution to camera matrix [numpy]
<p>I would like to use use numpy's least square algorithm to solve for a camera matrix from 6 known 3D -> 2D point correspondence.</p> <p>I have been using this website as a reference:</p> <p><a href="http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/OWENS/LECT9/node4.html" rel="nofollow noreferrer">http://home...
<blockquote> <p>I need to get scipy installed properly</p> </blockquote> <p>Just a note for installing scipy, ubuntu distributions since 8.04 have had a broken scipy build. That has been taken care of in the latest 9.10 beta build. You could build scipy from scratch, but it isn't in general an easy thing to do. Just...
python|numpy|computer-vision
2
359,075
1,791,791
Stacking numpy recarrays without losing their recarrayness
<p>Suppose I make two recarrays with the same dtype and stack them:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; dt = [('foo', int), ('bar', float)] &gt;&gt;&gt; a = np.empty(2, dtype=dt).view(np.recarray) &gt;&gt;&gt; b = np.empty(3, dtype=dt).view(np.recarray) &gt;&gt;&gt; c = np.hstack((a,b)) </code>...
<p>Alternatively, there are some helper utilities in <a href="http://pyopengl.sourceforge.net/pydoc/numpy.lib.recfunctions.html" rel="noreferrer"><code>numpy.lib.recfunctions</code></a> which I stumbled across <a href="http://www.astropython.org/resource/2011/7/recfunctions" rel="noreferrer">here</a>. This module has f...
python|numpy|recarray
11
359,076
1,903,462
How can I "zip sort" parallel numpy arrays?
<p>If I have two parallel lists and want to sort them by the order of the elements in the first, it's very easy:</p> <pre><code>&gt;&gt;&gt; a = [2, 3, 1] &gt;&gt;&gt; b = [4, 6, 7] &gt;&gt;&gt; a, b = zip(*sorted(zip(a,b))) &gt;&gt;&gt; print a (1, 2, 3) &gt;&gt;&gt; print b (7, 4, 6) </code></pre> <p>How can I do t...
<p><code>b[a.argsort()]</code> should do the trick.</p> <p>Here's how it works. First you need to find a permutation that sorts a. <code>argsort</code> is a method that computes this:</p> <pre><code>&gt;&gt;&gt; a = numpy.array([2, 3, 1]) &gt;&gt;&gt; p = a.argsort() &gt;&gt;&gt; p [2, 0, 1] </code></pre> <p>You can...
python|sorting|numpy
104
359,077
72,984,698
Pandas merging DF on different columns
<p>Texas Hold'em exercise in Python. I have two dataframes, the first one representing hole cards that each player has in hand, and the second one representing the whole deck of cards:</p> <pre><code> HC1 HC2 Player 1 51 46 2 48 28 3 14 2 4 41 12 5 5 38 6 52 30 7 ...
<p>I believe you can join the DF's using merge like so. You'd first do the first H, then the second:</p> <p>Create table for player and HC1 (triple check on how to make a df from previous ones, I'm not 100 the syntax will work creating the HC1 and HC2 tables)</p> <pre><code>HC1 = 1stDF[['Player','HC1']] HC1 = df.renam...
python|pandas|dataframe|merge
0
359,078
73,030,388
Pandas - How to append data to a column?
<p>Likely makes sense to for loop this, but I don't know what Pandas functions to use. I want to take data from one column and append it to another in parenthesis:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> </tr>...
<p>You can use an apply function that will work for each row:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'col1': ['A', 'B'], 'col2': [1, 2]}) df.apply(lambda x: f'{x.col1} ({x.col2})', axis=1) </code></pre> <p>Or you could use a vectorized solution:</p> <pre class="lang-py prettyprint-overri...
python|pandas
1
359,079
73,078,830
Pandas creating a column comparing with different sheets
<p>My excel includes id of users in current sheet/user sheet and id and name of the users in another sheet/name. I need to compare id and add the name of users in user sheet.Just as shown in figure.</p> <p><a href="https://i.stack.imgur.com/eK22z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eK22z....
<p>assuming:</p> <p>sheet1 is 's1'</p> <p>sheet2 is 's2'</p> <p>and names of the columns are user_id,names</p> <p>you can use dictionary to do this</p> <pre><code>s1 = pd.read_excel(r'path_to_your_excel.xlsx',sheet_name='Sheet1') s2 = pd.read_excel(r'path_to_your_excel.xlsx',sheet_name='Sheet2') #creating a new column...
python|pandas|data-analysis
1
359,080
73,148,463
How to decode a .csv .gzip file containing tweets?
<p>I'm trying to do a twitter sentiment analysis and my dataset is a couple of .csv.gzip files. This is what I did to convert them to all to one dataframe.</p> <p>(I'm using google colab, if that has anything to do with the error, filename or something)</p> <pre><code>apr_files = [file[9:] for file in csv_collection if...
<p>I just switched to Jupyter Notebook, and It worked fine there. As of now, I don't know what was the issue with Google Colab though.</p>
pandas|csv|utf-8|gzip|decode
0
359,081
73,130,577
Masking dimensions outside of a window
<p>I have a Pytorch tensor <code>t</code> of shape <code>(n, x, y)</code>, and I'd like to apply a mask such that, for all <code>y &gt; x + k</code> (with <code>k</code> being a constant), <code>t[n, x, y] = -inf</code>.</p> <p>I believe I can do this with advanced indexing, but can't figure out how.</p> <p>If not, a s...
<p>Notice that the condition <code>y ≥ x</code> corresponds to the upper triangle, while <code>y &gt; x</code> is the strict upper triangle. Therefore <code>y &gt; x + k</code> is the upper triangle part with a shift equal to <code>1 + k</code>.</p> <p>You can construct a triangle mask using <a href="https://pytorch.or...
pytorch
1
359,082
72,954,566
Create a table of longitudes and latitudes and implement the cells corresponding to the coordinates within a country (python)
<p>I could use some help. I have created a two-dimensional array filled with 0 which has as dimension the longitudes and latitudes of the northern hemisphere with a resolution of 0.5°. My goal is to go through the latitudes and longitudes of this array so that when they are included in the boundaries of France, the 0 i...
<p>check out <a href="https://regionmask.readthedocs.io/en/stable/" rel="nofollow noreferrer">regionmask</a> - it's designed to integrate with <a href="https://xarray.pydata.org/" rel="nofollow noreferrer">xarray</a> (which you should also take a look at) to facilitate transitioning from gridded to polygon-based data d...
python|tabs|contains|geopandas|shapefile
0
359,083
73,126,976
Setting time frequency makes dataframe's values all null
<p>I'm trying to decompose a time series using sm.tsa.seasonal_decompose() and I got a</p> <pre><code>ValueError: You must specify a period or x must be a pandas object with a &gt;DatetimeIndex with a freq not set to None </code></pre> <p>I followed the suggestions of the answer here: <a href="https://stackoverflow.com...
<p>so your code might be a little off. Would this work</p> <pre><code>df.index = pd.to_datetime(df.index) df.set_index('timestamp', inplace=True) </code></pre> <p>Could you share and print out the results of this?</p>
python|pandas
0
359,084
73,132,557
pandas how to applied fit_transform on standard scaler on group by data
<p>There is a dataframe like this</p> <p>df</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">group</th> <th style="text-align: center;">data</th> <th style="text-align: right;">other</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="te...
<p>Use:</p> <pre><code>from sklearn.preprocessing import StandardScaler scaler = StandardScaler() def sc(row): return scaler.fit_transform(row.values.reshape(-1,1)) df.groupby('group').agg(sc) </code></pre> <p>Please, note that your other column is not numeric so you can not apply standard scaler on that. I tried ...
pandas|group-by|normalize
1
359,085
73,078,692
Importing CSV into pandas with one column that contains all column names and another containing all the values
<p>I want to import a CSV into pandas. I currently use a for loop and turn the CSV into a dictionary before turning it into a data frame.</p> <p>The data looks like this:</p> <pre><code>| row id | attr name | attr value | | ______ | _________ | __________ | | 5 | beans. | 1. | | 5. | fruit. | 2 ...
<p>Try:</p> <pre><code>df.pivot(index='row id', columns=['attr name'], values=['attr value']) </code></pre> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html</a></p>
python|pandas|dataframe|csv
2
359,086
73,046,840
Is there a faster way to assign a column to a dataframe (that has a condition) other than iloc (willing to use Dask)
<p>df2.loc[(df2['feature'] == 0), 'package_loss'] =1 <br></p> <p>My code is above. Here, I am trying changing a value to the column 'package_loss' to 1 if another column equals 0.</p>
<p>This is not as terse as @jezrael's answer, but allows more flexible transformations using <code>pandas</code> syntax:</p> <pre class="lang-py prettyprint-override"><code>from dask.datasets import timeseries def add_col(df): df = df.copy() mask = df[&quot;name&quot;] == &quot;Dan&quot; df[&quot;new_colu...
python|python-3.x|pandas|dataframe|dask
1
359,087
73,137,009
new pandas column from a parsed json dictionary column
<p>I have the following structure</p> <pre><code>col1 col2 col3 1 2 {&quot;a&quot;:{&quot;b&quot;:2, &quot;c&quot;:3}} </code></pre> <p>col3 contains parsed json as a dictionary, im trying to make a new column for c but not for the rest. applying pandas i managed to do</p> <pre><code>df[&quot;col3&quot;].transfor...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.get.html" rel="nofollow noreferrer"><code>Series.str.get</code></a>:</p> <pre><code>In [390]: df['c'] = df['col3'].str.get('a').str.get('c') In [391]: df Out[391]: col1 col2 col3 c 0 1 2 {'a': {'b': 2, 'c'...
python|json|pandas|dataframe
0
359,088
72,995,628
Python Dictionary Values into Key and Append other keys
<p>I have a python DataFrame with the following:</p> <pre><code> myDF = pd.DataFrame({&quot;COLUMN_NAME&quot;: [&quot;Col1&quot;, &quot;Col2&quot;, &quot;Col3&quot;, &quot;Col4&quot;], &quot;RULE_1&quot;: [&quot;NULL&quot;, &quot;DUPLICATE&quot;, &quot;TEXT-ONLY&quot;, &quot;INTEGER-ONLY&quot;], &quot;RULE_2&quot;: [&q...
<p>Here is a solution that works with the format you have given us</p> <pre><code>import json myDF = pd.DataFrame({&quot;COLUMN_NAME&quot;: [&quot;Col1&quot;, &quot;Col2&quot;, &quot;Col3&quot;, &quot;Col4&quot;], &quot;RULE_1&quot;: [&quot;NULL&quot;, &quot;DUPLICATE&quot;, &quot;TEXT-ONLY&quot;, &quot;INTEGER-ONLY&qu...
python|pandas|dictionary
1
359,089
73,018,335
How to calculate squared sum quickly in Tensorflow2?
<p><a href="https://i.stack.imgur.com/OJW0J.png" rel="nofollow noreferrer">I wanna calculate this with huge input data.</a></p> <p><a href="https://i.stack.imgur.com/1wfhK.png" rel="nofollow noreferrer">I did it with tensorflow. but it is calculated one by one. so it is not fast enough. I tried to make fixed_mat and in...
<p>If you want to speed up tensorflow code, you should not use the eager mode. It is best to use the <code>@tf.function</code> decorator</p> <p>See this guide: <a href="https://www.tensorflow.org/guide/function" rel="nofollow noreferrer">https://www.tensorflow.org/guide/function</a></p> <p>This code works:</p> <pre><co...
python|tensorflow|keras
0
359,090
72,847,758
python pandas data frame create columns if list of string contained in one columns
<p>given this df:</p> <pre><code>data = {'Description': ['with milk and orange', 'champagne', 'BANANA', 'bananas and apple', 'fafsa Lemons', 'GIN LEMON'], 'Amount': ['10', '20', '10', '5', '9', '15']} df = pd.DataFrame(data) print (df) </code></pre> <p>and the following vector:</p> <pre><code>Fruits = ['apple'...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>str.extractall</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer"><code>groupby.agg</co...
python|pandas|string|search|match
1
359,091
72,909,455
Pandas: Drop rows if records conflict in datetime intervals
<p>I have a pandas dataframe in which I have three datetime columns. One of them is a log date and the other two (let say start and end) are used to define a datetime interval. What I want to do is to drop records if they are conflicting in datetime interval. I would like to keep the record with newest log time and dro...
<p>Below line will get the index which has starttime is grater than logtime and drop the identified indexes.</p> <pre><code>df.drop(df[ (df['start'] &gt; df['logtime'])].index, inplace=True) </code></pre>
python|pandas|datetime
1
359,092
73,095,240
Python: Convert RGB image array to array of integers, where each specific RGB triplet equals some specific integer
<p>I have an RGB numpy array <code>img</code> where <code>img.shape</code> returns <code>(1694, 2012, 3)</code> and where each pixel (e.g. <code>img[0,0]</code>) returns something like: <code>array([ 13, 8, 135], dtype=uint8)</code>.</p> <p>For every pixel in <code>img</code>, I want to convert the RGB triplet into a...
<p>You might generate an encoded value of the tuple by multiplying the red value by 65536 (256 * 256), then adding the value of the green value by 256, and then adding the value of the blue value and store that in a variable. Following is a &quot;proof of principle&quot; program snippet how the RGB colors could be tra...
python|image-processing|numpy-ndarray
1
359,093
72,997,637
Trouble opening dataframe with OOP
<p>I am new at OOP and I am stuck. I am trying to read in an excel file from the user and output the dataframe. My code does not give any errors but it also doesn't output anything. What am I doing wrong here?</p> <pre><code>class openSheet(): def openFile(self, filepath): #read in the file filepath...
<p>this line <code>df = openSheet()</code> only creates an <code>openSheet</code> object, you need to call the <code>openFile()</code> method on that object.</p> <p>Method: (in OOP) is what we call a function that is defined within a class.</p> <pre><code>df = openSheet() returned_df = df.openFile() #since you want to ...
python|pandas|oop
1
359,094
73,154,119
How do I convert Pandas DataFrame to a Huggingface Dataset object?
<p>I have the following df:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]}) </code></pre> <p>How do I convert to a Huggingface Dataset?</p>
<p>datasets have an easy way to convert pandas dataframes to hugginface datasets:</p> <pre><code>from datasets import Dataset dataset = Dataset.from_pandas(df) Dataset({ features: ['foo'], num_rows: 2 }) </code></pre> <p>more info here: <a href="https://huggingface.co/docs/datasets/main/en/loading#...
huggingface-datasets
0
359,095
72,863,426
Output of model after serving different with keras model output
<p>I have a model with input that has a shape like (145, 24, 24, 3)</p> <p>With model load by tensorflow keras output will have a shape like (145, 4)</p> <p>But when I convert input from tensor to list and POST it into model serving.</p> <p>Output return (,4)</p> <p>I was using tensorflow-serving with docker</p> <p>My ...
<p>My mistake was I did not get all predictions in output</p> <pre><code>res = res.json()['predictions'][0] </code></pre> <p>it should be:</p> <pre><code>res = res.json()['predictions'] </code></pre> <p>, output is an array dictionary I need to concat them by the same keys I will get output as I want. <code>{'predictio...
python|docker|tensorflow|tensorflow-serving|serving
0
359,096
72,938,274
How to find duplicated rows in Pandas with a "wildcard" string value?
<p>I'm trying to find an efficient way of finding duplicated rows when a value represents a set of values:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( { &quot;ID&quot;: [&quot;one&quot;, &quot;two&quot;, &quot;two&quot;, &quot;two&quot;, &quot;one&quot;], &quot;condition1&...
<p>Here is my take on your interesting question.</p> <p>With the toy dataframe you provided, modified to take into account more use cases:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;ID&quot;: [&quot;one&quot;, &quot;two&quot;, &quot;two&quot;, &quot;o...
python|pandas|performance|duplicates
1
359,097
72,891,136
How to evaluate a formula based on different values of one colume in Python Dataframe
<p>I have a dataframe and I want to evaluate a formula such like <code>result = 2*apple - melon - orange</code> and group by testid.</p> <p>my df is like below</p> <pre><code>df = pd.DataFrame({'testid':(1,2,1,2,1,2),'Name':('apple','apple','melon','melon','orange','orange'), 'A': (1,2,10,20,5,5), 'B': (1,5,4,2,3,1)}) ...
<p>Try this (the outside brackets are part of the code, copy them too when you copy this code).</p> <pre class="lang-py prettyprint-override"><code>( df .pivot('testid', 'Name', ['A', 'B'])# reshape df into a wide multiindex df .stack(0) # remove multiindex .eval('apple*2-melon...
python|pandas|dataframe
1
359,098
72,959,002
Using a target size that is different to the input size - pytorch autoencoder
<p>I am trying to train an autoencoder using a dataset with 116,247 rows and 51 features. I suspect the issue I am experiencing is due to the format of my training data, but I'm rather new to pytorch, and am finding difficulty researching this problem. Is the issue below resolved by somehow wrapping the dataset in a Da...
<p>change data to data.view(1, -1) and criterion(outputs, features) to criterion(outputs, inputs):</p> <pre><code>for epoch in range(1): running_loss = 0.0 for i, data in enumerate(features): inputs = data.view(1, -1) optimizer.zero_grad() outputs = net(inputs) loss = criterio...
python|deep-learning|pytorch
0
359,099
73,071,904
Replace every row in dataframe with a list
<p>I have a dataframe with a column containing a list with values to replace each column, and I'm not sure how to move the list to do this. Here is an example dataframe:</p> <pre><code> A B C D 2020-07-31 0 0 0 [2,3,4] 2020-08-31 0 0 0 [5,6,7] 2020-09-30 0 0 0 [8,9,10] ...
<p>You can use:</p> <pre><code>df[:] = df.pop('D').to_list() # or specifying columns # df[['A', 'B', 'C']] = df.pop('D').tolist() print(df) # Output A B C 2020-07-31 2 3 4 2020-08-31 5 6 7 2020-09-30 8 9 10 2020-10-31 0 1 2 </code></pre>
python|pandas|dataframe|numpy
2