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
20,700
54,102,357
Python - Compare Column Value To Row Value
<p>Having a bit of a logic issue at the moment... Basically, I'm trying to compare the column values of one CSV to row values in another CSV. Here's my code thus far:</p> <pre><code>import tkinter as tk from tkinter import filedialog #import numpy as np #import matplotlib.pyplot as plt import pandas as pd root = tk....
<p>You can do the following:</p> <pre><code>## set index, easy to look up df1 = df1.set_index('Variable Name') # convert to dict df2_dict = df2.to_dict(orient='list') result = [] for k,v in df2_dict.items(): vals = df1.loc[k].tolist() for j in v: if j &lt; min(vals): result.append('mini...
python-3.x|pandas|dataframe
2
20,701
38,132,498
Longest run/island of a number in Python
<p>I have an array with 0's repeating multiple times but I want to find the longest set of 0s. For example:</p> <pre><code>myArray= [[1,0],[2,0],[3,0][4,0][5,1][6,0][7,0][8,0][9,0][10,0][11,0][12,0][13,1][14,2][15,0][16,0][17,0][18,0][19,1][20,0]] </code></pre> <p>So the Y coordinate has zeros repeating continuously ...
<p>You can start by numbering the consecutive elements in a for loop and then simply get the index of the maximum value. </p> <pre><code>&gt;&gt;&gt; cv, a = [], 0 &gt;&gt;&gt; for x in myArray: &gt;&gt;&gt; if x[1] == 0: &gt;&gt;&gt; a += 1 &gt;&gt;&gt; else: &gt;&gt;&gt; a = 0 &gt;&gt;&gt; ...
arrays|python-2.7|numpy
0
20,702
66,047,320
Remove rows in which string contains other letters than A,C,T,G,N
<p>I'm fairly new to <code>numpy</code> and <code>pandas</code>, let's say that I have a 2D numpy array and I need to delete all rows in which the second value contain only the letters <code>'A'</code>, <code>'C'</code>, <code>'T'</code>, <code>'G'</code> and <code>'N'</code></p> <pre><code>file = [['id' 'genome'], [...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> with values and <code>^</code> for start and <code>$</code> for end of string:</p> <pre><code>file = [['id', 'genome'], ['0', 'ATGTTTGTTTTT'], ['1',...
python|arrays|pandas|numpy
3
20,703
66,171,774
Given a 1-d numpy array , convert to a 2-d numpy array of desired shape appending 0
<p>I have a numpy array of : x = np.array([5, 6, 7]) I would like to convert it to a 2-D array with a given size. For example lets say the size given is 5, then my resultant array should be :</p> <pre><code>[[0 0 0 0 5] [0 0 0 0 6] [0 0 0 0 7]] </code></pre> <p>Basically i want to convert the following code of MATLAB...
<p>Assume that your source data are:</p> <pre><code>tmp = [5, 6, 7] # Source sequence colNo = 5 # How many columns should have the target array </code></pre> <p>You can get your expected result as:</p> <pre><code>result = np.pad(np.array(tmp)[:, np.newaxis], ((0, 0), (colNo - 1, 0))) </code></pre> <p><code>np.a...
python-3.x|matlab|numpy
2
20,704
66,266,472
Logging sensor data, calculating rate of change, and data analysis support in python for raspberry pi
<p><em><strong>Edited to be more straightforward.</strong></em></p> <p><a href="https://github.com/sjgittins/KilnTemperatureLogger" rel="nofollow noreferrer">https://github.com/sjgittins/KilnTemperatureLogger</a></p> <p><strong>Link to sample csv data above in github cause I don't know how to append data to this site. ...
<p>Answers to your questions are wide and open. I would like to share my perspective</p> <p><strong>Temperature control</strong></p> <p>Do you intend to use the rate of change of temperature to maintain the temperature of the pottery kiln? If so, I would recommend you to consider a PID control solution.</p> <p>If you ...
python|pandas|logging|calculation
0
20,705
52,616,617
Python mean shift clustering of complex-number numpy array
<p>I’ve inherited some code that was written about a year ago, so I guess back then it was using <a href="https://github.com/numpy/numpy/releases/tag/v1.13.3" rel="nofollow noreferrer">numpy 1.13</a> (now v1.15.2), <a href="https://github.com/scipy/scipy/releases/tag/v1.0.0rc1" rel="nofollow noreferrer">scipy 1.00rc</a...
<p>In comments/chat we have identified at least one problem which is that the numerical eigen decomposition of</p> <pre><code>(cov_w + I)^-1 @ cov_b (1) </code></pre> <p>is not real as it should but returns significant imaginary components. Here @ is matrix multiplication, cov_w and cov_b are co...
python-3.x|numpy|scikit-learn|linear-discriminant|mean-shift
0
20,706
46,282,135
ValueError: could not convert string to float: '62,6'
<p>I am trying to convert dataframe to numpy array:</p> <pre><code>dataset = myset.values X = np.array(dataset[0:,6:68], dtype="float32") X[0:5,0:] </code></pre> <p><a href="https://i.stack.imgur.com/970OB.png" rel="nofollow noreferrer">Here is a piece of the data</a></p> <p>Here is an error:</p> <pre><code>-------...
<p>Try use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>replace</code></a> <code>,</code> to <code>.</code>:</p> <pre><code>dataset = myset.replace(',','.', regex=True).values </code></pre> <p>Or use parameter <code>decimal</code> in <a href="htt...
python|pandas|numpy|valueerror
5
20,707
46,575,219
Merging two dataframes with pandas
<p>This is a subset of data frame F1:</p> <pre><code>id code s-code l.1 1 11 l.2 2 12 l.3 3 13 f.1 4 NA f.2 3 1 h.1 2 1 h.3 1 1 </code></pre> <p>I need to compare the F1.id with F2.id and then add the differences ...
<p>By using <code>reindex</code></p> <pre><code>df2.set_index('id').reindex(df1.id).fillna(0).reset_index() Out[371]: id head sweat pain 0 l.1 1.0 0.0 1.0 1 l.2 0.0 0.0 0.0 2 l.3 1.0 0.0 0.0 3 f.1 0.0 0.0 0.0 4 f.2 3.0 1.0 1.0 5 h.1 0.0 0.0 0.0 6 h.3 1.0 1....
python|pandas|dataframe|merge
4
20,708
46,464,135
Fastest way of dropping zeros from a pandas series
<p>I read in several worksheets of an excel file (> 15 MB) where each sheet has > 10000 columns. Sencondly I choose a single column (consists of only integers), drop all values == 0 from this column and write this column to a new df2. Additionally I calculate the descriptie statistics.</p> <p>Data looks like this:</p>...
<p>Data taken from <a href="https://stackoverflow.com/questions/46449689/pandas-key-error-0-while-plotting-a-seaborn-boxplot">here</a> and modified.</p> <pre><code>df Gel.Menge Erf.datum Freig. 0 0.0 26.11.2014 26.11.2014 1 10.0 06.11.2014 07.11.2014 2 5.0 19.12.2014 08.01.2015...
python|pandas|series
5
20,709
58,534,094
I want to print tensor value by lldb
<p><a href="https://i.stack.imgur.com/eW8Uz.jpg" rel="nofollow noreferrer">enter image description here</a></p> <p>I want to print Buffer member variable in buf_, in other words, I want to <code>p *(tensorflow::Buffer*)buf_</code> to print member variables in class Buffer .</p> <p>Codes in tensorflow, 1.10.1 . </p> ...
<p>we can use tensor's data() function to solve this question .</p> <p>for example <code>p (std::__1::string *)(tensor-&gt;buf_-&gt;data())</code> and why we can use data() function in lldb ?</p>
c++|tensorflow|lldb
0
20,710
58,241,785
Find and replace float numbers on numpy array
<p>I have some big numpy lists (thousands of elements) that have specific values, e.g. one of the values must be one of those: 1.0, 2.0, 3.0, 4.0, 5.0.</p> <p>I need to find and replace some of these values, and what I want is to do this with minimum computational cost. Is there a way to do it without looping on each ...
<p>You can use <code>np.select</code>:</p> <pre><code>z_ = np.select( (z_==1,z_==2, z_==3), (150, 120, 110), default=z_) </code></pre>
python|numpy|replace
0
20,711
58,414,274
numpy concatenate with axis -1 visualize with matplotlib
<p>Given 2 images, <code>axis = 0</code> and <code>axis = 1</code> in <code>np.concatenate</code> concatenate images in rows and columns, respectively. </p> <p>but <code>axis = -1</code> changes the channel of the concatenated image to <strong>6</strong> which leads to the following error while visualizing using <code...
<p>You more or less answered your own question. If you concatenate on <code>axis=-1</code> (the last axis) then you're concatenating on the RGB channel. As you say, this results in 6 channels, and images can only have 1, 3, or 4 channels.</p> <p>Try:</p> <pre><code>conc_img = np.concatenate((img_A, img_B), axis=1) </...
python|numpy|matplotlib
0
20,712
68,924,396
pandas series row-wise comparison (preserve cardinality/indices of larger series)
<p>I have two pandas series, both string dtypes.</p> <ol> <li><p>reports['corpus'] has 1287 rows</p> <p>0 point seem peaking effects drug unique compari...</p> <p>1 mother god seen much difficult withstand spent...</p> <p>2 getting weird half breakthrough feels like sec...</p> <p>3 vomited three times bucke...
<p>Convert <code>uniq_labels</code> column from the <code>labels</code> dataframe to a list, and split the <code>corpus</code> column from <code>reports</code> dataframe on white space, and take the values that are in both the lists.</p> <pre class="lang-py prettyprint-override"><code>(reports['corpus'] .str.split(' ')...
python|pandas
0
20,713
44,594,239
Python: filling in missing data in an iterative dataset
<p>I have a grid map which has grid blocks of 175*175, so the total number of grid blocks in my map is 30625. Every grid block has the information of its coordinates and the property value (x and y are the coordinates and z is the value).So when I export the property values of this map it saves the information as xyz(s...
<p>I don't know how you're going to import the data (Pandas, Numpy, etc.) so I'm not going to assume that.</p> <p>Let's assume you already have the data stored in a Numpy array called <code>data</code>.</p> <pre><code>import numpy as np data = np.array([[1, 1, 2559.26], [2, 1, 2559.36], [3, 1, 2117.882], ...]) # Set...
python|numpy|grid|interpolation
1
20,714
44,606,257
imwrite 16 bit png depth image
<p>I have the following code. I am trying to save a 16 bit depth image which I retrieve from Kinect v1 as a png file. I wrote the following code sample:</p> <pre><code>def display_depth(dev, data, timestamp): global keep_runningp cv2.imshow('Depth', frame_convert2.pretty_depth_cv(data)) depthf.write(rep...
<p>Though type of my data was like this</p> <blockquote> <p><code>&lt;type 'numpy.uint16'&gt;</code></p> </blockquote> <p>Solution , to my problem was adding this line to my code </p> <pre><code>depth.astype(np.uint16) </code></pre>
python|opencv|numpy|kinect
6
20,715
44,726,288
Right way to update the data in a table?
<p>I need add three columns in a pandas dataframe, from existing data.</p> <pre><code>df &gt;&gt; n a b 0 3 1.2 1.4 1 2 2.8 3.8 2 3 2.3 2.0 3 3 1.7 5.7 4 2 6.9 4.9 5 1 3.9 19.0 6 9 2.3 8.3 7 5 8.5 3.1 8 18 6.7 7.0 9 10 5.6 6.4 </code></pre> <p>I have done the ...
<p><strong>Fun with <code>eval</code></strong></p> <ul> <li>define tuples of temporary column names with formulas</li> <li>create a <code>\n</code> separated string of formulas to pass to <code>eval</code></li> <li>use dictionary to make formulas into column names</li> </ul> <hr> <pre><code>ftups = [('aa', '(a+b)/n'...
python|pandas|indexing
1
20,716
44,738,365
Use python to divide data into different intervals (intervals are based on another column value)
<p>For example, this is data table:</p> <pre><code>1.1 300 1.5 200 1.7 234 2.4 356 2.8 234 3.4 456 </code></pre> <p>I want to put values in the 2nd column into corresponding intervals, like first three to 1.0-2.0 interval, next two to 2.0-3.0 interval, last one to 3.0-4.0 interval...
<p>Is this what you want?</p> <pre><code>import numpy as _np def bin_data(x, y, bins=[1.,2.,3.,4.]): """ """ import warnings import numpy as np xmin=np.min(x) xmax=np.max(x) bins_number=len(bins)-1 xsm = np.mean([bins[:-1], bins[1:]], axis=0) ysm = np.zeros(bins_number) #--...
python|numpy
0
20,717
44,388,358
Python numpy matrix multiplication with one diagonal matrix
<p>I have two arrays A (4000,4000) of which only the diagonal is filled with data, and B (4000,5), filled with data. Is there a way to multiply (dot) these arrays that is faster than the numpy.dot(a,b) function?</p> <p>So far I found that <code>(A * B.T).T</code> should be faster (where A is one dimensional (4000,), f...
<p>You could simply extract the diagonal elements and then perform broadcasted elementwise multiplication.</p> <p>Thus, a replacement for <code>B*A</code> would be -</p> <pre><code>np.multiply(np.diag(B)[:,None], A) </code></pre> <p>and for <code>A.T*B</code> -</p> <pre><code>np.multiply(A.T,np.diag(B)) </code></pr...
numpy|matrix-multiplication
8
20,718
44,697,379
Why is dill much faster and more disk-efficient than pickle for numpy arrays
<p>I'm using Python 2.7 and NumPy 1.11.2, as well as the latest versions of dill ( I just did the <code>pip install dill</code>) , on Ubuntu 16.04. </p> <p>When storing a NumPy array using pickle, I find that pickle is very slow, and stores arrays at almost three times the 'necessary' size. </p> <p>For example, in t...
<p>I'm the <code>dill</code> author. <code>dill</code> is an extension of <code>pickle</code>, but it does add some alternate pickling methods for <code>numpy</code> and other objects. For example, <code>dill</code> leverages the <code>numpy</code> methods for the pickling of arrays.</p> <p>Additionally, (I believe)...
python|numpy|serialization|pickle|dill
15
20,719
60,776,660
Can you append to a data frame, while simultaneously adding in and populating a field into the appended data frame?
<p>Can you append to a data frame (say from df_A -to- df_B), while simultaneously populating a new field into the appended data frame (df_B)?</p> <p>I'm appending rows of df_A into df_B under certain situations, but I'd love to populate a field in df_B with a string that explains why the appending occurs at the time o...
<p>Make the <em>assignment</em> on the <em>filtered</em> DataFrame.</p> <pre><code>&gt;&gt;&gt; dfa Acol Bcol 0 1 1 1 1 a 2 2 2 3 3 b &gt;&gt;&gt; mask = dfa['Bcol'].apply(type) == int &gt;&gt;&gt; dfb = dfa[mask].assign(New='bbbbb') &gt;&gt;&gt; dfb Acol Bcol New 0 1 1 bbb...
python|pandas
0
20,720
60,895,473
Excel misaligns columns when appending dataframe to csv
<p>I have a program that takes a <code>URL</code> as input, and checks it against a <code>df</code> that I'm reading from csv:</p> <pre><code> Name ID Date URL 0 Faye 111 12/31/16 https://www.url1.com 1 Faye 111 3/31/17 https://www.url2.com 2 Mike 222 3/31/17 https://www.ur...
<p>Instead of trying appending <em>another</em> (1-line) dataframe as <em>another</em> chunk of CSV-file:</p> <pre><code>df.to_csv('~/file.csv', mode='a', header=False, index=False) </code></pre> <p>append it first to your dataframe </p> <pre><code>df = df.append(your_1_row_df, ignore_index=True) </code></pre> <p>a...
python|pandas|csv
0
20,721
61,113,261
Unable to use tensorflow with python 3.8
<p>I have a CPU only laptop. I'm trying to use tensorflow in python using pycharm. I installed Python 3.8 (64 bit) and installed tensorflow successfully using <code>pip</code>. However, when i try to import tensorflow into python, it gives me the attached error. I'm new to python and pycharm. I'm running WIndows 10 on ...
<p>You need to download Visual Studio 2015-2019 x86 and x64 from here: <a href="https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads" rel="nofollow noreferrer">https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads</a></p> <p>Then restart your pytho...
python|tensorflow|pycharm|python-import
0
20,722
60,909,575
Numpy.savetxt ----- > How to save an array/matrix to a csv in python numpy?
<p>I have created a sort of matrix/data-table in python from multiple arrays containing various kinds of data, which looks like this in the variable view: </p> <pre><code>phones starts mids sil 308000.0 308195.0 DH 308390.0 308410.0 AH0 308430.0 308445.0 B 308460.0 308525.0 </code></pre> <p>These...
<p>Well, do you want to save np arrays to csv with labels? that is the type of work for which pandas were created.</p> <pre><code>import numpy as np import pandas as pd data = { "phone_starts": np.array([308000.0, 308390.0, 308430.0, 308460.0]), "phone_mids": np.array([308195.0, 308410.0, 308445.0, 308525.0]) } d...
python|arrays|numpy|csv
1
20,723
71,635,617
How to add a new column rank on based on increasing value of other column in Pandas
<p>I have this dataframe with which i am trying to create a new column <strong>rank</strong> on basis of increasing values of column <strong>Opportunity</strong> with pandas</p> <pre><code>State Brand DYA Opportunity Delhi Pampers -8.58 -1.24139 Delhi Ariel 0.53 0.04800 Delhi Fusion ...
<p>You can use <code>rank</code> function:</p> <pre><code>df['Rank'] = df['Opportunity'].rank() </code></pre> <p><a href="https://i.stack.imgur.com/ZzKlN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZzKlN.png" alt="enter image description here" /></a></p>
python|pandas|dataframe|data-science
0
20,724
71,686,956
About python coding relate to Tartans
<p>This link is the <a href="https://rahollis.github.io/Projects/tartans/tartans.html" rel="nofollow noreferrer">Project requirements</a> I'm doing pattern 28</p> <p>That's my code</p> <pre><code>import matplotlib.pyplot as plt import numpy as np color_dictionary = {'K' : [16/255, 16/255, 16/255], 'R' : [200/255, 0, 0]...
<p>I have a ipython notebook that does this <a href="https://github.com/drummonds/tartan-weaver/blob/main/notes/Pillow%20Tartan%20.ipynb" rel="nofollow noreferrer">https://github.com/drummonds/tartan-weaver/blob/main/notes/Pillow%20Tartan%20.ipynb</a>. What they are asking here is about twill weaving as against a plai...
python|arrays|numpy
-1
20,725
71,465,058
How to compare every value in a Pandas dataframe to all the next values?
<p>I am learning Pandas and I am moving my python code to Pandas. I want to compare every value with the next values using a sub. So the first with the second etc.. The second with the third but not with the first because I already did that. In python I use two nested loops over a list:</p> <pre><code>sub match_values ...
<p>Yes, vector comparison as pandas is built on Numpy:</p> <pre><code>df['columnname'] &gt; 5 </code></pre> <p>This will result in a Boolean array. If you also want to return the actually part of the dataframe:</p> <pre><code>df[df['columnname'] &gt; 5] </code></pre>
python|pandas|dataframe
0
20,726
71,752,718
pd.DataFrame.to_sql(method="multi") GCP Postgres raises struct.error 'h' format requires -32768 <= number <= 32767 with user defined dtypes
<p>Posting my first question on here - please go easy!</p> <p>I am trying to write a large pandas dataframe (3,000,000 x 8) to a GCP hosted Postgres database. I am using something similar to the following to write my data.</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import Table,MetaData,Column,...
<p>With similar setup, I avoided this error with a smaller chunksize.</p>
python|pandas|postgresql|ubuntu|sqlalchemy
1
20,727
42,535,795
Implementing stack denoising autoencoder with tensorflow
<p>I was trying to implement a stack denoising autoencoder in tensorflow. Here is the code I got. It worked with one layer, but when I tried to stack it(by changing the list of parameter n_neuron). It doesn't work anymore. I was trying to debug it for a long time but still couldn't get the answer. </p> <pre><code>i...
<p>Can you try this?</p> <pre><code>n_neuron = [n_visible,500,400] #n_visible is input layer size, the numbers after are hidden size neuorn unit nunmbers </code></pre> <p>This works perfectly for me on my computer. If it does not work for you, please let us know what error you get. </p>
python|tensorflow|autoencoder
1
20,728
42,567,398
InvalidArgumentError (see above for traceback): indices[1] = 10 is not in [0, 10)
<p>I am using tensorflow 1.0 CPU on ubuntu and python 3.5.</p> <p>I adapted an example of tensorflow to work on my own dataset <a href="https://github.com/martin-gorner/tensorflow-mnist-tutorial" rel="nofollow noreferrer">https://github.com/martin-gorner/tensorflow-mnist-tutorial</a></p> <p>It works fine as long as t...
<p>I also came across the same error, and after fiddling with it for 2 days I came to realize there are 2 main reasons this error was getting thrown for my code and I mentioned them below to help anyone struggling with the same problem:</p> <ol> <li><p>The dimensions of your data and your labels being different </p></...
python|python-3.x|tensorflow
4
20,729
72,475,611
New column based on existing string column in Python
<p>My dataframe looks like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">School</th> <th style="text-align: center;">Term</th> <th style="text-align: center;">Students</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">A</td> <td style="text-alig...
<p>You can use a regex with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>str.extractall</code></a> and filling of the values depending on the number of matches:</p> <pre><code>terms = ['summer', 'spring', 'fall', 'winter'] regex = r'('+'|'.join...
python|pandas|string|numpy|data-wrangling
2
20,730
72,412,418
Removing zero values from pivot table somehow creates another problem
<p>I have an assignment from my Python class to mine a set of data consisting CO2 emissions from (almost) all the countries in the world from 1960 to 2011. One of the task i've been working on is to produce a line graph that represents the growth of CO2 production in a specific country, and i'd like to avoid inserting ...
<p>To get the output in proper year format, you must enumerate the data first.</p> <p>So: <code>data = list(enumerate(rz1, start=1960))</code></p> <p>There are to ways to go about plotting this new data, one is by converting the data into a np Array and transposing, the other is by using the zip function. They both hav...
python|pandas|dataframe|numpy|pivot-table
1
20,731
50,477,534
Tensorflow's loss function returns NAN after changing RNN to LSTM cell
<p>I am training a model to predict Time Series using an RNN model. This model is trained without any issue. Here's the original code:</p> <pre><code>tf.reset_default_graph() num_inputs = 1 num_neurons = 100 num_outputs = 1 learning_rate = 0.0001 num_train_iterations = 2000 batch_size = 1 X = tf.placeholder(tf.float...
<p>Usually the "NAN" occurs when your gradients blow up. Here is some code for tf.softmax. Have a try.</p> <pre><code>#Output Layer logit = tf.add(tf.matmul(H1,w2),b2) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logit,labels=Y) #Cost cost = (tf.reduce_mean(cross_entropy)) #Optimizer optimizer = ...
python|tensorflow
0
20,732
50,501,777
Why does TensorFlow use `None` as the default activation?
<p>In the TensorFlow Python API, the default value for the <code>activation</code> kwarg of <code>tf.layers.dense</code> is <code>None</code>, then in the documentation it says:</p> <blockquote> <p>activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activatio...
<p>I don't think there is actually an identity function or any functions. For <a href="https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/python/layers/core.py#L151-L168" rel="nofollow noreferrer">example</a>:</p> <pre><code>class Dense(base.Layer): ... def call(self, inputs): ... if self.acti...
python|tensorflow|default
3
20,733
62,779,850
How to Iterate over two different DataFrame Columns with irregular indexing and better Time complexity?
<p>Assume there are two data frames, df1 and df2 with below data.</p> <pre><code> df1: Name Subject Quarter Chinnu MSCS Summer Vineeth MBA Winter Chinnu BSC Fall df2: Name SampleName Chinnu Sample 1 Vineeth Sample 2 </code></pre> <p>I was able to c...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">panda's merge function</a></p> <pre><code>df1.merge(df2, on='Name', how='left').rename(columns={'SampleName':'NewName'}) </code></pre> <p>Returns</p> <pre><code> Name Subject New...
python-3.x|pandas
0
20,734
62,858,732
Reindex Multiindex dataframe on a specific level based on other dataframe index
<p>I have a Multiindex dataframe [id, currency] as an input. I want it to be filtered by the <code>price</code> dataframe index on the level currency. Any contribution would be appreciated.</p> <p><code>balance</code> dataframe:</p> <pre><code> balance id currency 1 JPY 2322 USD ...
<p>Access the values of the desired level and filter based on the items present in <code>price</code> dataframe:</p> <pre><code>df = balance[np.in1d(balance.index.get_level_values(1), price.index)] </code></pre>
python|pandas
0
20,735
62,721,911
How do I stack a Tensorflow Dataset tensor on the second axis after a batch operation?
<p>I have a batch of 10 images, which gives the size <code>(10, 224, 224, 3)</code>, I want to create a larger image of size <code>(2240, 224, 3)</code>.</p> <pre><code>import tensorflow as tf x = tf.random.uniform(minval=0, maxval=1, shape=(100, 224, 224, 3), dtype=tf.float32) ds = tf.data.Dataset.from_tensor_slices...
<p>You could use <code>tf.split()</code> instead and build your new image using the following code.</p> <pre><code>import tensorflow as tf x = tf.random.uniform(minval=0, maxval=1, shape=(100, 224, 224, 3), dtype=tf.float32) ds = tf.data.Dataset.from_tensor_slices(x).batch(10) ds = ds.map(lambda x: tf.concat(tf.spli...
python|tensorflow|keras
0
20,736
62,559,248
Errors related to data type and input shape when building a sequential model
<p>I'm doing a little experiment to understand how a sequential model is built.</p> <p>I have a numpy array with the shape of (10, 10, 5), call it <code>feature_0</code>. And I created my sequential model as below:</p> <pre><code>model = tf.keras.models.Sequential([ layers.Dense(units=16, input_shape=(10, 5)), ...
<p>I have resolved this by converting <code>'int64'</code> to <code>'float64'</code> as follows:</p> <pre><code>features_1 = features_0.astype('float32') model = tf.keras.models.Sequential([ layers.Dense(units=16), layers.Dense(units=8), layers.Dense(units=1) ]) model(features_1) model.summary() </code></p...
python|tensorflow|machine-learning|keras
0
20,737
62,704,671
How to convert a Unix Timestamp of a Pandas DataFrame Column with NaN Values to a Datetime
<p>I have a pandas dataframe with a Unix timestamp column and some <code>NaN</code> values, like that:</p> <pre><code>&gt;&gt; df_to_datetime 0 1.571687e+09 1 1.586099e+09 2 NaN 3 1.589994e+09 4 1.593363e+09 5 1.585852e+09 6 1.580754e+09 7 1.582201e+09 8 1.576595e+09 9 1.586874e+...
<pre><code>df_to_datetime[i] = [datetime.utcfromtimestamp(df_to_datetime[i]).astimezone(time_zone), errors='coerce'] </code></pre>
python|pandas
0
20,738
54,412,326
Joining 101 columns from a dictionary of dataframes
<p>For the love of God! I have 101 single column features and I just want to join, or merge, or concatenate them so they all have the index of the first frame. I have all the frames in a dict already! I thought that would be the hard part. Below I've done manually what I'd like to do. What I'd like to do is loop throu...
<p>I would like to add that, if you want to keep the keys of the dictionary as the column headers of the final dataframe you just need to add this in the end:</p> <p>n.columns=d.keys()</p>
python|pandas|loops|dictionary|machine-learning
0
20,739
54,596,360
Pandas Groupby Multiple Columns - Top N
<p>I've got a fun one! And I've tried to find a duplicate question but was unsuccessful...<br></p> <p>My dataframe consists of all United States and territories for years 2013-2016 with several attributes.</p> <pre><code>&gt;&gt;&gt; df.head(2) state enrollees utilizing enrol_age65 util_age65 year 1 Alabam...
<p>Well, you could do something not that pretty.</p> <p>First getting a list of unique years using <code>set()</code>:</p> <pre><code>years_list = list(set(df.year)) </code></pre> <p>Create a dummy dataframe and a function to concat that I've made in the past:</p> <pre><code>def concatenate_loop_dfs(df_temp, df_ful...
python|pandas|pandas-groupby
3
20,740
73,589,836
Reassign a pandas df field to 'both' when the record contains both values
<p>In the pandas dataframe there are 3 columns including RiderID and Type. Types can be either A or B. The data looks like:</p> <pre><code>RiderID Type AnotherCol 1 A some information 2 B some information 2 B some information 3 A some information 3 B some informa...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.transform('nunique')</code></a> and <a href="https://pandas.pydata.org/docs/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:...
python|pandas
0
20,741
73,751,946
Combine two number columns but exclude zero
<p>I have the following dataframe from a database download that I cleaned up a bit. Unfortunately some of the single numbers split into a second column (row 9) from a single one. I'm trying to merge the two columns but exclude the zero values.</p> <pre><code> city crashes crashes_1 total_crashes 1 ...
<p>You can use <code>where</code> condition:</p> <pre><code>df['total_crashes'] = df['crashes'].astype(str) + df['crashes_1'].astype(str).where(df['crashes_1'] != 0, &quot;&quot;) </code></pre>
python|pandas
1
20,742
73,742,554
How to pass `--gpus all` option to Docker with Go SDK?
<p>I have seen how to do some basic commands such as running a container, pulling images, listing images, etc from the <a href="https://docs.docker.com/engine/api/sdk/examples/" rel="nofollow noreferrer">SDK examples</a>.</p> <p>I am working on a project where I need to use the GPU from within the container.</p> <p>My ...
<p>see: <a href="https://github.com/docker/cli/blob/9ac8584acfd501c3f4da0e845e3a40ed15c85041/cli/command/container/opts.go#L594" rel="nofollow noreferrer">https://github.com/docker/cli/blob/9ac8584acfd501c3f4da0e845e3a40ed15c85041/cli/command/container/opts.go#L594</a></p> <pre><code>import &quot;github.com/docker/cli/...
docker|tensorflow|go|pytorch|nvidia
2
20,743
73,544,687
Image Array "ValueError: setting an array element with a sequence"
<p>I want to do some operation in numpy array. Actually I'm trying to zoom an image using the nearest neighbour rule. I have facing that above titled issue.</p> <pre><code>import cv2 import numpy as np from numpy import ndarray img = cv2.imread('abc.jpg') rows = img.shape[0]*2 cols = img.shape[1]*2 zoomed = np.zeros...
<p>Try:</p> <pre><code>zoomed = np.zeros((rows, cols, 3), dtype=img.dtype) </code></pre> <p>The error you're getting is happening because <code>img[int(i/2)][int(j/2)]</code> is actually three RGB values and <code>zoomed[i][j]</code> can only hold integers. Creating <code>zoomed</code> to have shape <code>(rows, cols, ...
python|arrays|numpy
0
20,744
73,540,842
Can't remove the comma from price list using df['size_sq.ft'].str.strip(",") or .replace method
<p>I'm trying to clean 'size_sq.ft' column on a Kaggle dataset (link below) which is an object type.</p> <p>I have already removed the '$' sign using df['price'].str.strip(&quot;$&quot;) which is of the same type.</p> <p>However, I can't seem to do the same for removing the comma (',') from size_sq.ft using df['size_...
<p><code>.str.strip()</code> only operates on <em>leading and trailing characters</em>, if the comma is anywhere else than in first or last position in the string, it won't work. What you are looking for is <code>.str.replace(&quot;,&quot;, &quot;&quot;)</code> which will replace any comma by an empty string.</p>
python|numpy|data-cleaning|kaggle
1
20,745
71,171,519
ColumnTransformer(s) in various parts of a pipeline do not play well
<p>I am using <code>sklearn</code> and <code>mlxtend.regressor.StackingRegressor</code> to build a stacked regression model. For example, say I want the following small pipeline:</p> <ol> <li>A Stacking Regressor with two regressors: <ul> <li>A pipeline which: <ul> <li>Performs data imputation</li> <li>1-hot encodes ca...
<p>Imo the issue has to be ascribed to <code>StackingRegressor</code>. Actually, I am not an expert on its usage and still I have not explored its source code, but I've found this <a href="https://github.com/scikit-learn/scikit-learn/issues/16473" rel="nofollow noreferrer">sklearn issue - #16473</a> which seems implyin...
python|pandas|scikit-learn|mlxtend
1
20,746
71,162,459
Why does Anaconda install pytorch cpuonly when I install cuda?
<p>I have created a Python 3.7 conda virtual environment and installed the following packages using this command:</p> <p><code>conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch</code></p> <p>They install fine, but then when I come to run my program I get the following erro...
<p>I ran into a similar problem when I tried to install Pytorch with CUDA 11.1. Although <a href="https://anaconda.org/pytorch/pytorch/files" rel="nofollow noreferrer">the anaconda</a> site explicitly lists a pre-built version of Pytorch with CUDA 11.1 is available, conda still tries to install the <code>cpu-only</code...
python|pytorch|anaconda|conda
2
20,747
71,143,792
Python Dataframe - only keep oldest records from each month
<p>I have a Pandas Dataframe with a date column. I want to only have the oldest records for each month and remove any records that came before. There will be duplicates and I want to keep them. I also need a new column with only the month and year.</p> <p>Input</p> <div class="s-table-container"> <table class="s-table"...
<p>Create column <code>month_year</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> and then compare maximal datetimes per groups by original <code>date</code> column in <a href="https://pandas.pyd...
python|pandas|dataframe|date
1
20,748
71,308,399
Loaded PyTorch model has a different result compared to saved model
<p>I have a python script that trains and then tests a CNN model. The model weights/parameters are saved after testing through the use of:</p> <pre><code>checkpoint = {'state_dict': model.state_dict(),'optimizer' :optimizer.state_dict()} torch.save(checkpoint, path + filename) </code></pre> <p>After saving I immedi...
<p>You are loading a dictionary containing the state of your model as well as the optimizer's state. According to your error stack trace, the following should solve the issue:</p> <pre><code>&gt;&gt;&gt; model_state = torch.load(filePath+filename)['state_dict'] &gt;&gt;&gt; model_load.load_state_dict(model_state, stric...
pytorch
1
20,749
52,369,545
Label last row for given ID, quarter, and order of dataset, Pandas
<p>I currently have a dataset of sales orders in which each ordernumber is divided into lots. So, there may be various rows for each <code>ordernumber</code>. Other pertinent columns are account <code>id</code> and order <code>quarter</code> (i.e., 2018Q2). For each given <code>id</code> in each given <code>quarter</co...
<p>IIUC, use <code>duplicated</code> on a sorted dataframe:</p> <pre><code>df['Last Order'] = (df['ordernumber'].isin(df.loc[~df.duplicated(['id','quarter'], keep='last'),'ordernumber']).astype(int)) </code></pre> <p>Output:</p> <pre><code> index id quarter ordernumbe...
python|pandas
2
20,750
60,657,610
Is there a way to slice a list by its prime indices?
<p>Let </p> <pre><code>a = [1, 2, ... 99, 100] # numbers 1 to 100 b = [2, 3, ... 89, 97] # prime numbers under 100 </code></pre> <p>Is there a Pythonic way to slice <code>a</code> by <code>b</code>?</p> <p>i.e.</p> <pre><code>a[b] </code></pre> <p>output would be</p> <pre><code>[3, 4, ... 90, 98] </code></pre>
<p>How about:</p> <pre class="lang-py prettyprint-override"><code>result = [a[i] for i in b] </code></pre>
python|numpy|slice|numpy-slicing
2
20,751
60,648,655
How to iterate through selected rows in pandas dataframe with conditions matching three rows?
<p>if I have a sample dataframe like this: </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; a = [100,300,200,100,700,600,400,600] &gt;&gt;&gt; i = ["2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007"] &gt;&gt;&gt; df = pd.DataFrame(a, index = i, columns = {"gdp"}) &gt;&gt;&gt; df gdp 200...
<p>I prefer non loop solution, because better performance - use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a>, subtract by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sub.html" rel...
python|pandas
4
20,752
60,684,142
Splitting np array of tuples by last value, but only if the rest of the tuple matches
<p>I have a VERY long numpy array of 3d-tuples: </p> <pre><code>array([('Session A', 'mov1', 1932), ('Session A', 'mov1', 1934), ('Session A', 'mov1', 1936), ..., ('Session B', 'mov99', 5306), ('Session B', 'mov99', 5308), ('Session B', 'mov99', 5310)], dtype=object) </code></pre> <p>Each tuple's first...
<p>You can achieve what you want by using <code>itertools</code> to group the data by the first two elements of each tuple, and then looping over those results to break up the lists when the change in value of third element exceeds delta. This can be implemented as follows:</p> <pre><code>import itertools delta = 5 d...
python|arrays|numpy|tuples
3
20,753
72,766,777
Pandas merge columns with different names
<p>I am trying to merge a spreadsheet using the merge function with pandas. I'm trying to combine the columns ID &amp; id together, TrackName &amp; name, ArtistName &amp; artists, Danceability &amp; danceability, etc. from the 2018 and 2019 spreadsheets.</p> <p>Here is the code that I tried to use when merging,</p> <pr...
<p><code>pandas.merge()</code> is a class function orientated to produce joins of Databases with <em>primary keys</em> and <em>foreign keys</em> as in SQL Style databases. See <a href="https://www.geeksforgeeks.org/difference-between-primary-key-and-foreign-key/" rel="nofollow noreferrer">Difference Between Primary and...
python|pandas|dataframe|merge
0
20,754
59,758,066
Create dataframe from text file based on certain criterias
<p>I have a text file that is around 3.3GB. I am only interested in 2 columns in this text file (out of 47). From these 2 columns, I only need rows where <code>col2=='text1'</code>. For example, consider my text file to have values such as:</p> <p>text file:</p> <pre class="lang-py prettyprint-override"><code>col1~co...
<p>Okay, So I came up with a solution. Basically it has to do with loading the data in chunks, and filtering the chunks for <code>col2=='text1'</code>. This way, I only have a chunk loaded in memory each time and my final <code>df</code> will only have the data I need.</p> <p><strong>Code:</strong></p> <pre class="la...
python-3.x|pandas|performance|dataframe
0
20,755
59,809,369
Detect index of multiple maximum in a 2D array
<p>Let's say I have a 2D array with a size of m x n elements. Now, I want to get the indices of all maximums. So the result should be something like: <code>[(m1, n1), (m2, n2)]</code> where <code>m</code> and <code>n</code> indicate the x and y coordinates of my maximums.</p> <p>With only one maximum its quite easy, b...
<p>Try this:</p> <pre><code>x,y = np.where(pixel == np.max(pixel)) </code></pre> <p>this will return x axis and y axis of all the elements with maximum values Now,for your question you can do</p> <pre><code>np.array((x,y)).T </code></pre> <p><a href="https://stackoverflow.com/questions/35091879/merge-2-arrays-vert...
python|arrays|numpy|indexing|2d
0
20,756
40,610,958
How to retrain Inception image classifier in Hadoop environment
<p>Recently I tried Google's Inception image classifier on my PC with Win10 operating system. Basically I went through on this <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/?utm_campaign=chrome_series_machinelearning_063016&amp;utm_source=gdev&amp;utm_medium=yt-desc#0" rel="nofollow nore...
<p>You will need to configure your environment for HDFS. You can also run your program in docker with docker file: <a href="https://github.com/tensorflow/ecosystem/blob/master/docker/Dockerfile.hdfs" rel="nofollow noreferrer">https://github.com/tensorflow/ecosystem/blob/master/docker/Dockerfile.hdfs</a> . You may need ...
python|hadoop|tensorflow|pyspark|hadoop-streaming
0
20,757
40,540,112
Trilateration with LMFIT Python
<p>I'm trying to perform Non-Linear Least-Squares Fitting LMFIT for Trilateration purposes: </p> <ul> <li><a href="http://cars9.uchicago.edu/software/python/lmfit/intro.html" rel="nofollow noreferrer">LMFIT</a></li> <li>beacons includes beacon position x,y,z </li> <li><code>Parameters()</code> include <code>Xinit<...
<p>When fitting a function to data with any least-squares algorithm (linear or non-linear), you need at least as many data points (<code>m</code>) on your curve as you have parameters in your model (<code>n</code>). If you have more parameters than points, your algorithm will not converge to a single solution (in fact ...
python|numpy|least-squares|trilateration|lmfit
1
20,758
37,125,130
Pandas.plot(kind = 'bar') returns line plot
<p>I'm trying to produce a bar plot using pandas plot function but it keeps returning line plot, would someone please assist me in fixing this. Also, how do I auto-label plots with player names.</p> <pre><code># Dummy Data Frame df = pd.DataFrame({'Player': ['A', 'B']*5, 'plActual' : np.random.randn(10), ...
<pre><code>players = {'A': 'Player A', 'B': 'Player B'} for player in df.Player.unique(): df.loc[df.Player == player].plot(kind='bar', title=players.get(player)) </code></pre> <p><a href="https://i.stack.imgur.com/vfIfk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vfIfk.png" alt="enter image...
python|pandas|plot
1
20,759
54,916,319
How to multiply two columns in pandas, by only non-NaN values?
<p>I am curious if it is possible to multiply two columns <code>A,B</code> by only non NAN values.</p> <p>I have the following dataframe with the expected results: </p> <pre><code> A B C Date Symbol 1/1/2017 BTC Nan 2 Nan ETH 3 Nan ...
<p>Check with <code>ffill</code></p> <pre><code>#df=df.replace('Nan',np.nan)# Nan is not NaN , replace it #df=df.apply(pd.to_numeric,1) # convert to numeric df.C=df.A*(df.B.ffill()) df Out[130]: A B C Date Symbol 1/1/2017 BTC NaN 2.0 NaN ETH 3.0 NaN 6...
python|pandas|nan|multiplication
4
20,760
49,786,670
How to plot 2 sigma variation in a semilogy plot with python
<p>I am trying to fit some sample data in a semilogy plot with curve_fit function from scipy. My best fit curve looks okay with the code I am following, but I am having trouble with the 2 sigma curves, which I want to show simultaneously along with the best fit curve and grey-filled. My code looks like the following:</...
<p>In principle, a linear fit doesn't need non-linear least-squares curve-fitting at all: linear regression should work.</p> <p>That said, to address your questions, you might find lmfit (<a href="http://lmfit.github.io/lmfit-py/" rel="nofollow noreferrer">http://lmfit.github.io/lmfit-py/</a>) useful here. It has a ...
python|numpy|matplotlib|scipy|curve-fitting
2
20,761
49,384,846
What's the best alternative to using lists as elements in a pandas dataframe?
<p>I have a dataframe with days as indexes, categories as columns, and each element is a set of items corresponding to each day.</p> <p>I read that "keeping lists in a frame, while allowed, it not efficient at all": <a href="https://github.com/pandas-dev/pandas/issues/3435#issuecomment-16870881" rel="nofollow noreferr...
<p>I guess your data looks like this</p> <p><a href="https://i.stack.imgur.com/YHWAA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHWAA.png" alt="enter image description here"></a></p> <p>If you just melt the data to each row representing single item-category in a day, you can then use it any ki...
python|pandas
1
20,762
73,180,183
Says I don't have numpy, then it says it is already installed
<p>I am having issues with the numpy library. I am trying to code a webcam using the opencv library, but I am getting this issue:</p> <pre><code>OpenCV bindings requires &quot;numpy&quot; package. Install it via command: pip install numpy Traceback (most recent call last): File &quot;/home/pi/Documents/security-c...
<p>I figured out how to solve this issue: I was getting an issue with numpy earlier and was trying to reinstall it, so I deleted the numpy folder in <code>/usr/lib/python3/dist-packages</code>, then I tried to install it again but it did not work. Then I got this issue. There are actually two numpy folders in <code>/us...
python|numpy
0
20,763
73,425,067
how to access and manipulate rows from pandas dataframe in yahoo finance api
<p>I would like to use the yahoo finance API for my website, as it has the most thorough and complete information. I am googling how to work with pandas dataframes and nothing is working to access the information in row one to be able to save this to my database and display it on my site:</p> <pre><code>ipdb&gt; yahoo_...
<p>I found that there is inner mistake in module.</p> <p>It checks if data is already downloaded - <code>if self._earnings_history:</code> - and when you run it first time then <code>self._earnings_history</code> has value <code>None</code> and this works. But when you run it second time then <code>self._earnings_histo...
python|pandas
1
20,764
35,052,865
Merging CSV data empty
<pre><code>import pandas as pd left = 'E:\out\outfile.csv' right = 'E:\in\station-info.csv' output = 'E:\out\Concatenated-Merge.csv' left_df = pd.read_csv(left) right_df = pd.read_csv(right, converters={'USAF': str, 'WBAN': str}) right_df["USAF_WBAN"] = right_df["USAF"] + "-" + right_df["WBAN"] merged_df = pd.merge(le...
<p>Try this, your code slightly modified:</p> <pre><code>import pandas as pd left = 'E:/out/outfile.csv' right = 'E:/in/station-info.csv' output = 'E:/out/Concatenated-Merge.csv' left_df = pd.read_csv(left) right_df = pd.read_csv(right, converters={'USAF': str, 'WBAN': str}) right_df["USAF_WBAN"] = right_df["USAF"] +...
python|csv|pandas
0
20,765
31,171,651
Modifying Multiple Rows based on Specific Criteria
<p>I have a csv file which looks like this:</p> <pre><code>ID Class Status Species 1 Sands D Carex 1 Sands C Eupesu 1 Sands C Poapra 2 Limy D Carcra 2 Limy C Eupesu 2 Limy ...
<pre><code>import pandas as pd df = pd.read_table('data', sep='\s+') mask = ((df['Status'] == 'D') &amp; df['Species'].isin(['Carex','Carcra'])) mask = mask.groupby(df['ID']).transform('any') df.loc[mask, 'Class'] = 'Wet' print(df) </code></pre> <p>yields</p> <pre><code> ID Class Status Species 0 1 Wet...
python|csv|pandas
3
20,766
67,228,397
Updating large dataframe using numpy where
<p>I'm have a large dataframe, over 2 million records and 9 columns wide. I need to create a column and fill this with data derived from another column. This is what I have so far. I am using a numpy &quot;where&quot; to query one column and if it finds the matching string to update another column. There are a number o...
<p>It is hard to find out what the underlaying problem is without further code or info. My best guess would be that as <strong>AlexanderS</strong> said in the comments, you are creating new column on top of the already existing columns, which needs memory. On top of that the new column contains plain strings which are ...
python|pandas|dataframe|numpy
0
20,767
67,476,765
Pandas average values for the same hour for each day
<p>The post <a href="https://stackoverflow.com/questions/50806166/pandas-dataframe-getting-average-value-for-each-monday-1-am">Pandas Dataframe, getting average value for each monday 1 Am</a> described a similar problem as what I have right now, so I borrowed their dataframe. However, mine is a little bit harder and th...
<p>You can extract the hours in a separate column and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby()</a> by it:</p> <pre><code>df['hour'] = df.time.dt.hour result_df = df.groupby(['hour']).mean() </code></pre>
python|pandas
2
20,768
67,525,440
Perform operation on index of a Pandas series that has been grouped
<p>I would like to group a Pandas series based on values and then perform an aggregating operation on the index of the series. Pandas isn't recognizing me passing ser.index.</p> <pre><code>dti = pd.date_range(&quot;2021-05-13&quot;, periods=6, freq=&quot;H&quot;) ser = pd.DataFrame({'Value': ['a', 'a', 'b', 'c', 'c', ...
<p>Convert your index to series:</p> <pre><code>&gt;&gt;&gt; df.index.to_series().groupby(df[&quot;col1&quot;]).min() col1 a 2021-05-13 00:00:00 b 2021-05-13 02:00:00 c 2021-05-13 03:00:00 dtype: datetime64[ns] </code></pre>
python|pandas
1
20,769
67,495,963
Applying a function on pandas dataframe to perform a sentiment analysis
<p>I have the function below that performs a sentiment analysis in phrase and returns a tuple <code>(sentiment, % NB classifier)</code>, like <code>(sadness, 0.78)</code></p> <p>I want to apply this function on a pandas dataframe <code>df.Message</code> to analyse it and then create 2 another columns <code>df.Sentiment...
<p>Try returning both values at the end of the function, and saving them into separate columns with an <code>apply()</code>:</p> <pre><code>def avalia(teste): testeStemming = [] stemmer = nltk.stem.RSLPStemmer() for (palavras_treinamento) in teste.split(): comStem = [p for p in palavras_treinamento....
python|pandas|dataframe
0
20,770
34,493,821
Using tuples as inputs in functions
<p>Suppose I define a function like so, where args should be a tuple that contains two elements, an example would be <code>(1,2)</code>:</p> <pre><code>def func(some_matrix,*args): return some_multiplication = some_matrix[0,first element of args] * some_matrix[0,second element of args] </code></pre> <p>How do...
<p>You could do that using list indexing or tuple indexing in this case</p> <pre><code>def acd(val, *vag): print '''Given Fixed value:\t{} Given Variable Tuple:\t{} First Var Value:\t{} Second Var value:\t{} Len of var:\t{} Len of first var element:\t{} '''.format(val, vag, vag[0][0], vag[0...
python|arrays|function|python-2.7|numpy
2
20,771
60,213,602
In Python, how can I construct a loop that allows me read a txt file (tab delimited) and store each 1000 rows as its own dataframe?
<p>Below is a sample of my data, there is ten row header, then exactly 1000 rows of data, then it repeats for 30 cycles (these are trials for a lab experiment). I have 8 of these files with the same format and I would like to extract each batch so I can then do some stuff. How do I make a loop that creates a new datafr...
<p>After this line:</p> <pre><code>mydf = pd.read_csv(i,sep='\t',header=(0),index_col=False) </code></pre> <p>you already have the tab-delimited data in single dataframe. To break it into 1000-rows each, you can try this:</p> <pre><code>sub_frames = [mydf.iloc[startrow:startrow+1000] for startrow in range(0, len(myd...
python|pandas
0
20,772
60,300,010
Error in pandas multiprocessing code - dataframe is not callable
<p>I'm trying to optimise a distance calculation over a large file using multiprocessing. I've designed the below code, but can anyone explain why it throws the error ['DataFrame' object is not callable]?</p> <p>It appears to be something to do with "map" inside parallelize_dataframe, possibly caused by how I've desig...
<p>The problem is in the last line:</p> <pre><code>test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores)) </code></pre> <p><code>test_func(...)</code> will return a dataframe and you pass that into <code>parallelize_dataframe</code>. But this function is expecting a callable.</p> <p>You want s...
python|pandas|multiprocessing
2
20,773
60,222,755
Pandas lambda function won't recognize NaN
<p>I'm trying to evaluate a new column in a DF by values from two others, but if a value is missing I try to pass another expression. </p> <pre><code>df_merge["3"] = df_merge.apply(lambda row: row["1"] + row["2"] if pd.isnull(row["1"]) or pd.isnull(row["2"]) else (row["1"] + row["2"])/2, axis=1) ...
<p>The simpliest here is use <code>mean</code> per rows, because mean by default in pandas omit <code>NaN</code>s (if not both NaNs like row <code>2</code>):</p> <pre><code>df_merge = pd.DataFrame({'1':[np.nan, np.nan, 1, 2], '2':[5, np.nan, np.nan, 4]}) df_merge["3"] = df_merge[["1",'2']].mean(axi...
python|pandas|lambda|nan
1
20,774
60,242,617
Python Installing Modules on Mac OS
<p>I am new to Python and terminal prompts/installs and I keep running into installation errors when trying to install modules like Pandas.</p> <p>I have successfully installed "pip install pandas" I am unable to install this with pip3 however.</p> <pre><code>Collecting pandas Could not find a version that satisfi...
<p>As already said in the comments, <code>pip</code> installs modules for python2. Also, you can't run <code>pandas</code> as a command on the shell.</p> <p><code>pip3 install pandas</code> works for me, on python3 (v3.7.4), which was installed directly from a Mac installer package on the <a href="https://www.python.o...
python|pandas|module|pip
0
20,775
50,156,665
Plotly x axis values not same as input
<p>I am trying to create a bar chart using the following table and code:</p> <p>tracedata1:</p> <pre><code>Berth 01E 56.0 01W 0.0 02 59.0 08 92.0 09 5.0 ...
<p><code>plotly</code> is reading your x values, seeing some of them are numbers and automatically plotting the bars as numbers. We want to override that - so tell it your axis type is <code>'category'</code>. Here's some slightly neatened code:</p> <pre><code>tracedata1 = df3.groupby('Berth', as_index=False).agg({'Da...
python|pandas|bar-chart|plotly
2
20,776
50,007,292
String capture function giving unknown error
<p>df71 equals: </p> <pre><code> PIC_1 p_lgth Wgt 420294189300189843900787520557 30 112 420951119300189843900787520618 30 64 **PARTIAL-DECODE***P / 42011721930018984390078... 53 112 4201122893001898...
<p><code>row['PIC_1']</code> is already <code>str</code>. You are trying to get an attribute <code>str</code> from an already <code>str</code> type, which is why it's complaining. </p> <p>Instead change it to <code>row['PIC_1'].find('42)</code></p> <p>In the future if you have something that is not <code>str</code>, ...
python|string|pandas|dataframe
1
20,777
50,220,748
Selecting rows according to int and string criteria
<p>I have a dataframe that looks like this:</p> <pre><code> Capital Social Mark Porte 0 12345 B 1 0 A 2 0 A 3 12345631 A </code></pre> <p>If <code>Capital Social == 0</code> and <code>Mark == A</code> I want to turn Porte into <code>Big</code>. So I'm runni...
<p>The correct form is </p> <pre><code>df.loc[(df['Capital Social'] == 0) &amp; (df['Mark'] == 'A'), 'Porte'] = 'Big' </code></pre> <p><code>df['Porte']</code> returns a view/copy, and calling <code>loc</code> will modify the copy instead, leaving the original dataFrame untouched.</p>
python|pandas
3
20,778
63,817,303
Iterate through small list n times
<p>What i have:</p> <pre class="lang-py prettyprint-override"><code> list_1 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] rounds = 5 </code></pre> <p>What i need: get elements of a small list one at a time, for <code>n</code> times; considering that the length of the list is smaller than <code>n</code>:</p> <pre...
<p>Fetch as many values as you want from <code>itertools.cycle</code> iterator:</p> <pre><code>import itertools list_1 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] rounds = 5 i = itertools.cycle(list_1) print([next(i) for _ in range(rounds)]) </code></pre> <p>gives</p> <pre><code>['a', 'b', 'c', 'a', 'b'] </code></p...
python|list|numpy|loops
3
20,779
63,819,955
How do I add a column to a dataframe using date as a filter
<p>I'm trying to add a column from a pandas dataframe to another pandas dataframe using date columns to match them up. As you can see, one dataframe has one extra date I'd like to just skip. I figured an if statement would work for this but I'm getting: <code>ValueError: Can only compare identically-labeled Series obje...
<p>For this case you want to <strong>merge</strong> the two dataframes,</p> <p>Try:</p> <pre><code>merged_df = dshares_df.merge(price3, on='Date') # To filter out the extra row merged_df = merged_df.dropna() </code></pre> <p>see the docs: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|pandas|dataframe
1
20,780
64,038,633
SciPy cdist Speed Difference
<p>I am curious as to why the following <code>cdist</code> differ so much in time even though they produce the same results:</p> <pre><code>import numpy as np from scipy.spatial.distance import cdist x = np.random.rand(10_000_000, 50) y = np.random.rand(50) result_1 = cdist(x, y[np.newaxis, :]) result_2 = cdist(x, y...
<p>The C implementation of the Euclidean distance, <a href="https://github.com/scipy/scipy/blob/v1.5.2/scipy/spatial/src/distance_impl.h#L63-L66" rel="nofollow noreferrer">source lines 50-66</a>, uses multiplication and a <code>sqrt()</code> call while the Minkowski distance, <a href="https://github.com/scipy/scipy/blo...
python|numpy|scipy|scipy-spatial
3
20,781
64,061,103
Attribute Error: folium has no attribute map
<p>The error I am getting is like below:</p> <pre><code>Traceback (most recent call last) &lt;ipython-input-37-637818dcbe0d&gt; in &lt;module&gt; ----&gt; 1 mp = folium.map(location=[151.1780,33.7961], zoom_start=10) 2 3 choropleth = folium.Choropleth( 4 geo_data=suburbs, 5 ...
<p>The error you're seeing is not related to the installation of <code>folium</code>. Names in Python are case-sensitive so <code>.map()</code> is not the same as <code>.Map()</code>. Change your code to <code> mp = folium.Map(location=[151.1780,33.7961], zoom_start=10)</code> and it'll work fine.</p>
python|pandas|folium
0
20,782
64,033,349
Group by multiple columns and calc sum of True or False
<p>I have code below that gives me number of times a professor has a value for true or false ( true being 1 ) for various columns as:</p> <p>df below as:</p> <pre><code>Name | Factory | Restaurant | Store | Building Brian True False True False Mike True True True True Brian True ...
<p>The output that you seek can be done but would take some finagling in joining the column values AND column names. Don't know if it answers your question, but I would prefer to do it like:</p> <pre><code># sample data Name Factory Restaurant Store Building Status Brian True False True False...
python|python-3.x|pandas
3
20,783
63,900,776
Unexpected result with numpy.dot
<p>I have two matrices:</p> <pre><code>&gt;&gt;&gt; a.shape (100, 3, 1) &gt;&gt;&gt; b.shape (100, 3, 3) </code></pre> <p>I'd like to perform a dot product such that my end result is (100, 3, 1). However, currently I receive:</p> <pre><code>&gt;&gt;&gt; c = np.dot(b, a) &gt;&gt;&gt; c.shape (100, 3, 100, 1) </code></pr...
<p>This is how dot works in your case:</p> <pre class="lang-py prettyprint-override"><code>dot(b, a)[i,j,k,m] = sum(b[i,j,:] * a[k,:,m]) </code></pre> <p>Your output shape is exactly how the docs specify it:</p> <pre class="lang-py prettyprint-override"><code>(b.shape[0], b.shape[1], a.shape[0], a.shape[2]) </code></pr...
python|numpy
0
20,784
46,635,770
Numpy, how to repeat an array's elements according to corresponding numbers in another array
<p>What is the best way to repeat the elements of an array according to the corresponding numbers in another array? For example, given:</p> <pre><code>import numpy as np a = np.array([100,50,200,10]) b = np.array([0.5,0.1,0.15,0.25]) </code></pre> <p>How can I have an array <code>c</code> that includes numbers from <...
<pre><code>import numpy as np a = np.array([100,50,200,10]) b = np.array([0.5,0.1,0.15,0.25]) c = np.repeat(b,a) </code></pre>
python|arrays|numpy
1
20,785
47,082,454
Reshaping and averaging matrices of training data
<p>I am trying to "normalize" the shape of my training set so that I can feed them into a Vanilla Neural Net.</p> <p>The input always has the same number of "channels"/columns representing a feature but has a varying number of rows for a given "y"</p> <p>Is there a python or numpy or other utility that can take as in...
<p>you need to call insert_row(ar, positions) where ar is the 2d array you want to insert rows in and positions is a list of positions. It returns a numpy array with inserted rows.<br> try below code:</p> <pre><code>import numpy as np ar = [ [1,1,1,1], [2,2,2,2], [1,1,1,1], [4,4,4,4] ] def insert_row(ar,positions):...
python|arrays|numpy|machine-learning
0
20,786
46,882,380
Trying to print mapped data but function is returning nothing
<pre><code>import numpy as np with open("/Users/myname/Downloads/names/yob1880.txt","r") as f: text = f.readlines() for line in text: print (line) def mapper(): for lines in line: data = line.strip().split("\t") name, sex, number = data print ("{0}\t{1}".format(name, number)) </code>...
<p>Try this:</p> <pre><code>import numpy as np import csv with open("/Users/myname/Downloads/names/yob1880.txt","r") as f: csv_file = csv.reader(f) def mapper(): for line in csv_file: name, sex, number = line print ("{0}\t{1}".format(name, number)) mapper() </code></pre> <...
python|numpy|mapreduce|mapper
1
20,787
32,691,734
Error in matplotlib csv2rec function
<p>I am using csv2rec to read csv file. Many fields in that csv file are named like "MS1-API2_C". When this field is read by csv2rec, this field name is being converted to "ms1api2_c". Now I can not access this column elements by using converted field name or original field name. Please suggest solutions.</p>
<p><code>csv2rec</code> is designed to automatically lowercase headers, but you can get around this feature by using the following approach:</p> <pre><code>import matplotlib.mlab import csv filename = 'input.csv' with open(filename, 'r') as f_input: headers = next(csv.reader(f_input)) data = matplotlib.mlab.csv...
python|csv|numpy|matplotlib|ipython
2
20,788
38,627,981
How can I turn dataframe rows into headers?
<p>I have some data on each of the first 151 pokemon in 151 different dataframes.</p> <pre><code> id identifier pokemon_id stat_id base_stat local_language_id name 36 7 Squirtle 7 1 44 9 HP 37 7 Squirtle 7 2 48 9 Attack 38 7 Squirtle 7 3 65 9 Defense 39 7 Squirtle ...
<p>I believe this will do what you're after:</p> <pre><code>df.groupby(['id', 'identifier', 'name']).base_stat.first().unstack('name') </code></pre>
python|pandas
4
20,789
38,650,273
How to Compare Values of two Dataframes in Pandas?
<p>I have two dataframes <code>df</code> and <code>df2</code> like this</p> <pre><code> id initials 0 100 J 1 200 S 2 300 Y name initials 0 John J 1 Smith S 2 Nathan N </code></pre> <p>I want to compare the values in the <code>initials</code> columns found in (<code>df</code> and <code>df2</c...
<p>How about?:</p> <pre><code>df3 = df.merge(df2,on='initials', how='outer').drop(['initials'],axis=1).dropna(subset=['id']) &gt;&gt;&gt; df3 id name 0 100.0 John 1 200.0 Smith 2 300.0 NaN </code></pre> <p>So the 'initials' column is dropped and so is anything with <code>np.nan...
python|pandas|dictionary|dataframe
4
20,790
38,621,581
Compare Across Arrays by Index in Python
<p>I'm looking to compare values of several arrays by index.</p> <p>For example, if I have</p> <pre><code>a = [1, 1, 1, 1, 1, 1] b = [2, 2, 5, 5, 5, 2] c = [3, 3, 3, 3, 3, 3] </code></pre> <p>I'd like to be able to determine that index 2 of array b is out of range of a and c.</p> <p>Even more so, I'd like it to out...
<p>Here's a vectorized way using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>np.convolve</code></a> -</p> <pre><code># Get the index of first such occurance idx = np.where(np.convolve(b&gt;(a+c),[1]*3)&gt;=3)[0][0] # Index into b and get the tuple of index an...
python|arrays|numpy|indexing
1
20,791
63,218,805
Combining dataframe column values with lists to create a new dataframe
<p>I have a file 'customers.txt' with data of what items each customer bought and has following format:</p> <pre><code>0 customer_21: item_575,item_2703,... 1 customer_11: item_454,item_158,... 2 customer_10: item_1760,item_613,... 3 customer_4: item_1545,item_1312,... 4 customer_6: item_2608,item_1062,... 5 ...
<p>I'd use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html" rel="nofollow noreferrer">sklearn.preprocessing.MultiLabelBinarizer</a> in this case:</p> <pre><code>from sklearn.preprocessing import MultiLabelBinarizer df = pd.read_csv(filenames, sep=&quot;:\s*&quo...
python|pandas|dataframe
0
20,792
67,821,830
Using 3-channel (RGB) PyTorch model for classification 4-channel (RGBY) images
<p>I have labeled dataset with 4-channel images (RGBY). I want to use pretrained classification model (using <code>pytorch</code> and ResNet50 as a model). All of <code>pytorch</code> models for 3 channels though. So, the question is: <strong>How</strong> can I use <strong>3-channel</strong> pretrained models for <stro...
<p>You can modify the first layer of the CNN such that it expects 4 input channels instead of 3. In your case, the first layer is <code>resnet50.conv1</code>. So:</p> <pre><code>import torchvision.models as models resnet50 = models.resnet50(pretrained=True) # modify first layer so it expects 4 input channels; all othe...
computer-vision|pytorch|pre-trained-model
3
20,793
67,818,531
How to convert daily data into weekly data in batches
<p>My <code>Dataframe</code> has <code>11,516,015</code> <code>rows</code>, which are <code>daily</code> data. The data of <code>ts_code</code> is duplicated and <code>ts_code</code>+<code>trade_date</code> is unique. I need to convert all the data into <code>weekly</code> data, some of the data are as follows:</p> <pr...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby()</code></a> the data by <code>ts_code</code>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferre...
python|pandas|dataframe|numpy
1
20,794
67,690,079
python using @ method to substitute a value
<p>How do I use the @ method / environment variable in python? In order to substitute @var with the value defined previously in the sentence var= ?</p> <pre><code>var= 'column1' df.groupby('@var').count().unstack().ID.plot(kind='bar'); plt.title(@var) </code></pre>
<p>You can use a dictionary like <code>vars = {'var': 'column1'}</code> and then use it like <code>df.groupby(vars['var'])</code></p>
python|pandas|variables|methods
0
20,795
67,614,619
create dataframe in pandas, why the creation leads to the clear of the zip of tuples?
<pre><code>import pandas as pd sentences=['aaa','bbb','ccc'] labels = [1,2,3] infos = zip(sentences , labels) df_synthesize = pd.DataFrame(infos, columns = ['content','label']) print(df_synthesize) print(list(infos)) </code></pre> <p>I use the <code>infos</code> to initialize the dataframe, however, after the creation,...
<p>Try this. <code>panddas</code>: <code>1.1.5</code></p> <pre><code>import pandas as pd sentences=['aaa','bbb','ccc'] labels = [1,2,3] infos = list(zip(sentences , labels)) // ^----------------------------------- clue df_synthesize = pd.DataFrame(infos, columns = ['content','label']) print(df_synthesize) </code...
python|pandas
0
20,796
61,416,639
How to convert a pd.Series to a pd.DataFrame where indices are dates and columns are time?
<p>I have pd.Series whose index are pd.DataTimeIndex. I would like to convert the 1D series to a DataFrame whose indices are the dates and columns are time of each data. Something like this:</p> <pre><code> 08:01:00 08:02:00 08:03:00 08:04:00 08:05:00 2011-04-04 2.50 2.65 2.65 2.7 ...
<p>Let us do </p> <pre><code>s.index=pd.MultiIndex.from_arrays([s.index.date,s.index.time]) df=s.unstack() df 08:01:00 08:02:00 08:03:00 08:04:00 08:05:00 2011-04-04 2.50 2.65 2.65 2.7 2.8 2011-04-05 -4.30 -4.45 -4.70 -4.6 -5.0 2011-04-06 25.75 2...
python|pandas
1
20,797
61,574,171
Correlation between 2 timeseries dataframes
<p>I'm fairly new at python, and would like to perform correlation between 2 dataframes. </p> <pre><code>df1 = pd.DataFrame({'Date':['2015-01-04','2015-01-05','2015-01-06'], 'stockprice1':['1.01','1.01','1.01',], 'stockprice2':['1.04','1.05','1.03',]}) df2 = pd.DataFrame({'Date':...
<p>Few corrections, </p> <ol> <li><p><code>stockprice1</code> has 0 variance so the correlation between itself and other variables is going to be <code>NaN</code>.</p></li> <li><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corrwith.html" rel="nofollow noreferrer"><code>corrwit...
pandas|dataframe|correlation
1
20,798
61,362,942
concat() got an unexpected keyword argument 'join_axes'
<p>I am trying to use pymc3 in an ipynb on Google Colab.</p> <p>Here is my code:</p> <pre><code>regression_conjugate = pm.Model() with regression_conjugate: sigma2 = pm.InverseGamma("sigma2",alpha = 0.5*nu0,beta=0.5*lam0) sigma = pm.math.sqrt(sigma2) a = pm.Normal("a",mu = b0[0],sd = sigma*sd0[0]) b = pm.Norm...
<p>&quot;join_axes&quot; was deprecated in version 0.25 for some reason. You can achieve the same effect by reindexing.</p> <pre><code>#won't work: df3 = pd.concat([df1, df2], axis=1,join_axes=[df1.index]) #won't work #instead: df3 = pd.concat([df1, df2], axis=1) df3 = df3.reindex(df1.index) </code></pre>
python|pandas|pymc3
5
20,799
68,755,022
TypeError: __init__() got an unexpected keyword argument 'logdir'
<p>I'm new for NLP.I encounter the issue,as follows: '''TypeError: <strong>init</strong>() got an unexpected keyword argument 'logdir'''' How can I solve this issue?</p>
<p>We could have done detailed investigation if you had provided some code. Anyways, for <code>Tensorboard</code>, hyper-parameter <code>logdir</code> and <code>log_dir</code> are used at different situation. Refer the below links for detailed understanding and use it accordingly.</p> <ol> <li><p><a href="https://tenso...
tensorflow|nlp|pytorch
0