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 |
|---|---|---|---|---|---|---|
19,200 | 34,446,767 | Stripping all trailing empty spaces in a column of a pandas dataframe | <p>I have a <strong>pandas DF</strong> that has many <strong>string elements</strong> that contains words like this:</p>
<pre><code>'Frost '
</code></pre>
<p>Which has many leading white spaces in front of it. When I compare this string to:</p>
<pre><code>'Frost'
</code></pre>
<p>I real... | <p>Alternatively you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="noreferrer"><code>str.strip</code></a> method:</p>
<pre><code>rawlossDF['damage_description'] = rawlossDF['damage_description'].str.strip()
</code></pre> | python|pandas|strip | 25 |
19,201 | 34,643,636 | python 3 and numpy array | <p>I am trying write a code to work with arrays. I have arrays for variables and I am trying to call certain numbers from those variables for a defined function. I have attached a simplified snip of what I am trying to accomplish. The code works fine when I just have the variables as a single number but when I incor... | <p>Your <code>k_frame_local_6x6</code> - which is ugly, virtually unreadable for ordinary humans, produces a 6x6 array when given 4 numbers.</p>
<p>But as best I can tell, none of the terms is designed to work with arrays:</p>
<pre><code>def k_frame_local_6x6(E, I, A, L):
temp = np.array([[A, 0, 0, -A, 0, 0],
... | python|arrays|python-3.x|numpy | 1 |
19,202 | 59,972,518 | Combining two csv in python - Update if exists in newer csv | <p>I am trying to combine two csv, namely to update the csv consisting of older data (old.csv) if a new one exists in the csv of newer data (new.csv). Both have the same number of columns (headings) and can be identified by an unique id. </p>
<p><strong>old.csv</strong></p>
<pre><code>id,description,listing,url,defau... | <p>This should work:</p>
<pre class="lang-py prettyprint-override"><code>f1 = f1.set_index('id')
f2 = f2.set_index('id')
f1.update(f2)
f1.reset_index(inplace=True)
</code></pre>
<p><strong>Output:</strong></p>
<p>f1:</p>
<pre class="lang-py prettyprint-override"><code> id description listing url ... | python|pandas|csv | 1 |
19,203 | 60,157,188 | How can I resize a PyTorch tensor with a sliding window? | <p>I have a tensor with size: <code>torch.Size([118160, 1])</code>. What I want to do is split it up into n tensors with 100 elements each, sliding by 50 elements at a time. What's the best way to achieve this with PyTorch?</p> | <p>You can use Pytorch's unfold API. Refer this <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.unfold.html" rel="noreferrer">https://pytorch.org/docs/stable/generated/torch.Tensor.unfold.html</a></p>
<p>Example:</p>
<pre><code>x = torch.arange(1., 20)
x.unfold(0,4,2)
tensor([[ 1., 2., 3., 4.],
... | python|pytorch|tensor | 6 |
19,204 | 60,015,409 | Speeding up Numba distance calculation | <p>I've been recently trying to compute distances to top 2 nearest neighbors in Python Numba as follows</p>
<pre><code>@jit(nopython=True)
def _latent_dim_kernel(data, pointers, indices, nrange, sampling_percentage = 1):
pdists_t2 = np.zeros((nrange, 2))
for a in range(nrange):
rct = 0
for b ... | <h2>Make use of pairwise distances from sklearn</h2>
<ul>
<li>Pairwise distances of sparse matrices are supported (no dense temporary array needed)</li>
<li>This algorithm uses a algebraic reformulation like <a href="https://stackoverflow.com/a/42994680/4045774">in this answer</a></li>
<li>It can be a lot faster on hi... | python|numpy|numba | 0 |
19,205 | 65,125,252 | pandas multiple awnsers in one column, How to split? | <p>I have a data frame that looks like...</p>
<p><a href="https://i.stack.imgur.com/2mUhd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2mUhd.png" alt="enter image description here" /></a></p>
<p>or</p>
<pre><code> ConvertedComp LanguageWorkedWith
0 NaN C#;HTML/CSS;JavaScript
1 NaN... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>Series.str.get_dummies</code></a> for indicator with cast to boolean and in <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">... | python-3.x|pandas|dataframe | 1 |
19,206 | 49,811,865 | i have an error in using pandasql .my table is not getting identified | <p><strong>error:</strong></p>
<blockquote>
<p>PandaSQLException: (sqlite3.OperationalError) no such table: aadhaar_data [SQL: 'select registrar,enrolment_agency from aadhaar_data limit 50;'] (Background on this error at: <a href="http://sqlalche.me/e/e3q8" rel="nofollow noreferrer">http://sqlalche.me/e/e3q8</a>)</p... | <p>This is pretty straightforward - it means the table doesn't exist in the database. I can see some inconsistencies in the way you've typed it - for instance, your code there has the table as <code>Aadhaar_data</code> while in other places you've got it as <code>aadhar_data</code> and in another place as <code>aadhaar... | python|pandas|pandasql | 0 |
19,207 | 50,217,125 | How to convert a saved_model.pb to EvalSavedModel? | <p>I was going through the <code>tensorflow-model-analysis</code> documentation evaluating TensorFlow models. The getting started guide talks about a special SavedModel called the <code>EvalSavedModel</code>.</p>
<p>Quoting the getting started guide: </p>
<blockquote>
<p>This EvalSavedModel contains additional info... | <p>If I understand your question correctly, you have <code>saved_model.pb</code> generated, either by using <code>tf.saved_model.simple_save</code> or <code>tf.saved_model.builder.SavedModelBuilder</code>or by <code>estimator.export_savedmodel</code>. </p>
<p>If my understanding is correct, then, you are exporting Tra... | tensorflow|tensorflow-model-analysis | 0 |
19,208 | 49,896,177 | How to generate random samples of Gaussian distribution directly in the frequency domain through Python: NumPy/SciPy? | <p>One can easily draw (pseudo-)random samples from a normal (Gaussian) distribution by using, say, NumPy:</p>
<pre><code>import numpy as np
mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)
</code></pre>
<p>Now, consider the Fast Fourier transform of <code>s</code>:</p>
<pre><co... | <blockquote>
<p>the Fourier transform of white noise is white noise</p>
</blockquote>
<p>This is true, but it does not mean that they are axactly the same - otherwise there would not be much point in doing the FFT. </p>
<p>If you plot <code>s</code> and the real part of <code>fft(s)</code> you will see that the tra... | numpy|scipy|gaussian|noise | 3 |
19,209 | 49,999,551 | How to aggregate data hourly, weekly and monthly in pandas | <p>I have a python pandas dataframe named 'Red' with two columns TimeStamp and Red. The index is already set to TimeStamp. Sum() is applied but it aggregated on second based. I need to aggregate on Hourly, Weekly and monthly base. Plz guide, thanks </p>
<pre><code>In [56]: Red.columns
Out[56]: Index(['TimeStamp', 'R... | <p>It looks like you should use the Series method <code>.resample()</code> once you got a TimeSeriesStamp as index.</p>
<p>Look at the documentation for more detail. <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.resample.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-... | python|pandas | 0 |
19,210 | 49,869,805 | Categorical classification in Keras Python | <p>I am doing multi-class classification of 5 classes. I am using Tensorflow with Keras. My code is like this: </p>
<pre><code># load dataset
dataframe = pandas.read_csv("Data5Class.csv", header=None)
dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,0:47].astype(float)
Y = datas... | <p>As mentioned on the <a href="https://keras.io/losses/" rel="nofollow noreferrer">Keras documentation here</a>:</p>
<blockquote>
<p>Note: when using the categorical_crossentropy loss, your targets
should be in categorical format (e.g. if you have 10 classes, the
target for each sample should be a 10-dimensiona... | python-3.x|tensorflow|scikit-learn|keras|multiclass-classification | 0 |
19,211 | 50,203,732 | Compare column names of Pandas Dataframe | <p>How to compare column names of 2 different Pandas data frame. I want to compare train and test data frames where there are some columns missing in test Data frames??</p> | <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html" rel="noreferrer"><code>pandas.Index</code></a> objects, including dataframe columns, have useful <code>set</code>-like methods, such as <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" re... | python|pandas|numpy|machine-learning|data-science | 33 |
19,212 | 63,797,486 | Generate new columns based on conditions | <p>I have the following data frame:</p>
<pre><code>Hotel_id Month_Year Chef_Id Chef_is_Masterchef Transition_cnt Review_Polarity
2400614 May-2015 2297544 0 0 0.674450
2400614 June-2015 2297544 0 0 0.894450 ... | <p>I'm sure there are other ways to do this, but first, we'll list the indexes extracted by the change flags. For that list, I'll get the indexes from three months ago and two months later, and if it's three months later, I'll fix this place. Now that we have a list of conditions to extract, we can extract the original... | python|pandas | 1 |
19,213 | 46,905,471 | lambda: what's the output that a lambda function multiply numpy array? | <p>I am learning ML with python. I read the below code from that book.</p>
<pre><code>x, y = np.array(x), np.array(y)
x = (x - x.mean()) / x.std()
x0 = np.linspace(-2, 4, 100)
def get_model(deg):
return lambda input_x=x0: np.polyval(np.polyfit(x, y, deg), input_x)
def get_cost(deg, input_x, input_y):
return... | <p>The method <code>get_model(x)</code> is, as you noticed, not return predictions, but a model for predicting.
If you execute <code>get_model(1)</code> the method will return you a linear model, which allows you to fit your values into a linear function:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as p... | python|python-3.x|numpy|lambda | 1 |
19,214 | 38,714,365 | Windows ImportError numpy.core.multiarray failed to import | <p>I write the application using modules PyQt4, cv2(v.2.4.13), numpy(v.1.11.1) and etc. I use Python (2.7.11 on win32), Windows7 (x64).</p>
<p>Before the compiling (using py2exe) on Windows my application work correctly (run from python).</p>
<p>In setup.py:</p>
<pre><code>...
options = {
'py2exe': {
... | <p>I had a similar problem for me the solution was as easy as moving the image file to the folder where the executable was created. This worked for both py2exe and pyinstaller. </p> | windows|python-2.7|opencv|numpy|setup.py | 1 |
19,215 | 63,284,142 | Is there a function in pandas to help me count each string from each row list? | <p>I have a dataframe like this:</p>
<pre><code>df1
a b c
0 1 2 [bg10, ng45, fg56]
1 4 5 [cv10, fg56]
2 7 8 [bg10, ng45, fg56]
3 7 8 [fg56, fg56]
4 7 8 [bg10]
</code></pre>
<p>I would like to count the <em><strong>total</strong></em> occurences take place of each type in column 'c'. I would then lik... | <p>I would use apply the following way:</p>
<p>first I create the df:</p>
<pre><code>df1=pd.DataFrame({"b":[2,5,8,8], "c":[['bg10', 'ng45', 'fg56'],['cv10', 'fg56'],['bg10', 'ng45', 'fg56'],['fg56', 'fg56']]})
</code></pre>
<p>next use apply to count the number of (non unique) items in a list and sa... | python|pandas | 0 |
19,216 | 67,913,811 | String to Datetime onject in DataFrame while ignore empty strings | <p>I have a column <code>date</code> in a DataFrame, it is either empty or have a string in this format
<code>'2021-06-04T15:14:30.512Z'</code>
I want to convert this to Datetime object but not sure how to handle the empty columns. I want to keep them empty or null but convert the rest.
I tried to use this to convert s... | <pre><code>import pandas as pd
</code></pre>
<p>try with <code>errors='coerce'</code> parameter in <code>to_datetime()</code> method:</p>
<pre><code>df['date']=pd.to_datetime(df['date'],errors='coerce')
</code></pre>
<p>If you want only date part:</p>
<pre><code>df['date']=pd.to_datetime(df['date'],errors='coerce').dt.... | python|pandas|dataframe|datetime | 2 |
19,217 | 67,951,421 | Some problems with numpy array | <pre class="lang-py prettyprint-override"><code>li = np.array(list("123"))
li[0] = "fff"
print(li)
</code></pre>
<p>prints <code>['f' '2' '3']</code> and not <code>['fff' '2' '3']</code>. Why so? How can I tune/fix it?</p> | <p><strong>Why so?</strong></p>
<p>Some debugging will help here. Take the first line for example:</p>
<pre><code>>>> li = np.array(list("123"))
</code></pre>
<p>Then what is <code>li</code>?</p>
<pre><code>>>> li
array(['1', '2', '3'], dtype='<U1')
</code></pre>
<p>Note the datatype of ... | python|arrays|numpy | 2 |
19,218 | 67,844,159 | OrdinalEncoder and keeping Nans | <p>I have a 2d numpy array that was created with:</p>
<pre><code>array = dataset.to_numpy()
X = array[:, 1:]
</code></pre>
<p>I want to use OrdinalEncoder, but there are some Nans in X that I want to impute. I can't run OrdinalEncoder because it doesn't like the Nans and I can't run the KNNImputer until I encode.</p>
<... | <p>Too long for a comment, but if you don't mind some copying you can simply shuffle the <code>NaN</code>s out of the array temporarily.</p>
<pre class="lang-py prettyprint-override"><code>array = dataset.to_numpy()
X = array[:, 1:]
nan_free_mask = ~np.isnan(X)
nan_free_X = X[nan_free_mask]
nan_free_encoded = Ordinal... | python|numpy|scikit-learn | 2 |
19,219 | 67,765,805 | Python not equating empty cell with "" | <p>Python noob here. I am working on a project and I am getting some strange results. I have managed to duplicate the results in a small example. I saved the following in Excel as a csv file:</p>
<pre><code>var 1,var 2
20,a
10,a
,a
5,a
4,a
0,a
1,a
21,a
</code></pre>
<p>I am trying to count how many empty pieces of data... | <p>The data is stored as a null value or <code>np.nan</code>. See the output of test dataframe when loaded:</p>
<pre><code>test = pd.read_csv("test.csv")
var 1 var 2
0 20.0 a
1 10.0 a
2 NaN a
3 5.0 a
4 4.0 a
5 0.0 a
6 1.0 a
7 21.0 a
</code></pre>
<p>When you... | python|pandas | 0 |
19,220 | 32,080,645 | Can I add y-axis labels on a horizontal barchart using pandas? | <p>I'm using the <code>pandas</code> wrapper around matplotlib to create a horizontal barchart and would like to add labels to the y-axis.</p>
<p>Sadly it doesn't seem to be as simple as just adding a <code>labels=df['Labels']</code> parameter as we can with pie charts.</p>
<pre><code>import pandas
import matplotlib.... | <p>I've figured out what the problem is. If we set the 'Label' column as the index then the y-axis is labelled automatically.</p>
<pre><code>df = pandas.DataFrame(data, columns=['Label', 'Col1', 'Col2'])
df.index = df['Label']
df.plot(kind='barh')
plt.show()
</code></pre> | python|pandas|axis-labels | 2 |
19,221 | 27,503,851 | Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy | <p>I have a XML document that contains a hierarchical, tree-like structure, see the example below.</p>
<p>The document contains several <code><Message></code> tags (I only copied one of them for convenience).</p>
<p>Each <code><Message></code> has some associated data (<code>id</code>, <code>status</code>... | <p>I finally managed to solve the problem as described above and this is how.</p>
<p>I extended the above given XML document to include two messages instead of one. This is how it looks as a valid Python string (it could also be loaded from a file of course):</p>
<pre><code>xmlDocument = '''<?xml version="1.0" enc... | python|xml|pandas|tree|hierarchical-data | 7 |
19,222 | 61,386,867 | Faster way to index pandas dataframe multiple times | <p>For every row in df_a, I am looking to find rows in df_b where the id's are the same <strong>and</strong> the df_a row's location falls within the df_b row's start and end location.</p>
<p>df_a looks like:</p>
<pre><code>|---------------------|------------------|------------------|
| Name | id ... | <p>You can do this:</p>
<p>Consider my sample dataframes below:</p>
<pre><code>In [90]: df_a = pd.DataFrame({'Name':['a','b'], 'id':[1,2], 'location':[202013, 102013]})
In [91]: df_b = pd.DataFrame({'Na... | python|pandas | 1 |
19,223 | 61,578,172 | PythonAnywhere "Could not install packages due to an EnvironmentError: [Errno 122] Disk quota exceeded " | <p>I'm trying to upload a bot to the server and encountered this error when installing numpy. Although before that I also installed it and everything worked then I changed the virtual environment and this error popped up.</p>
<p><a href="https://i.stack.imgur.com/X1ISS.png" rel="nofollow noreferrer"><img src="https://... | <p>Disabling the cache worked for me</p>
<p>first clear the cache</p>
<pre><code>pip3 cache purge
</code></pre>
<p>then install without cache</p>
<pre><code>pip3 install -r requirements.txt --no-cache-dir
</code></pre> | numpy|pythonanywhere | 0 |
19,224 | 61,441,460 | create new rows based the values of one of the column in pandas or numpy | <p>I have a data frame as shown below. which is doctors appointment data.</p>
<pre><code>B_ID No_Show Session slot_num Cumulative_no_show
1 0.4 S1 1 0.4
2 0.3 S1 2 0.7
3 0.8 S1 3 1.5
4 0.3 S1 4 ... | <p>you can do it by slightly modify the function by creating a count column where to add the later walkin rows:</p>
<pre><code>def create_u_columns (ser):
l_index = []
arr_ns = ser.to_numpy()
# array for latter insert
arr_idx = np.zeros(len(ser), dtype=int)
walkin_id = 1
for i in range(len(arr_... | pandas|numpy|loops|pandas-groupby | 1 |
19,225 | 61,549,314 | Delete rows in a dataframe by a range of dates | <p><a href="https://i.stack.imgur.com/YOMn2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOMn2.jpg" alt="enter image description here"></a>I have a dataframe with a column 'date' (YYYY-MM-DD HH:MM:SS) and datetime64 type. </p>
<p>I want to drop/eliminate rows by selecting ranges of dates. How can... | <p>(I cannot post comments, thus I dare to put an answer) The following questions also refer to deleting or filtering a data frame based on the value of a given column:</p>
<p><a href="https://stackoverflow.com/questions/13851535/delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression-involving">Delete r... | pandas|date|range|drop | 0 |
19,226 | 61,511,112 | How can I get the sum of several columns grouping by other columns? | <p>What I'm trying to do is replicate this SQL code to Python:</p>
<pre><code>select column_1, column_2, column_3,
sum(column_4) as sum_column_4, sum(column_5) as sum_column_5
from df
group by 1,2,3;
</code></pre>
<p>In other words, I need to make this data frame:</p>
<pre><code>column_1 column_2 colunn... | <p>Like @Quang mentioned in comments, you need to reset indexing: </p>
<pre><code>df.groupby(list(df.columns)[0:3]).sum().reset_index()
</code></pre>
<p>When you groupby multiple columns at once, you create a hierarchical multi-indexing and that is why you see <code>column_1</code> groups index <code>AA</code>. </p>... | python|pandas|group-by | 0 |
19,227 | 68,751,693 | what does to_datetime() do in python pandas? | <p>I have a code <code>df['date'] = pd.to_datetime(df['date'], format = '%Y-%m-%d')</code>
I didn't understand what this code does? Can somebody please explain this.</p> | <p>This code convert your column <code>date</code> from string to datetime dtype. The <code>format</code> parameter indicates to pandas how to interpret the string.</p>
<p>Example:</p>
<pre><code>>>> df
Date
0 07/10/14
1 30/03/15
2 07/12/15
3 09/12/15
4 30/01/17
>>> df.info()
<class 'p... | python|pandas | 1 |
19,228 | 68,706,042 | call another function to another pandas dataframe file | <p>I have two scripts:
file1.py and file2.py</p>
<p>file1.py</p>
<pre><code>## file1.py
from file2 import *
class df_read():
def __init__(self):
self.df1 = df1
self.df2 = df2
def df1_read(self,fileloc,sheet_NAME):
self.df1 = pd.read_excel(file_loc,sheet_name=sheet_NAME)
self.start_t... | <p>You're not instantiating your class in the second snippet:</p>
<pre><code>df_obj = df_read()
result1 = df_obj .df1_read(C:\Users\exam1.xlsx,'01') - df_obj.df2_read(C:\Users\exam1.xlsx,'02')
result2 = df_obj.df1_read(C:\Users\exam2.xlsx,'01') - df_obj.df2_read(C:\Users\exam2.xlsx,'02')
</code></pre> | python|pandas|dataframe | 0 |
19,229 | 68,701,939 | VScode failed to run pip install | <p>Environment:
Windows10,
Python 3.9.6,
VScode 1.59.0,
No Pylance and Anaconda installation,
I tried to re-installed Python and VScode several times</p>
<p>But when I type
<strong>pip install pandas</strong>
Terminal still shows
<strong>pip install pandas
^
SyntaxError: invalid syntax</strong></p>
<p>Failed to run pip... | <p>First, make sure you have the latest version of pip:</p>
<pre><code>pip install --upgrade pip
</code></pre>
<p>Next, make sure that you are using command prompt or power shell, and not the python interactive window. The reason I say this is because the error you are getting does not usually occur in a normal powersh... | python|pandas|visual-studio-code|pip|syntax-error | 2 |
19,230 | 68,483,090 | Adding level 2 index as a sum of other indexes with a condition | <p>I have a <code>df</code>:</p>
<pre><code>df = pd.DataFrame.from_dict({('group', ''): {0: 'A',
1: 'A',
2: 'A',
3: 'A',
4: 'A',
5: 'A',
6: 'A',
7: 'A',
8: 'A',
9: 'B',
10: 'B',
11: 'B',
12: 'B',
13: 'B',
14: 'B',
15: 'B',
16: 'B',
17: 'B',
18: 'all',
19: 'all'},
('category', ''):... | <h3 id="solution-x5d2">Solution</h3>
<ul>
<li>Drop <code>all</code> in <code>level=0</code>, similarly <code>drop</code> the other unwanted level values in <code>level=1</code></li>
<li>Calculate the <code>sum</code> on <code>level=0</code> to aggregate the frame</li>
<li>Create <code>Multindex</code> to add the additi... | python|pandas|indexing | 4 |
19,231 | 36,508,860 | How do I actually execute a saved TensorFlow model? | <p>Tensorflow newbie here. I'm trying to build an RNN. My input data is a set of vector instances of size <code>instance_size</code> representing the (x,y) positions of a set of particles at each time step. (Since the instances already have semantic content, they do not require an embedding.) The goal is to learn to pr... | <p>You have to create a new graph that has the same structure but with the <code>batch_size = 1</code> and import the saved variables with <code>tf.train.Saver.restore()</code>. You can take a look at how they define multiple models with variable batch size in ptb_word_lm.py: <a href="https://tensorflow.googlesource.co... | neural-network|tensorflow|deep-learning|lstm|recurrent-neural-network | 2 |
19,232 | 52,993,397 | What is the default activation function of cudnnlstm in tensorflow | <p>What's the default activation function of <code>cudnnlstm</code> in TensorFlow? How can I set an activation function such as <code>relu</code>? Maybe it's just linear model? I read the document, but I did not find it.</p>
<p>For example, the code is below:</p>
<pre><code>lstmcell=tf.contrib.cudnn_rnn.CudnnLSTM(1,e... | <p>To answer OP's 2nd question which was edited in later, there is <a href="https://github.com/tensorflow/tensorflow/issues/24375#issuecomment-452122121" rel="nofollow noreferrer">currently no way to set a custom activation function for CudnnLSTM and CudnnGRU</a>.</p> | tensorflow|deep-learning|lstm | 1 |
19,233 | 53,166,786 | Pandas: Filter a data-frame, and assign values to top n number of rows | <pre><code>import pandas as pd
df = pd.DataFrame({'col1':[1,2,3,4,2,5,6,7,1,8,9,2], 'city':[1,2,3,4,2,5,6,7,1,8,9,2]})
# The following code, creates a boolean filter,
filter = df.city==2
# Assigns True to all rows where filter is True
df.loc[filter,'selected']= True
</code></pre>
<p>What I need, is a change in the... | <p>I believe you need filter by values defined in list first with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> and then for top 2 values use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.Group... | python|pandas | 2 |
19,234 | 53,318,939 | Creating smaller dataframes from a larger dataframe using multiple filter criteria: using python and pandas | <p>Good morning,</p>
<p>Basically I have 2 pandas dataframes from CSVs:</p>
<p><strong>Dataframe 1</strong>: each row is a group where the row index is a geographical area code, and the columns are the top 5 most similar areas. e.g:</p>
<pre><code> 0 1 2 3 4 5
Rank ... | <p>Going by the linked duplicate question this is what you should use (sketchy):</p>
<pre><code>for _, row in df1.iterrows():
broken_down = df2[df2['region'].isin(row)]
</code></pre> | python|pandas|dataframe | 1 |
19,235 | 65,680,301 | If a certain value appears at least once in a row, change the last value of the row in pandas | <p>I have a dataframe where there are multiple rows containing a certain value I want to find, but I want to change the last value of the row if the value appears at least once to something else. The first column of my dataframe is the ID number, followed by 10 rows containing data where the value I want to find could ... | <p>You describe two separate items</p>
<ol>
<li>add a row that contains 0 or 1 if column contains value you are searching for</li>
<li>replace last instance of search value in a row</li>
</ol>
<pre><code>import numpy as np
# synthesize data noted in question
search = "magic"
last = "hit"
df = pd.Dat... | python|pandas | 0 |
19,236 | 65,727,795 | Merging two df without any key | <p>I have two df and want to merge them because I need one df for dashboard. My problem is that my data has no unique key and all the data points are repeating. For example I have df1 like this:</p>
<pre><code>Web Obj
A ObJA
A ObjB
B ObjA
B ObjD
B ObjA
</code></pre>
<p>df2<... | <p>You could create a <code>key</code> column and do the <code>merge</code> that way:</p>
<pre><code>df2 = (df2.assign(key=df2['Web'] + (df2.groupby('Web').cumcount() + 1).astype(str))
.merge(df1.assign(key=df1['Web'] + (df1.groupby('Web').cumcount() + 1).astype(str))
.drop('Web', axis=1),
... | python|pandas|merge|key | 1 |
19,237 | 65,570,432 | Obtaining \r\n\r\n while scraping from web in Python | <p>I am workin on scraping text using Python from the link; <a href="https://www.hubertiming.com/results/2017GPTR10K" rel="nofollow noreferrer">tournament link</a></p>
<p>Here is my code to get the tabular data;</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
... | <p>Seems like some cells in the HTML code has a lot of leading and trailing spaces and new lines:</p>
<pre class="lang-html prettyprint-override"><code><td>
JARED WILSON
</td>
</code></pre>
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html?highlight=str#st... | python|pandas|web-scraping | 1 |
19,238 | 21,293,536 | List of pandas options for method set_option | <p>I couldn't find a list of options for <code>pandas.set_option()</code>. </p>
<p>Does anyone know if such a list exists?</p>
<p>The best I could find is this page : <a href="http://pandas.pydata.org/pandas-docs/dev/whatsnew.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/whatsnew.html</a></p> | <p>Call <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#working-with-package-options"><code>describe_option</code></a> the link here also shows other ways of using this function:</p>
<pre><code>In [37]:
pd.describe_option()
display.chop_threshold: [default: None] [currently: None]
: float or None
... | python|pandas | 7 |
19,239 | 63,445,182 | How to compare two columns using pandas? | <p>BACKGROUND:
I have two columns: 'address' and 'raw_data'. The dataset looks like this:
<a href="https://i.stack.imgur.com/GquSr.png" rel="nofollow noreferrer">this is just a sample I made up, the original dataset is over 6m rows and in a different language</a></p>
<p>Problem:
I need to find all the data where the 'a... | <pre><code>df = pd.DataFrame([[2, 2], [3, 6],[1,1]], columns = ["col1", "col2"])
comparison_column = np.where(df["col1"] == df["col2"], True, False)
df["equal"] = comparison_column
col1 col2 equal
2 2 True
3 6 False
1 1 True
</code></pre> | python|pandas | 3 |
19,240 | 63,629,498 | trying to covert json to csv ,index_col error | <p>trying to import a json file to csv
but its showing error</p>
<pre><code>import pandas as pd
eros=pd.read_json('E:\\gautam bhaiya\\pandas\\netflix_data (13).json',index_col=0)
eros.to_csv("new.csv")
</code></pre>
<p>TypeError: read_json() got an unexpected keyword argument 'index_col'</p> | <p>Pandas <code>read_json</code> does not have an <code>index_col</code> argument: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html</a></p>
<p>If you want to set the index... | python|json|python-3.x|pandas|csv | 1 |
19,241 | 21,869,371 | Pandas DataFrame Index by Month? | <p>Not sure if this is possible using pandas. However I would like to make a DataFrame as follows.<br>
Except I only want to have months and days in the index without years.</p>
<pre><code>import pandas as pd
import numpy as np
df2 = pd.DataFrame(np.random.randn(12, 4), index=pd.date_range('1-1', periods=12, freq='M... | <p>one possible solution would be to write a small class:</p>
<pre><code>class Month:
__slots__ = ['month', 'year']
def __init__( self, date ):
self.month, self.year = date.month, date.year
def __repr__( self ):
return '{}-{:0>2}'.format( self.year, self.month )
def __lt__( self, o... | python|pandas | 0 |
19,242 | 24,764,779 | Splitting members of a series in a pandas dataframe | <p>I felt like I found the answer to this before, but looking back I haven't been able to find anything.</p>
<p>Is there a quick, painless way to split strings in a specific series in a dataframe?</p>
<p>For example, the series <code>df['a']</code> looks like this:</p>
<pre><code>df['a'] = ['abc 123', 'bcd 2344456jl... | <p>You were very close, you simply need an extra <code>str</code> in there:</p>
<pre><code>>>> df = pd.DataFrame({"a": ['abc 123', 'bcd 2344456jlkj6', 'dfe 456jklj34534', 'akg bg23534535']})
>>> df["a"].str.split().str[0]
0 abc
1 bcd
2 dfe
3 akg
Name: a, dtype: object
</code></pre> | python|python-2.7|pandas | 2 |
19,243 | 29,901,993 | subtract current time from pandas date column | <p>I have a pandas data frame like </p>
<pre><code>x = pd.DataFrame(['05/06/2015 00:00', '22/06/2015 00:00', None], columns=['myDate'])
</code></pre>
<p>I want to find out the number of days between the dates in the <code>myDate</code> column and the current date. How can I do this? I tried the below without much suc... | <p>the following works for me:</p>
<pre><code>In [9]:
df = pd.DataFrame(['05/06/2015 00:00', '22/06/2015 00:00', None], columns=['myDate'])
df['myDate']= pd.to_datetime(df['myDate'], errors='coerce')
df
Out[9]:
myDate
0 2015-05-06
1 2015-06-22
2 NaT
In [10]:
df['diff'] = df['myDate'] - pd.Timestamp.now()... | python|pandas | 15 |
19,244 | 30,065,437 | Floating point math in python / numpy not reproducible across machines | <p>Comparing the results of a floating point computation across a couple of different machines, they are consistently producing different results. Here is a stripped down example that reproduces the behavior:</p>
<pre><code>import numpy as np
from numpy.random import randn as rand
M = 1024
N = 2048
np.random.seed(0)
... | <p>Floating point calculations are not always reproducible.</p>
<p>You <em>may</em> get reproducible results for floating calculations across different machines if you use the same executable image, inputs, libraries built with the same compiler and identical compiler settings (switches).</p>
<p>However if you use a ... | python|numpy|floating-point|blas | 5 |
19,245 | 53,366,175 | Compare columns of two dataframes and filter dataframe based on the condition | <p>The two dataframes are as shown</p>
<p><code>Name Score
John 0.27
Peter 0.34
David 0.89
Sarah 0.67
Tom 0.93</code></p>
<p><code>Name minScore
John 0.50
Peter 0.20
David 0.90
Sarah 0.50
Tom 0.90</code></p>
<p>I want to compare the column(Score) of first dataframe with column(minScore) of the sec... | <p>You need to join dataframes on field <em>Name</em></p>
<pre><code>df = dataframe1.merge(dataframe2, on='Name')
</code></pre>
<p>and filter result:</p>
<pre><code>df[df.Score > df.minScore]
</code></pre> | python|pandas|dataframe | 0 |
19,246 | 53,726,805 | Pandas: How to make bar vertical in style? | <p>In Excel, in the cell it only allows to make horizontal data bar by the value given in that cell. So I thought that Pandas would be more flexible, but couldn't find parameters to do so. Is it, how, possible to do vertical bar b) instead of horizontal bar a)? Data arangement has to stay fixed, so transposing data is ... | <p>I don't think there is an option but one could patch the CSS after it is generated by replacing: </p>
<pre><code>background: linear-gradient(90deg,
</code></pre>
<p>With:</p>
<pre><code>background: linear-gradient(0deg,
</code></pre>
<p>And then one would have to adjust the table cells so that they are tall rat... | python|pandas|dataframe | 0 |
19,247 | 20,269,726 | string to numeric array | <p>From one program I generate bunch of data and it is stored in a file. An example of the file's contents is</p>
<pre><code>[[1, 2, 3], [4, 5, 6]]
</code></pre>
<p>As you can see, the data has the exact form of an array. Later in another program I want to read the data and use it. I am using</p>
<pre><code>text_fil... | <p>You can use <a href="http://docs.python.org/2/library/ast.html#ast.literal_eval" rel="noreferrer"><code>ast.literal_eval</code></a>:</p>
<pre><code>>>> from ast import literal_eval
>>> mystr = '[[1, 2, 3], [4, 5, 6]]'
>>> x = literal_eval(mystr)
>>> x
[[1, 2, 3], [4, 5, 6]]
>&... | python|arrays|string|numpy|eval | 5 |
19,248 | 20,107,958 | Resample pandas dataframe only knowing result measurement count | <p>I have a dataframe which looks like this:</p>
<pre><code>Trial Measurement Data
0 0 12
1 4
2 12
1 0 12
1 12
2 0 12
1 12
2 N... | <p>Well, it's not the prettiest I've ever seen, but from a frame looking like</p>
<pre><code>>>> df
Trial Measurement Data
0 0 0 12
1 0 1 4
2 0 2 12
3 1 0 12
4 1 1 12
5 2 0 12
6 2 ... | python|pandas|time-series|resampling|multi-index | 1 |
19,249 | 71,814,281 | Compare two dataframe in pandas and edit results | <p>I have two dataframe, df1 and df2,, df1 contains correct data that will be used to match data in df2</p>
<p>I want to find latitudes and longitudes in df2 that don't match the City name in df1.</p>
<p>Also I want to find cities in df2 that are "located" in the wrong country</p>
<p><a href="https://docs.goo... | <p>First add <code>lat</code> and <code>lng</code> columns to <code>df2</code></p>
<pre class="lang-py prettyprint-override"><code>df2[['lat', 'lng']] = df2['location'].str.split(', ', expand=True)
df2[['lat', 'lng']] = df2[['lat', 'lng']].astype(float)
</code></pre>
<p>Then merge <code>df1</code> to <code>df2</code> b... | python|pandas|dataframe | 0 |
19,250 | 16,971,803 | Serialization of a pandas DataFrame | <p>Is there a fast way to do serialization of a DataFrame?</p>
<p>I have a grid system which can run pandas analysis in parallel. In the end, I want to collect all the results (as a DataFrame) from each grid job and aggregate them into a giant DataFrame.</p>
<p>How can I save data frame in a binary format that can be... | <p>The easiest way is just to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_pickle.html" rel="nofollow noreferrer">to_pickle</a> (as a <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow noreferrer">pickle</a>), see <a href="https://pandas.pydata.org/pandas-docs/stable/... | python|pandas | 27 |
19,251 | 22,407,027 | Concatenating numpy arrays vertically and horizontally | <p>I have a numpy multidimensional array array with the following format:</p>
<pre><code>a = [[1,2],
[8,9]]
</code></pre>
<p>Then I want to add a list with 3 values (e.g. <code>[4,5,6]</code> at the end horizontally and vertically with the following result:</p>
<pre><code>a = [[1,2,4],
[8,9,5],
[4,5... | <p>Here is a way using <code>hstack</code> and <code>vstack</code>:</p>
<pre><code>>>> a = [[1,2],
... [8,9]]
>>> x = np.array([4, 5, 6])
>>> b = np.vstack((a, x[:-1]))
>>> print np.hstack((b, x[:, None]))
[[1 2 4]
[8 9 5]
[4 5 6]]
</code></pre>
<p>You can combine this in... | arrays|python-2.7|numpy|concatenation | 4 |
19,252 | 22,418,363 | do i want rolling_apply? | <p>I have a data frame that has a number of subjects completing a number of trials (1:800) and I want to add a "block" column... There are 80 trials per block. I feel like rolling_apply could be the solution, but I can't seem to make it work.</p>
<p>I could do some sort of thing were every value of "trial" between t... | <p>I'd use groupby's <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#enumerate-group-items" rel="nofollow">cumcount</a>:</p>
<pre><code>In [11]: g = df.groupby(['SID', 'Trial'])
In [12]: g.cumcount()
Out[12]:
0 0
1 0
2 0
3 1
4 1
5 1
6 0
7 0
8 0
9 1
10 1
11... | python|pandas | 1 |
19,253 | 22,087,044 | Any solution for accelerating the reading of data from disk and converting them into numpy array for further processing? | <p>Is there any solution for accelerating the reading of raster data from disk and converting them into numpy array for further processing? I have been really tired since the following code takes number of days to reading (and converting into numpy array) the thousands of files.</p>
<pre><code>import glob, gdal, numpy... | <p>This is not to hard as your tiff_files are already a list, an important question is Does order matter - do the results have to be in the same order as the original files. If not</p>
<pre><code>from multiprocessing import Pool
from multiprocessing import cpu_count
def handle_tiff(some_file):
data_open = gdal.... | python|numpy|scipy|multiprocessing|gdal | 1 |
19,254 | 4,620,712 | Can I add extra header information to a numpy .npy file by using seek? | <p>I want to store an array to file with some extra information in a header. I want to use the numpy binary '.npy' format. Can I read an array form a .npy file with an extra header by first seeking to the beginning of the array part?</p>
<p>I want to do something like this. If a have a header that is 'n' bytes:</p>... | <p>Sure you can put metadata into a file header. But it is a bit complex, and unless the file format has a header for metadata already (which seems to be the case here, unless you can stick it into the description field .npy seems to have), it means you aren't actually using the .npy format, but your own format only yo... | python|serialization|numpy | 1 |
19,255 | 55,571,311 | Get part of day (morning, afternoon, evening, night) in Python dataframe | <p>Here is my dataframe , I need to create a new column based on the timehour which the row value be like (morning, afternoon, evening, night)</p>
<p><a href="https://i.stack.imgur.com/tmAWQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tmAWQ.png" alt="DataFrame"></a></p>
<p>Here is my code</p>
<pre><cod... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="noreferrer"><code>cut</code></a> or custom function with <code>and</code> and also changed <code><</code> to <code>></code> and <code>></code> to <code><=</code> and also for each value add <code>return</code>:</... | python|pandas|analytics | 21 |
19,256 | 55,317,804 | .csv loading repeats all entries from one column in every cell | <p>I am attempting to load a given csv file with the folowing structure:
<a href="https://i.stack.imgur.com/KdrPX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KdrPX.png" alt=".csv sample"></a></p>
<p>Then, I'd like to join all the words with the same "Sent_ID" into one row, with the following cod... | <p>Building on @Aravinds answer, OP wanted a working example:</p>
<pre><code>from io import StringIO
csv = StringIO('''
<paste csv snippet here>
'''
df = pd.read_csv(csv)
# Print first 5 rows
print(df.head())
id Doc_ID Sent_ID Word tag
0 1 1 1 Obesity O
1 2 1 ... | python|pandas|csv | 1 |
19,257 | 56,760,712 | Is it possible to append a pandas series to a list | <p>I have been working on project lately which predicts the most optimum team in fantasy premier league. After analysing different characteristics and parameters successfully I have been stuck because of the following "TypeError: 'Series' objects are mutable, thus they cannot be hashed"</p>
<p>I have completed writing... | <p>Pandas frames are mutable. Because of that, they cannot be used as keys of a dict, or elements of a set.</p>
<p>Look at line 11 in the first stacktrace. I've re-formatted it to be readable.</p>
<pre class="lang-py prettyprint-override"><code>if (len(team) < star_player_limit and
player not in injured and
... | python|pandas|list|hash|series | 0 |
19,258 | 56,659,030 | Creating an Alpha Overlay Image from the Difference of Two Images | <p>I've been having a weirdly difficult time with this problem. I have two images, we'll call them base</p>
<p><img src="https://i.imgur.com/f66E6oo.png" alt=""> </p>
<p>and light</p>
<p><img src="https://i.imgur.com/byPF1JS.png" alt=""> </p>
<p>(the actual images are much higher resolution, but the issue should be... | <p>I do not know Opecv that well, but in ImageMagick, I would do the following:</p>
<p>base:</p>
<p><a href="https://i.stack.imgur.com/C9OxI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C9OxI.png" alt="enter image description here"></a></p>
<p>light:</p>
<p><a href="https://i.stack.imgur.com/P... | python|numpy|opencv|python-imaging-library | 1 |
19,259 | 56,868,748 | How to convert text and numbers to dataframe in Python? | <p>I have a text document with spending information. I want to use pandas and Python 3 to convert the text to a dataframe with two columns, without repeating row names by combining same names into one row with the respective amounts added to produce a single total.</p>
<p>Original "spending.txt:"</p>
<pre><code>shavi... | <p>This should do it:</p>
<pre><code>df = pd.read_csv('spending.txt', header=None, sep='\s+')
df.columns = ['category', 'total']
df.groupby('category', as_index=False).sum()
category total
0 coffee 100
1 food 350
2 shaving 350
3 transport 100
</code></pre> | python|pandas | 1 |
19,260 | 56,673,861 | How do i convert my numpy array to 2D when it should already have 2 dims? | <p>I am trying to get some columns from my array using</p>
<pre><code>[:, x]
</code></pre>
<p>and my program is complaining that my numpy array isn't 2D but i am pretty sure it is.</p>
<pre><code>print(len(inputs))
</code></pre>
<p>gives me 13715</p>
<pre><code>print(len(inputs[x]))
</code></pre>
<p>gives me 402<... | <p>When you get a comma like (13715,), it means that you have 13715 rows and that number of columns is not defined, i.e. it's different for different rows. You cannot reshape it, since such operation makes no sense.</p>
<p>You can access each array with the row number, like you did: input[x].</p>
<p>And you can check... | python|arrays|numpy | 1 |
19,261 | 56,639,816 | how to fix "field units already exist in schema" for pandas gpq | <p>Versions:
Mac OS Mojave 10.14.5
Python 3.6.5
Pandas 0.24.2
pandas-gbq 0.10.0</p>
<p>I am trying to pull data from the shipstation api and load it into bigquery to use in our BI platform (tableau). I have successfully made the api call, which returned a json object. I have successfully turned that in a pandas df o... | <p>Hey maybe late but run into a similar problem,</p>
<p>Probably the column is duplicated in your DF, check for "field" (lower case) in your DF</p> | python|pandas|google-bigquery|python-bigquery | 2 |
19,262 | 56,742,631 | Why are axes flipped with a perspective camera? | <p>I am trying to implement a simple perspective camera in Python with a right hand-coordinate system where +x-axis is right, +y-axis is up and +z-axis is out of the screen. </p>
<p>I have some code which projects points from 3D-world coordinates to 2D images coordinates. To test it I tried to project three unit vecto... | <p>Things seem to work correctly if I instead change the intrinsics matrix to:</p>
<pre><code> K = np.array([
[fx, 0., -cx],
[0., fy, -cy],
[0., 0., -1.]
], dtype='float32')
</code></pre>
<p>With those entries negated. I'm not sure why but I saw in in some sample code and t... | python|numpy|opencv|computer-vision | 0 |
19,263 | 25,683,678 | Adding numpy matrices together | <p>I've several matrices, each one stored in a NumPy array and I would like to add them all.</p>
<pre><code>a1=np.load("20130101T054446")
a2=np.load("20130102T205729")
a3=np.load("20130104T153006")
a4=np.load("20130113T130758")
a5=np.load("20130113T212154")
</code></pre>
<p>I know its possible to add them in this awa... | <p>To avoid creating a lot of matrices in memory, it might be best to read them in one at a time and add them in place.</p>
<p>Start by loading your first matrix:</p>
<pre><code>z = np.load("20130101T054446")
</code></pre>
<p>Then read the remaining matrices in one at a time adding each one to <code>z</code> as you ... | python|numpy|matrix | 2 |
19,264 | 25,565,100 | How to place two existing columns under a hierarchy? | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(randn(10, 5), columns=['a', 'b1', 'b2', 'c1', 'c2'])
</code></pre>
<p>How can I add another hierarchy level to the columns that would bind 'b1' and 'b2' under 'b', and 'c1', 'c2' under 'c'?</p>
<p>I've only found examples for gen... | <p>You can do this by defining a MultiIndex (consisting of the original column labels and a new level) and assigning this to the columns (overwriting the existing columns):</p>
<pre><code>In [73]: upper_level = [i[0] for i in df.columns]
In [74]: df.columns = pd.MultiIndex.from_arrays([upper_level, df.columns])
In [... | pandas | 3 |
19,265 | 25,840,398 | Counting the number of results for a pandas.loc search | <p>I have a pandas DataFrame with two columns "user" (userid) and "TS" (timestamp).</p>
<pre><code>>>> print rawData
<class 'pandas.core.frame.DataFrame'>
Int64Index: 74883 entries, 0 to 74882
Data columns (total 2 columns):
TS 74883 non-null values
user 74883 non-null values
dtypes: float64(1... | <p>You can pass a one-element list as the index to force it to return a Series even if there is only one match:</p>
<pre><code>indexedDataFrame.loc[['user1'], 'TS']
</code></pre>
<p>(You can also use a multi-element list to get multiple indices at once, e.g., <code>indexedDataFrame.loc[['user1', 'user2'], 'TS']</code... | python|pandas | 4 |
19,266 | 67,013,361 | pivoting pandas dataframe with all string data in each column | <p>Sample dataframe:</p>
<pre><code>Name Attribute Response
Joe A Yes
Joe B smoking
Joe B headache
Mary A Null
Mary B Never
Bob C Today
Mary A Tomorrow
</code></pre>
<p>I have tried for several hours and searchi... | <p>You can do <code>.pivot_table()</code> with <code>aggfunc=list</code>:</p>
<pre><code>print(
df.pivot_table(
index="Name", columns="Attribute", aggfunc=list, fill_value="Null"
).droplevel(0, axis=1)
)
</code></pre>
<p>Prints:</p>
<pre><code>Attribute A ... | python|pandas|reshape | 3 |
19,267 | 66,845,050 | Pandas - how to find a sequence of 6 zero in any row in a data frame, and replace it to NaN? | <p>How can I find every row in a data frame that contains 6 zero (in adjacent columns),
and then to replace this 6 zero to Nan?</p> | <p>We could torture Numpy functions to get us some clever way to do this. But it is simpler and likely more efficient to loop with Numba.</p>
<pre><code>import numpy as np
import pandas as pd
from numba import njit
</code></pre>
<h2>Setup</h2>
<pre><code>np.random.seed([3, 14])
df = pd.DataFrame(
np.random.randint... | python|pandas|dataframe | 1 |
19,268 | 66,968,102 | python type hint - can tensorflow data type be used? | <p>Is it possible to use the Tensorflow data types <a href="https://www.tensorflow.org/api_docs/python/tf/dtypes/DType" rel="noreferrer">tf.dtypes.DType</a> such as tf.int32 in Python type hint?</p>
<pre><code>from typing import (
Union,
)
import tensorflow as tf
import numpy as np
def f(
a: Union[tf.int32, t... | <p>I assume you would like your function to accept:</p>
<ul>
<li><code>tf.float32</code></li>
<li><code>np.float32</code></li>
<li><code>float</code></li>
<li><code>tf.int32</code></li>
<li><code>np.int32</code></li>
<li><code>int</code></li>
</ul>
<p>and always return, say, <code>tf.float32</code>. Not completely sur... | python|tensorflow|type-hinting | 3 |
19,269 | 66,894,231 | Error with .map Function Tensorflow Dataset | <p>I am trying to import a directory full of images into Tensorflow and then use it for Keras Tuner. The problem is Keras Tuner requires the data to be split into images and labels. I was following a guide on Tensorflow's website and here is the code I have so far:</p>
<p>NOTE: I am using the COCO dataset meaning each ... | <p>You need to create the Train and Test split like this:</p>
<pre><code>train_data_gen = tf.keras.preprocessing.image_dataset_from_directory(
train_dir, labels='inferred', label_mode='int',
class_names=None, color_mode='rgb', batch_size=batch_size, image_size=(IMG_HEIGHT,IMG_WIDTH), shuffle=True, seed=123,
... | python-3.x|dataframe|tensorflow|keras|arguments | 0 |
19,270 | 66,865,649 | Generating date range from dataframe columns with start and end dates | <p>I have the following Pandas dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>shop</th>
<th>item</th>
<th>price</th>
<th>start_date_valid</th>
<th>end_date_valid</th>
</tr>
</thead>
<tbody>
<tr>
<td>shop1</td>
<td>item1</td>
<td>100.00</td>
<td>2019-01-01</td>
<td>2019-01-06</td... | <p>As your dataset is big, you have to use more efficient operations making use of pandas vectorized operation. You can use <a href="https://docs.python.org/3/library/functions.html#map" rel="noreferrer"><code>list(map())</code></a> together with <a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range... | python|pandas|dataframe|bigdata | 5 |
19,271 | 66,851,907 | How to solve SettingWithCopyWarning error when I add a new column with partial rows? | <p>I am trying to add a new column called running_std, but only on after row 365 onwards, the function running_std() will return one column of new data but 365 rows short, so my results are not full length. So I need to specify to save the result from running_std in a new column called df[running_std] but only after t... | <p>Problem is if use <code>df.iloc[364:]['running_std']</code>, because it create new <code>Series</code> from 365 rows called <code>running_std</code> instead new column, more info in <a href="https://pandas.pydata.org/docs/user_guide/indexing.html#evaluation-order-matters" rel="nofollow noreferrer">pandas docs</a>.</... | python|pandas | 2 |
19,272 | 47,421,346 | Can I create a list from groupby with only items that have equal value? | <pre><code>df.groupby(['foo'])[['bar']].count()
</code></pre>
<p><a href="https://i.stack.imgur.com/vhI7y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vhI7y.png" alt="enter image description here"></a></p>
<p>This is what I get from applying this groupby.
What I want to be able to do is to only ... | <p>Just adding <code>duplicated</code> and then <code>.index.tolist()</code> after <code>groupby</code></p>
<pre><code>df.groupby(['foo'])[['bar']].count().duplicated(keep=False).index.tolist()
Out[320]: ['ITEM3', 'ITEM4']
</code></pre> | python|pandas|dataframe | 0 |
19,273 | 68,436,544 | Create new pandas dataframe from an existing one only with max and min per day | <p>I have the following df</p>
<pre><code> ID Date Element Data_Value day month year
24805 USW00094889 2005-01-01 TMIN -56 1 1 2005
24863 USW00094889 2005-01-01 TMAX 44 1 1 2005
18049 USW00014853 2005-01-01 TMAX 56 1 1 2005
18066 USW00014853 20... | <p>If your min is defined by a single column, you can use the series groupby:</p>
<pre><code>>>> df.groupby('Date')['Data_Value'].agg(['min', 'max'])
min max
Date
2005-01-01 -56 156
</code></pre>
<p>If you want full rows, or other infos from that row, you can use <code>idxmin</co... | python|pandas | 2 |
19,274 | 68,403,571 | Applying rolling median across row for pandas dataframe | <p>I would like to apply a rolling median to replace NaN values in the following dataframe, with a window size of 3:</p>
<pre><code> 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 ... 2007 2008 2009 2... | <p>First compute the rolling medians by using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><strong><code>rolling()</code></strong></a> with <code>axis=1</code> (row-wise), <code>min_periods=0</code> (to handle <code>NaN</code>), and <code>closed='both'</... | python|pandas | 3 |
19,275 | 59,325,381 | Low accuracy after training a CNN | <p>I try to train a CNN model that classifies the handwritten digit using Keras, but I am getting low accuracy in the training (lower than 10%) and a big error.
I tried a simple neural network without concolutions and it didn't work as well.</p>
<p>This is my code.</p>
<pre><code>import tensorflow as tf
from tensorfl... | <p>Your problem is here:</p>
<pre class="lang-py prettyprint-override"><code>x_train = x_train/255
y_train = y_train/255 # makes no sense
</code></pre>
<p>You should have rescaled <code>x_test</code>, not <code>y_train</code>. </p>
<pre class="lang-py prettyprint-override"><code>x_train = x_train/255
x_test = x_test... | python|tensorflow|keras|conv-neural-network|mnist | 2 |
19,276 | 59,060,769 | How to open the binary log files generated by the tensor-board after training? | <p>I am trying to open an output log file produced from training of a deep network model. I activated the tensor-board option during training to view the accuracy and learning during training. It created a directory call “tb” and placed the log files there. The files look like this:</p>
<pre><code>events.out.tfevents.... | <p>I was able to get it by typing the following in the linux terminal:</p>
<pre><code>tensorboard --logdir=<path-to-log-directory>
</code></pre>
<p>Then I got the following:</p>
<pre><code>TensorBoard 1.13.1 at http://computername:6006
</code></pre>
<p>and I just opened the above link in my firefox browser.<... | python|tensorflow|deep-learning|tensorboard | 0 |
19,277 | 59,210,767 | Tensorflow.js: Resize image to specific byte size | <p>For the prediction I need an image of the shape [null,7,7,256].</p>
<blockquote>
<p>const image = tf.reshape(tf.fromPixels(loadedImage).resizeBilinear([?,?]), [null, 7, 7, 256]);</p>
</blockquote>
<p>But I don't know how to resize the image to be exactly 7*7*256 big.</p>
<blockquote>
<p>Error: Size(37632) mus... | <p>ResizeBilinear will resize the height and the width of the image, meaning that it does not affect the number of channel which is the last dimension of the shape of an image.</p>
<p>If your image has 256 as it last channel, then the following will work</p>
<pre><code>tf.fromPixels(loadedImage).resizeBilinear([7,7])... | image|tensorflow.js | 4 |
19,278 | 44,870,059 | tensorflow:Casting <dtype: 'int64'> labels to bool | <p>I'm running the <a href="https://www.tensorflow.org/tutorials/wide_and_deep" rel="nofollow noreferrer">wide and deep tutorial</a> code and without changes I get the error:</p>
<pre><code>WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
</code></pre>
<p>My question is: what does this mean and how d... | <p>I encountered exactly the same error when using DNNClassifier. To resolve it, I need to specify <code>n_classes</code> parameter to the number of classes in your target. </p>
<p>The <code>n_classes</code> parameter is to specify how many classes in your target.By default, it presume there are only two classes in yo... | tensorflow | 1 |
19,279 | 45,241,221 | Python Pandas Calculate average days between dates | <p>Working with the following python pandas dataframe df: </p>
<pre><code>Customer_ID | Transaction_ID
ABC 2016-05-06-1234
ABC 2017-06-08-3456
ABC 2017-07-12-5678
ABC 2017-12-20-6789
BCD 2016-08-23-7891
BCD 2016-09-21-2345
BCD 2017-10-23-4567... | <p>You can get previous visit date (grouped by customer and year) by shifting the "date" column down by 1:</p>
<pre><code>df['previous_visit'] = df.groupby(['Customer_ID', 'year'])['date'].shift()
</code></pre>
<p>From this, days between visits is simply the difference:</p>
<pre><code>df['days_bw_visits'] = df['date... | python|pandas|if-statement|group-by|average | 11 |
19,280 | 44,971,085 | How to decode my tiff pictures to input tensorflow using pipline? | <p>I am trying to train a neural network using my own tiff pictures with tensorflow pipline. Here is the problem: tensorflow only has 4 kinds of pictures which can be decoded(decode_jpeg, decode_bmp, decode_gif, decode_png), there is no way to decode tiff pictures. So, how can i decode my tiff pictures to use tensorflo... | <p>Try this: <a href="https://www.tensorflow.org/io/api_docs/python/tfio/experimental/image/decode_tiff" rel="nofollow noreferrer">tfio.experimental.image.decode_tiff</a>.</p>
<pre><code>tfio.experimental.image.decode_tiff(
contents, index=0, name=None
)
</code></pre>
<blockquote>
<p><strong>contents:</strong> A T... | batch-file|input|tensorflow|decode|tiff | 0 |
19,281 | 57,283,168 | Want a pandas Series of Trips Completed to count(Request) ratio for each hour as index for the given dataframe | <p>The link to the dataset: '<a href="https://drive.google.com/file/d/19P0Trh_vJ2UuC9qZi7xLL_ZFTeKLTvWR/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/19P0Trh_vJ2UuC9qZi7xLL_ZFTeKLTvWR/view?usp=sharing</a>'</p>
<p>What I want: To plot seperate graphs for every 'Status' value and 'Pickup po... | <p><strong>Data manipulation</strong></p>
<pre><code>agg = df.pivot_table(index=["Req_hour", "Status", "Pickup point"], values=["Request id"], aggfunc="count").rename(columns={"Request id": "Count"}).reset_index()
hr_totals = df[["Req_hour", "Request id"]].groupby(["Req_hour"]).count().rename(columns={"Request id": "T... | python|pandas|dataframe|seaborn | 0 |
19,282 | 57,093,810 | How to do backward resampling on time series data starting from the last row? | <p>I have rows of data (per second) that I used to resample by two hour, and for each feature I applied different calculation, in short:</p>
<pre><code>data = data.resample('2H').agg({'id':'first','x1': np.sum,
'x2': np.mean}).dropna()
</code></pre>
<p>Since each file contains one day... | <p>You can do this by applying a transformation to your time stamp, resampling on the transformed index and then reverting the transformation.</p>
<pre><code>end_time = data.index[-1]
data['time to end'] = end_time - data.index
data.set_index('time to end', inplace=True)
data = data.resample('2h').mean() # Or your fu... | python|pandas|csv|time-series | 1 |
19,283 | 56,877,350 | numpy.sum transition to kahan but with masked arrays for increased precision | <p>I have a multi-array stack of data that is masked to exclude 'bad' or problematic values- this is in the 3rd dimension. Current code utilizes np.sum, but the level of precision (both large and small numbers) has negatively impacted results. I've attempted to implement the kahan_sum referenced here but forgotten abou... | <p>If you really need more precision, consider using <code>math.fsum</code> which is accurate to fp resolution. If <code>A</code> is your 3D masked array, something like:</p>
<pre><code>i,j,k = A.shape
np.frompyfunc(lambda i,j:math.fsum(A[i,j].compressed().tolist()),2,1)(*np.ogrid[:i,:j])
</code></pre>
<p>But before ... | python|arrays|numpy | 1 |
19,284 | 57,190,292 | Check if records with same value in one column are the same throughout | <p>I have a pandas df called with ~1 million records. The df has over 80 columns, with one of those columns being asset_id. I want to create a subset of all the records which have duplicate asset_ids, but have a different value in at least one of the other columns.</p>
<p>Example:</p>
<pre><code>df = pd.DataFrame({"a... | <p>You could directly filter out the groups that have more than one <code>Name</code> or more than one <code>Country</code> and then drop any remaining duplicates with:</p>
<p><code>df.groupby('asset_id').filter(lambda x: (x.Name.nunique()>1) | (x.Country.nunique()>1)).drop_duplicates()</code></p>
<p>Output:</p... | python|pandas | 3 |
19,285 | 57,194,169 | How to add element to empty 2d numpy array | <p>I'm trying to insert elements to an empty 2d numpy array. However, I am not getting what I want.</p>
<p>I tried np.hstack but it is giving me a normal array only. Then I tried using append but it is giving me an error.</p>
<p>Error:</p>
<p>ValueError: all the input arrays must have same number of dimensions</p>
... | <p>The recommended list append approach:</p>
<pre><code>In [39]: alist = []
In [40]: for i in range(3):
...: alist.append([i, i+10])
...: ... | python|numpy | 1 |
19,286 | 57,244,089 | Tensorflow InvalidArgumentError Matrix size incompatible | <p>When I start the simple neural net I got an error. By the way, the code should output the first number of the test array.</p>
<p>There have been other errors(there was one having to do with the data's dtype).</p>
<pre><code>import tensorflow as tf
import numpy as np
from tensorflow import keras
data = np.array([[... | <p>You are getting above error because of below line:</p>
<pre><code>prediction = model.predict([0, 1, 0])
</code></pre>
<p>You are passing a <code>list</code> which should be a numpy array and of shape <code>Nx3</code>, where <code>N</code> is basically batch size and can be 1, 2, etc. In this case, it will be <code... | python|tensorflow|keras | 1 |
19,287 | 56,964,729 | scipy.sparse.csr.csr_matrix not showing in variable explorer | <p>This question is not the duplicate of <a href="https://stackoverflow.com/questions/31526983/newly-assignmed-variables-not-showing-up-in-spyders-variable-explorer">this</a>, because only scipy.sparse.csr.csr_matrix type is not showing in variable explorer whereas any other code when executed shows successfully in var... | <p>As Carlos commented above it worked, I needed to deselect the <code>Exclude unsupported data types</code> option in spyder's variable explorer.</p> | python-3.x|pandas|scikit-learn|ipython|spyder | 1 |
19,288 | 45,930,352 | How to add a boundary to a figure (data set) using matplotlib and SVM algorithm? | <p>My code:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('data/data.csv')
X = data[['x1','x2']]
y = data['y']
from sklearn.svm import SVC
classifier = SVC()
classifier.fit(X,y)
plt.scatter(data['x1'], data['x2'], c=y, s=50)
plt.show()
</code></pre>
<p>My data:</p>
<pre><co... | <p>Building off of Sun Yi's <a href="https://stackoverflow.com/a/45930412/1193874">answer</a>, you can use the example code from <a href="https://github.com/rasbt/python-machine-learning-book/blob/master/code/ch03/ch03.ipynb" rel="nofollow noreferrer">here</a>. For example, you don't have all the points in your <code>... | python|pandas|matplotlib|scikit-learn|sklearn-pandas | 2 |
19,289 | 46,165,393 | Find Position of Value in numpy Array | <p>I am trying to find the position in the Array called ImageArray </p>
<pre><code>from PIL import Image, ImageFilter
import numpy as np
ImageLocation = Image.open("images/numbers/0.1.png")
#Creates an Array [3d] of the image for the colours
ImageArray = np.asarray(ImageLocation)
ArrayRGB = ImageArray[:,:,:3]
#Remov... | <p>As an example, let's consider this array:</p>
<pre><code>>>> import numpy as np
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
</code></pre>
<p>Now, let's apply your transformation to it:</p>
<pre><code>>>> np.where(a>a.mean(), 255, 0)
array([[ 0, 0, 0],
[ ... | python|arrays|numpy|python-imaging-library | 2 |
19,290 | 23,043,959 | Dynamically Generating Pandas Views | <p>I have several classes that all reference the same pandas dataframe, but only part of the data frame is relevant to each class. I also want to make it easy to access the relevant rows without using the advanced indexing as it gets repetitive due to number if levels in the index. As a result, I wrote code that gene... | <p>Well I personally would suggest you wrap your DataFrame in an object like so:</p>
<pre><code>class MyDataFrameView(object):
def __init__(self, df):
self.data = df
def x(self):
return self.data.ix['foo', 'x']
def y(self):
return self.data.ix['bar', 'y']
</code></pre>
<p>you us... | python|pandas|functools | 3 |
19,291 | 23,301,231 | How to Append Masked Arrays | <p>I have two arrays, and I want to append them into a new array but I need the masked information to be kept. I tried numpy.append(), but it lose the masked information.</p>
<pre><code>>>> maska
masked_array(data = [-- 1 3 2 1 -- -- 3 6],
mask = [ True False False False False True True False False],
... | <p>This is indeed very strange that even <code>np.ma.hstack</code> doesn't work, but you can achieve what you need by manually combining the masks:</p>
<pre><code>In [1]: import numpy as np
In [2]: def masked_hstack(tup):
...: return np.ma.masked_array(np.hstack(tup),
...: mask=np.hstack([arr.mas... | python|numpy | 2 |
19,292 | 35,659,897 | Using the softmax layer within the objective function itself | <p>This is going to be long and hard to describe so apologies in advance.</p>
<p>I have a regular CNN like network with standard MLP layers on top of it. On top of the MLP, I have a softmax layer too, however, unlike conventional networks, this is NOT fully connected to the MLP below and it consists of subgroups.</p>
... | <p>Apologies.. I realized that the problem is that tf.argmax function obviously does not have a gradient defined.</p> | python|tensorflow|neural-network|conv-neural-network|softmax | 1 |
19,293 | 35,496,704 | numpy *= not working | <p>I use numpy to calculate matrix multiply.
If I use t = t * x, it works just fine, but if I use t *= x, it doesn't.
Do I need to use t = t * x?</p>
<pre><code>import numpy as np
if __name__ == '__main__':
x = [
[0.9, 0.075, 0.025],
[0.15, 0.8, 0.05],
[0.25, 0.25, 0.5]
]
t = [1, 0... | <p>You filled <code>t</code> with ints rather than floats, so NumPy decides you want a matrix of integer dtype. When you do <code>t *= x</code>, this requests that the operation be performed in place, reusing the <code>t</code> object to store the result. This forces the results to be cast to integers, so they can be s... | python|numpy | 6 |
19,294 | 35,525,694 | Memory error when using read_csv | <p>I'd like to convert the csv files into hdf5 format,which are used for caffe training.Because the csv files is 80G,it will report memory error.The machine memory is 128G.So can it possbile to improve my code?handle it one by one?Below is my code,it reported memory error when run in np.array</p>
<pre><code>if '__main... | <p>The best approach would be to read n lines and then write these to the HDF5 file, extending it be n elements each time. This way the amount of memory needed is not dependent on the size of the csv file. You could read a line at a time as well, but that would be slightly less efficient.</p>
<p>Here's code that app... | csv|pandas|hdf5|caffe|np | 0 |
19,295 | 28,638,094 | Using Cython to wrap a c++ template to accept any numpy array | <p>I'm trying to wrap a parallel sort written in c++ as a template, to use it with numpy arrays of any numeric type. I'm trying to use Cython to do this. </p>
<p>My problem is that I don't know how to pass a pointer to the numpy array data (of a correct type) to a c++ template. I believe I should use fused dtypes for ... | <p>Yes, you want to use a fused type to have Cython call the sorting template for the appropriate specialization of the template.
Here's a working example for all non-complex data types that does this with <code>std::sort</code>.</p>
<pre><code># cython: wraparound = False
# cython: boundscheck = False
cimport cython... | python|c++|arrays|numpy|cython | 6 |
19,296 | 28,814,309 | How can I format this into a date in pandas? | <blockquote>
<p>26JAN2015:14:42:03</p>
</blockquote>
<p>How do I format that data properly in pandas as a date? I have two columns in a raw file which have that format and I need them to be in date so I can subtract their values to measure the time in between.</p>
<p>Also, for a quick sanity check. When I am dealin... | <p>Call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html#pandas.to_datetime" rel="nofollow"><code>to_datetime</code></a> and pass the format string:</p>
<pre><code>In [114]:
df = pd.DataFrame({'date':['26Jan2015:14:42:03']})
df['date'] = pd.to_datetime(df['date'], format='%d%b%Y:... | python|pandas | 2 |
19,297 | 28,865,352 | Manipulate A Group Column in Pandas | <p>I have a data set with columns Dist, Class, and Count.</p>
<p>I want to group that data set by dist and divide the count column of each group by the sum of the counts for that group (normalize it to one).</p>
<p>The following MWE demonstrates my approach thus far. But I wonder: is there a more compact/pandaific wa... | <p>One alternative way to get the normalised 'Count' column could be to use <code>groupby</code> and <code>transform</code> to get the sums for each group and then divide the returned Series by the 'Count' column. You can reassign this Series back to your DataFrame:</p>
<pre><code>s['Count'] = s['Count'] / s.groupby('... | python|pandas|dataframe|pandas-groupby | 2 |
19,298 | 50,864,103 | From dataFrame to list with TypeError: string indices must be integers | <p>I would like to create a list that looks like this at the end:</p>
<pre><code>[
{'name': 'Chrome', 'y': 550},
{'name': 'IE', 'y': 203},
]
</code></pre>
<p>my data frame is:</p>
<pre><code>df = pd.DataFrame({"CATEGORY":["Chrome","IE","FireFox","Safari","Opera","QQ"],"Users":[550,203,25,305,15,132]})
</code... | <p>You need to use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer">.apply()</a> with <code>axis=1</code> so as to access columns. As you go, you need to construct your dictionary. </p>
<pre><code>list(df.apply(lambda x: {'name': x['CATEGORY'],... | python|python-3.x|pandas|lambda | 1 |
19,299 | 50,904,164 | Delete element in DataFrame under condition | <p>my DataFrame is looking at this : </p>
<pre><code>indeed.fr
11.41%
career2.successfactors.eu
8.53%
37.16%
pracuj.pl
7.40%
80.42%
corporate.danone.com.br
6.64%
indeed.com.br
4.68%
61.73%
</code></pre>
<p>Thus I want to only conserve the first % as follows : </p>
<pre><code>indeed.fr
11.41%
career2.successfactors.e... | <pre><code>mydata =['indeed.fr','11.41%','career2.successfactors.eu','8.53%','37.16%','pracuj.pl','7.40%','80.42%','corporate.danone.com.br','6.64%','indeed.com.br','4.68%','61.73%']
df = pd.DataFrame(mydata)
</code></pre>
<p>Was the sample you created.</p>
<p>The solution is below</p>
<pre><code>rowList = []
row =... | python-3.x|pandas|dataframe|conditional | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.