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
7,900
56,186,710
Does Tensorflow automaticaly use multiple CPUs?
<p>I have programmed some code doing an inference with Tensorflow's C API (CPU only). It is running on a cluster node, where I have access to 24 CPUs and 1 GPU. I do not make use of the GPU as I will need to do the task CPU-only later on.</p> <p>Somehow every time I call the Tensorflow-Code from the other program (Ope...
<p>I am not sure how you are using tensorflow. But a typical TensorFlow training has an input pipeline which can be thought as an ETL process. Following are the main activities involved: </p> <p><strong>Extract</strong>: Read data from persistent storage</p> <p><strong>Transform</strong>: Use CPU cores to parse and p...
tensorflow|deep-learning|c-api
2
7,901
56,077,273
Replacing NAN value in a pandas dataframe from values in other records of same group
<p>I have a dataframe <code>df</code> </p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': [np.nan, 1, 2,np.nan,2,np.nan,np.nan], 'B': [10, np.nan, np.nan,5,np.nan,np.nan,7], 'C': [1,1,2,2,3,3,3]}) </code></pre> <p>which looks like :</p> <pre><code> A ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a> with forward and back filling missing values:</p> <pre><code>df[['A','B']] = df.groupby('C')['A','B'].apply(lambda x: x.ffill().bfill()) print (df) ...
python|pandas|nan
3
7,902
55,922,703
Multiplying a certain row of a dataframe by the values of another row of another dataframe of the same dimensions
<p>I have a dataframe that I am populating by iterating through it by rows and trying to multiply the previous row by the values contained in another row of another dataframe of the same dimensions and then insert the resulting row into the first dataframe.</p> <p>I've used .loc to filter the row of each dataframe and...
<p>OK, I found a solution... not an elegant one, but it works.</p> <p>I suspect the issue was being caused by the fact that pandas / python was not reading the dfReturns1 single row as a Series while dfPortW was one. What solved it was:</p> <pre><code> j = dfReturns1["Dates"][dfReturns1["Dates"] == date] j = j...
python|pandas
0
7,903
65,044,179
PyTorch is giving me a different value for a scalar
<p>When I create a tensor from float using PyTorch, then cast it back to a float, it produces a different result. Why is this, and how can I fix it to return the same value?</p> <pre><code>num = 0.9 float(torch.tensor(num)) </code></pre> <p>Output:</p> <pre><code>0.8999999761581421 </code></pre>
<p>This is a floating-point &quot;issue&quot; and you read more about how Python 3 handles those <a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow noreferrer">here</a>.</p> <p>Essentially, not even <code>num</code> is actually storing 0.9. Anyway, the print issue in your case comes from the ...
floating-point|pytorch|tensor
2
7,904
64,720,445
Remove the weight_orig in Pytorch after Pruning a model
<p>After a model is pruned in Pytorch, the saved model contains both the pruned weights and weight_orig. This causes the pruned model size to be greater than the unpruned model. Is there a way to remove the weight_orig and reduce the pruned model size?</p>
<p>As explained in the <a href="https://pytorch.org/tutorials/intermediate/pruning_tutorial.html#remove-pruning-re-parametrization" rel="nofollow noreferrer">offcial documentation</a>, you can use <code>torch.nn.utils.prune.remove()</code> for this very purpose.<br /> <code>remove()</code> removes the re-parametrizatio...
deep-learning|pytorch|pruning
0
7,905
64,776,592
Transpose multiple columns in pairs of two - pandas python
<p>I would like to transpose multiple columns in pairs of two</p> <p>I have the following columns:</p> <pre><code>user_id', 'fullname', 'email', 'handle', 'audience_ethnicities_code0', 'audience_ethnicities_weight0', 'audience_ethnicities_code1', 'audience_ethnicities_weight1', 'audience_ethnicities_code2', 'audience_e...
<p>I would iteratively do the pivot for each column and then merge the dataframes by their index.</p> <p>Here an example:</p> <pre><code>from functools import reduce index = ['user_id', 'fullname', 'email', 'handle'] dfList = [] for i in range(3): dfList.append(df.pivot_table(index=index, ...
python|pandas|pivot|transpose
0
7,906
39,883,656
Combining dataframes in pandas with the same rows and columns, but different cell values
<p>I'm interested in combining two dataframes in pandas that have the same row indices and column names, but different cell values. See the example below:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN], 'B':[23,4,np.NaN,np.NaN], ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>:</p> <pre><code>print (df1.combine_first(df2)) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0...
python|pandas|dataframe|merge|concat
2
7,907
39,957,815
Not a JPEG file: starts with 0xc3 0xbf
<p>I am trying to decode jpeg file using tf.image.decode_jpeg but it says its not a JPEG file. I don't know what the problem is.Can anyone help me to solve this problem?</p> <p>This is my test code.</p> <pre><code>import tensorflow as tf path = "/root/PycharmProjects/mscoco/train2014/COCO_train2014_000000291797.jpg"...
<p>You're reading an image file as if it were a text file.</p> <p>Just change the line:</p> <pre><code>with open(path, "r", encoding="latin-1") as f: </code></pre> <p>with</p> <pre><code>with open(path, "rb") as f: </code></pre> <p>To read the image as a binary ("rb" = Read Binary) file.</p>
python|tensorflow
3
7,908
44,228,539
Delete based on index, without knowing where it is
<p>Say I have a <code>pandas.DataFrame</code> with a <code>MultiIndex</code> and I know it has two levels and <code>year</code> is in the first one, and I want to keep particular years, I can do</p> <pre><code>df = df.loc[yearStart:, :] </code></pre> <p>If I know the index has only two levels, but not in which <code...
<p>You can use <code>get_level_values</code> to get a column-like view of an index level.</p> <pre><code>df = pd.DataFrame({'a': range(100)}, index=pd.MultiIndex.from_product([range(10), range(2010,2020)], names=['idx1', 'year'])) df.head() Out[41]: a idx1 year 0 2010 0 2011 1 2012 2 ...
python|pandas
4
7,909
44,226,065
TF-slim layers count
<p>Would the code below represent one or two layers? I'm confused because isn't there also supposed to be an input layer in a neural net?</p> <pre class="lang-python3 prettyprint-override"><code>input_layer = slim.fully_connected(input, 6000, activation_fn=tf.nn.relu) output = slim.fully_connected(input_layer, num_out...
<p><a href="https://i.stack.imgur.com/6O50G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6O50G.png" alt="enter image description here"></a></p> <p>You have a neural network with one hidden layer. In your code, <code>input</code> corresponds to the 'Input' layer in the above image. <code>input_lay...
tensorflow|neural-network|tf-slim
1
7,910
44,163,155
Python - Pulling Indices data from Google Finance
<p>I am trying to pull Historical data of Indices from Google Finance, but it's not working. While I am able to pull historical data of an individual stock easily. Am I doing something wrong with Indices?</p> <p>My code for Stock</p> <pre><code>from pandas_datareader import data from dateutil.relativedelta import rel...
<p>I am not sure where the issue is, however there is a difference on GOOGLE Finance website.</p> <p>When you try to see historical data for GOOGL:<br> <a href="https://finance.google.com/finance/historical?q=NASDAQ:GOOGL" rel="nofollow noreferrer">https://finance.google.com/finance/historical?q=NASDAQ:GOOGL</a></p> ...
python|pandas|google-finance
2
7,911
69,540,950
Count observations per date and per date & category
<p>I need to explain one behavior of pandas. Suppose this dataframe:</p> <pre class="lang-py prettyprint-override"><code>index;day;id;value 0;2020-01-03;1;14 1;2020-01-03;1;2 2;2020-01-03;2;5 3;2020-01-05;1;7 4;2020-01-05;1;9 </code></pre> <p>When I want to compute number of observation per day and id I can simple do:<...
<p>It's a <em>warning</em>, not an error. I think the code will have done what you want it to do.</p> <p>And it's a very common error, Googling &quot;SettingWithCopyWarning&quot; returns hundreds of articles and StackOverflow posts</p>
python|pandas|date
0
7,912
69,621,513
Extract strings from pandas df using regex
<p>I need help with regex for Python Pandas dataframe. Testing strings would be:</p> <pre><code>s = pd.Series(['xslF345X03/was-form4_163347386959085.xml', 'xslF345X03/wf-form4_163347386959085.xmlasdf', 'xslF345/X03/wf-form4_163347386959085.xml']) </code></pre> <p>I would like to:</p> <ul> <li><strong>extract starting f...
<p>Use <code>str.extract</code>:</p> <pre><code>&gt;&gt;&gt; s.str.extract(r'.*/(.*\.xml)$') 0 0 was-form4_163347386959085.xml 1 NaN 2 wf-form4_163347386959085.xml </code></pre>
python|regex|pandas
1
7,913
69,590,456
I am trying to pivot a json file using pandas to be in a specific format. I want to pivot it on certain columns
<p>So I tried searching on the web to find a way in which I can convert the following json.</p> <pre><code>{ &quot;eTask_ID&quot;: &quot;100&quot;, &quot;Organization&quot;: &quot;Power&quot;, &quot;BidID&quot;: &quot;2.00&quot;, &quot;Project&quot;: &quot;IPP - C&quot;, &quot;Forecast%&quot;: &quot;67&quot;, &quot;Spo...
<p>Use <code>pd.melt</code>:</p> <pre><code>import json with open('data.json') as json_data: data = json.load(json_data) out = pd.DataFrame.from_dict(data, orient='index').T \ .melt(['eTask_ID', 'Organization', 'BidID', 'Project'], var_name='Attribute', value_name='AttrValue...
python|json|pandas|dataframe
0
7,914
40,904,392
Easy pythonic way to classify columns in groups and store it in Dictionary?
<pre><code> Machine_number Machine_Running_Hours 0 1.0 424.0 1 2.0 458.0 2 3.0 465.0 3 4.0 446.0 4 5.0 466.0 5 6.0 466.0 6 ...
<p>I think you need substract <code>1</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sub.html" rel="nofollow noreferrer"><code>sub</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.floordiv.html" rel="nofollow noreferrer"><code>floor...
python|pandas|numpy
2
7,915
41,150,846
One-hot encoding
<p>I have a csv file like this:</p> <pre><code>text short_text category ... ... ... </code></pre> <p>I have opened the file and stored it in a Pandas data frame like so:</p> <pre><code>filepath = 'path/data.csv' train = pd.read_csv(filepath, header=0, delimiter=",") </code></pre> <p>The category fields for ...
<p>you can use <code>pd.value_counts</code> to help</p> <pre><code>df = pd.DataFrame(dict( text=list('ABC'), short_text=list('XYZ'), category=[list('abc'), list('def'), list('abefxy')] )) df.category.apply(pd.value_counts).fillna(0).astype(int) </code></pre> <p><a href="https://i.stack.im...
python|pandas|scikit-learn|one-hot-encoding
0
7,916
41,164,473
Write Pandas Dataframe via SQLAlchemy in MySQL database
<p>I am trying to write a pandas dataframe into a mysql database using pandas. This works perfect for me using </p> <blockquote> <p>to_sql</p> </blockquote> <p>But what I want is to write the date, ticker and the adj_close in the table test on my own using sqlalchemy. Somehow I tried doing it but it is not working....
<p>To insert multiple rows in a single <code>INSERT</code>, don't pass a <code>Series</code> for each column, pass a list of records.</p> <pre><code>test.insert().values(DataLevels[['Date', 'ticker', 'adj_close']].to_dict('records')) </code></pre>
python|mysql|pandas|dataframe|sqlalchemy
2
7,917
40,822,250
how to save Python pandas data into excel file?
<p>I am trying to load data from the web source and save it as a Excel file but not sure how to do it. What should I do? The original dataframe has different columns. Let's say that I am trying to save 'Open' column</p> <pre><code>import matplotlib.pyplot as plt import pandas_datareader.data as web import datetime imp...
<p>Once you have made the pandas dataframe just use <code>to_excel</code> on the entire thing if you want:</p> <p><code>aa.to_excel('output/filename.xlsx')</code></p>
python|pandas|dataframe|pandas-datareader
3
7,918
54,244,613
How to transpose and transform to "one-hot-encode" style from a pandas column containing a set?
<p>I want to perform a break down to a pandas column similarly to the <a href="https://stackoverflow.com/questions/45312377/how-to-one-hot-encode-from-a-pandas-column-containing-a-list">question</a>:</p> <p>I want to transpose and then "one-hot-encode" style. For example, taking dataframe <strong>df</strong></p> <pre...
<p>Here is a possible answer (assuming Col1 is your index):</p> <pre><code>from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() one_hot_encoded = pd.DataFrame(mlb.fit_transform(df['Col2']), columns=mlb.classes_, index=df.index) one_hot_encoded.T </code></pre>
python|pandas|numpy|scikit-learn|sklearn-pandas
2
7,919
66,299,739
Append a tensor vector to tensor matrix
<p>I have a tensor matrix that i simply want to append a tensor vector as another column to it.</p> <p>For example:</p> <pre><code> X = torch.randint(100, (100,5)) x1 = torch.from_numpy(np.array(range(0, 100))) </code></pre> <p>I've tried <code>torch.cat([x1, X)</code> with various numbers for both <code>axis</c...
<p>You can also use <a href="https://pytorch.org/docs/stable/generated/torch.hstack.html#torch-hstack" rel="nofollow noreferrer"><code>torch.hstack</code></a> to combine and <a href="https://pytorch.org/docs/stable/generated/torch.unsqueeze.html" rel="nofollow noreferrer"><code>unsqueeze</code></a> for reshape <code>x1...
python|pytorch
3
7,920
66,047,584
Replacing specific values in a Pandas dataframe basing on the values of another column
<p>I have a DataFrame similar to this:</p> <pre><code>Chr Start_Position End_Position Type 1 10000 10001 SNP 5 45321 45327 INS 12 44700 44710 DEL </code></pre> <p>I need to change the values of some cells depending on what <code>Type</code> is:</p> <ul> <li><code...
<p>You can just do:</p> <pre><code>df.loc[df['Type'].isin(['SNP','INS']), 'Start_Position'] += 1 df.loc[df['Type'].eq('INS'), 'End_Position'] += 1 </code></pre>
python|pandas|dataframe
4
7,921
52,811,542
when trying to run tf.confusion matrix it gives end of sequence error
<p>I am preparing my dataset using new tensoflow input pipeline, here is my code:</p> <pre><code>train_data = tf.data.Dataset.from_tensor_slices(train_images) train_labels = tf.data.Dataset.from_tensor_slices(train_labels) train_set = tf.data.Dataset.zip((train_data,train_labels)).shuffle(500).batch(30) valid_data = ...
<p>The problem is related with the graph flow execution. Look at this line:</p> <pre><code>print(sess.run(confusion, feed_dict={keep_prob: 1.0})) </code></pre> <p>You are running the graph for getting the 'confusion' value. So all dependent nodes will be also executed. Then:</p> <pre><code>finalprediction = tf.argma...
python-3.x|tensorflow
1
7,922
52,835,711
add numeric prefix to pandas dataframe column names
<p>how would I add variable numeric prefix to dataframe column names </p> <p>If I have a DataFrame df</p> <pre><code> colA colB 0 A X 1 B Y 2 C Z </code></pre> <p>How would I rename the columns according to the number of columns. Something like this:</p> <pre><code> 1_colA 2_colB 0 A X ...
<p>Use <code>enumerate</code> for count with <code>f-string</code>s and list comprehension:</p> <pre><code>#python 3.6+ df.columns = [f'{i}_{x}' for i, x in enumerate(df.columns, 1)] #python below 3.6 #df.columns = ['{}_{}'.format(i, x) for i, x in enumerate(df.columns, 1)] print (df) 1_colA 2_colB 0 A X 1...
python-3.x|pandas
4
7,923
58,584,908
How to make pandas pivot table look like excel pivot table
<p><a href="https://i.stack.imgur.com/pbxS6.png" rel="nofollow noreferrer">pivot table in excel</a></p> <pre><code>df=pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Orange', 'Orange'], 'Variety':['Fuji', 'Navel', 'Honeycrisp', 'Gala', 'Tangerine', 'Clementine'], 'Count':[2, 5, 5, ...
<p>IIUC,</p> <pre><code>df_grand = df[['Count']].sum().T.to_frame(name='Count').assign(Fruit='Grand Total', Variety='').set_index(['Fruit','Variety']) df_sub = df.groupby('Fruit')[['Count']].sum().assign(Variety='').set_index('Variety', append=True) df_excel = df.set_index(['Fruit','Variety']).append(df_sub).sort_in...
python|excel|pandas
0
7,924
58,374,112
Can not remove 'Unmamed:' row
<p>I am reading an excel sheet and got the result like below image,</p> <p><a href="https://i.stack.imgur.com/BbuN9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BbuN9.png" alt="enter image description here"></a></p> <pre><code>df_result = pd.read_excel(file_path, sheet_name='Person', index=False...
<p>You can skip some number of rows before headers, here 1 row (working because empty rows are excluded by default):</p> <pre><code>df_result = pd.read_excel(file_path, sheet_name='Person', index=False, skiprows=1) </code></pre>
python|excel|pandas
1
7,925
69,069,041
Finding string length and append with another column in dictionary format from csv in python
<p>My dataframe - <a href="https://i.stack.imgur.com/FrrJO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FrrJO.png" alt="enter image description here" /></a></p> <p>Basically -I want to append house and district column</p> <ul> <li>Then find the string length for both columns; in this case House 26...
<p>Try using this list comprehension:</p> <pre><code>&gt;&gt;&gt; [(k, {'entities': [[[0, len(k.rpartition(' ')[0]) - 1], v['label1']], [(k.rfind(' ') + 1, len(k) - 1), v['label2']]]}) for k, v in df.set_index(['house', 'district']).set_axis(df[['house', 'district']].agg(' '.join, axis=1)).to_dict('index').items()] [('...
python|pandas|list|dataframe|dictionary
1
7,926
68,898,150
Speeding up a complex python dataframe transposition
<p>I've got three tables. I need to manipulate table 1 and 2 to get table 3.</p> <p>Table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>GENEID</th> <th>person_1</th> <th>person_2</th> </tr> </thead> <tbody> <tr> <td>ENSG001</td> <td>0.01</td> <td>1.6</td> </tr> <tr> <td>ENSG002</td> <td...
<p>You can use <code>melt</code> on <code>df1</code> before merging:</p> <pre><code>&gt;&gt;&gt; df1.melt(id_vars='GENEID', value_vars=['person_1', 'person_2'], var_name='person_id', value_name='expression') \ .merge(df2, left_on='GENEID', right_on='ENSG') \ .drop(columns='ENSG') GENEI...
python|pandas|dataframe|optimization
4
7,927
69,134,379
How to make prediction based on model Tensorflow lite?
<p>I would like to make a prediction with my Tensorflow lite model. for that I've already trained my model and saved this in <code>tflite</code>. Know I would like to make a preditcion with my trained model. How can I do that? Ive tried something but its showing a error message</p> <blockquote> <p>hand = model_hands.pr...
<p>The problem is in the line <code>hand = model_hands.predict(X)[0]</code>. You are trying to call function <code>predict</code> on a string you defined above as <code>model_hands = 'converted_model.tflite'</code>.</p> <p>I believe what you want to do is load the model using an Interpreter, set the input tensor, and i...
python|tensorflow
0
7,928
68,998,096
Why is tf.GradientTape.jacobian giving None?
<p>I'm using the IRIS dataset, and am following this official tutorial: <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/customization/custom_training_walkthrough.ipynb" rel="nofollow noreferrer">Custom training: walkthrough</a></p> <p>In the Training loop, I am trying to ...
<p>You need to understand how the GradientTape operates. For that, you can follow the guide: <a href="https://www.tensorflow.org/guide/autodiff" rel="nofollow noreferrer">Introduction to gradients and automatic differentiation</a>. Here is an excerpt:</p> <blockquote> <p>TensorFlow provides the <code>tf.GradientTape</c...
tensorflow|keras|gradient|gradienttape
0
7,929
44,394,346
Matplotlib - plot wont show up
<p>I want to plot a function graph (using matplotlib) when a button is pressed, to do so I wrote the following code:</p> <pre><code>##--IMPORT #Tkinter from tkinter import Tk, ttk from tkinter import Frame, LabelFrame, Button from tkinter import FALSE #Numpy from numpy import linspace #Sympy from sympy import symbols,...
<p>You would need to redraw the canvas after you have plotted to it.</p> <p>Adding the line </p> <pre><code>plotToDrawTo.figure.canvas.draw_idle() </code></pre> <p>at the end of your <code>pr_draw</code> function should do that. </p> <p>Note that I also had to add <code>_root.mainloop()</code> at the end of the scr...
numpy|matplotlib|python-3.4|sympy
0
7,930
44,516,609
Tensorflow : What is the relationship between .ckpt file and .ckpt.meta and .ckpt.index , and .pb file
<p>I used <code>saver=tf.train.Saver()</code> to save the model that I trained, and I get three kinds of files named:</p> <ul> <li>.ckpt.meta </li> <li>.ckpt.index</li> <li>.ckpt.data</li> </ul> <p>And a file called:</p> <ul> <li>checkpoint</li> </ul> <p>What is the connection with the <strong>.ckpt</strong> file? ...
<ul> <li><p>the .ckpt file is the old version output of <code>saver.save(sess)</code>, which is the equivalent of your <code>.ckpt-data</code> (see below)</p></li> <li><p>the "checkpoint" file is only here to tell some TF functions which is the latest checkpoint file.</p></li> <li><p><code>.ckpt-meta</code> contains th...
python|tensorflow
44
7,931
60,828,618
Is there a way to make custom function in pandas aggregation function?
<p>Want to apply custom function in a Dataframe eg. Dataframe</p> <pre><code> index City Age 0 1 A 50 1 2 A 24 2 3 B 65 3 4 A 40 4 5 B 68 5 6 B 48 </code></pre> <p>Function to apply</p> <pre><code>def count_people_above_60(age): ** ...
<p>If performance is important create new column filled by compared values converted to <code>integer</code>s, so for count is used aggregation <code>sum</code>:</p> <pre><code>df = (df.assign(new = df['Age'].gt(60).astype(int)) .groupby(['City']) .agg(Mean= ("Age" , "mean"), People_Above_60= ('new',"s...
python|python-3.x|pandas|aggregate|pandas-groupby
2
7,932
71,608,700
Count occurrences of a string ocurring in multiple columns at the same time
<p>I have a data frame that looks like this:</p> <pre><code> data_ID col1 col2 0 001 Word1 Word1 1 002 Word2 Word2 2 003 Word1 Word3 3 004 Word1 Word1 </code></pre> <p>I would like to count the number of times <code>Word1</code> appear in both <code>col1</code> and <code>col2</code>. F...
<p>Just compare with <code>==</code> or <code>.eq()</code>, and then use <code>all</code> across the rows with <code>axis=1</code>. That'll a True for each row where <code>col1</code> and <code>col2</code> are both <code>Word1</code>. Then just use <code>sum</code>:</p> <pre><code>count = df[['col1', 'col2']].eq('Word1...
python|pandas
3
7,933
71,564,992
Aggregating in pandas with two different identification columns
<p>I am trying to aggregate a dataset with purchases, I have shortened the example in this post to keep it simple. The purchases are distinguished based on two different columns used to identify both customer and transaction. The reference refers to the same transaction, while the ID refers to the type of transaction.<...
<p>Use <code>drop_duplicates</code>, <code>groupby</code>, and <code>agg</code>:</p> <pre><code>new_df = df.drop_duplicates().groupby(['Name', 'Side']).agg({'Size': 'sum', 'ID': 'first'}).reset_index() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; new_df Name Side Size ID 0 Alex BUY 5400 0 1 Alex S...
python|pandas|sum|logic|aggregate
1
7,934
71,648,305
3-dimensional array reshaping? HDF5 dataset type?
<p>I have data in the following <strong>shape: (127260, 2, 1250)</strong></p> <p>The type of this data is <code>&lt;HDF5 dataset &quot;data&quot;: shape (127260, 2, 1250), type &quot;&lt;f8&quot;&gt;</code></p> <p>The first dimension (127260) is the number of signals, the second dimension (2) is the type of signal, and...
<p>If I understand, you want a new dataset with shape: <code>(2*127260, 2, 625)</code>. If so, it's fairly simple to read 2 slices of the dataset into 2 NumPy arrays, create a new array from the slices, then write to a new dataset. Note: reading slices is simple and fast. I would leave the data as-is and do this on-the...
python|multidimensional-array|reshape|numpy-ndarray|hdf5
1
7,935
42,516,341
Why there are missing nodes after graph intersection - NetworkX, igraph, python and r
<p>I'm experiencing something strange while trying to obtain the intersection between two networks/graphs. I found missing nodes when I check the resulting intersection and I wish to understand why this is happening.</p> <p>Originally I'm working with python 3.5.2 / pandas 0.17.1. on Linux Mint 18, and the dataset and...
<p>The reason is that the graphs are undirected. <code>intersection</code> in <code>igraph</code> and <code>networkx</code> treats an <em>I--J</em> tie and a <em>J--I</em> tie as equivalent. <code>panda.intersection</code> will only treat exact matches (i.e. column 1 in data frame A matches column 1 in data frame B <em...
python|r|pandas|igraph|networkx
1
7,936
42,300,123
Combining values from multiple rows into a single row
<p>I am working with several tables which have many-to-many relationships. What is the most efficient way to transform this data to ensure that the category column is unique and that all of the corresponding units are combined into a single row?</p> <pre><code>category unit A01 97337 A01 97333 A01 ...
<p>You can use <code>groupby</code> with <code>apply</code> <code>join</code>, if <code>unit</code> column is numeric is necessary cast to <code>string</code>:</p> <pre><code>df1 = df.groupby('category')['unit'] .apply(lambda x: ', '.join(x.astype(str))) .reset_index() print (df1) category ...
pandas
4
7,937
69,875,550
Python Flatten Deep Nested JSON
<p>I have the following JSON structure:</p> <pre><code>{ &quot;comments_v2&quot;: [ { &quot;timestamp&quot;: 1196272984, &quot;data&quot;: [ { &quot;comment&quot;: { &quot;timestamp&quot;: 1196272984, &quot;comment&quot;: &quot;OSI Beach Party Weekend, CA&quot...
<p>Use <code>record_path='data'</code> as argument of <code>pd.json_normalize</code>:</p> <pre><code>import json import codecs with codecs.open(infile, 'r', 'utf-8-sig') as jsonfile: data = json.load(jsonfile) df = pd.json_normalize(data['comments_v2'], 'data') </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&...
python|json|pandas|json-flattener
1
7,938
69,997,327
Tensorflow: ValueError: Input 0 is incompatible with layer model: expected shape=(None, 99), found shape=(None, 3)
<p>I am trying to predict with a ANN classification model made in Tensorflow to classify pose keypoints with MediaPipe. The mediapipe pose tracker has 33 keypoints for x y and z coordinates for a total of 99 data points.</p> <p>I am training for 4 classes.</p> <p>This is running the pose embedding</p> <pre><code>import...
<p>Maybe try changing the shape of <code>pose_landmarks</code> from <code>(33, 3)</code> to <code>(1, 99</code>) after your assertion and before you make a prediction:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf pose_landmarks = tf.random.normal((33, 3)) assert pose_landmarks.shape == (...
python|tensorflow|opencv|keras|neural-network
1
7,939
43,391,009
Pandas DataFrame to Seaborn
<p>I'm attempting to draw seaborn heatmap using pandas DataFrame. My data format is as below</p> <pre><code>visit_table yyyymm visit_cnt 0 201101 91252 1 201102 140571 2 201103 141457 3 201104 147680 4 201105 154066 ... 68 201609 591242 69 201610 650174 70 201611 507579 7...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> for converting the column <code>yyyymm</code> and then create new <code>Series</code> (columns) with <a href="http://pandas.pydata.org/pandas-docs/stable/generate...
pandas|dataframe|seaborn
2
7,940
43,402,017
Tensorflow LSTM - Matrix multiplication on LSTM cell
<p>I'm making a LSTM neural network in Tensorflow.</p> <p>The input tensor size is 92.</p> <pre><code>import tensorflow as tf from tensorflow.contrib import rnn import data test_x, train_x, test_y, train_y = data.get() # Parameters learning_rate = 0.001 epochs = 100 batch_size = 64 display_step = 10 # Network Para...
<p>static_rnn for making the simplest recurrent neural net.<a href="https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/static_rnn" rel="nofollow noreferrer">Here's the tf documentation</a>.So the input to it should be a sequence of tensors. Let's say you want to input 4 words calling "Hi","how","Are","you". So y...
python|tensorflow|lstm
1
7,941
43,104,965
Does groupby automatically group over all non numeric columns in pandas?
<p>I have a sample of a dataset below (only showing the first couple rows but there are 193 rows):</p> <pre><code>country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continent Afghanistan,0,0,0,0.0,Asia Albania,89,132,54,4.9,Europe Algeria,25,0,14,0.7,Africa Andorra,245,138,312,12.4,Europe...
<p>No!</p> <p>What is happening is that <code>head</code> is a method on the <code>groupby</code> object and behaves a little differently than <code>pd.DataFrame.head</code>.</p> <p>What the the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.head.html" rel="nofollow norefer...
python|pandas
2
7,942
45,408,544
Zip in python does not work properly with lists
<p>Here is what I tried: </p> <pre><code>&gt;&gt;&gt; d array([ 0.71428573, 0.69230771, 0.69999999], dtype=float32) &gt;&gt;&gt; f [('name', 999), ('ddd', 33), ('mm', 112)] &gt;&gt;&gt; for n1,s1,normal in zip(d,f): ... print(n1,s1,normal) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, i...
<p><code>f</code> is a nested list, hence to unpack its item to individual variables you need to do:</p> <pre><code>&gt;&gt;&gt; for n1, (s1, normal) in zip(d, f): ... print(n1, s1, normal) ... (0.71428573, 'name', 999) (0.69230771, 'ddd', 33) (0.69999999, 'mm', 112) </code></pre> <p>This is basically equivalent ...
python|python-2.7|list|numpy|zip
8
7,943
62,844,737
How to calculate monthly annual average from daily dataframe and plot it by abbreviated month
<p>I have daily values of precipitation and temperature for a period of several years. I would like to compute the average of the precipitation and temperature for each month of the year (January to December). For precipitation I first need to calculate the summation of daily precipitation for each month, and then comp...
<p>Here's working code for your problem:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import matplotlib.dates as mdates example = [['01.10.1965 00:00',13.88099957,5.375], ...] names = [&quot;date&quot;,&quot;Pobs&quot;,&quot;Tobs&quot;] data = pd.DataFr...
python|pandas|matplotlib|pandas-groupby
1
7,944
62,572,369
How to calculate mean in a particular subset and replace the value
<p>csv table :</p> <p><img src="https://i.stack.imgur.com/GkgrS.png" alt="csv table" /></p> <p>So I have a csv file that has different columns like nodeVolt, Temperature1, temperature2, temperature3, pressure and luminosity. Under temperatures column, there are various cells where the value is wrong (ie. 220). I want t...
<p>Here you go:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { &quot;something&quot;: 3.37, &quot;temperature3&quot;: [ 31.94, 31.93, 31.85, 31.91, 31.92, 31.89, 31.9, 31.94, ...
python|pandas|dataframe|csv|numpy-ndarray
1
7,945
54,488,667
.py file not running properly in py.exe, works in eclipse
<p>Hi I have a simple python script that uses an odbc driver to connect to a database get a dataframe and store it/overwrite an excel file. When I run the script using eclipse, it works just fine. However, when I run it by right clicking the .py file and open with py.exe, the excel file is not being overwritten/saved. ...
<p>Make a python file like this:</p> <pre><code>from sys import version_info, path print(version_info) print(path) </code></pre> <p>Then try opening with both methods you mentioned. The results should match, and if they don't then there is your issue. If they do match, you should add more logging/exception handling s...
python|excel|database|pandas|pyodbc
0
7,946
73,811,474
Numpy: Is there any simple way to solve equation in form Ax = b such that some x's takes fixed values
<p>So basically I want to solve Ax = b but I want the value of x1 to always be equation to say 4.</p> <p>For example, if A is 3x3 and x is 3x1 then the answer of the above equation should be in form x = [4, x2, x3]</p>
<p>if always x1=4, then x1 is no longer a unknown --&gt; insert x1=4 in each place of the system and simplify the equations (algebraically = manually) --&gt; you will get a system where A is 2x2 and x is 2x1.</p>
numpy|linear-equation
0
7,947
73,682,132
Read and tabulate table-like data from website
<p>I want to tabulate and store into Pandas this linked data from the <a href="https://water.weather.gov/ahps2/crests.php?wfo=jan&amp;gage=jacm6&amp;crest_type=historic" rel="nofollow noreferrer">U.S. Weather Service</a>.</p> <p>Here are the first four lines of the webpage.</p> <blockquote> <p>Historic Crests</p> <p>(1...
<p>You could create a <em>regex</em> pattern and feed it to <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>Series.str.extractall</code></a>. E.g.:</p> <pre><code>tbl = soup.find('div', class_='water_information') vals = tbl.get_text().split(r'\n'...
python|html|pandas|dataframe
2
7,948
73,685,342
Efficient approach to append zeroes to product id which are not present on a particular date
<p>I'm trying to append zeroes to product id's data which are not present for any particular date and my code takes lot of time to append zeroes. Looking for an alternate approach in pandas/numpy.</p> <p>Here is the sample data:</p> <pre class="lang-none prettyprint-override"><code>rpt_date product_id total_views...
<p>You should almost certainly be solving this problem in the query that generated the data to begin with. But one way to work around it is to create a &quot;blank&quot; dataFrame with all the <code>rpt_date</code> and <code>product_id</code> combinations, then <code>concat</code> that to the original data and drop all...
python-3.x|pandas|numpy
2
7,949
73,719,673
Skipping one specific excel tab from multiple tabs in multiple excel sheet (Pandas Python)
<p>I have a routine in place to convert my multiple excel files, with multiple tabs and multiple columns (<strong>some tabs are present in the excel sheets, some are not, but the column structuring inside all the tabs is the same for all the sheets</strong>) to a dictionary of dictionaries. I'm facing an issue while sk...
<p>I was able to resolve this query by creating two functions. The first function I created takes the input as the sheet name I want to skip/delete and the master dictionary (df_dict). Below is the code for the function:</p> <pre><code>def delete_key(rm_key, df_dict): '''This routine is used to delete any tab from ...
python|excel|pandas|dataframe|data-extraction
0
7,950
71,236,651
Tensorflow importing custom layers, runs training of custom model
<p>My use case is the following: I am creating a dimensionality reducing AutoEncoder with Tensorflow. I have implemented three custom layers and with that a model</p> <pre><code>class ConvLayer(Layer): def __init__(self, filter, kernel, act, **kwargs): super().__init__() self.filter = filter self.ke...
<p>To stop your code from automatically running, convert your code in the following format, it always prevents the code from auto running.</p> <pre><code>def __main__(): #do whatever you want in this function as this will run if you run this file directly print('hello world') if __name__ == &quot;__main__&quot;...
python|tensorflow
1
7,951
71,238,264
Python Pandas drop a specific raneg of columns that are all NaN
<p>I'm attempting to drop a range of columns in a pandas dataframe that have all NaN. I know the following code:</p> <pre><code>df.dropna(axis=1, how='all', inplace = True) </code></pre> <p>Will search all the columns in the dataframe and drop the ones that have all NaN.</p> <p>However, when I extend this code to a spe...
<p>Don't use <code>inplace=True</code>. Instead do this:</p> <pre><code>cols = df.columns[48:179] df[cols] = df[cols].dropna(axis=1, how='all') </code></pre>
python|pandas|dataframe
1
7,952
52,301,279
Error loading TensorFlow graph with C API
<p>I'm trying to use the TensorFlow C API to load and execute a graph. It keeps failing and I can't figure out why.</p> <p>I first use this Python script to create a very simple graph and save it to a file.</p> <pre><code>import tensorflow as tf graph = tf.Graph() with graph.as_default(): input = tf.placeholder(...
<p>First of all, I think you should write the Graph with <code>as_graph_def()</code>, in your case:</p> <pre class="lang-py prettyprint-override"><code>with open('test.pb', 'wb') as f: f.write(graph.as_graph_def().SerializeToString()) </code></pre> <p>Apart from it, I recommend you not to use the C API directly a...
tensorflow
1
7,953
60,671,246
Change type Column with 2 format Python
<p><strong>Hello World,</strong></p> <p>New in Python, I am trying to convert a column (YEAR) into one format.</p> <p>The column contains 2 formats: - yy - yyyy</p> <p>Here is an example</p> <pre><code>year 2007 07 1999 2001 99 </code></pre> <p>What I have tried is to fill 20 before year column but what about when...
<p>Use <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 for <code>YY</code> - <code>%y</code> and <code>errors='coerce'</code> and with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas...
python|pandas
4
7,954
60,720,213
pandas: get rows by comparing two columns of dataframe to list of tuples
<p>Say I have a pandas DataFrame with four columns: A,B,C,D.</p> <pre class="lang-py prettyprint-override"><code>my_df = pd.DataFrame({'A': [0,1,4,9], 'B': [1,7,5,7],'C':[1,1,1,1],'D':[2,2,2,2]}) </code></pre> <p>I also have a list of tuples:</p> <pre class="lang-py prettyprint-override"><code>my_tuples = [(0,1),(4,...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="noreferrer"><code>DataFrame.merge</code></a> with <code>DataFrame</code> created by tuples, there is no <code>on</code> parameter for default interecton of all columns in both <code>DataFrames</code>, here <code>...
python|pandas
7
7,955
72,595,974
How do I divide accross all columns in a pandas DF
<p>I have a large data set with over 25 columns in a pandas df and I would like to calculate the growth rate from one month to the other.</p> <p>How do I get from this:</p> <p><a href="https://i.stack.imgur.com/FOYzr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FOYzr.png" alt="enter image descript...
<p>You need to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pct_change.html" rel="nofollow noreferrer"><code>pct_change</code></a>:</p> <pre><code>out = df.pct_change(axis=1).iloc[:,1:] </code></pre>
python-3.x|pandas|dataframe
2
7,956
72,581,847
How to take tf.Tensor type to number type in Typescript
<p>I'm working with Tensorflow.js in typescript and I want to get the cosine similarity of two 1D tensors, but I am having trouble with dealing with the types that tensorflow uses. When I calculate the cosine similarity, using this function I should be getting a number, but instead I get a bunch of different other type...
<p>I don't believe it is the best practice, but if you do not want the return type of the function to list all of those type options, or be Any, then you can force the coercion of the response variable to unknown, if necessary, and then to the type you are expecting.</p> <pre><code>return similarityScore.arraySync() as...
javascript|typescript|tensorflow|tensorflow.js
0
7,957
72,806,145
Keep columns if column contains string
<p>This has been answered similarly at <a href="https://stackoverflow.com/questions/66715267/how-to-keep-a-row-if-any-column-contains-a-certain-substring">How to keep a row if any column contains a certain substring?</a>. However, my problem involves multiple dataframes within a list which is a different set-up to the ...
<p>You can booleaing mask <code>df.columns</code> then use <code>df.loc</code> to select the remaining columns</p> <pre class="lang-py prettyprint-override"><code>dfs = [df.loc[:, df.columns[df.apply(lambda col: col.str.contains('Sepal.Width')).any()]] for df in reply_pred] </code></pre> <pre><code>for df in dfs...
python|pandas
1
7,958
59,523,972
Dimension mismatch between input data and trained data when using conv1D
<p>I have tried to build my first CNN using Conv1D, as i deal with time series data. My target is to make compression for input_data of 1501 shape. The x_train shape is (550, 1501) and I increased it's dimension to fit the model.</p> <p>However, the compiler complains:</p> <blockquote> <p>ValueError: A target arra...
<p>The error is in the <code>decode</code> output dimension at <code>axis=1</code>, i.e., <code>1500</code> which is different from the target <code>x_train1</code> dimension of <code>1501</code>.</p> <p>This is happening due to <em>this chain</em> of <em>max-pooling</em> and <em>upsampling</em> operations: <code>1501...
python|tensorflow|keras|conv-neural-network|convolution
0
7,959
59,851,196
How to have a batch size greater than 1 in a Keras LSTM network?
<p>I've been training a LSTM using Keras with a batch size of 1 and it's been very slow. I'd like to increase the batch size in an attempt to speed up training time but I can't work out how to do it.</p> <p>Below is code (my minimum, reproducible example) that shows my problem. It works with a batch size of 1, but how...
<p>Only use <code>batch_size</code> in <code>model.fit</code>. The following code works for me:</p> <pre><code>import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import TimeDistributed #the demo data contains 10 in...
python|tensorflow|keras|lstm
2
7,960
59,746,744
parsing a list of dictionaries in a pandas data frame rows
<p>I have a list dictionaries in pandas dataframe column. I want to parse it and create new rows from it even though other column value repeat.</p> <p>Here is the dataframe:</p> <pre><code>event_date event_timestamp event_name event_params 20191118 1.57401E+15 user_engagement [{'key': 'firebase_event_origin', 'v...
<p>You have to explode your Data Frame First using pandas.series.explode() and then write a couple of for loops to get the expected result. Here is the Answer.</p> <pre><code>import pandas as pd d = {'event_date': [1, 2], 'event_name': [3, 4] ,'event_params': [[{'key': 'firebase_event_origin', 'value': {'string_value...
python-3.x|pandas|dataframe|dictionary
2
7,961
61,823,039
How to create pandas dataframe and fill it from function?
<p>I have that function: </p> <pre><code>def count (a,b): x = a*b </code></pre> <p>Values of 'a' and 'b' must be 1...99 for 'a' and 100...800 for 'b'. So the question is how to create pandas dataframe with a-values vertically and b-values horizontally and x-values inside that are counted with 'count' function (us...
<p>Hope this may help</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def count(a,b): x = a*b return x a = list(range(1,100)) b = list(range(100,801)) data = [] for i in a: temp = [i] for j in b: temp.append(count(i,j)) data.append(temp) df = pd.DataFrame(data, co...
python|pandas
2
7,962
61,821,288
Multiindex "get_level_values"-function for arbitrarily many levels
<p>Is there a way to construct a function that uses "get_level_values" an arbitrarily number of times and returns the sliced dataframe? An example can explain my need.</p> <p>Multiindex:</p> <pre><code>arrays = [['bar', 'bar', 'bar', 'baz', 'baz', 'foo', 'foo','foo','qux', 'qux'], ['one', 'two', 'three', 'o...
<p>Try this and see if it works for you : since ur multiindex has names, it is easier using <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#multiindex-query-syntax" rel="nofollow noreferrer">query</a> for your function : </p> <pre><code>def my_func(df,levels, values): # Code using qu...
python|pandas|function|dataframe|multi-index
1
7,963
58,023,598
Filter DataFrame rows based on groups
<p>I'm learning Python/Pandas with a DataFrame having the following structure:</p> <pre><code>import pandas as pd df = pd.DataFrame({"cus_id" : ["2370", "2370", "5100", "5100", "8450", "8450", "1630", "1630", "1630"], "cus_group" : ["A", "A", "A", "B", "B", "B", "A", "A", "B"]}) print(df) cus_...
<p>You can simply change your keep value to first. It would give you the desired result. </p> <pre><code>import pandas as pd df = pd.DataFrame({"cus_id" : ["2370", "2370", "5100", "5100", "8450", "8450", "1630", "1630", "1630"], "cus_group" : ["A", "A", "A", "B", "B", "B", "A", "A", "B"]}) prin...
python|pandas|dataframe
1
7,964
49,458,902
Does applying a Dropout Layer after the Embedding Layer have the same effect as applying the dropout through the LSTM dropout parameter?
<p>I am slightly confused on the different ways to apply dropout to my Sequential model in Keras.</p> <p>My model is the following:</p> <pre><code>model = Sequential() model.add(Embedding(input_dim=64,output_dim=64, input_length=498)) model.add(LSTM(units=100,dropout=0.5, recurrent_dropout=0.5)) model.add(Dense(units...
<p>When you add a dropout layer you're adding dropout to the output of the previous layer only, in your case you are adding dropout to your embedding layer.</p> <p>An LSTM cell is more complex than a single layer neural network, when you specify the dropout in the LSTM cell you are actually applying dropout to 4 diffe...
python|tensorflow|machine-learning|keras|lstm
24
7,965
67,546,315
One-hot encode labels in keras
<p>I have a set of integers from a label column in a CSV file - <code>[1,2,4,3,5,2,..]</code>. The number of classes is <code>5</code> ie range of <code>1</code> to <code>6</code>. I want to one-hot encode them using the below code.</p> <pre><code>y = df.iloc[:,10].values y = tf.keras.utils.to_categorical(y, num_class...
<p>If you use <code>tf.keras.utils.to_categorical</code> to one-hot the label vector, the integers should start from <code>0</code> to <code>num_classes</code>, <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical#args" rel="noreferrer">source</a>. In your case, you should do as follows</p>...
tensorflow|keras|one-hot-encoding
5
7,966
67,461,808
Is there a way to loop through pandas dataframe and drop windows of rows dependent on condition?
<ol> <li><strong>Problem Summary</strong> - I have a dataframe of ~10,000 rows. Some rows contain data aberrations that I would like to get rid of, and those aberrations are tied to observations made at certain temperatures (one of the data columns).</li> <li><strong>What I've tried</strong> - My thought is that the ea...
<p>It can be tricky to repeatedly delete parts of the dataframe and keep track of what you're doing. A cleaner approach is to keep track of which rows you want to delete within the loop, but only delete them outside of the loop, all at once. This should also be faster.</p> <pre class="lang-py prettyprint-override"><cod...
python|pandas|dataframe|drop
1
7,967
67,380,650
Stacking with CONV2D + LSTM
<p>I'm trying to use 2 methods, such as <em>Conv2D</em> and LSTM. I have already run ImageDataGenerator code.<a href="https://i.stack.imgur.com/F3RXS.jpg" rel="nofollow noreferrer">enter image description here</a></p> <p>it shows that: Found 1312 images belonging to 3 classes. Found 876 images belonging to 3 classes.</...
<p>Try using the expand_dims() function from TF.</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/expand_dims" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/expand_dims</a></p>
tensorflow|image-processing|deep-learning|conv-neural-network|lstm
1
7,968
67,502,981
AttributeError: 'float' object has no attribute '_get_axis_number'
<p>I am trying to get the percentage change in value of today compared to yesterday, for every day in the dataframe. This is the line that throws the error-</p> <pre><code>import pandas as pd df = pd.DataFrame({'new_cases':[368060.0, 357316.0, 382146.0, 412431.0, 414188.0, 401078.0, 403405.0, 366494.0, 329942....
<p>Another, simpler method of doing this would be</p> <pre><code>df['percent_increase_cases'] = df[['new_cases']].apply(pd.Series.pct_change) </code></pre> <p>Notice the extra pair of <code>[]</code> when selecting columns.</p> <p>Selecting a single column from a dataframe returns a series, which would run in to the pr...
python|pandas
1
7,969
60,324,226
Pandas combine multiple pivot tables
<p>Suppose I have <code>df1</code>, <code>piv1</code>, and, <code>piv2</code> below:</p> <pre><code>df1 = pd.DataFrame({'R': [1, 2], 'S': ['s1', 's2'], 'G1': ['g1a', 'g1b'], 'G2': ['g2a', 'g2b']}) df1 R S G1 G2 0 1 s1 g1a g2a 1 2 s2 g1b g2b piv1 = df1.pivot_table(index=(['S']), columns=(['G1']), a...
<p>IIUC</p> <pre><code>s=df1.melt(['R','S']).groupby(['S','value']).R.mean().unstack() Out[63]: value g1a g1b g2a g2b S s1 1.0 NaN 1.0 NaN s2 NaN 2.0 NaN 2.0 </code></pre>
python|pandas|dataframe|pivot-table|pandas-groupby
4
7,970
65,257,150
Select rows and sort them values and add result as new string column
<p>Hello how can i simplify this code, i take 5 rows a need them as sorted string i new column:</p> <p><code>nba_data['lineup']</code> is data frame and 'lineup' is last column</p> <pre><code>nba_data['lineup'] = 0 for i in range(len(nba_data.index)): single_lineup = [] df_single_lineup = nba_data.iloc[i, 59:64...
<p>Data:</p> <pre><code>np.random.seed(4) nba_data = pd.DataFrame(np.random.randint(1,1000, 25).reshape(5,5)) </code></pre> <p>nba_data:</p> <pre><code> 0 1 2 3 4 0 123 175 440 710 898 1 361 600 457 819 394 2 59 765 872 110 607 3 824 952 314 873 677 4 947 45 295 127 565 </code...
python|pandas|dataframe
0
7,971
65,203,203
Pandas: counting unique combinations from four columns that have NaN values
<p>I've been scratching my head with the this.. I have a dataframe with four columns</p> <pre><code> a b c d 0 1 1 Nan NaN 1 2 1 1 NaN 2 1 1 Nan NaN 3 3 2 1 3 </code></pre> <p>and I want the count of unique combinations from the columns to a new column</p> <pre><code> a b ...
<p>One way to go around is to replace <code>NaN</code> values with the string <code>'NaN'</code>:</p> <pre><code>(df.fillna('NaN') .groupby(list(df.columns))['a'].size() .reset_index(name='count') ) </code></pre> <p>Output:</p> <pre><code> a b c d count 0 1 1 NaN NaN 2 1 2 1 1 NaN 1 ...
pandas
1
7,972
65,190,217
How to process TransformerEncoderLayer output in pytorch
<p>I am trying to use bio-bert sentence embeddings for text classification of longer pieces of text.</p> <p>As it currently stands I standardize the number of sentences in each piece of text (some sentences are only comprised of (&quot;[PAD]&quot;) and run each sentence through biobert to get sentence vectors as they d...
<p>So the input and output shape of the transformer-encoder is <code>batch-size, sequence-length, embedding-size)</code>. There are three possibilities to process the output of the transformer encoder (when not using the decoder).</p> <ol> <li>you take the mean of the <code>sequence-length</code> dimension:</li> </ol> ...
pytorch|bert-language-model|transformer-model
1
7,973
65,317,427
how to map two dataframes on condition while having different rows
<p>I have two dataframes that need to be mapped (or joined?) based on some condition. These are the dataframes:</p> <p><code>df_1</code></p> <pre><code> img_names img_array 0 1_rel 253 1 1_rel_right 255 2 1_rel_top 250 3 4_rel 180 4 4_rel_right 182 ...
<p>Looks like you can just extract the digit parts and merge:</p> <pre><code>df_1['List_No'] = df_1['img_names'].str.split('_').str[0].astype(int) df_3 = df_1.merge(df_2, on='List_No') </code></pre> <p>Output:</p> <pre><code> img_names img_array List_No time 0 1_rel 253 1 38 1 1_rel_righ...
python-3.x|pandas|dataframe|mapping
3
7,974
65,097,963
Efficiently update rows of a postgres table from another table in another database based on a condition in a common column
<p>I have two <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">DataFrames</a>:</p> <p><code>df1</code> from database A with connection parameters <code>{&quot;host&quot;:&quot;ho...
<p>Pandas can't do partial updates of a table, no. There is a <a href="https://github.com/pandas-dev/pandas/issues/14553" rel="nofollow noreferrer">longstanding open bug</a> for supporting sub-whole-table-granularity updates in <code>.to_sql()</code>, but you can see from the discussion there that it's a very complex f...
python-3.x|pandas|postgresql|dataframe|sqlalchemy
0
7,975
65,092,912
Python Pandas Filter but results are inversed
<p>Hi I've built a filter where I expect the results to only show 'New'. However the result shows everything but new?</p> <pre><code>filt = (export['jiraStatus'] == 'New') print(export.loc[~filt]) </code></pre> <p>Thoughts?</p> <p>TIA</p> <p>Neil</p>
<p>The <code>~</code> negates/inverts the filter. Just use <code>.loc[filt]</code> instead of <code>.loc[~filt]</code> to get the un-negated result.</p>
python|pandas
0
7,976
65,261,873
find geometry distance between rows x y z in pandas
<p>I have such dataframe</p> <pre><code> x y z 0 1202.3235 541.05555 2.835000e+01 1 1202.3235 541.05555 2.835000e+01 </code></pre> <p>It is necessary to find the rows, which have got very small distance from other rows. Distance should be calculated by analythical ge...
<p>Grouping similar data points is normally done using cluster analysis.</p> <p>You will find suitable methods in Scipy (<a href="https://docs.scipy.org/doc/scipy/reference/cluster.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/cluster.html</a>) or scikit-learn (<a href="https://scikit-learn...
pandas|geometry
0
7,977
65,474,427
How can pandas str.extract method returns more match from my list?
<p>I have rows like this in a pandas series object:</p> <pre><code>['Blazic M.', 'Boli F.', 'Botka E.', 'Civic E.', 'Dibusz D. (K)', 'Kharatin I.', 'N. Tokmac', 'Otigba K.', 'Sigér D.', 'Vécsei B.', 'Zubkov O.']` </code></pre> <p>it is a &lt;class 'str'&gt;</p> <p>I want with .str.extract('[\w,]') to only match the alp...
<p>You can use <code>findall</code>:</p> <pre><code>&gt;&gt; pd.Series(['Blazic M., 123 Boli F.']).str.findall('([a-zA-Z,])') 0 [B, l, a, z, i, c, M, ,, B, o, l, i, F] dtype: object </code></pre>
python|regex|pandas
1
7,978
64,134,929
Fishers Exact Test from Pandas Dataframe
<p>I'm trying to work out the best way to create a p-value using Fisher's Exact test from four columns in a dataframe. I have already extracted the four parts of a contingency table, with 'a' being top-left, 'b' being top-right, 'c' being bottom-left and 'd' being bottom-right. I have started including additional cal...
<p>Following the <a href="https://stackoverflow.com/questions/34947578/how-to-vectorize-fishers-exact-test">answer here</a> which came from the author of pyranges (i think), let's say you data is something like:</p> <pre><code>import pandas as pd import scipy.stats as stats import numpy as np np.random.seed(111) df =...
python|python-3.x|pandas|statistics|combinations
1
7,979
46,730,272
Pandas: Difference of of two datetime64 objects yields NaT rather than correct timedelta value
<p>This question "gets asked a lot" - but after looking carefully at the other answers I haven't found a solution that works in my case. It's a shame this is still such a sticking point.</p> <p>I have a <code>pandas</code> dataframe with a column <code>datetime</code> and I simply want to calculate the time range cove...
<p>There is problem different indexes, so one item Series cannot align and get <code>NaT</code>.</p> <p>Solution is convert first or second values to numpy array by <code>values</code>:</p> <pre><code>timespan_a = df['datetime'][-1:]-df['datetime'][:1].values print (timespan_a) 2 20:00:00 Name: datetime, dtype: tim...
python|pandas|datetime
3
7,980
63,069,276
Pandas to_sql ignoring dtype when column contains null values
<p>First SO Question. I hope this is descriptive enough.</p> <p>Pandas 0.25, Oracle 11g</p> <p>I have a dataframe read from a csv. It contains a mix of numeric, string and date data.</p> <p>I force data types within the dataframe using <code>.astype(str)</code>, <code>.astype(int)</code> and <code>.to_datetime</code>....
<p>The issue with the numeric fields with some null and some non-null values was due to Pandas using NaN for null and numpy treating NaN as float.</p> <p><code>.astype(int)</code> doesn't handle NaN's and actually raises an exception due to the NaNs (which a try block had caught and handled incorrectly in my case).</p>...
python|pandas|oracle|dtype|pandas-to-sql
0
7,981
63,189,077
SimpleITK reading a slice of an image
<p>Good day to all.</p> <p>I happen to have a very large .mha file on my HDD (9.7 Gb) which is a 3D image of a brain. I know this image's shape and for the needs of a report, I would like to extract a slice of it, in order to get a 2D image that I can save as a .png.</p> <p>The problem is that my 16 Gb RAM computer doe...
<p>With SimpleITK you can read the header of an image, to get it's size information (and other meta-data). Then you can tell the ImageFileReader to only read in a sub-section of the image.</p> <p>The following example demonstrates how to do it:</p> <p><a href="https://simpleitk.readthedocs.io/en/master/link_AdvancedIm...
python|numpy|memory-management|simpleitk|numpy-memmap
1
7,982
63,234,851
How to extract data from a dictionary?
<p>I am trying to get the asset/free/locked fields along with the corresponding data to populate into columns. Currently, I can only get the balances column where these fields fall.</p> <p>Here is the data format. I don't need anything before 'balances'. Thinking if I could remove this part of the string maybe then ...
<ul> <li>If <code>account</code> is a <code>string</code>, it must be converted to a <code>dict</code> with <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a>.</li> <li>With <code>account</code> as a <code>dict</code>, use <a href="https://p...
python|pandas|dataframe|dictionary|json-normalize
2
7,983
62,960,690
Difference in rounding - float64 vs. float32
<p>This scenario is a simplification of an ETL scenario involving multiple sets of data pulled from MySQL tables. I have a merged dataframe where one price column is type <code>float64</code> and the other is type <code>object</code>.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'price1': [0.066055], ...
<p>Printing the floats with higher precision shows that <code>pd.to_numeric</code> converted <code>'.066055'</code> to <code>0.06605499999999998872</code>.</p> <pre class="lang-py prettyprint-override"><code>with pd.option_context('display.float_format', '{:0.20f}'.format): print(float64_df) </code></pre> <p>Output...
python|pandas
2
7,984
63,055,152
np.genfromtxt returns string with 'b'
<p>I am learning about different functions of NUmpy, And I have a dummy dataset <a href="http://eforexcel.com/wp/downloads-18-sample-csv-files-data-sets-for-testing-sales/" rel="nofollow noreferrer">here</a> named as 100-Sales-Records.</p> <p>Now I want to read it using <code>np.genfromtxt</code>. My code to read it is...
<p>The answer is that <code>b</code> before strings means that it is a byte object normally returned with <code>utf-8</code> encoding. It is a bytes object.</p> <p>To remove it, there is a parameter in <code>genfromtxt</code> that is <code>encoding</code>, set it to <code>utf-8</code></p> <p>i.e</p> <pre class="lang-py...
python|pandas|numpy|genfromtxt
3
7,985
67,675,174
Check if at least one column contains a string in pandas
<p>I would like to check whether several columns contain a string, and generate a Boolean column with the result. This is easy to do for a single column, but generates an Attribute Error (<code>AttributeError: 'DataFrame' object has no attribute 'str'</code>) when this method is applied to multiple columns.</p> <p>Exam...
<p>An option via <code>applymap</code> :</p> <pre><code>df['C'] = df.applymap(lambda x: 'c' in str(x).lower()).any(1) </code></pre> <p>Via <code>stack/unstack</code>:</p> <pre><code>df['C'] = df.stack().str.contains('c', case=False).unstack().any(1) df['C'] = df.stack().str.lower().str.contains('c').unstack().any(1) </...
python|pandas
4
7,986
68,003,064
Pandas - optimize percentile calculation
<p>I have a dataset like this:</p> <pre><code>id type score a1 ball 15 a2 ball 12 a1 pencil 10 a3 ball 8 a2 pencil 6 </code></pre> <p>I want to find out the rank for each type for each id. As I later would translate the rank into percentiles, I prefer using <code>ra...
<p>Check with <code>groupby</code></p> <pre><code>df['rnk'] = df.groupby('type').score.rank(ascending=False) Out[67]: 0 1.0 1 2.0 2 1.0 3 3.0 4 2.0 Name: score, dtype: float64 </code></pre>
python|pandas|rank
2
7,987
67,905,777
how to use the input with pandas to get all the value.count linked to this input
<p>my dataframe looks like this:</p> <pre><code>Index(['#Organism/Name', 'TaxID', 'BioProject Accession', 'BioProject ID', 'Group', 'SubGroup', 'Size (Mb)', 'GC%', 'Replicons', 'WGS', 'Scaffolds', 'Genes', 'Proteins', 'Release Date', 'Modify Date', 'Status', 'Center', 'BioSample Accession', 'Assembly Accessi...
<p>If I understand your question correctly, this is what you're trying to achieve:</p> <pre><code>import wget import numpy as np import pandas as pd URL='https://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/prokaryotes.txt' data = pd.read_csv(wget.download(URL) , sep = '\t', header = 0) species = input(&quot;Ent...
python|pandas|dataframe
1
7,988
67,728,773
Flip a Data Frame in Pandas and keep one column's values as the new row's values
<p>I currently have a Data Frame that looks like so when I read it in:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Country</th> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>01/01/2020</td> <td>AFG</td> <td>0</td> <td>1</td> <td>5</td> </tr> <tr> <td>01/...
<p>You can do it in this way:</p> <ol> <li><p>TRY <code>pivot_table</code> to get the required.</p> </li> <li><p>Use <code>rename_axis</code> to remove the axis name.</p> </li> <li><p>Finally reset the index via <code>reset_index()</code>.</p> </li> </ol> <pre><code>df = df.pivot_table(index='Country', columns='Date', ...
python|pandas|dataframe|group-by|time-series
1
7,989
53,235,718
Change column values in pandas based on condition
<p>df:</p> <pre><code> A 0 219 1 590 2 272 3 945 4 175 5 930 6 662 7 472 8 251 9 130 </code></pre> <p>I am trying to create a new column quantile based on which quantile the value falls in, for example:</p> <pre><code>if value &gt; 1st quantile : value = 1 if value &gt; 2nd quantil...
<p>Yes, using <a href="http://pandas.pydata.org/pandas-docs/version/0.15.0/generated/pandas.qcut.html" rel="nofollow noreferrer"><code>pd.qcut</code></a>:</p> <pre><code>&gt;&gt;&gt; pd.qcut(df.A, 4).cat.codes + 1 0 1 1 3 2 2 3 4 4 1 5 4 6 4 7 3 8 2 9 1 dtype: int8 </code></pre> <p>(Give...
python|pandas
2
7,990
52,908,588
Vectorization and optimization of matrix subtraction
<p>Is it possible to vectorize / optimize the following loop?</p> <pre><code>In [33]: a = np.arange(10000 * 700).reshape([10000, 700]) In [34]: b = np.arange(1000 * 700).reshape([1000, 700]) In [35]: c = np.empty([b.shape[0], a.shape[0]]) In [36]: for i in range(b.shape[0]): ...: c[i] = np.argsort(np.linalg...
<p>Simplest way would be with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>cdist</code></a> -</p> <pre><code>from scipy.spatial.distance import cdist cdist(b,a).argsort(axis=1) </code></pre> <p>Equivalent one with <a href="http://sci...
numpy|vectorization
2
7,991
53,300,353
Python every three rows to columns using pandas
<p>I have a text file with data that repeoates every 3 rows. Lets say it is <code>hash</code>, <code>directory</code>, <code>sub directory</code>. The data looks like the following:</p> <pre><code>a3s2d1f32a1sdf321asdf Dir_321321 Dir2_asdf s21a3s21d3f21as32d1f Dir_65465 Dir2_werq asd21231asdfa3s21d Dir_76541 Dir2_wb...
<p>You can use:</p> <pre><code>df_final = pd.DataFrame(np.reshape(df.values,(3, df.shape[0]/3))) df_final.columns = ['Hash', 'Dir_1', 'Dir_2'] </code></pre> <p>Output:</p> <pre><code> Hash Dir_1 Dir_2 0 a3s2d1f32a1sdf321asdf Dir_321321 Dir2_asdf 1 s21a3s21d3f21as32d1f Dir_65465...
python|pandas
2
7,992
65,672,181
how many epoch for training 1k images
<p>am doing training for detecting the objects using yolov3 but i face some problem when i set batch_size &gt; 1 it causes me cuda out of memory so i searched in google to see another solution found it depends on my GPU (GTX 1070 8G) .</p> <p>may be the number of epoch is high and it require to be optimized .</p> <p>m...
<p>your model's overfitting wont depend on the no. of epochs you set.....<br /> since you hav made a val split in your data, make sure that your <strong>train loss - val loss OR train acc - val acc</strong> is nearly the same.This will assure that your model is not overfitting</p>
python|machine-learning|deep-learning|pytorch
0
7,993
65,513,530
Create interactive plot of the Continuous Uniform Distribution with sliders for parameter values
<p>How can I create an interactive plot of the pdf and the cdf of the <a href="https://en.wikipedia.org/wiki/Continuous_uniform_distribution" rel="nofollow noreferrer">Continuous Uniform Distribution</a> using python?</p> <p><a href="https://i.stack.imgur.com/k7AnJ.png" rel="nofollow noreferrer"><img src="https://i.sta...
<p><strong>1. The simplest way is to use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html" rel="nofollow noreferrer">scipy.stats.uniform()</a> to get the pdf and the cdf of the distribution and then using <a href="https://panel.holoviz.org/user_guide/Interact.html" rel="nofollow no...
python|pandas|scipy|holoviews|panel-pyviz
2
7,994
65,485,987
How do I convert a .dbf file into a Pandas DataFrame?
<p>I have a <code>.dbf</code> file that I would like to convert into a pandas <code>DataFrame</code>, but <code>DataFrame</code>s aren't able to directly convert the data.</p>
<p>Using <a href="https://pypi.org/project/dbf/" rel="nofollow noreferrer">my <code>dbf</code> library</a>, the following function will do the job:</p> <pre><code>def dbf_to_dataframe(filename): &quot;&quot;&quot; converts the dbf table at filename into a Panda's DataFrame data types and field names are pre...
python|pandas|dataframe|dbf
2
7,995
65,671,476
How to implement a Forward Selection using KNN?
<p>I am trying to use a wrapper method in Python to implement a simple forward selection using KNN from the data I have.</p> <p>My data:</p> <pre><code>ID S_LENGTH S_WIDTH P_LENGTH P_WIDTH SPECIES ------------------------------------------------------------------ 1 3.5 2.5 5.6...
<p>I do <a href="https://stats.stackexchange.com/questions/363662/can-you-derive-variable-importance-from-a-nearest-neighbor-algorithm">not believe that KNN has a features importance</a> built-in, so you have basically three options. First, you can use a model agnostic version of feature importance like permutation imp...
python|pandas|scikit-learn|knn|feature-selection
0
7,996
63,638,082
Access groupby Pandas taking first n quantity
<p>I have a data frame looking like this:</p> <pre><code>Date Product Quantity Price Buy/Sell 8/11 Apple 5 5 b 8/11 Apple 5 4 b 8/12 Pear 11 4 b 8/13 Pear 4 3 b 8/13 Pear 5 6 s </code></pre> <p>I am trying to distribute them according to ...
<p>I think you are OK going this route. You will have to devise some quick function to split up the ones that need to be divided, which will be a bit of work.</p> <p>You can access the groups out of the grouped object as below. The &quot;GroupBy&quot; object is iterable, and when you iterate on it, you get back a tup...
python-3.x|pandas
1
7,997
53,613,006
How to sum all values with one index greater than X in MultiIndexed Datarfame, grouping on the other indices?
<p>I am trying to do the exact same thing as described in this <a href="https://stackoverflow.com/questions/39125695/how-to-sum-all-values-with-index-greater-than-x">post</a> but with a MultiIndexed Pandas DataFrame. I've been trying to adapt the answer to the other post so that it would work with my DataFrame but with...
<p>First create boolean mask by level <code>ms</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow noreferrer"><code>get_level_values</code></a> compared by scalar. Then filter rows by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.ht...
python|pandas|dataframe|aggregate|pandas-groupby
1
7,998
71,943,413
Roll over 1 day when you have repeated dates
<p>I have this set of data :</p> <pre><code>df = pd.DataFrame() df['Date'] = [&quot;29/07/2021&quot;, &quot;29/07/2021&quot;, &quot;29/07/2021&quot;, &quot;29/07/2021&quot;, &quot;30/07/2021&quot;, &quot;30/07/2021&quot;, &quot;30/07/2021&quot;, &quot;30/07/2021&quot;, &quot;31/07/2021&quot;, &quot;31/07/2021&quot;, &q...
<p>Rather than <code>rolling</code>, the desired output calls for <code>groupby</code> + <code>mean</code>:</p> <pre><code>out = df.groupby('Date', as_index=False)['Column1'].mean() </code></pre> <p>Output:</p> <pre><code> Date Column1 0 01/08/2021 0.000443 1 02/08/2021 0.000314 2 29/07/2021 0.015398 3 ...
python|python-3.x|pandas|dataframe|pandas-groupby
2
7,999
71,899,250
Python reading the first entry of a paranthesis in a series of paranthesis
<p>I have thousands of lines of the following sample in a csv file. The header of the file is as follows:</p> <p><strong>File Hearder:</strong></p> <blockquote> <p>field1, field2, field3, field4</p> </blockquote> <p><strong>Sample Data:</strong></p> <blockquote> <p>field1, field2, 1, &quot;[('entryA', 'typeA'), ('entry...
<p>you don't need <code>re</code>, use <code>ast.literal_eval</code></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; s = &quot;[('entryA', 'typeA'), ('entryB', 'typeB'), ('entryC', 'typeC'), ('entryD', 'typeD')]&quot; &gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; literal_eval(s) [('entryA', 't...
python|pandas|dataframe
1