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 |
|---|---|---|---|---|---|---|
357,700 | 60,126,470 | How can I concatenate dynamic values with the flatten vector in CNN | <p>I'm trying to increase the accuracy of CNN by computing some dynamic values such as Hu moments of the images during the training phase and then feed them to the fully connected layer with the flatten vector as shown in the image of my model:</p>
<p><a href="https://i.stack.imgur.com/LF7uO.png" rel="nofollow norefer... | <p>Hmm I don't know what the Hu moments and the Extend and Soidty are, but I'm assuming they're 1dimensional:</p>
<pre><code># image = tf.Tensor
@tf.function
def calc_hu(image):
""" calculate hu """
hu = ...
return hu
class HuLayer(tf.keras.layers.Layer):
def call(self, inputs):
return calc_hu(inp... | python|tensorflow|keras|deep-learning|conv-neural-network | 1 |
357,701 | 59,915,618 | How to read a csv containing english and thailand charecters in pandas python | <p>I am not able to split the columns properly when I am reading the CSV file containing data in thai characters and English characters in pandas read_csv.</p>
<pre><code>import pandas as pd
df=pd.read_csv("test.csv",delimeter=";")
</code></pre> | <p>You are trying to read a file with a different <a href="https://en.wikipedia.org/wiki/Character_encoding" rel="nofollow noreferrer">encoding</a> than the western standard, <em>UTF-8</em>. You should specify the encoding of the text of the file you are trying to read. In your case this is <em>TIS-620</em>. Each langu... | python|pandas|csv | 0 |
357,702 | 60,288,808 | Get Start and Stop Values For Incrementing Groups in NumPy Vector | <p>I have a NumPy vector that is sorted and contains no repeats like:</p>
<pre><code>[ 1, 2, 6, 12, 13, 14, 16, 18, 19, 22, 23, 26, 29,
31, 32, 34, 37, 38, 39, 40, 42, 43, 44, 49, 50, 52,
55, 63, 64, 67, 68, 75, 78, 82, 84, 86, 88, 90, 93,
95, 97, 98, 100, 103, 104, 106, ... | <p>If your input is called <code>x</code>:</p>
<pre><code>r = np.full(len(x),2)
d = np.diff(x)==1
r[1:]-=d
r[:-1]-=d
np.repeat(x,r).reshape(-1,2)
</code></pre>
<p>Output:</p>
<pre><code>array([[ 1, 2],
[ 6, 6],
[ 12, 14],
[ 16, 16],
...
</code></pre>
<p>This works by repeating each ite... | python|numpy | 2 |
357,703 | 60,169,100 | Is it possible to implement this version of matrix multiplication using Numpy? | <p>I am looking to quickly evaluate the function below, which at a high level resembles matrix multiplication. For large matrices, the below implementation is orders of magnitude slower than numpy multiplication of the matrices, leading me to believe there is better way to implement this using numpy. Is there any way t... | <p>Since <code>log(a) + log(b) == log(a * b)</code>, you can save a lot of logarithm computations by replacing the additions by multiplications and doing the logarithm only at the end, which should save you a lot of time.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import numba as nb
@nb.nj... | python|arrays|numpy|matrix-multiplication|numba | 2 |
357,704 | 60,284,470 | Reading binary data file in python for analysis | <p>I use Fortran to write data to a binary file in the following format</p>
<pre><code>open(unit=99,form='unformatted',status='unknown')
do i=1,N
write(99) (i),(A(i)),(B(i))
enddo
close(99)
</code></pre>
<p>Here, <strong>A</strong> and <strong>B</strong> are double precision arrays.
How can this binary data file be r... | <p><strong>Updated Answer</strong></p>
<p>I played around with this some more in Numpy and you can read the file much more cleanly like this - the information below still applies and explains how it works:</p>
<pre><code>import numpy as np
# Read file and reshape as "records" of 28 bytes each
n = np.fromfile('fort.9... | python|numpy|fortran|binary-data | 5 |
357,705 | 60,120,476 | Find sum of all the records for a specific index name in a panda pivot table dataframe | <p>I have panda pivot table dataframe like below:</p>
<pre><code>Account ACC1 ACC2 ACC3 GRAND TOTAL
Product
PROD1 2 3 4 9
PROD2 3 5 7 15
REFUND 2 3 8 13
</code></pre>
<p>In pivot table code I used <code>index = "Product"</code> and <code... | <p>Use .loc to select row then column and retrieve the value.</p>
<pre><code>df_pivot.loc['REFUND',"GRAND TOTAL"]
</code></pre>
<p>Example:</p>
<pre><code>df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "t... | python|pandas|pivot-table | 0 |
357,706 | 60,266,563 | 2d array as index of a 3d array | <p>I had a 2D array (C) with 8000x64 elements, an 1D array (s) with 8000x1 elements and another 1D array (d) with 1x64 elements.
Every row of index i, where s[i] is True, shall be added by vector d.
This works quite well:</p>
<pre><code>C[s == True] += d
</code></pre>
<p>Now I have added one dimension to C, s, and d ... | <p>It's easier with the extra dimension at the beginning:</p>
<pre><code>In [376]: C = np.zeros((4,2,3),int)
In [377]: s = np.array([[0,0],[0,1],[1,0],[1,1]],bool)
In [378]: d = np.arange(1,13).reshape(4,3) ... | python|arrays|numpy | 2 |
357,707 | 60,102,667 | How to convert this type of "Dictionary" into a Dataframe? | <p>I want to send these results to a pandas dataframe. But first I want to know what it is. I mean, do I have 5 dictionaries? Is it a list of tuples inside each one?</p>
<p><a href="https://i.stack.imgur.com/x7iUY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x7iUY.png" alt="enter image descriptio... | <p><a href="https://i.stack.imgur.com/Y6Pba.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y6Pba.png" alt="enter image description here"></a></p>
<pre><code>items = []
for item in reader:
items.append(item)
import pandas as pd
df=pd.DataFrame(items)
df
</code></pre> | python-3.x|pandas | 0 |
357,708 | 60,313,903 | Pre pulling docker images in AMI to reduce node and pod fresh start time slows down it's execution when using nvidia-docker with GPU enabled pods | <p>Using Kubernetes v1.16 on AWS I am facing a weird issue while trying to reduce the time it takes to start a pod on a newly spawned node.</p>
<p>By default, a node AMI does not contains any pre cached docker image, so when a pod is scheduled onto it, its 1st job is to pull the docker image.</p>
<p>Pulling large doc... | <p>This is most likely due to the new instance not having "fully downloaded" all parts of the disk. <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-initialize.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-initialize.html</a> has details on this.</p>
<... | amazon-web-services|docker|tensorflow|kubernetes | 0 |
357,709 | 59,912,071 | How can I eliminate these values associated with the keys? | <p>I am working with some data sets here to hone my skills working with csv's. I am experiencing an issue when I go to plot the data. I am working with this dataset: <a href="http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv" rel="nofollow noreferrer">Housing Dataset</a></p>
<p>I have created a v... | <p>The answer to my question was to add <code>.values()</code> to my definition of the x values list and y values list. The reason I had this lapse in judgement was because I was thinking that the key I was pulling information from was simply filled with values. I didn't realize this until later on, that the key contai... | python|pandas | 0 |
357,710 | 60,149,519 | Python pie chart / Show several columns combined | <p>I have dataframe with 2 columns:</p>
<p>Col1- managers' name </p>
<p>Col2 - their profit</p>
<p>I want plot a pie chart where I can show most profitable 5 managers seperately , and others in one slice as 'others'</p> | <p>How about that:
With automatic labeling of the pie pieces using autopct argument.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
data = {'managers':['mike1','mike2','mike3','mike4','mike5','mike6','mike7'],
'profit':[110,60,40,30,10,5,5],
}
df = pd.DataFrame(data)
df = df.sort_values(by = 'p... | pandas|pie-chart | 1 |
357,711 | 60,070,636 | In Pandas merge colum1 value with colum2, both col data type is object and only few values are null in first column? | <p>Data Frame is having two columns
Data Frame is having two columns</p>
<pre><code>df1
col1 col2
A A
B A
B A
C B
C
D
E
E E
F G
G
H
H
</code></pre>
<p>here both columns are object type, trying to merge value of column 2 with column 1 where column 1 value is... | <p>You can also use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a>.</p>
<pre><code>df['col1'] = np.where(df['col1'], df['col1'], df['col2'])
</code></pre>
<p>Or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pand... | python|pandas|dataframe | 3 |
357,712 | 65,427,461 | Defining a Torch Class in R package "torch" | <p>this post is related to my earlier <a href="https://stackoverflow.com/questions/65416903/how-to-define-a-python-class-which-uses-r-code-but-called-from-rtorch">How to define a Python Class which uses R code, but called from rTorch?</a> .</p>
<p>I came across the <code>torch</code> package in R (<a href="https://torc... | <p>You can do that directly using R's <code>torch</code> package which seems quite comprehensive at least for the basic tasks.</p>
<h2>Neural networks</h2>
<p><a href="https://torch.mlverse.org/docs/articles/getting-started/nn.html" rel="nofollow noreferrer">Here</a> is an example of how to create <code>nn.Sequential</... | r|pytorch|reticulate | 2 |
357,713 | 65,187,037 | Why doesn't Pandas round when dtype is float16? | <p>Why does Pandas not round DataFrames when the dypes are <code>np.float16</code>?</p>
<p><code>pd.DataFrame(np.random.rand(10) for x in range(0, 10)).astype(np.float16).round(2)</code></p>
<p>Or</p>
<p><code>np.round(pd.DataFrame(np.random.rand(10) for x in range(0, 10)).astype(np.float16), 2)</code></p>
<p>Or</p>
<p... | <p>It <em>is</em> rounding. Up to the limits of float16 precision, the results are exactly what you asked for. However, the limits of float16 precision are significantly lower than the 6 significant figures Pandas attempts to print by default, so you see some of the representation imprecision that is usually hidden whe... | python|pandas | 0 |
357,714 | 65,184,346 | Replacing string by float in a dataframe according to their value in a different dataframe | <p>I have the following dataframes:</p>
<pre><code>df.head()
Out[65]:
PU IN PR
NUTS_ID
BE 110.4 129.3 136.4
BG 72.1 74.4 73.2
CZ 68.3 75.9 89.1
DK 94.8 125.1 135.4
DE 77.4 101.1 113.5
df2.head()
Out[66]:
category
NUTS_ID... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.lookup.html#pandas-dataframe-lookup" rel="nofollow noreferrer">pd.DataFrame.lookup</a> with some string manipulation:</p>
<pre><code>df2['category'] = df.lookup(df2.index.str[:2], df2['category'])
</code></pre>
<p>Output:</p>
<pre><code> ... | python|pandas|dataframe | 2 |
357,715 | 65,174,354 | Pandas Series - groupby and take cumulative most recent non-null | <p>I have a dataframe with a <code>Category</code> column (which we will group by) and a <code>Value</code> column. I want to add a new column <code>LastCleanValue</code> which shows the most recent non null value for this group. If there have not been any non-nulls yet in the group, we just take null. For example:</p>... | <p>This is more like <code>ffill</code></p>
<pre><code>df['new'] = df.groupby('Category')['Value'].ffill()
Out[430]:
0 NaN
1 NaN
2 34.0
3 40.0
4 42.0
5 25.0
6 25.0
7 42.0
8 31.0
9 33.0
10 42.0
Name: Value, dtype: float64
</code></pre> | python|pandas|pandas-groupby | 1 |
357,716 | 65,315,436 | Two-step training in neural network | <p>In the article <a href="https://www.nature.com/articles/s41598-019-51269-8" rel="nofollow noreferrer">https://www.nature.com/articles/s41598-019-51269-8</a> on sleep-stage classification, the author mentions two-step training. Specifically,</p>
<p>"In the pretraining step, the scoring module (Fig. 2) is tempora... | <p>You could use the <a href="https://keras.io/guides/functional_api/" rel="nofollow noreferrer">Functional API of Keras</a>. It enables you to define your layers separately and assing to a variable. Hence you could connect and disconnect your layers at any time.</p> | python|tensorflow|keras | 0 |
357,717 | 65,387,990 | Python Pandas: Filter rows based on position letter in string | <p>I'm pretty new to python and I'm still learning Pandas. I've been playing around and trying to learn things with Pandas that I wouldn't be able to do with excel ordinaril using it's filter function.</p>
<p>One thing that I have been trying to do is to filter based on the second letter in the column I choose to filte... | <p>IIUC, then use <code>str.contains</code> with a <code>regex</code> match.</p>
<pre><code>df[df.Name.str.contains(r'^\wh\w*')]
</code></pre>
<p>Prints:</p>
<pre><code> Name HP Type
1 Charizard 200 Fire
</code></pre> | python|python-3.x|pandas|sorting|filter | 0 |
357,718 | 65,447,729 | Insert index after every 2nd row that lists down total of two columns? | <p>I have this data frame:</p>
<pre><code>Ind1 Ind2 M F
Business Analyst 1-2 years 50 55
Business Analyst 10-20 years 47 23
DBA Engineer 1-2 years 31 12
DBA Engineer 10-20 years 21 10
</code></pre>
<p>I want to calculate the total count for M and F indi... | <p>One approach is to <code>groupby</code> the dataframe on <code>Ind1</code> and aggregate using <code>sum</code>, then append this aggregated dataframe to <code>df</code> and <code>sort</code> the values on <code>Ind1</code>:</p>
<pre><code>df1 = df.append(df.groupby('Ind1', as_index=False).sum()\
.assign(Ind... | python|pandas|dataframe | 1 |
357,719 | 65,302,953 | New column with incremental occurance, like countif($A$2:A2,A2) in excel | <p>I would like to get a new column of Occurance like df2. Thanks</p>
<pre><code>import pandas as pd
import sys
import numpy as np
df=pd.DataFrame({'A':['1','2','1','3','4','2','1']})
print(df)
#my ideal case
df2=pd.DataFrame({'A':['1','2','1','3','4','2','1'],'Occurance':['1','1','2','1','1','2','3']})
print(df2)
</c... | <p>Try <code>groupby</code> function with <code>cumcount</code>:</p>
<pre><code>df["Occurence"] = df.groupby("A").cumcount() + 1 # +1 since cumcount starts at 0
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> A Occurence
0 1 1
1 2 1
2 1 2
3 3 1
4 4 1
5 2 2
6 ... | python|pandas|dataframe|countif | 0 |
357,720 | 65,152,068 | Comparing results within a column and appending to pandas dataframe | <p>I am doing a dummy project to hone my python skills and there is a problem I am encountering. I have a pandas column with many values inside it, I want to do the following (I have set chunksize = 1440 because I want to process the data in groups of 1440's and store the output for each group of 1440 separately.):</p>... | <p>This is what you want?</p>
<p>when value > 3 than previous the <code>Changing</code> column appended <code>profit</code>, and when value < 3 than previous the <code>Changing</code> column appended <code>Loss</code>.</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
np.random.seed(199)
... | python|pandas | 0 |
357,721 | 65,277,404 | Pandas- locate a value based on logical statements | <p>I am using the <a href="https://www.kaggle.com/anikannal/solar-power-generation-data" rel="nofollow noreferrer">this dataset for a project.</a>
I am trying to find the total yield for each inverter for the 34 day duration of the dataset (basically use the final and initial value available for each inverter). I have ... | <p>So if I'm understanding this right, what you want is the <code>TOTAL_YIELD</code> for each inverter for the beginning of the time period starting <code>5-05-2020 02:00</code> and ending <code>17-06-2020 23:45</code>. Try this:</p>
<pre class="lang-python prettyprint-override"><code># enumerate lets you have an index... | python|pandas|numpy | 0 |
357,722 | 65,122,298 | Add two data frames with different size by date | <p>I have two data frames that I need to add together.</p>
<p>The two data frames could look something like this:</p>
<pre><code>df1 =
date col1 col2
01-01-20 1 2
02-01-20 2 4
03-01-20 3 6
04-01-20 4 8
05-01-20 5 10
df2 =
date col1 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add.html" rel="nofollow noreferrer"><code>DataFrame.add</code></a> with <code>fill_value</code> parameter:</p>
<pre><code>df_sum = df1.set_index("date").add(df2.set_index("date"), fill_value=0)
</code></pre>
<... | python|pandas | 4 |
357,723 | 65,161,699 | Filtering rows in pandas dataframe in python | <p>I am trying to filter rows in dataframe by multiple strings and I have searched and found this</p>
<pre><code>search_values = ['vba','google']
df[df[0].str.contains('|'.join(search_values), case=False)]
</code></pre>
<p>But this I think based on finding either of the two strings <code>vba</code> or <code>google</cod... | <p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer">contains</a> function uses regex to find the rows that match the string. Using <code>|</code> is like <code>OR</code> in regex. If you want rows that contain both, this should work:</p>
... | python|pandas | 1 |
357,724 | 65,334,798 | Lookup and add value to new column python | <p>I have a CSV with 2 columns and I need to create a lookup table within pandas that will add a column according to the some of the values of that row. Example:</p>
<pre><code>DIMENSION ACCOUNT NAME
Tax Tiger Beta
Config Tiger Alpha
S3 Lion Alpha
Lambda Tiger Cigna
Glacier Beta -... | <p>You can do this:</p>
<pre><code>rank = {"Alpha", "Beta","Cigna"}
Animal = {"Tiger", "Lion"}
def Lookup1(x):
df_words = set(x.split(' '))
extract_words = rank.intersection(df_words)
return ', '.join(extract_words)
def Lookup2(x):
df_words = set(x.sp... | python|pandas|csv | 0 |
357,725 | 65,176,204 | tensorflow 2, using tensor as index without for loop | <p>Let's say I have a tensor of shape <code>[3000,20,10],</code> I'll call it <code>input</code>... I have another tensor of shape [3000] that contains only indices for the 3rd dimension of the first tensor, I'll call it "indices"</p>
<p>Basically, for every <code>i</code> in <code>0:2999</code>, I want <code... | <p>Try this code:</p>
<pre><code>from tensorflow.keras.layers import Conv2D, Input, BatchNormalization, Activation, Add, MaxPooling2D, LSTM, Dense
import tensorflow as tf
input = tf.range(3000*20*10)
input = tf.reshape(input, (3000,20,10))
indices = tf.random.uniform((3000,), 0, 10, dtype=tf.int32)
inds = indices[:, tf... | python|tensorflow|indexing | 0 |
357,726 | 65,146,265 | Subset dataframe based on multiple like conditions | <p>I have this dataframe-</p>
<pre><code> Name Age
0 Alex 10
1 NaN 12
2 Clarke 13
3 Lexy 14
4 Marie 10
</code></pre>
<p>I need to subset the dataframe based on <code>Name</code> column. I want to only keep rows having name like <code>%lex%</code> or <code>%clarke%</code> or <code>%bob%</code... | <p>So you can do</p>
<pre><code>out = df[df['Name'].str.contains('lex|clarke', na=False, case=False)]
Out[5]:
Name Age
0 Alex 10
2 Clarke 13
3 Lexy 14
</code></pre> | python|pandas|dataframe | 1 |
357,727 | 65,426,157 | Display 20 graphs based on four columns using subplots | <p>There is a dataframe with Date, Type, Price and Location columns. It is necessary to build graphs (each - on a separate picture) of the dependence of Price on Date for each Type - this is done, I get 10 graphs:</p>
<pre><code>import pandas as pd
dat = pd.read_csv('ap-northeast-1.csv', parse_dates = True, names=['Dat... | <p>The groupby is the key, just group by both then allow subplots.
This will get you the 20 you need.</p>
<pre><code>(df
.set_index("Date")
.groupby(['Type','Location'])
.apply(lambda x: x[["Price"]].plot(grid=True, \
title=[x.name], \
... | python|pandas|matplotlib | 1 |
357,728 | 65,296,068 | Using itertools, melt and groupby correctly to count pairs of event per attribute value using Pandas | <p>I have a table on the following format</p>
<pre><code> Id | Sequence | Attribute A | Attribute B |
ID1 [A,B,C,D] A1 B1
ID2 [A,B,F,G] A2 B3
ID3 [A,B,C,D] A1 B1
</code></pre>
<p>I want to calcu... | <p>You could do:</p>
<pre><code>from itertools import combinations
# create function for creating a list the 2-combinations
combs = lambda x: list(combinations(x, r=2))
# create new DataFrame with now the Sequence column is the list of the 2-combinations
res = df.assign(seq=df['Sequence'].apply(combs)).drop('Sequence... | python|pandas | 2 |
357,729 | 65,450,774 | What is the opacity graph in tensorboard? | <p>I am new to Tensorboard.</p>
<p>This is an output I have by this line:</p>
<p><code>self.logger.experiment.add_scalars("losses", {"train_loss": loss}, global_step=self.current_epoch)</code></p>
<p><a href="https://i.stack.imgur.com/uyIz5.png" rel="nofollow noreferrer"><img src="https://i.stack.im... | <p><a href="https://github.com/PyTorchLightning/pytorch-lightning/issues/5316" rel="nofollow noreferrer">I asked the same question on Github</a>.</p>
<blockquote>
<p>The light one is the actual data, and the bold curve is the smoothed
curve. Use the slider in the UI to adjust it.</p>
</blockquote> | tensorflow|machine-learning|pytorch|tensorboard|pytorch-lightning | 0 |
357,730 | 65,420,683 | SWIG passing multiple arrays from python to C | <p>Using SWIG, I've been trying to wrap a C function with the following signature:</p>
<p><code>void mainline(double *data, int datasize, char *metadata, int metasize, char *path)</code></p>
<p>The python caller is passing numpy 1D arrays, so (ignoring the final char *path for the moment), I thought an interface file s... | <p>When you use a multi-parameter typemap, then multiple C parameters are represented by one Python parameter. In this case, A single numpy array or Python list can be used as a parameter for the pointer and size, since Python knows the length of its objects and the typemap accounts for that.</p>
<p>Also, the error wa... | c|numpy|swig | 0 |
357,731 | 65,131,383 | Pandas Structured 2D Data to XYZ Table | <p>I want to create an xyz table from a structured grid representation of data in a Pandas DataFrame.</p>
<p>What I have is:</p>
<pre><code># Grid Nodes/indices
x=np.arange(5)
y=np.arange(5)
# DataFrame
df = pd.DataFrame(np.random.rand(5,5), columns=x, index=y)
>>>df
0 1 2 3 ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>df.stack</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>df.reset_index</code></a... | python|pandas | 1 |
357,732 | 65,327,548 | Python Pandas - Appending to dataframe: One by One or Batch | <p>I'm writing an app that monitors an applications scanning process. Of course to check this overtime I have to log the progress (don't ask me why this isn't in the app already).</p>
<p>To do this the app runs every half hour, determines what's worth loggin and not and adds them to a pandas dataframe that is then save... | <p>This really depends on what you mean by <code>large amounts of data</code>. If it's <code>MB</code> then keeping everything as a df in memeory is fine; however if <code>GB</code> then it's better to saving them to CSV and <code>concat</code> to a new df</p>
<pre><code>from glob import glob
df = pd.concat([pd.read_cs... | python|pandas|dataframe | 0 |
357,733 | 65,150,022 | How could I plot the relative frequency of data split into categories? | <p>I want to get the relative frequency of peoples weights based on a category label and then graph that as a bar chart that would look something like this:</p>
<p><a href="https://i.stack.imgur.com/8uApc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8uApc.png" alt="enter image description here" />... | <p>Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. (<a href="https://seaborn.pydata.org/" rel="nofollow noreferrer">https://seaborn.pydata.org/</a>)</p>
<p>you will not have the same flexibility as with r... | python|python-3.x|pandas|matplotlib | 2 |
357,734 | 65,301,450 | Does tensorflow rely on a specific version of protobuf? | <p>I am having a problem with tensorflow (V2.3.1) and protobuf (V3.14.0). When executing a python script I get the following errors:</p>
<p>AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'append'</p>
<p>This appears to be coming from within tensorflow, but I could be wrong.... | <p>It does not always depend on the versions but sometimes due to the constant improvement and updating of both <code>Tensorflow</code> and <code>Protobuf</code> causes these conflicts.<br />
Since you are already using latest <code>Protobuf</code> version you can upgrade to the latest <code>Tensorflow</code> version.<... | python|tensorflow2.0 | 0 |
357,735 | 65,324,533 | Geopandas in Google Colab | <p>I am using Google Colab. I have installed the PyGMT. Now, I want to install the Geopandas but I got lots of errors when i type "!pip install geopandas" or "!conda install geopandas". Can you help me to install geopandas in googlecolab?
Here is my code;</p>
<pre class="lang-py prettyprint-override... | <p>have you tried using</p>
<pre><code>!pip install --upgrade geopandas
</code></pre>
<p>don't forget to also update the other dependencies</p>
<pre><code>!pip install --upgrade pyshp
!pip install --upgrade shapely
!pip install --upgrade descartes
</code></pre>
<p>Found it in this Google Colab tutorial, <a href="http... | geopandas | 6 |
357,736 | 65,405,662 | It's possible to select distinct and no distinct in Pyspark? | <p>I need to select 2 columns from a fact table (attached below). The problem I find is that for one of the columns I need unique values and for the other one I'm happy to have them duplicated as they below to a specific ticket id.</p>
<p>Fact table used:</p>
<pre><code>df = (
spark.table(f'nn_table_{country}.fac... | <p>Use <code>dropDuplicates</code>:</p>
<pre><code>df.select('customer_id','external_id').dropDuplicates(['customer_id'])
</code></pre> | pandas|dataframe|apache-spark|pyspark|apache-spark-sql | 1 |
357,737 | 65,405,390 | How to use np.unique on big arrays? | <p>I work with geospatial images in tif format. Thanks to the <a href="https://rasterio.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>rasterio</code></a> lib I can exploit these images as <code>numpy</code> arrays of dimension (nb_bands, x, y). Here I manipulate an image that contains patches of unique val... | <p>The uint64 array is probably allocated during argsort <a href="https://github.com/numpy/numpy/blob/v1.19.0/numpy/lib/arraysetops.py#L319" rel="nofollow noreferrer">here in the source code</a>.</p>
<p>Since the labels from scipy.ndimage.label are consecutive integers starting at zero you can use numpy.bincount:</p>
<... | python|numpy|scipy|rasterio | 1 |
357,738 | 65,287,177 | calculate cosine similarity in Pytorch | <p>I have a candidate document embedding tensor, namely <code>cdd_doc_embeddings</code> of size <code>[batch_size, cdd_size, signal_length, embedding_dim]</code>, a history clicked document embedding tensor, namely <code>his_doc_embeddings</code> of size <code>[batch_size, his_size, signal_length, embedding_dim]</code>... | <p>OK I've figured it out.</p>
<pre class="lang-py prettyprint-override"><code>import torch.nn.functional as F
# [bs, cs, 1, sl, ed]
cdd_news_embedding = F.normalize(self.embedding[cdd_news_batch].unsqueeze(dim=2), dim=-1)
# [bs, 1, hs, ed, sl]
his_news_embedding = F.normalize(self.embedding[his_news_batch].unsqueeze(d... | deep-learning|nlp|pytorch | 0 |
357,739 | 65,256,636 | How to assign column with string values to dataframe | <p>I have a csv file with multiple columns of which I want to return these 4 columns. There exist duplicates in the Case_ID column with a different start and or completion time. The goal is to return the case_id with the min start_time and max completion_time and the corresponding casetype.</p>
<pre><code>Case_ID ... | <p>One possible solution:</p>
<pre><code>min_max = appeals.groupby('Case_ID').agg({'Start_time' : 'min', 'Completion_time' : 'max', 'Casetype': 'first'}).reset_index()
</code></pre>
<p>I removed your selection of columns (<code>[['Case_ID','Start_time','Completion_time']]</code>) in order to keep all the columns, inclu... | python-3.x|pandas|dataframe | 2 |
357,740 | 65,221,839 | Plotly: How to use scatter chart to display a multiIndex dataframe? | <p>I'm using a multi-index data frame to plot a line chart. I can see the correct result when I plot the graph using Matplotlib but the data frame shows the wrong output when plotted using Plotly scatter charts- why?</p>
<code>
<pre><code>import pandas as pd
data = pd.DataFrame([
('Q1','Blue',100),
('Q1... | <p>Your question is a bit unclear, but I'm assuming that your primary objective here is to display values accross an array of quarters where values are split in two groups ['blue', 'red']. (I can't quite understand why you're asking for a plotly scatter figure but showing a matplotlib bar chart...). Anyway, If I'm righ... | python|pandas|plotly|jupyter|plotly-python | 1 |
357,741 | 65,202,106 | Is it possible to append values to a column if it is missing a value from a master column in Python? | <p>I'm trying to compare between different columns in an Excel sheet/csv.
<a href="https://i.stack.imgur.com/6xjSy.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>For example, the master column has all the variables that I want to look at, but as you can see in the year 2015 and 2016, there are m... | <p>Yes, assuming I understand correctly what you want to do and your dataframe is called <code>df</code>, you can use <code>where</code> from <code>numpy</code> and do this:</p>
<pre><code>import numpy as np
df['2015'] = np.where(df['2015'].isnull(),'df['Master'],'df['2015'])
df['2016'] = np.where(df['2016'].isnull(),... | python|pandas|dataframe | 1 |
357,742 | 65,439,688 | Pandas rows multiple rows as one, adding specific column | <pre><code>import pandas as pd
training_data = pd.DataFrame()
training_data['a'] = [401,401.2,410,420,425,426, 426.1]
training_data['b'] = [1,1,2,2,2,3,3]
training_data['condition'] = [True, False, True, True, True,False, False]
</code></pre>
<p>My training data:</p>
<pre><code>a b condition
401 ... | <p>Here we go with <code>cumsum</code></p>
<pre><code>out = training_data.groupby(training_data['condition'].cumsum()).agg({'a':'first','b':'sum','condition':'first'})
Out[271]:
a b condition
condition
1 401.0 2 True
2 410.0 2 True
3 420.0 ... | python|pandas|dataframe|loops|aggregation-framework | 7 |
357,743 | 65,438,159 | What is the equivalent of h(t)=0 Matlab expression in Python? | <p>I am translating a MATLAB code to Python code but I couldn't understand what <code>h(t) = 0</code> means. What is the equivalent in Python?</p>
<p>Where <code>h</code> and <code>t</code> is <code>(494,475,3)</code> array:</p>
<pre><code>t = sum((h.^2+v.^2),3)<lambda/beta;
t = repmat(t,[1,1,D]);
h(t) = 0; v(t) = 0... | <p><code>t</code> is a MATLAB matrix with elements that are either true or false.
<code>h(t)</code> gives all elements of <code>h</code> where the corresponding elements in <code>t</code> are true.
These are set to 0 with <code>h(t) = 0</code></p>
<p>You can do the same in Python.</p>
<pre><code>h[t] = 0
</code></pre>
... | python|matlab|numpy|matrix | 2 |
357,744 | 65,462,849 | How to Stack Columns with Pandas | <p>Let's say I have data that I imported as a .csv:</p>
<pre><code>T_1 T_2 A B C
0 1 Apple Banana Orange
1 2 Book Pen Pencil
2 3 Blue Red Green
</code></pre>
<p>And I want it to stacked into one column like this:</p... | <p>Apart from the answers from David, You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer">stack</a>().</p>
<pre><code>>>> dta= pd.DataFrame({"T_1":[0,1,2], "T_2":[1,2,3],"A":["Apple",&... | python-3.x|pandas | 1 |
357,745 | 65,170,862 | Why a small network (<2k parameters) exceed the limit of Keras optimizer? | <p>I'm working on a very small model with less than 2K parameters:</p>
<pre><code>Model: "model"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
===============... | <p>That error refers to the number of elements in a tensor being greater than the max int32 value, not a memory error related to the number of weights. If your dimensions are correct and nothing in your custom layer generates a massive tensor, reducing your batch size should resolve the problem.</p> | tensorflow|optimization|keras|deep-learning|neural-network | 1 |
357,746 | 65,333,091 | Python Pandas: sort a dataframe by multiple columns but different sorting order | <br/>
I have a question about sorting a dataframe in Pandas.<br/>
For example I have a dataframe 'df_cars' with the columns 'Year','Model','Mileage','Price'.<br/>
And I want to display the dataframe ordered by 'Year' (desc) and 'Mileage' (asc).<br/>
I know how to sort by multiple colulmns but the same order (asc/or des... | <p>I will try.
By myself I did:</p>
<pre><code>print(df_cars.sort_values(by=['Year','Price'],
inplace = False,
ascending = (False,True))
</code></pre>
<p>I suppose it is the same as your suggestion.
I tried both versions and got the same output.</p>
<p>Thank you.</p> | python|pandas|sorting | 0 |
357,747 | 65,418,257 | RNN+CTC model seems not getting the data dimension correctly | <p>I'm training a simple RNN model (GRU) with CTC loss function. Below is the code and the model summary. I keep getting this error as below. It seems somewhere in the model the data dimension, probably the input data length (i.e. the length in [batch_size, <strong>length</strong>, mfcc_feature]) gets reduced by 2. Whe... | <p>Okay... I found out why... because i have this</p>
<p>y_pred = y_pred[:, 2:, :]</p>
<p>in the ctc_lambda_loss function</p> | python|tensorflow|keras | 0 |
357,748 | 65,366,442 | Cannot convert a symbolic Keras input/output to a numpy array TypeError when using sampled_softmax in tensorflow 2.4 | <p>I'm trying to train a word embedding classifier using TF2.4 with Keras and using the <code>tf.nn.sampled_softmax_loss</code>. However, when calling the <code>fit</code> method of the model, "Cannot convert a symbolic Keras input/output to a numpy array" TypeError occurs. Please help me to fix the error or ... | <p>The error is caused by your custom loss function. You should disable TF eager execution mode.</p>
<p><code>from tensorflow.python.framework.ops import disable_eager_execution</code></p>
<p><code>disable_eager_execution()</code></p>
<p>Also, in <code>model.compile(...)</code> use <code>experimental_run_tf_function=Fa... | python-3.x|keras|deep-learning|tensorflow2.0 | 34 |
357,749 | 65,140,121 | Pandas read_sql_query converts 32-bit data to 64-bit | <p>I am using <code>pandas.read_sql_query</code> to read some data from Sql server. The data types I read are <code>int</code> and <code>real</code> in Sql server, that is 32-bit integers and 32-bit floating-point values. But in the resulting dataframe the dtypes are <code>int64</code> and <code>float64</code>. I could... | <p>Looking at the current Pandas code, I believe the only option is to develop your own solution using a loop approach. Using "read_sql_query" or "read_sql" will ultimately end up calling "pandas.DataFrame.from_records" from a list of pyodbc rows. "DataFrame.from_record" doesn't ... | python|sql-server|pandas | 1 |
357,750 | 65,358,503 | How to sum same id and value from the second column across different csv files and save results into a new csv with pandas? | <p>I have 3 csv files that contain IDs and activeUsers columns. The IDs in those files are sometimes present in only one file, two files but sometimes they can be present in every file. My IDs are unique in each file.</p>
<p><strong>each csv file format:</strong></p>
<pre><code> id activeUsers
470c-... | <p>If not duplicated <code>activeUsers</code> in some file you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> for join together with aggregate by counts and sum and last set new column by conditions:</p>
<pre><code>df4 = (... | python|pandas|csv | 1 |
357,751 | 65,474,059 | Exclude item from value_counts over multiple columns | <p>I got the following dataframe:</p>
<pre><code> ae264e3637204a6fb9bb56bc8210ddfd ... 2906b810c7d4411798c6938adc9daaa5
1 not received ... not received
3 completed ... not received
5 not received ... | <p>Let's <code>mask</code> the <code>not received</code> values in <code>relevant_columns</code>, then apply <code>pd.value_counts</code> with <code>normalize=True</code> to count proportion of unique values per column:</p>
<pre><code>profile[relevant_columns].mask(lambda x: x.eq('not received'))\
.apply(pd.valu... | python|pandas | 4 |
357,752 | 65,113,768 | Remove index that isn't followed by an index in other pd.Series | <p>I have two Pandas Series, I want to filter out data which has an index that is not followed by an index in the other Series. So when joining these Series, based on index, only <em>every other</em> datapoint should be from <code>data1</code> and vice versa.</p>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><... | <p>You can join the two series together in a dataframe and compare them according to your comment using <code>shift()</code> and filter out those rows.</p>
<pre><code>df = data1.reset_index().join(data2.reset_index(), rsuffix='_y')
df = df[(df['index'].shift(-1) > df['index_y']) | (df['index'] == df['index'].iloc[-1... | python|pandas|dataframe | 1 |
357,753 | 65,136,886 | Directional plots in Python and matplotlib and pandas | <p>In the matplotlib, we just the throw the samples and it plots. Now, I want to the sample display an arrow pointing towards the direction of next sample. It is like directional plot used for drawing electro-magnetic fields. I have put it into a simple example below.</p>
<p>My code:</p>
<pre><code>dfx = pd.DataFrame({... | <p>Based on the suggestion from <code>Mr. T</code> in above comments, I got to know about <code>quiver</code>. I tried a few things and found a simple way to answer.</p>
<pre><code>dfx = pd.DataFrame({'x':[0,np.nan,1,2,np.nan,3,4,5],'y':[9,8,7,6,5,4,10,12]})
plt.quiver(dfx['x'],dfx['y'],dfx['x'].diff(),dfx['y'].diff())... | python|pandas|dataframe|matplotlib | 0 |
357,754 | 65,324,757 | list of dicts to dataframe inserting multiple enteries into single row? | <p>I have a function that parses json and then loads it into a dataframe. My general approach was to loop through each file and then concat it to the existing DF that was adding all the entries over time:</p>
<pre><code>HoldingsDF = loadFundETFData(ticker1, fundsDict[ticker1])
holdingsFullDF = pd.concat([holdingsFullDF... | <p>Your issue is that you have unecessary steps when getting your data. I am assuming that you intend to get the reference (or index) of each element from your Json along with the associated data.</p>
<p>It seems you end up with data that has this shape :</p>
<pre><code>holdingsFullList = [{"Column1": {0: &qu... | python|pandas | 1 |
357,755 | 65,172,757 | Python, lambda function as argument for groupby | <p>I'm trying to figure out what a piece of code is doing, but I'm getting kinda lost on it.</p>
<p>I have a pandas dataframe, which has been loaded by the following .csv file:</p>
<pre><code>origin_census_block_group,date_range_start,date_range_end,device_count,distance_traveled_from_home,bucketed_distance_traveled,me... | <p>If you run your code exactly as you wrote it (both the creation of df and the groupby) you can see the result. I print first couple of columns of the output of <code>groupby</code></p>
<pre><code> device_count distance_traveled_from_home
----- -------------- -----------------------------
01053 ... | python|pandas|dataframe|lambda|pandas-groupby | 2 |
357,756 | 65,258,629 | How to identify zones in a table using pandas? | <p>I have a file with a table (.csv file).
The table is composed by many sub "areas" like this example:</p>
<p><a href="https://i.stack.imgur.com/TucnE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TucnE.png" alt="Image 1" /></a></p>
<p>As you can see, there are more some data which can b... | <p>You can create an index and insert into the first position per your desired output. I have also used <code>ffill()</code> to get rid of nulls, but that is optional for you</p>
<pre><code># without ffill()
df.insert(0, 'index', (df[['X', 'Y', 'Z']].notnull().sum(axis=1) == 3).cumsum())
# df = df.ffill() # uncomment i... | python|pandas | 1 |
357,757 | 65,244,833 | Pandas read_csv for a no quote file | <p>I'm trying to read a file that doesn't have any quotes, which is causing inconsistent number of row lengths</p>
<p>Data looks as follows:</p>
<pre><code>col_a, col_b
abc, inc., 5
xyz corb, 10
</code></pre>
<p>Since there are no quotes around "abc, inc.", this is causing the first row to get split into 3 va... | <p>Its not a CSV but since there is only one column with the errant commas you can process with the <code>csv</code> module and fix the slice that holds too many column values. When a row has too many cells, assume they are the ones from the unescaped comma.</p>
<pre><code>import pandas as pd
import csv
def split_badr... | python|pandas|csv | 1 |
357,758 | 65,095,968 | Conditional regular expression in Python | <p>I am currently trying to match the following using a regular expression:</p>
<pre><code>label string
a disvt
b disv2
c disv1
d disv1f
e disv10
f disr1
</code></pre>
<p>I am trying to capture vt, v2, v1 and v10, using a conditional regular expression to captu... | <p>try this :</p>
<pre><code>v(?:t|\d{1,2})\b
</code></pre>
<blockquote>
<p>(?:t|\d{1,2}) : mean t character or digit with size between 1 and 2 <br>
(?!\w) : not followed by alphanumeric character</p>
</blockquote>
<p><a href="https://regex101.com/r/UgiWGE/2" rel="nofollow noreferrer">demo</a></p> | python|regex|pandas | 0 |
357,759 | 65,097,577 | How to convert a Pandas dataframe to dictionary while retaining dtype? | <p>I have a dataframe (simplified):</p>
<pre><code> Factors low high
0 amount 2.5 4
1 grind_size 8 10
2 brew_time 3.5 4.5
3 grind_type burr blade
4 beans light dark
</code></pre>
<p>which I would like to select columns from to make a dictionary:</p>
<pre><code>lows ... | <p>What about forcing a casting? It looks like the numbers in your dataframe are actually <code>str</code> instances.</p>
<pre><code>def to_float(val):
try:
val = float(val)
except ValueError:
pass
return val
lows = dict(zip(df.Factors, map(to_float, df.low)))
print(lows)
#{'amount': 2.5,... | python|pandas|dataframe | 1 |
357,760 | 65,438,870 | Python numpy array add / update / delete row on value from other array | <p>I have a numpy array and depending on the value from another array, I would like to either update the value of the row, or delete it, or add one.</p>
<p>Example:</p>
<p>I have <code>arr</code>, the one with all values and to keep updated with value from <code>new_arr</code>. If a value in the first column of <code>n... | <p>Keeping the input arrays as numpy constructs, here's how I would do it.</p>
<pre><code>def process_arrays(np1, np2):
np1d = dict((np1[x][0], np1[x][1]) for x in range(len(np1)))
np2d = dict((np2[x][0], np2[x][1]) for x in range(len(np2)))
for ky2 in np2d.keys():
if ky2 in np1d.keys():
... | python|python-3.x|numpy | 1 |
357,761 | 50,019,928 | how do you read Images into a classifier by Folder name instead of File name? | <p>I am trying to use this script I found online to classify images however I'm not the best with python. The script reads the data in by files name. All the images start with cat or dog. instead id like to make two folders for training and the trainer will know what the images are based on folder name instead of file ... | <p>Supposing your folders names are thus:</p>
<pre><code> TRAIN_DIRS = ['/path/to/dataset/train/cat', '/path/to/dataset/train/dog']
</code></pre>
<p>You only need to change your <code>label_img()</code> function to parse the image classes from the parent directory instead of the filename:</p>
<pre class="lang-python... | python|python-2.7|tensorflow | 1 |
357,762 | 50,148,374 | Replacing all negative values in certain columns by another value in Pandas | <p>Suppose I have four successively arranged columns as a part of a data frame and I want to replace all the negative values in these 4 columns by another value (-5 let's say), how do I do it? </p>
<pre><code>T1 T2 T3 T4
20 -5 4 3
85 -78 34 21
-45 22 31 75
-6 5 7 -28
</code></pre>
<p>Logically, I... | <p>You can just use <code>indexing</code> by applying a condition statement.</p>
<pre><code>cols = ['T1','T2','T3','T4']
df[df[cols] < 0] = -5
</code></pre>
<p>Output</p>
<pre><code>In [35]: df
Out[35]:
T1 T2 T3 T4
0 20 -5 4 3
1 85 -5 34 21
2 -5 22 31 75
3 -5 5 7 -5
</code></pr... | python|pandas|dataframe|replace | 5 |
357,763 | 49,886,763 | Get matrix from a pandas Series with desired shape | <p>I have a very large Series called s and I want to turn this into a matrix. The series repeats - so i want each set of unique values to be one row. Here's an example, s = </p>
<pre><code>weights
10
5
15
6
10
5
15
6
10
5
15
6
</code></pre>
<p>And I w... | <p>Using <code>reshape()</code>:</p>
<pre><code>In [143]: df.as_matrix().reshape(-1,4)
Out[143]:
array([[10, 5, 15, 6],
[10, 5, 15, 6],
[10, 5, 15, 6]], dtype=int64)
</code></pre> | python|pandas | 3 |
357,764 | 50,090,052 | Efficient way to read a set of 3 channel images from Python into a two dimensional array to be used in C | <p>I am working on a project involving object detection through deep learning, with the underlying detection code written in C. Due to the requirements of the project, this code has a Python wrapper around it, which interfaces with the required C functions through ctypes. Images are read from Python, and then transferr... | <p>Regarding the <code>ascontiguousarray</code> method, I'm assuming that it's pretty slow as python has to do some memory works to return a C-like contiguous array. </p>
<p>EDIT 1:
I saw <a href="https://stackoverflow.com/a/33674655/3283333">this answer</a>, apparently openCV's <code>imread</code> function should al... | python|c|arrays|numpy|ctypes | 2 |
357,765 | 50,106,047 | How to get k cluster mean for a given data based on a condition? | <p>I have a csv file which contains date and mse (mean square error) values shown below.</p>
<pre><code>date mse
2018-02-11 14.34
2018-02-12 7.24
2018-02-13 4.5
2018-02-14 3.5
2018-02... | <p>You can apply KMeans directly to your dataframe after filtering it by a specific condition.</p>
<p>In your case, you can use:</p>
<pre><code>kmeans = KMeans(n_clusters=2).fit(df.query('mse < 40'))
</code></pre> | python-3.x|pandas|matplotlib|scikit-learn|k-means | 0 |
357,766 | 49,977,723 | Adding column of weights to pandas DF by a condition on the DFs column | <p>Whats the most pythonic way to add a column (of weights) to an existing Pandas DataFrame <code>"df"</code> by a condition on <code>dfs</code> column?</p>
<p>Small example:</p>
<pre><code>df = pd.DataFrame({'A' : [1, 2, 3], 'B' : [4, 5, 6]})
df
Out[110]:
A B
0 1 4
1 2 5
2 3 6
</code></pre>
<p>I'd Like t... | <p>You can use <code>numpy.where</code> for a vectorised solution:</p>
<pre><code>df['weight'] = np.where(df['B'] >= 6, 20, 1)
</code></pre>
<p>Result:</p>
<pre><code> A B weight
0 1 4 1
1 2 5 1
2 3 6 20
</code></pre> | python|pandas|numpy|dataframe | 4 |
357,767 | 49,944,362 | Simple auto-correct neural network not learning | <p>I'm building a simple auto-correct neural network in Python. Here's the full code: <a href="https://www.dropbox.com/s/i85z91a9zb9sn4c/Code.zip?dl=0" rel="nofollow noreferrer">Code&Data</a></p>
<p>Training data is just a list of words(included in link above) eg: </p>
<pre><code>yellow
woods
four
</code></pre>
... | <p>If your code works for a small number of words it may very well be that there is no code errors in your code but rather errors in the way you encoded your problem.</p>
<p>For one I don't think it's a good idea to encode words in float numbers. In that case you can have two different words which have very similar en... | python|numpy|machine-learning|neural-network | 3 |
357,768 | 50,197,878 | Tensorflow - using estimator in interactive mode | <p>I am trying to use a tensorflow neural network in "interactive" mode:
my goal would be to load a trained model, keeping it in memory, and then perform inference on it once in a while.</p>
<p>The problem is that apparently the tensorflow Estimator class (tf.estimator.Estimator) does not allow to do so.</p>
<p>The m... | <p>You may want to have a look at <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/eager/make_template" rel="nofollow noreferrer"><code>tfe.make_template</code></a>, its goal is precisely to make graph-based code available in eager mode.</p>
<p>Following <a href="https://youtu.be/T8AW0fKP0Hs?t=778" rel="... | python|tensorflow|tensorflow-estimator | 0 |
357,769 | 49,986,216 | TensorFlow: Load model and just do a forward pass on an image | <p>Is it possible to load my model and just do a single forward operation on an image.</p>
<p>My network is defined as follow:</p>
<pre><code>def network(x, weights, biases, name="network"):
# 1. Hidden layer, ReLU
layer_1 = tf.add(tf.matmul(x, weights["h1"]), biases["b1"])
layer_1 = tf.nn.relu(layer_1)
... | <p>When you define a model, you define a graph. This graph contains operations (nodes) and each node has a unique name.</p>
<p>If you don't explicitly set a name to a node, Tensorflow assigns a name for you.</p>
<p>If you want to execute the chain of operations that are required to evaluate a node, you have to know i... | python|tensorflow|machine-learning | 3 |
357,770 | 50,087,413 | Numpy gradient in masked array | <p>When I compute the gradient of a masked array in numpy as</p>
<pre><code>import numpy as np
import numpy.ma as ma
x = np.array([100, 2, 3, 5, 5, 5, 10, 100])
mx = ma.masked_array(x, mask=[1, 0, 0, 0, 0, 0, 0, 1])
</code></pre>
<p>the mask of the resulting array is different from the original mask:</p>
<pre><code>... | <p>I think the reason is that you expect masked elements of the <code>mx</code> array to be skipped during the computation of the gradient, so that instead of computing gradient on <code>x = np.array([100, 2, 3, 5, 5, 5, 10, 100])</code> we will compute it on <code>x = np.array([2, 3, 5, 5, 5, 10])</code>, but the real... | python|numpy | 1 |
357,771 | 49,927,501 | Pandas: Collapse a mxn multi-index dataframe into a series by repeating each row index n times | <p>I have a two dimensional dataframe in Pandas with two levels of indexing. For a sample, it looks like this:</p>
<pre><code>Location 1 2 3 4 5
Time
0 2 4 6 8 10
1 1 3 5 7 9
2 0 0 0 0 0
</code></pre>
<p>I want to collapse this into a single-indexed ... | <p>You just need <code>stack</code> </p>
<pre><code>df.stack().reset_index()
</code></pre> | python|pandas|dataframe|multi-index | 2 |
357,772 | 50,063,685 | Interpolate a DataFrame column and sort based on another column in PySpark or Pandas | <p>Given the following DataFrame we need to interpolate <code>my_column</code> values from the example and use them as separate columns and then sort by the <code>int_column</code> values that belong to each <code>some_id</code> column in descending order. The example:</p>
<pre><code>+--------------------+-----------+... | <p>We need a helper key , create by using <code>cumcount</code> , then we using <code>groupby</code> + <code>apply</code> (This part just like <code>pivot</code>, or you can using <code>pivot_table</code> or <code>crosstab</code> )</p>
<pre><code>df=df.assign(key=df.groupby('my_column').cumcount())
df.groupby(['key','... | python|pandas|apache-spark|dataframe|pyspark | 3 |
357,773 | 50,014,365 | PyTorch - How to set Activation Rules of neurons to increase efficiency of Neural Network? | <p>I'm trying to make a Back Propagation Neural Network with PyTorch. I can successfully execute and test its accuracy, but it doesn't work very efficiently. Now, I'm supposed to increase its efficiency by setting different activation rules for neurons, so that those neurons that don't contribute to the final output ge... | <p>I'm not sure if that question is supposed to be on stackoverflow, but I will give you a hint anyway. You are working with a sigmoid activation function at the moment, the gradient of which vanishes if the input value is too large to small. A commonly used approach is to use the ReLU activation function (stands for r... | python|pandas|neural-network|pytorch | 2 |
357,774 | 50,101,491 | Tensorflow Eager Execution does not work with Learning Rate decay | <p>trying here to make an eager exec model work with LR decay, but no success. It seems to be a bug, since it appear that the learning rate decay tensor does not get updated. If I am missing something can you land a hand here. Thanks.</p>
<p>The code bellow is learning some word embeddings. However, the <strong>learni... | <p>Note that when eager execution is enabled, the <code>tf.Tensor</code> objects <a href="https://www.tensorflow.org/programmers_guide/eager#setup_and_basic_usage" rel="noreferrer">represent concrete values</a> (as opposed to symbolic handles of computation that will occur on <code>Session.run()</code> calls). </p>
<p... | tensorflow | 7 |
357,775 | 49,816,235 | Running TensorFlow layer with same input gives differing output | <p>I am attempting to visualize the activations within a TensorFlow convolutional network. However, I seem to be getting different activations for the same input data. If I have some features and a function <code>get_input_tensors</code> which creates an input tensor and run the following twice:</p>
<pre><code>data = ... | <p><code>tf.global_variables_initializer()</code> will initialize all the variables. That means it will run the random number generator to generate convolution weights according to their initializer. In your case, you run it twice so you'll get different random numbers for the weights.</p>
<p>If you want it to be repr... | tensorflow|convolution|deterministic | 0 |
357,776 | 50,187,713 | Indication of overfitting | <p>I'm training an image recognition model using Inception and transfer learning, based on the Tensorflow of Poets tutorial.</p>
<p>I have it running for 500k steps, looking to see the optimum number of steps before overtraining strats. The below tensorboard image displays my training accuracy steadily rising but vali... | <p>It is crystal clear that you are overfitting your model. To solve the overfitting problem there are several solutions:
<br/>
1) Early stopping.
<br/>
2) Regularization.
<br/>
3) Reducing your model VC dimension by reducing the number of layers or number of units per layer.
<br/>
4) Augmenting your dataset.
<br/>
5) ... | tensorflow|machine-learning|tensorboard | 3 |
357,777 | 49,995,643 | Input Layer in keras model class gives type-error with numpy array or tensors as input. What is the correct type then? | <p>How to give input to the model if not a numpy array? </p>
<pre><code>def createmodel():
myInput = Input(shape=(96, 96, 3))
x = ZeroPadding2D(padding=(3, 3), input_shape=(96, 96, 3))(myInput)
x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1')(x)
x = BatchNormalization(axis=3, epsilon=0.00001, name='bn1')(x)
x... | <p>You are passing numpy arrays as inputs to build a Model, and that is not right, you should pass instances of Input.</p>
<p>In your specific case, you are passing <code>in_a, in_p, in_n</code> but instead to build a Model you should be giving instances of Input, not K.variables (your <code>in_a_a, in_p_p, in_n_n</co... | numpy|tensorflow|keras|tensor | 1 |
357,778 | 49,822,414 | Drop rows of a pandas dataFrame with unique elements in a given column. (by unique I mean repeated once) | <p>Let's say I have the following dataFrame and I want to drop the rows containing 10, and 100, i.e. the elements that have appeared only once in col1.</p>
<p><a href="https://i.stack.imgur.com/Qx1pR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qx1pR.png" alt="DataFrame"></a></p>
<p>I can do the... | <p>You can use the <code>duplicated</code> method on <code>col1</code>, which can detect whether an element has duplicates with <code>keep=False</code> parameter and returns a boolean Series which you can use to <em>subset/filter/drop</em> rows:</p>
<pre><code>df[df.col1.duplicated(keep=False)]
# col1 col2 months... | python|pandas|dataframe|row|unique | 3 |
357,779 | 49,881,751 | MultiIndex Pivot Table with Subtotals in Pandas | <p>Helllo,</p>
<p>I have the following data:</p>
<pre><code>date item_type item_name gold_exit
2018-01-25 type1 item1 1
2018-01-25 type2 item2 2
2018-01-25 type3 item3 3
2018-01-25 type1 item4 4
2018-01-25 type2 item5 5
2018-01-26 type3 item6 6
2018-01-26... | <p>This will need the <code>pd.concat</code> and <code>sum</code> notice i pass the para to level , cause you want to have the subtotal for index date and item_type</p>
<pre><code>s=pd.concat([table,table.sum(level=[0,1]).assign(iten_name='result').set_index('iten_name',append=True)]).sort_index(level=[0,1,2])
s
Out[7... | pandas|pivot-table|subtotal | 2 |
357,780 | 49,831,072 | Drop with condition | <p>I have certain rows that I want to drop from the df1. I did write the conditions this way and showed me the exact rows that I wanted to delete. However, when I try to apply drop on this data, it doesn't work :</p>
<pre><code>to_be deleted = df1.loc[df1['barcode'].str.contains('....-..-....-11.', regex=True)]
</code... | <p>You do not need to use <code>pd.DataFrame.drop</code> for this:</p>
<pre><code>mask = df1['barcode'].str.contains('....-..-....-11.', regex=True)
df1 = df1[~mask]
</code></pre>
<p>The <code>~</code> operator represents negation. Since <code>mask</code> is a Boolean array, it is negated and used as a row filter on... | python|python-3.x|pandas | 0 |
357,781 | 50,117,840 | pandas dataframe: identifiy NaN and zero values in one statement | <p>Is there any way to combine the two statements
<code>df.isnull().sum()</code> and
<code>(df == 0).sum()</code> to get the following overview?</p>
<p>Demo:</p>
<pre><code>df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,NaN,1,NaN,1], 'c':[0,0,0,0,NaN]})
df
a b c
0 1 0.0 0.0
1 0 NaN 0.0
2 0... | <p>With <code>fillna</code></p>
<pre><code>df.fillna(0).eq(0).sum()
Out[8]:
a 2
b 3
c 5
dtype: int64
</code></pre> | python|pandas|dataframe | 5 |
357,782 | 49,793,652 | Find different rows between 2 dataframes of different size with Pandas | <p>I have 2 dataframes df1 and df2 of different size.</p>
<pre><code>df1 = pd.DataFrame({'A':[np.nan, np.nan, np.nan, 'AAA','SSS','DDD'], 'B':[np.nan,np.nan,'ciao',np.nan,np.nan,np.nan]})
df2 = pd.DataFrame({'C':[np.nan, np.nan, np.nan, 'SSS','FFF','KKK','AAA'], 'D':[np.nan,np.nan,np.nan,1,np.nan,np.nan,np.nan]})
</co... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a> with<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> :</p>
<p>Also om... | python|pandas|for-loop|dataframe|row | 3 |
357,783 | 50,097,947 | Pandas reshape DataFrame | <blockquote>
<p>I have the following dataframe:</p>
</blockquote>
<pre><code>data = {"start_date" : ["2018-04-30", "2018-05-01"]
,"end_date" : ["2018-05-01", "2018-05-02"]
,"budget" : [10, 12]}
df = pd.DataFrame(data)
df["start_date"] = pd.to_datetime(df["start_date"])
df["end_date"] = pd.to_d... | <p>The solution is based on this thread:</p>
<p><a href="https://stackoverflow.com/questions/46659378/python-duplicate-rows-x-number-of-times-based-on-a-value-in-a-column">python - Duplicate rows x number of times based on a value in a column</a></p>
<pre><code>df['Number of days'] = (df['end_date']-df['start_date'])... | python|pandas | 0 |
357,784 | 50,109,452 | how transform vector to another vector space in python/pandas? | <p>I have a vector with fixed column size, for example from 0 to 9, initially are all 0s.[0,..0]</p>
<p>And, I want to transform vectors like [1,2,3] as [0, 1, 1, 1, 0, 0,...0]</p>
<p>Is there any way to do it other than iterate through every number?</p>
<p>I created a data frame already and trying to insert each ve... | <p>Use <code>numpy</code>.</p>
<pre><code>zeros = np.zeros(9)
zeros[[1,2,3]] = 1
</code></pre> | python|pandas | 0 |
357,785 | 50,067,224 | Hyperparameter optimization for Neural Network written in keras | <p>Is there a python3 library that optimizes KERAS NN hyperparameters on GPU? </p>
<p>I have tried using sklearn with KerasClassifier wrapper, but it uses cpu. </p> | <p>Yes there is. You can use <a href="https://github.com/autonomio/talos" rel="nofollow noreferrer">Talos</a>, which is a hyperparameter optimization solutions specifically for Keras models. It supports both GPU and multi-GPU use. Full disclosure: I'm the maintainer of the package.</p> | tensorflow|optimization|keras|hyperparameters|talos | 0 |
357,786 | 50,175,080 | Select Rows Where MultiIndex Is In Another DataFrame | <p>I have one DataFrame (DF1) with a MultiIndex and many additional columns. In another DataFrame (DF2) I have 2 columns containing a set of values from the MultiIndex. I would like to select the rows from DF1 where the MultiIndex matches the values in DF2.</p>
<pre><code>df1 = pd.DataFrame({'month': [1, 3, 4, 7, 10],... | <p>You could just <code>set_index</code> on <code>df2</code> the same way and pass the index:</p>
<pre><code>In[110]:
df1.loc[df2.set_index(['year','month']).index]
Out[110]:
sale
year month
2012 1 55
2014 10 31
</code></pre>
<p>more readable version:</p>
<pre><code>In[111]:
idx = df... | pandas | 2 |
357,787 | 50,139,669 | Pandas how to use column name in output string | <p>Real simple question that I cant seem to get. For the following single column DF:</p>
<pre><code>Cost
1
</code></pre>
<p>What syntax would I use to print "Cost = 1". i know print df['Cost'] would be 1. But i want the column name to be in the output. </p> | <p>This is one way without having to reference your column name(s) explicitly.</p>
<pre><code>df = pd.DataFrame({'Cost': [1]})
for k in df:
print('{0} = {1}'.format(k, df[k].iloc[0]))
# Cost = 1
</code></pre> | python|pandas | 2 |
357,788 | 49,893,124 | Issues with freezing Python Pandas | <p>I just upgraded from Python 2.7 to 3.6.
I have a rather large script with a GUI which I had frozen to an .exe file with pyinstaller. </p>
<p>I have now made a few changes to the .py script and it works with the new Python version before I freeze it.</p>
<p>However, when I freeze I get a "Failed to execute script" ... | <p>@apogalacticon Thanks! </p>
<p>Adding the following line to the .spec file solved the problem:</p>
<pre><code>hiddenimports = ['pandas._libs.tslibs.timedeltas']
</code></pre> | python|pandas|pyinstaller | 2 |
357,789 | 50,046,134 | How to get the shortest array shape in a python numpy multidimensional array? | <p>If I have a multidimensional numpy array like:</p>
<pre><code>>> x = np.array([
np.array([0, 1, 2, 3, 4, 5]),
np.array([0, 1, 2, 3, 4]),
np.array([0, 1, 2, 3]),
np.array([0, 1, 2, 3, 4]),
np.array([0, 1, 2, 3, 4, 5, 6]),
])
>> x.shape
(5,)
</code></pre>
<p>Is there a "pythonic way"... | <p>Do you need just the shortest array?</p>
<p>If yes I believe this is the easiest way </p>
<pre><code>import numpy as np
l = []
x = np.array([
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 5, 6],
])
for i in x:
l.append(np.shape(i))
print (min(l))
</code></pre> | python|arrays|numpy|multidimensional-array|shapes | 0 |
357,790 | 49,845,666 | Python pandas tolist() not returning a list but [[]] | <p>Why is the tolist() method not returning a list in my case, but something looking like the following?</p>
<blockquote>
<p>Loaded metadata for ShotID: 007_0030
[['007_0030', '01.02.2018', '1001-1085', '28 mm', 'T. 4', '10 m', 'Super 35', 'Sony FS7', 'Zeiss Ultra Prime', '30', '172.8°', 'dolly', '', '', '', '']]<... | <p>A DataFrame is a table. <code>.tolist()</code> returns a list of lists, one list per row. If you have only one row, extract it with <code>df.values[ix].tolist()[0]</code>.</p> | python|pandas | 1 |
357,791 | 50,051,040 | Could not convert string to float while using numpy.loadtxt | <p>Code:</p>
<pre><code>import csv
import numpy
raw_data = open('C:\\Users\\train.csv', 'rt')
data = numpy.loadtxt(raw_data, delimiter=",")
print(data.shape)
</code></pre>
<p>Below is the sample data used</p>
<pre><code>Time Freq
8:00 91.1
8:03 91.1
8:06 91.1
8:09 91.1
8:12 91.1
8:15 91.1
8:18 ... | <pre><code>In [350]: txt ='''Time Freq
...: 8:00 91.1
...: 8:03 91.1
...: 8:06 91.1
...: 8:09 91.1
...: 8:12 91.1
...: 8:15 91.1
...: 8:18 91.1
...: 8:21 91.1
...: 8:24 91.1
...: 8:27 91.1
...: 8:30 91.1
...: '''
</code></pr... | python|python-3.x|numpy|machine-learning|scikit-learn | 2 |
357,792 | 50,124,158 | Keras Loss Function with Additional Dynamic Parameter | <p>I'm working on implementing prioritized experience replay for a deep-q network, and part of the specification is to multiply gradients by what's know as importance sampling (IS) weights. The gradient modification is discussed in section 3.4 of the following paper: <a href="https://arxiv.org/pdf/1511.05952.pdf" rel=... | <p>OK. Here is an example. </p>
<pre><code>from keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten
from keras.models import Model
from keras.losses import categorical_crossentropy
def sample_loss( y_true, y_pred, is_weight ) :
return is_weight * categorical_crossentropy( y_true, y_pred )
x = Input(sha... | tensorflow|keras | 30 |
357,793 | 50,175,711 | Pytorch: Gradient of output w.r.t parameters | <p>I'm interested in Finding the Gradient of Neural Network output with respect to the parameters (weights and biases).</p>
<p>More specifically, assume I have the following Neural Network Structure [6,4,3,1]. The input samples size is 20. What I'm interested in, is finding the gradient of Neural Network output w.r.t ... | <p>The matrix of partial derivatives of a function with respect to its parameters is known as the <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant" rel="nofollow noreferrer">Jacobian</a>, and can be computed in PyTorch with:</p>
<pre class="lang-py prettyprint-override"><code>torch.autograd.functi... | python|neural-network|pytorch|gradient-descent|autograd | 0 |
357,794 | 49,863,742 | Calculating monthly retention | <p>I've been performing a cohort analysis for a SaaS company, and I have been using <a href="http://www.gregreda.com/2015/08/23/cohort-analysis-with-python/" rel="nofollow noreferrer">Greg Rada's</a> example, and I ran into some trouble looking up a cohorts retention. </p>
<p>Right now, I have a dataframe set up as:</... | <p>You can use multi_indexing and then grouping on 2 columns.</p>
<pre><code>dfsort = dfsort.set_index(['Cohort', 'Retention'])
dfsort.groupby(['Cohort', 'Retention']).count()
</code></pre>
<p>However, in your data, you only have one 'Retention' date for each cohort, which is why you don't see different Retention dat... | python|pandas | 0 |
357,795 | 50,026,456 | get pandas dataframe group meeting condition | <p>I have a dataframe say with columns as course, section, student_id
Each course can have one or more sections, each section one or more students:
course . section student_id
maths . sec1 . stu1
maths . sec1 . stu2
maths . sec2 . stu3
physics . sec1 . stu4
...
...</p>
<p>How can I get t... | <p>If you have a <code>DataFrame</code> like this:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'course': ['A','A','A','A','A','A','B','B', 'C'],
'section': [1,1,1,2,3,3,1,2, 1],
'student_id': ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'aaa', 'aaa', 'fff', 'gg... | pandas|dataframe|pandas-groupby | 0 |
357,796 | 49,943,442 | Randomly sized chunking of a numpy array in python | <p>I would like to divide an index array in randomly sized chunks (taken from a limited range of possible sizes) which are also shuffled between each other. I tried the following I found <a href="https://codereview.stackexchange.com/questions/4872/pythonic-split-list-into-n-random-chunks-of-roughly-equal-size">here</a>... | <p>This'll work:</p>
<pre><code>from itertools import chain
import numpy as np
a = np.arange(1, 100)
def chunk(xs, nlow, nhigh, shuffle=True):
xs = np.asarray(xs)
if shuffle:
# shuffle, if you want
xs = xs.copy()
np.random.shuffle(xs)
# get at least enough random chunk sizes in th... | python|arrays|numpy | 2 |
357,797 | 50,030,448 | Rows not being appended correctly in Pandas | <p>I am currently trying to scrape data from the research database - ScienceDirect. I am obtaining the title of each research article using Beautiful Soup and adding it to an empty pandas dataframe. Following this, I obtain information on the type of research article for above articles. However, when I try to append th... | <p>As per comments, <code>pd.DataFrame.append</code> is used to append the dataframe - by definition <em>add</em> new rows - that's why data you try to insert are instead attached in new rows. You can insert data into the dataframe individually but it's not pretty. For example, you can insert with <code>data.loc[i,'Tit... | python|pandas|selenium|dataframe|web-scraping | 0 |
357,798 | 49,990,758 | Combining two dataframes into one dataframe w/ condtional | <p>I'm trying to calculate the crime rate per 100,000 population using values from two separate pivot table dataframes. </p>
<pre><code>Crime Total
Year 2010 2011 2012 2013 2014 2015 2016
CountyName
Alameda ... | <pre><code>df_pop
Out[97]:
Year 2010 2011 2012 2013 2014 2015 \
CountyName
Alameda 1510271.0 1525695.0 1543027.0 1567091.0 1588348.0 1611318.0
Alpine 1175.0 1169.0 1166.0 1164.0 1... | python|pandas|dataframe|pivot-table | 0 |
357,799 | 50,146,481 | Python Pandas Dataframe loop iteration | <pre><code>import pandas as pd
import re
df1 = pd.DataFrame({"Greetings": ["Greetings to you too", "hi", "hello", "hey", "greetings", "sup", "what's up", "yo"]})
df2 = pd.DataFrame({"Farewell": ["GoodBye", "See you", "Bye", "Laters"]})
frames = [df1, df2]
df3=pd.concat(frames, axis=1, join='outer', copy=True)
sente... | <p>I got the answer finally, the code just needed a tweak:</p>
<pre><code>for index, row in df3.iterrows():
if index>0:
if sentence.lower() in df3.iloc[index,:].values:
print((df3.iloc[:index]).iloc[0,0])
</code></pre> | python|pandas|for-loop|iteration | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.