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 |
|---|---|---|---|---|---|---|
376,100 | 72,711,734 | I want to create new features from a pandas dataset by an arbitrary process | <p>The following data sets are currently being used.</p>
<pre><code>import pandas as pd
import io
csv_data = '''
ID,age,get_sick,year
4567,76,0,2014
4567,78,0,2016
4567,79,1,2017
12168,65,0,2014
12168,68,0,2017
12168,69,0,2018
12168,70,1,2019
20268,65,0,2014
20268,66,0,2015
20268,67,0,2016
20268,68,0,2017
20268,69,1,2... | <p>First I created a column with the year for which <code>get_sick = 1</code>.</p>
<pre><code>df_mer = df[df.get_sick == 1].reset_index()[['ID', 'year']].drop_duplicates(subset = 'ID')
df = df.reset_index().merge(df_mer, on = 'ID', suffixes=('', '_max'))
</code></pre>
<p>Then you can use <code>year_max</code> to compu... | python|pandas | 0 |
376,101 | 72,670,379 | Split Columns in Pandas | <p>So I have a pandas column that looks like this:</p>
<pre><code>full_name = pd.Series([
'Reservoir 1 Compartment 1',
'Reservoir 1 Common Inlet',
'Reservoir 2 Compartment 1',
'Vyrnwy Line 2 Balancing Tank 1',
'Reservoir 1'
])
</code></pre>
<p>I am trying to split it into two columns. The expecte... | <p>Try the following:</p>
<pre><code>import pandas as pd
full_name = pd.Series([
'Reservoir 1 Compartment 1',
'Reservoir 1 Common Inlet',
'Reservoir 2 Compartment 1',
'Vyrnwy Line 2 Balancing Tank 1',
'Reservoir 1'
])
res = full_name.str.split('(?<=\d)\s+(?=[A-Z])', expand=True)
</code></pre... | python|regex|pandas|split | 3 |
376,102 | 72,697,587 | How is Pandas Block Manager improving performance? | <p>The Pandas documentation says :
<em>The primary benefit of the BlockManager is improved performance on certain operations (construction from a 2D array, binary operations, reductions across the columns), especially for wide DataFrames.</em></p>
<p>I thought I understood how the BlockManager improves performance than... | <p>Long story short : you need to work on more than 20 columns to benefit from the BlockManager for columns addition/multiplication.</p>
<p>There's actually a great explanation in Pandas documentation that I had missed :</p>
<p><em>What is BlockManager and why does it exist?</em></p>
<p><em>The reason for this is not r... | python|pandas|numpy|performance | 1 |
376,103 | 72,558,725 | Error running tfjs BlazePose pose detection on single HTMLImageElement | <p>I'm trying to get 3d pose detection working in the browser using tfjs.
I've followed the instructions at <a href="https://github.com/tensorflow/tfjs-models/tree/master/pose-detection/src/blazepose_mediapipe" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs-models/tree/master/pose-detection/src/blazepose_... | <p>I managed to replicate your issue locally and it seems the script tags are in the wrong order. This will work if you drop the "pose-detection" script tag to the bottom.</p>
<p>See the correct order as per documentation <a href="https://github.com/tensorflow/tfjs-models/tree/master/pose-detection/src/blazep... | javascript|tensorflow.js | 0 |
376,104 | 72,664,476 | np.random.choice Throws Exception when p Value Provided | <p>I can call <code>np.random.choice(5, 3)</code> with success:</p>
<p><a href="https://i.stack.imgur.com/NljlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NljlH.png" alt="enter image description here" /></a></p>
<p>However, adding any <code>p</code> values (e.g. <code>np.random.choice(5, 3, p=[0... | <p>The issue might be with the version of numpy please check it once as the piece of code is working fine for me</p>
<pre><code>import numpy as np
print(np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]))
</code></pre>
<p>output</p>
<pre><code>[0 3 0]
</code></pre>
<p>my numpy version is <strong>1.21.2</strong></p> | python|numpy | 1 |
376,105 | 72,741,431 | How to get matrix position of the max element in sliding window view of an array? | <p>I have successfully found the maximum of the array in each sliding window view using <code>amax</code> and <code>sliding_window_view</code> functions from NumPy as follows:</p>
<pre><code>import numpy as np
a = np.random.randint(0, 100, (5, 6)) # 2D array
array([[51, 92, 14, 71, 60, 20],
[82, 86, 74, 74, ... | <p>This solution gives indices per-window but does not give unique indices if a max-value appears twice in some window:</p>
<pre><code>maxvals = np.amax(windows, axis=(2, 3))
# array([[92, 92, 87, 87],
# [86, 86, 87, 87],
# [75, 75, 83, 87]])
indx = np.array((windows == np.expand_dims(maxvals, axis = (2,... | python|numpy|sliding-window | 2 |
376,106 | 59,840,427 | Submit a Keras training job to Google cloud | <p>I am trying to follow this tutorial:
<a href="https://medium.com/@natu.neeraj/training-a-keras-model-on-google-cloud-ml-cb831341c196" rel="nofollow noreferrer">https://medium.com/@natu.neeraj/training-a-keras-model-on-google-cloud-ml-cb831341c196</a></p>
<p>to upload and train a Keras model on Google Cloud Platform... | <p>I was able to follow the tutorial you mentioned successfully, with some modifications along the way.</p>
<p>I will mention all the steps although you made it halfway as you mentioned.</p>
<p>First of all create a Cloud Storage Bucket for the job:</p>
<pre><code>gsutil mb -l europe-north1 gs://keras-cloud-tutorial... | tensorflow|keras|gcloud|gcp-ai-platform-training | 3 |
376,107 | 59,881,163 | How to load a sklearn model in Tensorflowjs? | <p>I have a gradient boost model saved in the .pkl format. I have to load this model in tensorflowjs. i can see that there is a way to load a keras model but I can't find a way to load a sklearn model. Is it possible to do this?</p> | <p>It is not possible to load sklearn model in tensorflow.js. Tensorflow.js allows to load models written in tensorflow.</p>
<p>Though, I haven't tried myself, but I think that you can possibly use the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/wrappers/scikit_learn" rel="nofollow noreferrer">scikit ... | scikit-learn|tensorflow.js | 0 |
376,108 | 59,895,682 | My code has created a numpy array inside another numpy array for one list but it does not for another list that goes through the exact same process | <p>I'm developing a simple Artificial Intelligence for a college project and so far it has worked until it randomly began creating a numpy array inside another numpy array. One of the lists that are being converted is a dataset that I've created myself that then is iterated through and each image is read by cv2 and add... | <p>The problem is in</p>
<pre><code>for i in range (0, len(images)):
img = cv2.imread(images[i])
readyImages.append(img)
</code></pre>
<p><code>cv2.imread</code> can fail (e.g., if the image file is truncated), in which case <code>img</code> will be <code>None</code>. When you convert a list with <code>None</code... | python|arrays|numpy|artificial-intelligence | 2 |
376,109 | 59,846,499 | Slice the middle of a nd array | <p>I have a numpy array with shape <code>(20,50,100,500,500)</code> and I want to slice the array based on the 3rd dimension, let's say 40/60.</p>
<p>All that I can think of is to do. <code>array[:,:,:40,:,:]</code> and <code>array[:,:,60:,:,:]</code>, but how does one connect those without messing up the dimensions? ... | <p>I used np.stack, setting <code>axis=2</code> as following:</p>
<pre><code>>>> a = np.random.rand(2,2,2,2,2)
>>> a1 = a[:,:,:1,:,:] ... | python|numpy | 1 |
376,110 | 59,562,795 | Iteration of groups of columns | <p>I have a dataset that looks like this:</p>
<pre><code>A B C D E ecc
x1A x1B x1C x1D x1E x1N
x2A x2B x2C x2D x2E x1N
xnA xnB xnC xnD xnE xnN
</code></pre>
<p>where A, B, C, D, E are the column names and xi are numbers. I would like to perform a certain operation considering stretches of 3 columns, so firs... | <p>Use <code>.rolling</code>:</p>
<pre><code>df.sum().rolling(window=3).var()
</code></pre> | python|pandas | 0 |
376,111 | 59,612,743 | Create new column based on group-by function | <p>I have a dataframe:</p>
<pre><code>df1 = pd.DataFrame({'Name': ['Bob', 'Bob', 'Bob', 'Joe', 'Joe', 'Joe', 'Alan', 'Alan', 'Steve', 'Steve'],
'ID': [1,2,3,4,5,6,7,8,9,10],
'Value': ['Y','Y','Y','N','N','N','Y','N','N','Y']})
Name ID Value
Bob 1 Y
Bob ... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> f... | python|pandas|dataframe|group-by | 2 |
376,112 | 59,799,635 | Keep common rows within every group of a pandas dataframe | <p>Given the following pandas data frame: </p>
<pre><code> | a b
--+-----
0 | 1 A
1 | 2 A
2 | 3 A
3 | 4 A
4 | 1 B
5 | 2 B
6 | 3 B
7 | 1 C
8 | 3 C
9 | 4 C
</code></pre>
<p>If you group it by column <code>b</code> I want to perform an action that keeps only the rows where they have column <code>a<... | <p>You can try <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.pivot_table.html" rel="noreferrer"><code>pivot_table</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="noreferrer"><code>dropna</code></a> here the... | python|pandas | 8 |
376,113 | 59,835,767 | Min and Max frequency using pandas? | <p>is it possible to find the min and max frequency using pandas? I have a series of values and i'd like to know the min and max frequency of it appearing. Example for 1, it appears three times out of 24 counts. Therefore, average frequency is 3/24 or 1/8. Which can be derived with count of 1 / total. </p>
<p>However,... | <p>Use:</p>
<pre><code>#changed sample data for possible non 1 before first 1 occurence
df = pd.DataFrame(data = {'X':[5,8,1,1,8,5,8,11,7,11,12,7,2,2,6,7,9,2,1,3,10,2,10,13,4,6]})
#print (df)
</code></pre>
<p>You can compare values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq... | python|pandas | 2 |
376,114 | 59,778,744 | pandas- grouping and aggregating consecutive rows with same value in column | <p>I have a pandas DataFrame from a long list of datetime ranges pulled from a database, each range with a label. The dates are ordered such that the start date of one row, is the end date of the row before. A workable example is here:</p>
<pre><code>import pandas as pd
bins = [{'start': '2020-01-12 00:00:00', 'end... | <p>First we use <code>Series.shift</code> with <code>Series.cumsum</code> to make a group indicator for each consecutive <code>label</code> value.</p>
<p>Then we use <code>groupby.agg</code> with <code>min</code> and <code>max</code>. </p>
<pre><code>label_groups = bins_df['label'].ne(bins_df['label'].shift()).cumsum... | django|pandas|dataframe|pandas-groupby|aggregation | 3 |
376,115 | 59,722,739 | How to calculate the mean/median/standard deviation of multiple matrices in a dictionary? | <p>Could you provide some solutions or suggestions for the following problem?</p>
<p>If I have a dictionary which contains three pandas dataframe, how should I calculate the mean/median/standard deviation of the three dataframes in the dictionary? </p>
<pre><code>df1 = pd.DataFrame(np.random.randint(10, size=(3,4)))
... | <p>IIUC, try:</p>
<pre><code>(pd.concat(df_dict).groupby(level=1)
.agg(['mean','median','std'])
.swaplevel(0,1, axis=1)
.sort_index(level=0, axis=1))
</code></pre>
<p>Output:</p>
<pre><code> mean median std ... | python|pandas|dictionary | 3 |
376,116 | 59,719,283 | Plotting time series information with missing date values | <p>I have the following dataset: </p>
<pre><code>dataset.head(7)
Transaction_date Product Product Code Description
2019-01-01 A 123 A123
2019-01-02 B 267 B267
2019-01-09 B 267 B267
2019-02-11 C 139 ... | <p>I believe <code>reindex</code> should work for you:</p>
<pre><code># First convert the index to datetime
dataset.index = pd.DatetimeIndex(dataset.index)
# Then reindex! You can also select the min and max of the index for the limits
dataset= dataset.reindex(pd.date_range("2019-01-01", "2019-02-12"), fill_value="Na... | python|pandas|indexing|time-series|seaborn | 0 |
376,117 | 59,761,699 | Tensorflow no module named '_pywrap_tensorflow_internal' (DLL's appear to be fine) | <p>I had to reinstall python (it was a whole mess but to my knowledge, it does appear to have fully reinstalled without remnants) and, while I never ran it beforehand, I recently have wanted to start running TensorFlow, unfortunately, whenever I try to import the module it raises an error. I have spent the last days ad... | <p>You are using Python 3.8.</p>
<p>from the file list of
<a href="https://pypi.org/project/tensorflow/#files" rel="nofollow noreferrer">pypi for tensorflow</a>
and <a href="https://pypi.org/project/tensorflow-gpu/#files" rel="nofollow noreferrer">pypi for tensorflow</a>, </p>
<p>here is the <a href="https://github.c... | python|tensorflow|python-import|importerror | 0 |
376,118 | 59,733,569 | Reporting with Pandas | <p>I'm trying to generate reports using Pandas, grouping by a set of fields:</p>
<p>This is what I'm doing:</p>
<pre><code>#!/usr/bin/env python3
import pandas as pd
data = [
{
'id': 1,
'name': 'name1',
'pretty_name': 'Pretty Name 1',
'server_name': 'exampleserver.local',
... | <p>You can create helper column for compare if match <code>provider1</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Seri... | python|pandas|report | 3 |
376,119 | 59,784,933 | iterrows() of 2 columns and save results in one column | <p>in my data frame I want to iterrows() of two columns but want to save result in 1 column.for example df is</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>x y ... | <p>First never use <a href="https://stackoverflow.com/questions/24870953/does-pandas-iterrows-have-performance-issues/24871316#24871316"><code>iterrows</code></a>, because really slow.</p>
<p>If want <code>1, 2</code> sequence by number of columns convert values to numy array by <a href="http://pandas.pydata.org/panda... | pandas|postgresql | 0 |
376,120 | 59,518,694 | Filter 2 coordinate index in xarray dataframe | <p>I am trying to filter large dataset in xarray for exact <code>latitude</code>, <code>longitude</code> values from following dataset:</p>
<pre><code><xarray.Dataset>
Dimensions: (latitude: 23, level: 6, longitude: 21, time: 178486)
Coordinates:
* time (time) datetime64[ns] 1979-01-01 ... 2019-11-26T... | <p>Have a look at <a href="http://xarray.pydata.org/en/stable/generated/xarray.Dataset.sel.html" rel="nofollow noreferrer"><code>Dataset.sel</code></a> (see also examples <a href="http://xarray.pydata.org/en/stable/indexing.html#indexing-and-selecting-data" rel="nofollow noreferrer">here</a>). I think something like t... | python|numpy|python-xarray | 1 |
376,121 | 59,569,943 | Replace column of pandas multi-index DataFrame with another DataFrame | <p>I have a pandas DataFrame like this:</p>
<pre><code>import pandas as pd
import numpy as np
data1 = np.repeat(np.array(range(3), ndmin=2), 3, axis=0)
columns1 = pd.MultiIndex.from_tuples([('foo', 'a'), ('foo', 'b'), ('bar', 'c')])
df1 = pd.DataFrame(data1, columns=columns1)
print(df1)
foo bar
a b c
0 ... | <p>For lack of better alternative, I'm currently doing this:</p>
<pre><code>df2.columns = pd.MultiIndex.from_product([['bar'], df2.columns])
df1.drop(columns='bar', level=0, inplace=True)
df1 = df1.join(df2)
</code></pre>
<p>Which gives the desired result. One needs to be cautious though if the order of columns is im... | python|pandas|multi-index | 1 |
376,122 | 59,761,890 | IndexError: tuple index out of range when using Datasets with tensorflow 2.1 | <p>Generating my own TFRecords and I can't seem to properly use datasets in my models. Just to test if it was my current files or something in the model code I used tfds with MNIST and am having the same error. </p>
<p>The error is: <code>IndexError: tuple index out of range</code>
The full output is below. I'm doing ... | <p>Adding <code>as_supervised=True</code> to <code>tfds.load()</code> will solve the problem. Another question is why this problem occurs in the first place, probably a bug in TF.</p> | python|tensorflow|keras|tensorflow-datasets | 0 |
376,123 | 59,724,593 | How to iterate over dataframe rows, replacing values from a matching tuple in a more pythonic way? | <p>I am able to replace values in a specific column of a pandas dataframe by iterating over the rows, and match these values to the corresponding tuple pairs which are contained in a list of tuples.</p>
<p>However, when I run this code on a large dataframe, it becomes relatively slow as it has to iterate over the enti... | <p>Use <code>map</code></p>
<pre><code>z = dict(zip(x,y))
df['Number'] = df['Number'].map(z)
</code></pre>
<hr>
<pre><code> Strings Number
0 some 345
1 random 363
2 stuff 371
3 which 359
4 is 387
5 irrelevant 391
</code></pre>
<hr>
<p>To map only <em>... | python|pandas|loops|dataframe|optimization | 3 |
376,124 | 59,787,897 | How does TensorFlow SparseCategoricalCrossentropy work? | <p>I'm trying to understand this loss function in TensorFlow but I don't get it. It's <strong>SparseCategoricalCrossentropy</strong>. All other loss functions need outputs and labels of the same shape, this specific loss function doesn't.</p>
<p>Source code:</p>
<pre><code>import tensorflow as tf;
scce = tf.keras.lo... | <p>SparseCategoricalCrossentropy and CategoricalCrossentropy both compute categorical cross-entropy. The only difference is in how the targets/labels should be encoded.</p>
<p>When using SparseCategoricalCrossentropy the targets are represented by the index of the category (starting from 0). Your outputs have shape 4x... | tensorflow|machine-learning|deep-learning|loss-function|cross-entropy | 30 |
376,125 | 59,521,480 | Extract Keras concatenated layer of 3 embedding layers, but it's an empty list | <p>I am constructing a Keras Classification model with Multiple Inputs (3 actually) to predict one single output. Specifically, my 3 <strong>inputs</strong> are:</p>
<ol>
<li>Actors</li>
<li>Plot Summary</li>
<li>Relevant Movie Features</li>
</ol>
<p><strong>Output:</strong></p>
<ol>
<li>Genre tags</li>
</ol>
<p><s... | <p>Concatenate layer does not have any weights (it does not have trainable parameter as you ca see from your model summary) hence your <code>get_weights()</code> output is coming empty. Concatenation is an operation.
<br>
For your case you can get weights of your individual embedding layers after training.</p>
<pre><c... | python|tensorflow|keras|nlp|word-embedding | 1 |
376,126 | 59,830,168 | layer Normalization in pytorch? | <p>shouldn't the layer normalization of <code>x = torch.tensor([[1.5,0,0,0,0]])</code> be <code>[[1.5,-0.5,-0.5,-0.5]]</code> ? according to this paper <a href="https://arxiv.org/pdf/1607.06450.pdf" rel="noreferrer">paper</a> and the equation from the <a href="https://pytorch.org/docs/stable/nn.html#layernorm" rel="nor... | <p>Yet another simplified implementation of a Layer Norm layer with bare PyTorch.</p>
<pre class="lang-py prettyprint-override"><code>from typing import Tuple
import torch
def layer_norm(
x: torch.Tensor, dim: Tuple[int], eps: float = 0.00001
) -> torch.Tensor:
mean = torch.mean(x, dim=dim, keepdim=True)
... | machine-learning|deep-learning|nlp|pytorch | 4 |
376,127 | 59,492,723 | How do I change a torch tensor to concat with another tensor | <p>I'm trying to concatenate a tensor of numerical data with the output tensor of a resnet-50 model. The output of that model is tensor shape <code>torch.Size([10,1000])</code> and the numerical data is tensor shape <code>torch.Size([10, 110528,8])</code> where the <code>10</code> is the batch size, <code>110528</code... | <p>Starting tensors.</p>
<pre><code>a = torch.randn(10, 1000)
b = torch.randn(10, 110528, 8)
</code></pre>
<p>New tensor to allow concatenate.</p>
<pre><code>c = torch.zeros(10,1000,7)
</code></pre>
<p>Check shapes.</p>
<pre><code>a[:,:,None].shape, c.shape
</code></pre>
<pre><code>(torch.Size([10, 1000, 1]), tor... | pytorch | 1 |
376,128 | 59,735,946 | Is there any problem in DataGenerator for 3D data? | <p>I tried to use DataGenerator for 3D data set. But I got some error.</p>
<p><img src="https://i.stack.imgur.com/gj8jh.png" alt="Error message"></p>
<p>class DataFeedGenerator(tf.keras.utils.Sequence):</p>
<pre><code>def __init__(self,x1,x2,y,batch_size=32, dim=(44,52,52,1), n_channels=1, n_classes=1, shuffle=True,... | <p>Does the error only occurs for the 208th batch?<br>
Considering your shapes and batch_size, the total number of batches should be 15000/32=468, since you have 245 as total number it means that you give a batch_size of 61? is that correct?<br>
Also, </p>
<pre class="lang-py prettyprint-override"><code>self.currentX1... | tensorflow|keras | 0 |
376,129 | 59,796,225 | combining three dataframes with matching timestamps and duration match | <p>Note: This question is some similar to the answered question here <a href="https://stackoverflow.com/questions/56980740/combining-three-different-timestamp-dataframes-using-duration-match">combining three different timestamp dataframes using duration match</a></p>
<p>I have two master and one slave data frame. The ... | <p>Is this what you are looking for?</p>
<pre><code>import pandas as pd
# create dataframes
mas_df1 = pd.DataFrame({'S1': [2202.517620, 2392.173558]}, index=pd.to_datetime(['2019-01-09 13:20:17', '2019-01-09 14:00:17']))
mas_df2 = pd.DataFrame({'S2': [2134.791454, 1958.719125]}, index=pd.to_datetime(['2019-01-09 13:2... | python|pandas|dataframe | 2 |
376,130 | 59,759,565 | Pandas error cannot convert String to Float setting a value at index | <p>that I know this was working for me last time I ran my script. but it looks like is not anymore. I have a scraping module which returns a dict, at my main script im running the <strong>scraping</strong> and assigning values . but now im getting this error about cannot convert a the string value to a float ( should i... | <p>Well guys, I did find the solution. doesn't look as elegant though .</p>
<pre><code>dataset = pd.read_csv(openFilename, delimiter = ',',encoding = my_encoding)
dataset['UserPhotoUrl'] = " "
dataset['PostPhotoUrl'] = " "
dataset.astype({'UserPhotoUrl': 'str'})
dataset.astype({'PostPhotoUrl': 'str'})
</code></pre>
<... | python|json|pandas|screen-scraping | 0 |
376,131 | 59,772,302 | How to return columns of dataframe held in dictionary | <p>I have a dictionary <code>dict</code> of dataframes <code>df1, df2, df3</code>, I want to return the columns of any dataframe (they are always the same)?</p>
<p>I want to use them as a graph titles, I've tried a few variantions of;</p>
<p><code>titles = dict.items(df1.columns)</code> </p>
<p>I know this is likely... | <pre class="lang-py prettyprint-override"><code># if you don't know dict keys
titles = dict_df[[*dict_df.keys()][0]].columns
# if you know dict keys you can use this
titles = dict_df['df1'].columns
</code></pre> | python|pandas | 1 |
376,132 | 59,815,840 | matplotlib plot line and bar chart together on same x-axis | <p>When I plot two pandas dfs together as two line charts, I get them on the same x-axis properly. When I plot one as a bar chart, however, the axis seems to be offset.</p>
<pre><code>ax = names_df.loc[:, name].plot(color='black')
living_df.loc[:, name].plot(figsize=(12, 8), ax=ax)
</code></pre>
<p>This works properl... | <p>Use <code>matplotlib</code> instead of calling the <code>plot</code> method of the pandas object:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
# Line plot
plt.plot(names_df.loc[:, name], color='black')
plt.plot(living_df.loc[:, name])
plt.show()
plt.close()
# Bar plot
plt.pl... | python|pandas|matplotlib | 1 |
376,133 | 59,609,829 | Weighted Pixel Wise Categorical Cross Entropy for Semantic Segmentation | <p>I have recently started learning about Semantic Segmentation. I am trying to train a UNet for the same. My input is RGB 128x128x3 images. My masks are made up of 4 classes 0, 1, 2, 3 and are One-Hot Encoded with dimension 128x128x4.</p>
<pre><code>def weighted_cce(y_true, y_pred):
weights = []
t_inf... | <p>You should have weights based on you entire data (unless your batch size is reasonably big so you have sort of stable weights).</p>
<p>If some class is underrepresented, with a small batch size, it will have near infinity weights. </p>
<p>If your target data is numpy array:</p>
<pre><code>shp = y_train.shape
tota... | tensorflow|keras|deep-learning|image-segmentation|semantic-segmentation | 0 |
376,134 | 59,775,640 | Python : How to find the count of empty cells in one column based on another column element wise? | <pre><code>df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'],
'income': [40000, np.nan, 42000, 50000, np.nan, np.nan, 30000]})
user income
0 Bob 40000.0
1 Jane NaN
2 Alice 42000.0
3 Jane 50000.0
4 Alice NaN
5 Bob NaN
6 Alice 30000.0... | <p>You can use the method <code>value_counts()</code>:</p>
<pre><code>df.loc[df['income'].isna(), 'user'].value_counts()
</code></pre>
<p>Output:</p>
<pre><code>Jane 1
Bob 1
Alice 1
Name: user, dtype: int64
</code></pre> | python|pandas|dataframe | 3 |
376,135 | 59,775,373 | How can i solve InvalidArgumentError: cycle_length must be > 0 when load tfrecords file | <p>I am starting out with build a efficient data pipeline of audio file using <code>tf.TFRecord and tf.Example</code>. But i get an error <code>tensorflow.python.framework.errors_impl.InvalidArgumentError</code> when i trying to load data from saved tfrecords file. I have been looking for a lot of solutions for this pr... | <p>i encountered similar problem, on tensorflow 2.0, however,upgrading to 2.1 solves the issue</p> | python|python-3.x|tensorflow|tfrecord|data-pipeline | 0 |
376,136 | 59,774,367 | How to split ' ; ' separated CSV file in pandas after using read_csv() in pandas? | <p><a href="https://i.stack.imgur.com/xZepu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZepu.png" alt="enter image description here"></a></p>
<p>I am trying to split the comma-separated column into 4 individual columns shown in the picture using split() but it's not working after importing CSV ... | <pre><code>df = pd.read_csv('nat2018.csv', sep=';')
</code></pre>
<p>Should work for you.</p> | python|pandas | 3 |
376,137 | 59,612,914 | Difference about "BinaryCrossentropy" and "binary_crossentropy" in tf.keras.losses? | <p>I'm training a model using TensorFlow 2.0 using tf.GradientTape(), but I find that the model's accuracy is <code>95%</code> if I use <code>tf.keras.losses.BinaryCrossentropy</code>, but degrade to <code>75%</code> if I use <code>tf.keras.losses.binary_crossentropy</code>. So I'm confused about the difference about ... | <p>They should indeed work the same; <a href="https://github.com/tensorflow/tensorflow/blob/8d40fa56169d08c6a9911242dfdf8ba74876673b/tensorflow/python/keras/losses.py#L371" rel="nofollow noreferrer"><code>BinaryCrossentropy</code></a> uses <a href="https://github.com/tensorflow/tensorflow/blob/8d40fa56169d08c6a9911242d... | python|tensorflow|tf.keras | 2 |
376,138 | 59,612,966 | Matching data frame rows based on opposite values of two columns? | <p>I am trying to perform a calculation on this table of movements between location codes, snippet below:</p>
<pre><code>origin destination age sex moves
E06000019 E06000019 98 m 0
E06000019 E06000019 99 f 0
E06000019 E06000019 99 m 0
E06000019 E06000019 100 f 0
E06000019 E06000019 ... | <p>You gave a bad example: the first 4 rows have the same <code>origin</code> and <code>destination</code> so they will inevitably match themselves.</p>
<p>Having said that, your problem can be solved with a self-join:</p>
<pre><code>df.merge(df, how='left', suffixes=('', '_'),
left_on=['origin', 'destinatio... | python|pandas | 0 |
376,139 | 59,597,242 | Pandas: Replace all values in column with column maximum | <p>I have the following dataframe</p>
<pre><code> NDQ CFRI NFFV [more columns....]
2002-01-24 92.11310000 57.78140000 90.95720000
2002-01-25 57.97080000 91.05430000 58.19820000
</code></pre>
<p>I want to set all values in a column equal to the maximum value of the respective column.</p... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.clip.html" rel="noreferrer"><code>df.clip</code></a> and set the <code>lower</code> param to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html" rel="noreferrer"><code>df.max</c... | python|pandas|dataframe | 7 |
376,140 | 59,529,080 | Pandas - Extract unique column combinations and count them in another table | <p><strong>TASK 1:</strong></p>
<p>I have table like this:</p>
<pre><code>+----------+------------+----------+------------+----------+------------+-------+
| a_name_0 | id_qname_0 | a_name_1 | id_qname_1 | a_name_2 | id_qname_2 | count |
+----------+------------+----------+------------+----------+------------+-------... | <p>You can remove <code>count</code> column and convert all rows to list of dicts by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>DataFrame.to_dict</code></a> with <code>orient='r'</code> (<code>records</code>) and then filter out dict... | python|pandas|dictionary | 3 |
376,141 | 59,714,963 | How to reshape my data as per model requirement? | <p>I have data which consist training as train_x and testing train_y. but major problem is that while fitting to model it shows error like.</p>
<p>Error when checking input: expected dense_12_input to have shape (8,) but got array with shape (13923,)</p>
<p>Training data shape is</p>
<pre><code>d=np.array(train_x)
d.sh... | <pre><code>classifier.add(Dense(3923, activation='relu', kernel_initializer='random_normal', input_dim=13923))
classifier.add(Dense(923, activation='relu', kernel_initializer='random_normal'))
classifier.add(Dense(23, activation='relu', kernel_initializer='random_normal'))
classifier.add(Dense(8, activation='sigmoid'... | python|tensorflow|machine-learning | 0 |
376,142 | 59,481,741 | Generating a random integer in a range while excluding a number in the given range | <p>I was going through the <a href="https://github.com/google-research/bert" rel="nofollow noreferrer">BERT</a> repo and found the following piece of code:</p>
<pre class="lang-py prettyprint-override"><code>for _ in range(10):
random_document_index = rng.randint(0, len(all_documents) - 1)
if random_document_i... | <p>Had <code>len(all_documents)</code> been small, a pretty solution would be to realize all valid numbers (e.g. in a <code>list</code>) and use <code>random.choice()</code>. Since your <code>len(all_documents)</code> is supposedly large, this solution will waste a lot of memory.</p>
<p>A more memory efficient solutio... | python|numpy|random | 2 |
376,143 | 59,803,949 | Concatenate Multiples CSV files in one dataframe | <p>I'm relatively new in python. Here is what I'd like to do. I got a folder with multiple csv files (<code>2018.csv</code>, <code>2017.csv</code>, <code>2016.csv</code>,... etc.), 500 CSV files to be precise. Each CSV file contains header "<code>date</code>", "<code>Code</code>", "<code>Cur</code>", "<code>Price</code... | <p>You can do the following:</p>
<pre><code>def clean_up(df):
df = df.iloc[:,[0,4,5,6]]
df.columns = ["date","Code","Cur","Price"]
df['Code'] = df['Code'].map(lambda x:x.lstrip('@').rstrip('@'))
df['Cur'] = df['Cur'].map(lambda x:x.lstrip('@').rstrip('@'))
df['date'] = df['date'].apply(lambda x:pd.... | python|pandas | 2 |
376,144 | 59,805,561 | Python using curve_fit to fit a logarithmic function | <p>I'm trying to fit a log curve using <code>curve_fit</code>, assuming it follows <code>Y=a*ln(X)+b</code>, but the fitted data still looks off.</p>
<p>Right now I'm using the following code: </p>
<pre><code>from scipy.optimize import curve_fit
X=[3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, 4.1, 4.2, 4.3,... | <p>The X data values sometimes need to be shifted a bit for this equation, and when I tried this it worked rather well. Here is a graphical Python fitter using your data and an X-shifted equation "y = a * ln(x + b)+c".</p>
<p><a href="https://i.stack.imgur.com/KxaDl.png" rel="noreferrer"><img src="https://i.stack.imgu... | python|numpy|matplotlib|curve-fitting|logarithm | 5 |
376,145 | 59,518,785 | numpy broadcasting to each column of the matrix separately | <p>I have to matrices:</p>
<pre><code>a = np.array([[6],[3],[4]])
b = np.array([1,10])
</code></pre>
<p>when I do:</p>
<pre><code>c = a * b
</code></pre>
<p>c looks like this:</p>
<pre><code>[ 6, 60]
[ 3, 30]
[ 4, 40]
</code></pre>
<p>which is good.
now, lets say I add a column to a (for the sake of the example ... | <p>One way is using <strong><code>numpy.einsum</code></strong>:</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>> a = np.array([[6],[3],[4]])
>>> b = np.array([1,10])
>>> print(a * b)
[[ 6 60]
[ 3 30]
[ 4 40]]
</code></pre>
<pre class="lang-py prettyp... | python|numpy|array-broadcasting | 1 |
376,146 | 59,662,420 | Pandas read csv skips some lines | <p>Following an old <a href="https://stackoverflow.com/questions/59090572/does-pandas-automatically-skip-rows-do-a-size-limit">question</a> of mine. I finally identified what happens.</p>
<p>I have a csv-file which has the sperator <code>\t</code> and reading it with the following command:</p>
<pre><code>df = pd.read... | <p>According to pandas documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html</a></p>
<blockquote>
<p>sep : str, default ‘,’
Delimiter to use. If sep is None, t... | python|pandas|csv | 1 |
376,147 | 59,716,875 | Remove quotation marks when printing data frame | <p>I have a data frame that consists of 2 columns (Main, Sub). I iterate through the data frame and print the results.</p>
<p>The second column, however, keeps having quotation marks, which is not ideal. </p>
<p>How do I remove them? I tried using <code>.strip("'")</code>, but nothing changed.</p>
<p><a href="https:... | <p>You have to convert dataframe object to string:</p>
<pre class="lang-py prettyprint-override"><code>row[1].str.strip("'")
</code></pre> | python|pandas|dataframe | 0 |
376,148 | 59,870,915 | Pandas : reshaping dataframe | <p>I have a dataframe which is currently looks like this,</p>
<p><a href="https://i.stack.imgur.com/aZfFe.png" rel="nofollow noreferrer">dataframe 1</a></p>
<p>I need to create a dataframe that looks like this.</p>
<p><a href="https://i.stack.imgur.com/vcUiN.png" rel="nofollow noreferrer">dataframe 2</a></p>
<p>I n... | <p>There is a similar question here :<a href="https://stackoverflow.com/questions/26255671/pandas-column-values-to-columns">Pandas column values to columns?</a>. See if their solutions with <code>.pivot_table</code> or <code>unstack</code> work for you.</p> | python|pandas|dataframe | 0 |
376,149 | 59,616,757 | Combine index header row and column header row in Pandas | <p>I create a dataframe and export to an html table. However the headers are off as below</p>
<p><strong>How can I combine the index name row, and the column name row?</strong></p>
<p>I want the table header to look like this:</p>
<p><a href="https://i.stack.imgur.com/sQdnl.png" rel="nofollow noreferrer"><img src="h... | <h3>Setup</h3>
<pre><code>import pandas as pd
from IPython.display import HTML
l0 = ('Foo', 'Bar')
l1 = ('One', 'Two')
ix = pd.MultiIndex.from_product([l0, l1], names=('L0', 'L1'))
df = pd.DataFrame(1, ix, [*'WXYZ'])
HTML(df.to_html())
</code></pre>
<p><a href="https://i.stack.imgur.com/bUDFS.png" rel="nofollow nor... | pandas|python-3.6 | 4 |
376,150 | 59,616,087 | Getting a strange error when attempting to subtract the minimum of a column from the entire column | <p>I'm getting a weird error when I attempt to subtract the min of a column in pandas from the column itself.</p>
<p>My code looks like this:</p>
<pre><code>self.portfolio.number = self.portfolio.number - self.portfolio.number.min()
</code></pre>
<p>The dataframe itself is member data of a class - not sure if this i... | <p>Ok I figured it out. Had to change my code to:</p>
<pre><code>self.portfolio.loc[:, 'number'] = self.portfolio['number'].sub(self.portfolio['number'].min())
</code></pre>
<p>This works but I'm not sure why. If someone could enlighten me I would hugely appreciate it.</p> | python|pandas | 0 |
376,151 | 59,618,058 | Percentage of events before and after a sequence of zeros in pandas rows | <p>I have a dataframe like the following:</p>
<pre><code> ID 0 1 2 3 4 5 6 7 8 ... 81 82 83 84 85 86 87 88 89 90 total
-----------------------------------------------------------------------------------------------------
0 A 2 21 0 18 3 0 0 0 2 ... 0 ... | <p>Give this a try:</p>
<pre><code>def percent_before(row, n, ncols):
"""Return the percentage of activities happen before
the first sequence of at least `n` consecutive 0s
"""
start_index, i, size = 0, 0, 0
for i in range(ncols):
if row[i] == 0:
# increase the size of the islan... | python|pandas|cumsum | 1 |
376,152 | 59,636,048 | How to create matrix from same column with relation between previous element in Pandas? | <p>I have a dataframe like this,</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> data = {
'user_id': [1, 1, 1, 2, 2, 3, 3, 4, 4, 4],
'movie_id': [0, 1, 2, 0, 1, 2, 3, 2, 3, 4]
}
>>> df = pd.DataFrame(data)
>>> df
user_id movie_id
0 ... | <p>You can do the following:</p>
<pre><code># add row_numbers as a column
df.reset_index(inplace=True)
# merge df on itself
df2 = df.merge(df, how='inner', on='user_id')
# remove some entries, keep only pairs where movie_id_x was liked before movie_id_y
df2 = df2[df2['index_x']<df2['index_y']].drop(['index_x','i... | python|pandas|dataframe | 2 |
376,153 | 59,654,229 | Remove all characters before a pipe and also remove pipe using regex in python | <p>Hi I'm at work and I'm working in pandas and trying to remove all characters before this pipe in this csv file. Also replacing semi colons with a pipe would also be very helpful.</p>
<pre><code>Size| Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge; 5xXlarge;
Size| Medium; Large; Xlarge; 2Xlarge; 3Xlarge; 4Xlarge;... | <p>You may use</p>
<pre><code>data['Variations'] = data['Variations'].str.replace(r'^[^|]*\|\s*|;\s*$', '').str.replace('\s*;\s*', '|')
</code></pre>
<p>The <code>.replace(r'^[^|]*\|\s*|;\s*$', '')</code> will remove all substrings from start of string till the first <code>|</code> including it and any subsequent whi... | python|regex|pandas|dataframe|e-commerce | 1 |
376,154 | 32,566,320 | Dealing with missing data in Pandas and Numpy | <p>I have the following data sample. I would like to </p>
<ul>
<li>a) in column C, <strong>replace the <code>np.NaN with 999</code></strong>, </li>
<li>b) in column D, <strong>place '' with <code>np.NaN</code></strong>.</li>
</ul>
<p>Neither of my attempts is working, and I am not sure why.</p>
<pre><code>import ... | <p>Those operations return a copy of the data (most of the pandas ops behave the same), they don't operate in place unless you explicitly say so (the default is <code>inplace=False</code>), see <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html#pandas.Series.fillna" rel="nofollow">... | python-2.7|numpy|pandas|missing-data | 3 |
376,155 | 32,203,293 | numpy.correlate vs numpy documentation - is there a contradiction here ? Why is the resulting list reversed ? | <p>I get the following result using numpy's correlate function:</p>
<pre><code>In [153]: np.correlate([1],np.arange(100))
Out[153]:
array([99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83,
82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66,
65, 64, 63, 62, 61, 60, 59, 58... | <p>Looks like you are expecting the <code>old_behaviour</code> of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html" rel="nofollow noreferrer"><code>numpy.correlate</code></a>. The book you link to is very old (2006), so it looks like <code>numpy.correlate</code> has changed since it was... | python|numpy|scipy|correlation | 6 |
376,156 | 32,447,900 | Reading and writing CSV files into a data structure suitable for Excel-style column/row manipulations | <p>So I am currently working on a web-application with a few other people for a client, and we've hit a stumbling block. Basically we need to be able to upload a CSV file in a specific layout - and the application will take that CSV file and based on specific columns and their values, it will perform the algorithm and ... | <p>Reading a <code>.csv</code> is easy with the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> standard library module.</p>
<p>A more efficient library that allows for better manipulation of <code>.csv</code> files is <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>, you shoul... | php|python|excel|csv|pandas | 0 |
376,157 | 32,298,047 | Efficient storage of large string column in pandas dataframe | <p>I have a large pandas dataframe with a string column that is highly skewed in size of the strings. Most of the rows have string of length < 20, but there are some rows whose string lengths are more than 2000.</p>
<p>I store this dataframe on disk using pandas.HDFStorage.append and set min_itemsize = 4000. Howeve... | <p>When using <code>HDFStore</code> to store strings, the maximum length of a string in the column is the width for that particular columns, this can be customized, see <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#string-columns" rel="nofollow">here</a>.</p>
<p>Several options are available to handle v... | python-2.7|pandas|hdf5 | 6 |
376,158 | 32,393,217 | numpy, return of array of indices in shape of | <p>I want to get the result of a list (or array) of indices from a numpy array, in the shape: ( len(indices), (shape of one indexing operation) ).</p>
<p>Is there any way to use a list of indices directly, without using a for loop, like I used in the mininal example, shown below?</p>
<pre><code>c = np.random.randint(... | <p>Your example can be rewritten as a list comprehension:</p>
<pre><code>In [121]: [c[idx] for idx in indices]
Out[121]:
[array([4, 2, 1, 2]),
array([3, 2, 2, 3]),
array([3, 2, 2, 3]),
array([0, 3, 4, 4])]
</code></pre>
<p>which can be turned into a nice 2d array:</p>
<pre><code>In [122]: np.array([c[idx] for id... | python|arrays|numpy|matrix-indexing | 0 |
376,159 | 32,221,946 | Numpy matrix of arrays without copying possible? | <p>I got a question about numpy and it's memory. Is it possible to generate a view or something out of multiple numpy arrays without copying them?</p>
<pre><code> import numpy as np
def test_var_args(*inputData):
dataArray = np.array(inputData)
print np.may_share_memory(inputData, dataArray) # ... | <p>There's a useful discussion in the answer here: <a href="https://stackoverflow.com/questions/45943160/can-memmap-pandas-series-what-about-a-dataframe">Can memmap pandas series. What about a dataframe?</a></p>
<p>In short:</p>
<ul>
<li>If you initialize your DataFrame from a single array of matrix, then it may not ... | python|c++|arrays|numpy | 0 |
376,160 | 40,777,201 | Is this a good log loss for multiclass regression? | <p>I have multiple classes to predict at once, so I see the problem as a non-linear regression on the binary labels/classes I have as true output. </p>
<p>That said, the loss function is a sum of the log losses of every label which is then averaged for each example in the batch. Here is my loss function: </p>
<pre><c... | <p>You can use a loss that is already implemented for multiclass logistic regression instead of your loss: <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/nn.html#sigmoid_cross_entropy_with_logits" rel="nofollow noreferrer">sigmoid_cross_entropy_with_logits</a>. It was carefully designed to avoid num... | machine-learning|tensorflow|classification|regression|deep-learning | 1 |
376,161 | 40,613,850 | Conditional data selection with text string data in pandas dataframe | <p>I've looked but seem to be coming up dry for an answer to the following question. </p>
<p>I have a pandas dataframe analogous to this (call it 'df'):</p>
<pre><code> Type Set
1 theGreen Z
2 andGreen Z
3 yellowRed X
4 roadRed ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="noreferrer"><code>str.contains</code></a>:</p>
<pre><code>df['color'] = np.where(df['Type'].str.contains('Green'), 1, 0)
print (df)
Type Set color
1 theGreen Z 1
2 andGreen Z 1
3 yell... | python|string|pandas|numpy|dataframe | 7 |
376,162 | 40,340,131 | Debugging python tests in TensorFlow | <p>We want to debug Python tests in TensorFlow such as <em>sparse_split_op_test</em> and <em>string_to_hash_bucket_op_test</em> </p>
<p>The other c++ tests we could debug using gdb, however we cannot find a way to debug python tests.</p>
<p>Is there a way in which we can debug specific python test case run via Bazel ... | <p>I would first build the test:</p>
<pre><code>bazel build //tensorflow/python/kernel_tests:sparse_split_op_test
</code></pre>
<p>Then use pdb on the resulting Python binary:</p>
<pre><code>pdb bazel-bin/tensorflow/python/kernel_tests/sparse_split_op_test
</code></pre>
<p>That seems to work for me stepping through... | python|tensorflow | 3 |
376,163 | 40,335,140 | How to highlight both a row and a column at once in pandas | <p>I can highlight a column using the syntax </p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,0],[0,1]])
df.style.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x])
</code></pre>
<p><a href="https://i.stack.imgur.com/TGnFb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TG... | <p>How about doing something like this? Enumerate the column and check the index while building up the style list:</p>
<pre><code>df.style.apply(lambda x: ['background: lightblue' if x.name == 0 or i == 0 else ''
for i,_ in x.iteritems()])
</code></pre>
<p><a href="https://i.stack.imgur.com... | python|pandas | 13 |
376,164 | 40,651,005 | python pandas columns contain dict | <p>I got some trouble.</p>
<pre><code>import pandas
df=pandas.DataFrame([[{'a':1,'b':2},3,3],[{'a':2,'b':4},6,5]],columns=['c1','c2','c3'])
print df
c1 c2 c3
0 {u'a': 1, u'b': 2} 3 3
1 {u'a': 2, u'b': 4} 6 5
</code></pre>
<p>I want to get the result like this:</p>
<pre><code> b c3
... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <code>df1</code> created with <code>DataFrame</code> constructor - first convert column <code>c1</code> to <code>numpy array</code> by <a href="http://pandas.pydata.or... | python|pandas|dictionary | 3 |
376,165 | 40,576,876 | Efficient Haskell equivalent to NumPy's argsort | <p>Is there a standard Haskell equivalent to NumPy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>argsort</code></a> function?</p>
<p>I'm using <a href="http://hackage.haskell.org/package/hmatrix" rel="nofollow noreferrer">HMatrix</a> and, so, would ... | <p>Use <a href="http://hackage.haskell.org/package/vector-algorithms" rel="noreferrer">vector-algorithms</a>:</p>
<pre class="lang-hs prettyprint-override"><code>import Data.Ord (comparing)
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Algorithms.Intro as VAlgo
argSort :: (Ord a, VU.Unbox... | haskell|numpy|hmatrix | 5 |
376,166 | 40,603,278 | Running SyntaxNet with designated instance (in Python-level) | <p>Could you please let me know how I designate which instance to use when training/testing SyntaxNet?</p>
<p>In other tensorflow models we can easily change configurations by editing Python code:</p>
<p>ex) <code>tf.device('/cpu:0')</code> => <code>tf.device('/gpu:0')</code>.</p>
<p>I could run parsey mcparseface m... | <p>You can refer to this page for instructions on running syntax net on GPU: <a href="https://github.com/tensorflow/models/issues/248" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/248</a></p>
<p>Tensorflow would automatically assign devices including GPU to the ops: <a href="https://www.tensor... | python|nlp|tensorflow|gpu|syntaxnet | 0 |
376,167 | 40,495,732 | Creating an RGB composite SAR image | <p>I am quite new at Python programming and I need your help. I always do a research for my problem first before posting.</p>
<p>I have SAR dual polarization image (2^16 gray level values) in tiff format. In this tiff image there are two bands. The first band (HH_band) is a horizontal polarization channel and the seco... | <p>Here is a possible way to accomplish the band composition programmatically:</p>
<pre><code>import numpy as np
tif = io.imread('dual_polarization_image.tif')
band = {'HH': 0, 'HV': 1}
r = tif[:, :, band['HH']]
g = tif[:, :, band['HV']]
hh = r.astype(np.float64)
hv = g.astype(np.float64)
b = np.divide(hh, hv, ou... | python|opencv|numpy|image-processing|tiff | 3 |
376,168 | 40,642,295 | Timeseries charts with Bokeh | <p>Hi I am trying to create a timeseries chart using Bokeh.
The data I have looks like this, 2 columns one for the timestamp which is effectively the current time, the value and the sensor that provided the value</p>
<p>Time | Value | Sensor</p>
<p>2011-05-03 17:45:35.177000 | 213.130005... | <p>1) You don't <em>have</em> to use pandas, but this route makes it much easier.
<br/>
2) You can parse the <em>time</em> feature by just using pandas' <code>to_datetime()</code> function (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">pandas docs refe... | pandas|bokeh | 1 |
376,169 | 40,472,912 | hdf5 file to pandas dataframe | <p>I downloaded a dataset which is stored in .h5 files.
I need to keep only certain columns and to be able to manipulate the data in it.</p>
<p>To do this, I tried to load it in a pandas dataframe. I've tried to use:</p>
<pre><code>pd.read_hdf(path)
</code></pre>
<p>But I get: <code>No dataset in HDF5 file.</code></... | <p>Easiest way to read them into Pandas is to convert into <code>h5py</code>, then <code>np.array</code>, and then into <code>DataFrame</code>. It would look something like: </p>
<pre><code>df = pd.DataFrame(np.array(h5py.File(path)['variable_1']))
</code></pre> | python|pandas|hdf5 | 12 |
376,170 | 40,454,713 | python pandas dataframe to_sql converting an object to Mysql INT datatype yields incorrect results | <p>I am trying to read a csv file into a Pandas dataframe and insert the final dataframe into Mysql using pandas.to_sql function.</p>
<p>All the columns are inserting the correct data except for one column in dataframe which has a length of 25 characters. This column (transaction_id) is defined as a INT(25) in MYSQL a... | <p>Apparently, the issue stems from MySQL. My transaction id, having a length of 25, was big for BIGINT. I have to convert it to VARCHAR(25) to get the right value in the table. Thanks @MaxU for improving my code. </p> | python|mysql|pandas|dataframe | 0 |
376,171 | 40,754,040 | I am getting error KeyError: 'duration' when it exists | <p>The following code returns error </p>
<pre><code>KeyError: 'duration'
for i in range(0, 3):
exam_df['duration'] = pd.to_datetime(i,(exam_df['Duration '])[i])
exam_df['grade'] = exam_df['Grade'].astype(np.int64)
exam_df.plot.scatter(x='duration', y='grade')
</code></pre> | <p>I think that you misspelled the key 'duration', try to change:</p>
<pre><code>exam_df['duration'] = pd.to_datetime(i,(exam_df['Duration '])[i])
</code></pre>
<p>With:</p>
<pre><code>exam_df['duration'] = pd.to_datetime(i,(exam_df['duration'])[i])
</code></pre> | python|pandas | 3 |
376,172 | 40,473,299 | How to save out in a new column the url which is reading pandas read_html() function? | <p>I am interested in extracting some tables from a website, I defined a list of links where the tables live in. Each link has a several tables with the same number of columns. So, I am extracting all the tables from the list of links into a single table with pandas <a href="http://pandas.pydata.org/pandas-docs/stable/... | <p>This should do the trick:</p>
<pre><code>def process_url(link):
return pd.concat(pd.read_html(link), ignore_index=False).assign(link=link)
</code></pre>
<p>Explanation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer">DataFrame.assign(new_co... | python|python-3.x|pandas|dataframe|beautifulsoup | 2 |
376,173 | 40,705,480 | Python pandas: remove everything after a delimiter in a string | <p>I have data frames which contain e.g.:</p>
<pre><code>"vendor a::ProductA"
"vendor b::ProductA"
"vendor a::Productb"
</code></pre>
<p>I need to remove everything (and including) the two :: so that I end up with:</p>
<pre><code>"vendor a"
"vendor b"
"vendor a&quo... | <p>You can use <code>pandas.Series.str.split</code> just like you would use <code>split</code> normally. Just split on the string <code>'::'</code>, and index the list that's created from the <code>split</code> method:</p>
<pre><code>>>> df = pd.DataFrame({'text': ["vendor a::ProductA", "vendor b::ProductA", ... | python|python-3.x|pandas | 106 |
376,174 | 40,519,046 | Insert dataframe into postgresql sqlalchemy with idx autoincrement | <p>I'm <code>requests.get()</code> to get some json. After that, I want to insert the data into postgresql. Something very interesting is happening, if I use the <code>df.to_sql(index=False)</code>, the data gets appended into postgresql with no problem, but the Id in postgresql is not creating the autoincrement value;... | <p>One way (among many) to do this would be:</p>
<p>to fetch maximum <code>Id</code> and store it to a variable (let's call it <code>max_id</code>):</p>
<pre><code>select max(Id) from quotes;
</code></pre>
<p>now we can do this:</p>
<p>Original DF:</p>
<pre><code>In [55]: quote_df
Out[55]:
Adj_Close Cl... | python|postgresql|pandas|sqlalchemy | 0 |
376,175 | 40,739,585 | Error in scikit code | <p>I am new to Machine Learning and am trying the <a href="https://www.kaggle.com/c/titanic/" rel="nofollow noreferrer">titanic problem</a> from Kaggle. I have written the attached code that uses decision tree to do computations on data. There is an error that I am unable to remove.</p>
<p>Code :</p>
<pre><code>#!/us... | <p>Try each feature one by one and you will probably find one of them has some nulls. I note you do not check if sex has nulls.</p>
<p>Also by coding each categoric variable manually it would be easy to make an error perhaps by misspelling one of the categories. Instead you can use df=pd.get_dummies(df) and it will au... | python|numpy|scikit-learn | 1 |
376,176 | 40,717,105 | Why do I need lambda to apply functions to a Pandas Dataframe? | <p>I have a Pandas data frame and am attempting to pass a function over the entries in one column using the apply() function.</p>
<p>My function is of the form:</p>
<pre><code>def foo(Y):
#accepts a pandas data frame
#carries out some search on the text in each row of the dataframe
#groups successful sear... | <p>The lambda is unnecessary, you can just do </p>
<pre><code>df['SR'] = df['Info'].apply(foo)
</code></pre>
<p>here it will still work</p> | python|pandas|lambda|apply | 3 |
376,177 | 40,420,240 | Grouped Bar graph Pandas | <p>I have a table in a pandas <code>DataFrame</code> named <code>df</code>:</p>
<pre><code>+--- -----+------------+-------------+----------+------------+-----------+
|avg_views| avg_orders | max_views |max_orders| min_views |min_orders |
+---------+------------+-------------+----------+------------+-----------+
| 2... | <p>Using pandas:</p>
<pre><code>import pandas as pd
groups = [[23,135,3], [123,500,1]]
group_labels = ['views', 'orders']
# Convert data to pandas DataFrame.
df = pd.DataFrame(groups, index=group_labels).T
# Plot.
pd.concat(
[df.mean().rename('average'), df.min().rename('min'),
df.max().rename('max')],
... | python|pandas|matplotlib | 34 |
376,178 | 40,555,477 | Unable to install GPU enabled TensorFlow | <p>To install TensorFlow with GPU on an Ubuntu system, I installed CUDA v 8.0 using "cuda-repo-ubuntu1404_8.0.44-1_amd64.deb" and cuDNN using "cudnn-8.0-linux-x64-v5.1", however, on uncompressing the file and copying them into CUDA toolkit the following files are added to the /usr/local/cuda/lib64 folder:</p>
<pre><co... | <p>This might be because of multiple versions of CUDA installed in your system.
Remove all the CUDA versions using <code>sudo apt-get purge cuda-.</code>
Install the CUDA 8.0.</p>
<p>Download the CUDA toolkit from this <a href="https://developer.nvidia.com/cuda-downloads?target_os=Linux" rel="nofollow noreferrer">link<... | tensorflow|gpu | 0 |
376,179 | 18,475,651 | Download future price series from Yahoo! with Pandas | <p>That's strange, I have been unable to download future price series from Yahoo! with panda.</p>
<p>Take this snippet which is supposed to download prices for CBoT corn Sept-13 :</p>
<pre><code>import pandas.io.data as fetch
ts = fetch.get_data_yahoo('CU13.CBT', '8/8/2013', '10/8/2013')
print(ts)
</code></pre>
<p>I... | <p>It is not a pandas problem, historical data for <strong>CU13.CBT</strong> is not available, you can check that <a href="http://finance.yahoo.com/q?s=CU13.CBT&ql=1" rel="nofollow noreferrer">here</a> you wont find the link to historical prices (compare with <a href="http://finance.yahoo.com/q?s=F&ql=1" rel="n... | python|pandas|yahoo|finance | 4 |
376,180 | 18,334,121 | Numpy array: concatenate arrays and integers | <p>In my Python program I concatenate several integers and an array. It would be intuitive if this would work:</p>
<pre><code>x,y,z = 1,2,np.array([3,3,3])
np.concatenate((x,y,z))
</code></pre>
<p>However, instead all ints have to be converted to np.arrays:</p>
<pre><code>x,y,z = 1,2,np.array([3,3,3])
np.concatenate... | <p>They just have to be sequence objects, not necessarily numpy arrays:</p>
<pre><code>x,y,z = 1,2,np.array([3,3,3])
np.concatenate(([x],[y],z))
# array([1, 2, 3, 4, 5])
</code></pre>
<p>Numpy also does have an <code>insert</code> function that will do this:</p>
<pre><code>x,y,z = 1,2,np.array([3,3,3])
np.insert(z, ... | python|arrays|numpy|integer|concatenation | 6 |
376,181 | 18,722,296 | How to count the frequency of an element in an ndarray | <p>I have a numpy ndarray of strings and want to find out how often a certain word appears in the array. I found out this solution:</p>
<pre><code>letters = numpy.array([["a","b"],["c","a"]])
print (numpy.count_nonzero(letters=="a"))
</code></pre>
<blockquote>
<p>-->2</p>
</blockquote>
<p>I'm just wondering if i s... | <p>You can also use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="noreferrer"><code>sum</code></a>:</p>
<pre><code>>>> letters = numpy.array([["a","b"],["c","a"]])
>>> (letters == 'a').sum()
2
>>> numpy.sum(letters == 'a')
2
</code></pre> | python|numpy|count|element|multidimensional-array | 5 |
376,182 | 18,287,806 | Numpy way to determine the value(s) in an array which is causing a high variance | <p>Is there a numpy way to determine the value(s) in an array which is causing a high variance?</p>
<p>Consider the set of numbers</p>
<pre><code>array([164, 202, 164, 164, 164, 166], dtype=uint16)
</code></pre>
<p>A quick scan reveals, 202 would cause a high variance which if I remove from the list would reduce the... | <p>Suppose this is your data:</p>
<pre><code>In [19]: import numpy as np
In [167]: x = np.array([164, 202, 164, 164, 164, 166], dtype=np.uint16)
</code></pre>
<p>Here is a boolean array indicating which values in <code>x</code> are more than 1 standard deviation away from the mean:</p>
<pre><code>In [170]: abs(x-x.m... | python|numpy | 5 |
376,183 | 18,290,123 | disable index pandas data frame | <p>How can I drop or disable the indices in a pandas Data Frame?</p>
<p>I am learning the pandas from the book "python for data analysis" and I already know I can use the dataframe.drop to drop one column or one row. But I did not find anything about disabling the all the indices in place.</p> | <p><code>df.values</code> gives you the raw NumPy <code>ndarray</code> without the indexes.</p>
<pre><code>>>> df
x y
0 4 GE
1 1 RE
2 1 AE
3 4 CD
>>> df.values
array([[4, 'GE'],
[1, 'RE'],
[1, 'AE'],
[4, 'CD']], dtype=object)
</code></pre>
<p>You cannot have a DataF... | python|pandas | 19 |
376,184 | 61,994,759 | ResNet152 - High Training Accuracy but Failed to Classify Binary Labels | <p>I am working on the Skin Cancer Images available in <a href="https://www.kaggle.com/fanconic/skin-cancer-malignant-vs-benign" rel="nofollow noreferrer">Kaggle</a> for my mini-project. I am trying to use different CNN models for comparison. Both VGG16 and VGG19 work on the data and yield acceptable results with >90... | <p>I think the problem, i.e. why VGG works while ResNet doesn't, is caused by the keras <code>BatchNormalization</code> layer. Long story in short, because of the domain gap between the ImageNet dataset and your own dataset, the pretrained BatchNormalization parameters don't reflect the actual batch statistics of your ... | python|tensorflow|keras|resnet|vgg-net | 1 |
376,185 | 61,658,267 | How to map data within Pandas DataFrame w.r.t index and column from another DataFrame | <p>Let's say I have two DataFrames as below :</p>
<p><strong>DF1:</strong></p>
<pre><code>from datetime import date, timedelta
import pandas as pd
import numpy as np
sdate = date(2019,1,1) # start date
edate = date(2019,1,7) # end date
required_dates = pd.date_range(sdate,edate-timedelta(days=1),freq='d')
# initia... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a> with <code>max</code> for indicators (always <code>0, 1</code>) or <code>sum</code> if want count values:</p>
<pre><code>df = pd.get_dummies(df1.set_index('OnlyDate'... | pandas|dataframe|dictionary|time-series | 1 |
376,186 | 61,935,177 | value of years on X axis is not displaying correctly | <p>value of years on X axis is not displaying correctly . it is displaying years in two parts but I want it as single value</p>
<p>here is what I have tried<a href="https://i.stack.imgur.com/QywOL.jpg" rel="nofollow noreferrer">pandas</a></p>
<p><a href="https://i.stack.imgur.com/M2cpl.jpg" rel="nofollow noreferrer">... | <p>You can convert year to date format and plot. Eg.:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame({"year" : [2010,2011,2012,2013,2014],
"count" :[1000,2200,3890,5600,8000] })
data["year"] = pd.to_datetime(data["year"].astype(str), format="%Y")
ax = data... | python-3.x|pandas | 0 |
376,187 | 61,772,146 | How to convert a dataframe into datetime format | <p>I have this dataframe: </p>
<pre><code>3_21_19_59
1
4
22
25
28
31
34
37
.
.
.
.
</code></pre>
<p>It has 410 rows. </p>
<p>Here in <code>3_21_19_59</code>: <code>3</code> indicates month, <code>21</code> indicates date, <code>19</code> is hours and <code>59</code> is minutes. The numbers in the rows below that: <c... | <p>First convert datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with format and <code>errors='coerce'</code> parameter, so missing values for not matched values. Then forward fillinf them for repating <code>... | python-3.x|pandas|data-science|datetime-format | 1 |
376,188 | 61,709,168 | How to map dictionary values to data frame column which has values as lists | <p>I have a data frame as:</p>
<pre><code>df = pd.DataFrame(
{'title':['a1','a2','a3','a4','a5'],
'genre_name':[
['family', 'animation'],
['action', 'family', 'comedy'],
['family', 'comedy'],
['horror','action'],
['family', 'animation','comedy']]}
)
df
title... | <p>Change dictionary name from <code>dict</code> to some another variable, because builtins (python code word), then swap keys with values and map values in list comprehenesion:</p>
<pre><code>d={'1':'family','2':'animation','3':'action','4':'comedy','5':'horror'}
d1 = {v:k for k, v in d.items()}
df['genre_ids'] = df... | python|pandas|dataframe|dictionary | 9 |
376,189 | 61,657,519 | Dataframe with two index columns - reset to one index column | <p>I have a data-frame <code>df1</code> that looks like:</p>
<pre><code> col2 col3
date dept
2020-05-07 A 29 21
2020-05-08 B 56 12
2020-05-09 C 82 15
2020-05-10 D 13 9
2020-05-11 E 35 13
2020-05-12 F 53 87
2020-05-13 G 25 ... | <p>Here is necessary select column(s) or position(s) for converting to columns:</p>
<pre><code>#convert dept to columns
df1 = df1.reset_index(level='dept')
#convert date to columns
#df1 = df1.reset_index('date')
</code></pre>
<p>Or:</p>
<pre><code>df1 = df1.reset_index(level=1)
</code></pre> | python|pandas | 1 |
376,190 | 62,032,932 | How to split pandas record with one large timedelta into multiple records with smaller ones? | <p>I have a dataframe with 3 columns: timedeltas (duration) of time slot, datetime of slot start and datetime informing when record was created. Timedeltas are all multipliers of 15 minutes:</p>
<pre><code>Index duration slot_start creation_time
1. 15 minutes some datetime 1 some datetime 3
2.... | <p>Try this:</p>
<pre><code>unit = pd.Timedelta(minutes=15)
s = pd.to_timedelta(df['duration']).div(unit) \
.apply(lambda n: unit * np.arange(n)) \
.rename('offset') \
.explode()
df = df.join(s)
df['slot_start'] = df['slot_start'] + df['offset']
</code></pre> | python|pandas | 1 |
376,191 | 61,614,935 | Trying to extract data from JSON URL into Pandas | <p>I am trying to extract data from a JSON URL into pandas but this file has multiple "layers" of lists and dictionaries which i just cannot seem to navigate.</p>
<pre><code>import json
from urllib.request import urlopen
with urlopen('https://statdata.pgatour.com/r/010/2020/player_stats.json') as response:
source... | <p>You are missing a layer.</p>
<p>To simplify the data, we are trying to access:</p>
<pre><code>"stats": [{
"statId":"106",
"name":"Eagles",
"tValue":"0",
}]
</code></pre>
<p>The data of 'stats' starts with <code>[{</code>. This is a dictionary within an array. </p>
<p>I <em>think</em> this should work... | python|arrays|json|pandas | 1 |
376,192 | 61,631,553 | How to handle memory errors with adjacency matrix? | <p>I am doing graph clustering with python. The algorithm requires that the data passed from graph <code>G</code> should be adjacency-matrix. However, in order to get <code>adjacency-matrix</code> as <code>numpy-array</code> like this:</p>
<pre><code>import networkx as nx
matrix = nx.to_numpy_matrix(G)
</code></pre>
... | <p>The matrix you are trying to create is of size <code>609627x609627</code> of float64. With each float64 using 8 bytes of memory, you will need <code>609627*609627*8~3TB</code> memory. Well your system has only 8GB and even with added physical memory, 3TB seems too large to operate. Assuming your node ids are integer... | python|pandas|numpy|cluster-analysis|networkx | 2 |
376,193 | 61,996,588 | Is there any way to access layers in tensorflow_hub.KerasLayer object? | <p>I am trying to use a pre-trained model from tensorflow hub into my object detection model. I wrapped a model from hub as a KerasLayer object following the official instruction. Then I realized that <strong>I cannot access the layers in this pre-trained model</strong>. But I need to use outputs from some specific lay... | <p>There is an undocumented way to get intermediate layers out of some TF2 SavedModels exported from TF-Slim, such as <a href="https://tfhub.dev/google/imagenet/inception_v1/feature_vector/4" rel="nofollow noreferrer">https://tfhub.dev/google/imagenet/inception_v1/feature_vector/4</a>: passing <code>return_endpoints=Tr... | tensorflow|keras|tensorflow-hub | 2 |
376,194 | 61,951,626 | Pandas: calculation of the number of days when the sum of the durations on that day was more than 30 minutes | <p>Here is a sample source:</p>
<pre><code>ID Date Duration
111 2020-01-01 00:42:23
111 2020-01-01 00:23:23
111 2020-01-02 00:37:22
222 2020-01-02 00:13:08
222 2020-01-03 01:52:11
....
999 2020-01-31 00:15:21
999 2020-01-31 ... | <p>Try this,</p>
<pre><code>df['_duration'] = pd.to_datetime(df['Duration'], format="%H:%M:%S").dt.hour
df_g = df.groupby('id')['_duration'].sum().reset_index()
# this should yield greater than 30.
df_g = df_g[df_g['_duration'] > 30]
</code></pre>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/referenc... | python|pandas | 0 |
376,195 | 61,817,378 | Count regex matches in one column by values in another column with pandas | <p>I am working with pandas and have a dataframe that contains a list of sentences and people who said them, like this:</p>
<pre><code> sentence person
'hello world' Matt
'cake, delicious cake!' Matt
'lovely day' Maria
'i like cake' Matt
'a new day' ... | <p>since this primarily involves strings, I would suggest taking the computation out of Pandas - Python is faster than Pandas in most cases when it comes to string manipulation : </p>
<pre><code>#read in data
df = pd.read_clipboard(sep='\s{2,}', engine='python')
#create a dictionary of persons and sentences :
from c... | python|regex|pandas|dataframe | 0 |
376,196 | 61,836,221 | In which form should the input and the label data be needed into Keras fit function? | <p>I am trying to train a sequential classifier, with 1 input neuron, 3 output neurons. The data is in data frames <code>X</code> and <code>Y</code>, but how must I feed this data into <code>fit</code> function in <code>keras</code> library? In other words, what should be the variable type of <code>train_x</code> and <... | <p>The variable type for <code>fit</code> should be of vector, matrix, or array.</p>
<p>As per the <a href="https://keras.rstudio.com/reference/fit.html" rel="nofollow noreferrer">documentation</a>, it states below,</p>
<blockquote>
<p>x -
Vector, matrix, or array of training data (or list if the model has multip... | r|tensorflow|keras|deep-learning|neural-network | 1 |
376,197 | 61,842,615 | No such file or directory exists Error from server request | <p>Actually my flask app runs fine in local host but after deploying it to server,I used pythonanywhere to deploy my flask web app it got some errors.
My motive is to send a path of a file from input and python takes the path and uses to locate the file and perform some operations on the data(excel file),if works good ... | <p>Your Flask code only has access to files that are stored on the machine where it is running; when you run it locally, it has access to files on your local machine, but if you run it on a server like PythonAnywhere, it will only have access to files that are stored on that server. If you want people to be able to sp... | python|pandas|file|flask|xlrd | 1 |
376,198 | 61,681,307 | Loc filter and exclude null values | <pre><code>1. vat.loc[(vat['Sum of VAT'].isin([np.nan, 0])) &
2. (vat['Comment'] == "Transactions 0DKK") &
3. (vat['Type'].isin(['Bill', 'Bill Credit'])) &
4. (vat['Maximum of Linked Invoice'].notnull()), 'Comment'] = 'Linked invoice'
5. vat[vat["Comment"] == "Linked invoice"]
</code></... | <p>If anyone is reading this then I have found an answer. There is nothing wrong with my syntax, but the problem lies with the CSV file itself. The reason why pandas read the column 'Maximum of Linked Invoice' as 62107 non-null, is because there was a space embedded within each row in that column. The only thing I saw ... | python|python-3.x|pandas|filter|pandas-loc | 0 |
376,199 | 61,812,567 | How to remove wrong values in the pandas dataframe? | <p>I have a dataframe which has multiple columns and I am interested to take one column out of it and create a new dataframe with that column.
My dataframe is</p>
<pre><code>category_id category_name channel_id
24 Entertainment UCv1ZjbkebUwVOJCgtstOBZQ
</code></pre>
<p>I am creating a new dataframe as want the c... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.repeat.html" rel="nofollow noreferrer"><code>Series.repeat</code></a>:</p>
<pre><code>print (df)
category_id category_name channel_id
0 10 Entertainment UCv1ZjbkebUwVOJCgtstOBZQ
1 ... | python|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.