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
12,300
71,502,608
How do you deal with datetime obj when applying ANN models?
<p>How do you deal with datetime obj when applying ANN models? I have thought of writing function which iterates through the column but there has to be a cleaner way to do so, right?</p> <pre><code>dataset.info() # Column Non-Null Count Dtype --- ------ -------------- ----- ...
<p>I would suggest doing the following steps:</p> <ol> <li>converting string to datetime.datetime objects</li> </ol> <pre class="lang-py prettyprint-override"><code>from datetime import datetime t = datetime.strptime(&quot;2022-03-16 11:55:00&quot;,&quot;%Y-%m-%d %H:%M:%S&quot;) </code></pre> <p>Then extract the necess...
pandas|dataframe|machine-learning|neural-network
1
12,301
42,444,078
Pandas merge creates unwanted duplicate entries
<p>I'm new to Pandas and I want to merge two datasets that have similar columns. The columns are going to each have some unique values compared to the other column, in addition to many identical values. There are some duplicates in each column that I'd like to keep. My desired output is shown below. Adding how='inner' ...
<pre><code>import pandas as pd dict1 = {'A':[2,2,3,4,5]} dict2 = {'A':[2,2,3,4,5]} df1 = pd.DataFrame(dict1).reset_index() df2 = pd.DataFrame(dict2).reset_index() df = df1.merge(df2, on = 'A') df = pd.DataFrame(df[df.index_x==df.index_y]['A'], columns=['A']).reset_index(drop=True) print(df) </code></pre> <p>Output...
python|pandas|merge
6
12,302
42,362,969
How to create a corpus with a set of text files - python?
<p>I have a set of document <code>ID</code>s (keys.csv) that I am using to get a set of text documents from a document source. I would like to collect all these text documents into a corpus for further analysis (like cosine similarity).</p> <p>I am using the below code to append each text document into the corpus, but...
<p>If <code>csv</code> has column <code>IDcol</code> with unique <code>ID</code> use <code>list comprehension</code>, output is <code>list</code>:</p> <pre><code>corpus = [function_to_get_document(ID) for ID in pd.read_csv('keys.csv')['IDcol']] </code></pre> <p>Sample:</p> <pre><code>print (pd.read_csv('keys.csv')) ...
python|pandas|scikit-learn|nlp|corpus
1
12,303
69,795,567
slower parallel compute and write to shared numpy array using joblib
<p>I would like to use joblib to perform parallel computation on numpy array. A minimal example of working code is below:</p> <pre><code>import time import math import numpy as np from joblib import Parallel, delayed def compute(i, I): I[i] = math.sqrt(i) N = 10000 I = np.zeros(N) t = time.time() for i in range(N...
<p>It seems that you are not doing enough work in <code>compute</code> to mask the parallel computing overheads. I modified your code slightly to add <code>time.sleep(1)</code> within <code>compute</code> and changed <code>N</code> from <code>10000</code> to <code>10</code>.</p> <p>I get</p> <pre><code>sequential time ...
numpy|joblib
0
12,304
69,935,263
Why Python replaces double backslashes with one and how can I keep it double
<p>I am new to Python and I have difficulties with the above-mentioned problem.</p> <p>I have a loop here that gives me paths of all folders that I need</p> <pre><code> for i in folder_names: print(str(&quot;pd.read_csv('C:\\Users\\User\\Desktop\\Python\\4_Мини-проект\\data\\2020-12-03\\&quot;) + i + str(&qu...
<p><code>\</code> is know as an escape character. In simple terms when you type a <code>\</code> in your code, the <code>\</code> and the proceeding character will act as one single character, such as <code>\n</code> or <code>\t</code>.</p> <p>When you want to type a backslash in your code, not as an escape character, ...
python|pandas|csv|path|backslash
2
12,305
43,241,380
Wrong date displayed when converting in pandas
<p>I do not know why this snippet is producing 01/01/1970 for all the dates when I am sure this is not accurate.</p> <p>My Original File:</p> <pre><code>Appreciation Start Funding Date 41266 41432 41266 41715 41266 415...
<p>Pandas is not able to decipher 41266 as a date. You can add a preceding zero to the date so that it looks like 041266. Then use pd.to_datetime</p> <pre><code>df['Appreciation'] = '0'+df['Appreciation'].astype(str) df['Appreciation'] = pd.to_datetime(df['Appreciation'], format = '%m%d%y') </code></pre>
python|pandas
1
12,306
72,434,744
Pandas drop_duplicates drops too many rows
<p>I have a dataset of liked and unliked songs. There are 8764 liked and 2213 unliked songs, 11000 rows in total. I have many duplicate like songs but I expected the duplicates to be around max 2000-5000 songs and I'm pretty sure there aren't any duplicate unliked songs. However when I drop duplicate rows with the same...
<p>Can you find and provide some examples of what you expect to remain but doesn't (with provided dataframes not a screenshot). I tested your code and it appeared to work for me.</p> <pre><code>data = { 'Artist' : ['An Artist', 'Another Artist', 'Last Artist', 'An Artist'], 'Track_Name' : ['A Track', 'Another T...
python|pandas
0
12,307
50,382,104
Concatenating DataFrames through function calls
<p>I am trying to concatenate a single row dataframe (df) and add it to the end of another dataframe (df_all) using the following code:</p> <pre><code>import pandas as pd import numpy as np from IPython.display import display, HTML global df_all df_all = pd.DataFrame() def save_data(df): df_all = pd.concat(...
<p>I don't believe in functions that rely on global variables—it just isn't good hygiene.</p> <p>Functions should be pure. First, define your <code>opt</code> function. This just generates <code>df</code> and nothing more. </p> <pre><code>def opt(): df = ... # df is generated here return df </code></pre> <p...
python|pandas|function|dataframe|concatenation
1
12,308
50,485,492
combine DataFrame MultiIndex to string column
<p>I have following DataFrame:</p> <pre><code>df = pd.DataFrame([[1,2,3], [11,22,33]], columns = ['A', 'B', 'C']) df.set_index(['A', 'B'], inplace=True) C A B 1 2 3 11 22 33 </code></pre> <p>How I make additional 'text' column that will be string combination of the MultiIndex.</p> <p>Without remo...
<p>Perhaps a simple list comprehension might help i.e </p> <pre><code>df['new'] = ['_'.join(map(str,i)) for i in df.index.tolist()] C new A B 1 2 3 1_2 11 22 33 11_22 </code></pre>
python|pandas|dataframe
3
12,309
50,449,628
How to remove 0% from pie chart
<p>I am working with text data to find the sentiment analysis. I have a data frame of sentiment score of each sentence. Using this data i am creating a pie chart but it shows the 0% in the graph. I am not able to understand the meaning of this 0%. Here is my data frame df1:</p> <pre><code> score Negative ...
<p>Sorry, for a very 'actual' answer.</p> <p>Then you give</p> <pre class="lang-py prettyprint-override"><code>df1.plot(kind='pie', autopct='%1.1f%%', subplots=True,startangle=90, legend = False, fontsize=14) </code></pre> <p>It takes full df with zeroes, like <code>[100,0,0]</code> You can filter df, as un answer abo...
python|pandas|matplotlib|pie-chart
6
12,310
50,601,927
ValueError when I try to run my deep neural network
<p>I am following this tutorial:</p> <p><a href="https://pythonprogramming.net/train-test-tensorflow-deep-learning-tutorial/" rel="nofollow noreferrer">Training and Testing on our Data for Deep Learning</a></p> <p>The code is:</p> <pre><code>import tensorflow as tf #from tensorflow.examples.tutorials.mnist import in...
<p>Without having tried it myself: you need to change</p> <pre><code>cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=prediction,logits=y) ) </code></pre> <p>to </p> <pre><code>cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction) ) </code></pre> <p>The TF d...
python|tensorflow|deep-learning
1
12,311
45,661,424
tensorflow RNN implementation
<p>I'm building a RNN model to do the image classification. I used a pipeline to feed in the data. However it returns</p> <pre><code>ValueError: Variable rnn/rnn/basic_rnn_cell/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at: </code></pre> <p>I wonder what can I d...
<p>You need to use the <code>reuse</code> option correctly. following changes would solve it. For prediction you need to use the already existed variables in the graph.</p> <pre><code>def RNN(inputs, reuse): with tf.variable_scope('cells', reuse=reuse): basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=b...
tensorflow|recurrent-neural-network
2
12,312
45,411,815
Converting pandas Dataframe with Numpy values to pysparkSQL.DataFrame
<p>I created a 2 columns pandas df with random.int method to generate a second two column dataframe applying groupby operations. df.col1 is a series of lists, df.col2 a series of integers, and elements inside the list are <em>type 'numpy.int64'</em>, same for the elements of the second column, as result of random.int.<...
<p>Well the way how you do it doesn't work. If you have something like this. You will get the error because of the first column. Spark doesn't understand a list with the type numpy.int64</p> <pre><code>df.col1 df.col2 [1,2,3...] 1 [2,5,6...] 2 [6,4,....] 3 ... </code></pre> <p>If you have something li...
python|pandas|numpy|pyspark|apache-spark-sql
1
12,313
45,417,391
Iterate over pairwise combinations of column names and row indices in pandas
<p>If I have the following <code>pandas</code> <code>DataFrame</code> :</p> <pre><code>&gt;&gt;&gt; df x y z x 1 3 0 y 0 5 0 z 0 3 4 </code></pre> <p>I want to iterate over the pairwise combinations of column names and row indices to perform certain operation. For example, for the pair of <code>x</code> and <co...
<p>How about a simple one-liner, using Pandas DataFrame elements:</p> <pre><code>df.apply(lambda x: x.index+x.name) </code></pre> <p>Output:</p> <pre><code> x y z x xx xy xz y yx yy yz z zx zy zz </code></pre> <h3>Update: Using numpy.ufunc.outer method.</h3> <pre><code>pd.DataFrame(np.add.outer(df...
python|pandas
10
12,314
45,312,336
Cannot run imagenet download and preprocess script (suggestion in issue 202 did not work)
<p>I am following the instruction here: <a href="https://github.com/tensorflow/models/tree/master/inception" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/inception</a></p> <p>After running <code>bazel-bin/inception/imagenet_train --num_gpus=1 --batch_size=32 --train_dir=/tmp/imagenet_trai...
<p>I solved the problem by replacing the LABELS_FILE with the actual full file path in download_and_preprocess_imagenet.sh</p>
tensorflow|imagenet
0
12,315
62,756,584
Specific Python cumsum
<p>I'm currently working on python Dataframes, using Pandas. And I need to create a specific dataframes using another.</p> <p>The first Dataframes looks like this</p> <pre><code>Index | Value ______|_______ 0 | 1.1 0 | 0.3 1 | 1 2 | 0.2 2 | 3 2 | 1.3 </code></pre> <p>I need to create a other dat...
<p>Use custom lambda function with convert Series to list per groups after <code>cumsum</code>:</p> <pre><code>df = df.groupby('Index')['Value'].apply(lambda x: x.cumsum().tolist()).reset_index() print (df) Index Value 0 0 [1.1, 1.4000000000000001] 1 1 [1.0] 2 ...
python|pandas
1
12,316
62,530,983
Python - Why does timedelta64 values appear as 0 in excel
<p>I have a dataframe with one of the column as <code>timedelta64</code> dtype. The values appear to be fine in IDE but when I export the dataframe to excel using <code>ExcelWriter</code> and <code>to_excel()</code>, the values in the Excel are all 0. <em>(It's actually not 0 but a very small floating points.)</em></p>
<p>If you export the values to an .xls file do you get the same issue? XLS is a binary file format, not a collection of XML files. This should allow you to check whether this is a file format issue or not.</p>
python|pandas
0
12,317
62,805,628
Pandas - Some columns not working properly after groupby()
<p>I'm trying to generate a simple graph but doesn't make any sense to me after applied <code>groupBy()</code></p> <p><a href="https://i.stack.imgur.com/JBeTN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBeTN.png" alt="enter image description here" /></a></p> <pre><code>df_cumulate = df.groupby([...
<p>I think you just want to group by the date. Does this look like what you expected?</p> <pre><code>df_cumulate = df.groupby(['date'], as_index=False).sum() display(df_cumulate) def plot_df(df, x, y, title=&quot;&quot;, xlabel='Date', ylabel='Sentiment', dpi=100): plt.figure(figsize=(16,5), dpi=dpi) plt.plot(...
python|pandas|matplotlib
0
12,318
62,631,456
How can I join a dataframe and invert the joining column?
<p>I currently have two dataframes which I wish to join:</p> <pre><code>df1 = {'col1': [1, 2, 3, 4, 5]} col1 0 1 1 2 2 3 3 4 4 5 df2 = {'col2': ['nan', 'nan', 3, 4]} col2 0 nan 1 nan 2 3 3 4 </code></pre> <p>Currently I ...
<p>Idea is set index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> in <code>df2</code> by index of df1 from bottom by indexing for same length and then is used <a href="http://pandas.pydata.org/pandas...
python|pandas
1
12,319
54,510,296
Create pandas dataframe from a series containing list of dictionaries
<p>One of the columns of my pandas dataframe looks like this</p> <pre><code>&gt;&gt; df Item 0 [{"id":A,"value":20},{"id":B,"value":30}] 1 [{"id":A,"value":20},{"id":C,"value":50}] 2 [{"id":A,"value":20},{"id":B,"value":30},{"id":C,"value":40}] </code></pre> <p>I want to expand it as </p> <pre><code> ...
<p>I agree with @JeffH, you should really look at how you are constructing the <code>DataFrame</code>.</p> <p>Assuming you are getting this from somewhere out of your control then you can convert to the your desired <code>DataFrame</code> with:</p> <pre><code>In []: pd.DataFrame(df['Item'].apply(lambda r: {d['id']: d...
python|pandas|dictionary|series
0
12,320
54,388,191
Pandas: Copy a value in a dataframe to multiple rows based on a condition
<p>I need to parse a price series in a pandas dataframe for occurrences of two consecutive lower lows which creates a price level we call NLBL. I'm able to do this with a simple conditional (see below) but instead of the TRUE values I need the value of the third previous candle high. PLUS I need to copy that very same ...
<p>Thanks for the clarification, pretty sure I understood you (though if I understood correctly then there's a small error in the sample output).</p> <p>Here's my solution: basically adds a helper column, swaps out 0 for <code>NaN</code> (if performance is a serious concern you could look into <code>map</code> instead...
python|pandas
1
12,321
54,415,345
How to balance (oversampling) unbalanced data in PyTorch (with WeightedRandomSampler)?
<p>I have a 2-class problem and my data is highly unbalanced. I have 232550 samples from one class and <code>13498</code> from the second class. PyTorch docs and the internet tells me to use the class WeightedRandomSampler for my DataLoader. </p> <p>I have tried using the WeightedRandomSampler but I keep getting error...
<p>The problem is in the type of trainset.labels To fix the error it is possible to convert trainset.labels to float</p>
python|machine-learning|pytorch|data-cleaning
0
12,322
54,309,599
Parallel loading of Input Files in Pandas Dataframe
<p>I have a Requirement, where I have three Input files and need to load them inside the Pandas Data Frame, before merging two of the files into one single Data Frame.</p> <p>The File extension always changes, it could be .txt one time and .xlsx or .csv another time.</p> <p>How Can I run this process parallel, in ord...
<p>Try this:</p> <pre><code>from time import time import pandas as pd from multiprocessing.pool import ThreadPool start_time = time() pool = ThreadPool(processes=3) Primary_File = "//ServerA/Testing Folder File Open/Report.xlsx" Secondary_File_1 = "//ServerA/Testing Folder File Open/Report2.csv" Secondary_File_2 ...
python|pandas|anaconda
11
12,323
71,324,551
Extract attributes from the original dataframe used to create a tensorflow dataset
<p>I have the following dataframe <code>df</code>:</p> <pre><code> sales 2015-10-05 -0.462626 2015-10-06 -0.540147 2015-10-07 -0.450222 2015-10-08 -0.448672 2015-10-09 -0.451773 ... ... 2019-10-16 -0.594413 2019-10-17 -0.620770 2019-10-18 -0.586660 2019-10-19 -0.586660 2019-10-20 -0.671934 11340 r...
<p>You could try using another dataset as a lookup. That way you can add further attributes if needed:</p> <pre><code>import pandas as pd import numpy as np import tensorflow as tf df = pd.DataFrame(data={'date': ['2015-10-05', '2015-10-06', '2015-10-07', '2015-10-08', '2015-10-09', '2019-10-16', '2019-10-17', '2019-1...
python|pandas|tensorflow|tensorflow-datasets
1
12,324
71,280,666
python dataframe to dictionary with multiple columns in keys and values
<p>I am working on an optimization problem and need to create indexing to build a mixed-integer mathematical model. I am using python dictionaries for the task. Below is a sample of my dataset. Full dataset is expected to have about 400K rows if that matters.</p> <pre><code># sample input data pd.DataFrame.from_dict({'...
<p>You can loop through the DataFrame.</p> <p>Assuming your DataFrame is called &quot;df&quot; this gives you the dict.</p> <pre><code>result_dict = {} for idx, row in df.iterrows(): result_dict[(row.origin, row.dest, row['product'], row.ship_date )] = ( row.origin, row.dest, row['product'], row.tr...
python|python-3.x|pandas|dataframe|dictionary
2
12,325
71,279,976
Pandas - How do you find the top n elements of 1 column based on a condition from another column
<p>I am struggling with a question based on Pandas. I have an earthquake data set with columns of countries and magnitudes. I am asked to: &quot;Find the top 10 states / countries where the strongest and weakest earthquakes occurred.&quot;</p> <p>From this question, I garnered that I am meant to find the top 10 countri...
<p>Are you sure you did not find something useful? If I understand your question correct, it is a simple one. After creating a dataframe by using below methods, you will get what you need.</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;.csv&quot;) df.nlargest(x, ['Column Name']) </code></pre> <p>x is the ...
python|pandas|sorting
0
12,326
71,097,198
Python Multiply Matrix by Vector of Matrices
<p>Does anybody know of a way (preferably using numpy or something similar) to multiply a matrix by a vector of matrices and obtain the desired product shown below? Basically the idea is to follow the normal rules of matrix multplication of a matrix and a vector, only the elements of the vector are matrices themselves ...
<p>If I understand the question correctly, you can try this:</p> <pre><code>import numpy as np A = np.arange(3*3*3).reshape(3, 3, 3) b = np.arange(9).reshape(3, 3) print(f&quot;A=\n{A}\n\nb=\n{b}&quot;) </code></pre> <p>It gives:</p> <pre><code>A= [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [1...
python|numpy|matrix
2
12,327
71,254,660
How do to a partial match check across strings in two different pandas columns?
<p>I have two dataframes, one with 300 names and one with 2000. I want to check if all of the words in each of the 300 names are contained in the 2000 in any iteration. For example:</p> <p>Name 1: Mark, Alex, Smith,</p> <p>Name 2: Mark, Joseph, Smith, Alex, the, first</p> <p>Dataframe 1</p> <div class="s-table-containe...
<p>Assuming that each of your dataframes have a column with list of strings:</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame({ &quot;Name 1&quot;: [['Mark', 'Alex', 'Smith'], ['S1', 'S2', 'S3']], }) &gt;&gt;&gt; df2 = pd.DataFrame({ &quot;Name 2&quot;: [['Mark', 'Joseph', 'Alex', 'Smith', 'the', 'Fir...
python|pandas
0
12,328
60,708,556
How to copy and paste data from excel to another excel using python
<p>I would like to copy excel data from source excel file to destination excel file. However, I am not just simply copy whole data from source file.</p> <p>I need keep copying ONLY certain rows and columns like the first 5 rows by 4 columns (this data covered, row: 1st to 5th, column: A to D) from source file and past...
<p>Not sure why you are copying to the same destination range each time but try this</p> <pre class="lang-py prettyprint-override"><code>#!python import openpyxl as xl COPY_ROWS = 5 COPY_COLS = 4 FOLDER = 'C:/Users/aaa/Desktop/' # source filename1 = 'combine_all.xlsx' wb1 = xl.load_workbook(FOLDER + file...
python|excel|pandas
1
12,329
72,745,519
How do I turn a float into a stringer in python?(Jupyter Notebook/Google Colab)
<p>How do I turn a a float into a string? Hey guys, I've been trying to turn the column ileads_address into a string. In all the addresses, there's a .0 behind them. But when I did turn the float into the string, it didn't take away the 0s. Anyone know how to fix this.</p> <p>'''df4['ileads_address'] = df4['ileads_addr...
<p>Try this:</p> <pre><code>df4['ileads_address'] = df['ileads_address'].apply(str) </code></pre>
pandas|jupyter-notebook|google-colaboratory
0
12,330
59,479,738
dateutil conflict with django
<p>Here is the question: an error occurs when I import pandas:</p> <pre><code>dateutil: No module named 'dateutil' </code></pre> <p>So i installed dateutil, which is successfully installed, with pip:</p> <pre><code>pip3 install python-dateutil </code></pre> <p>but when i run my django project i got error like this:...
<p>This problem has been solved. It turns out I did not describe what the real problem is, it's pandas(0.25.3) conflict with django(2.2) instead of dateutil. I reinstalled a old version of pandas(0.24.1) and it can work. I don't know why, but it works. Hope this can give other people a hint when they have the same ques...
python|django|pandas|python-dateutil
0
12,331
32,504,143
Python - Calculating the second column from the first one in a file
<p>I am a beginner in Python and cannot cope with one of the moments of my project, so I would be glad you to help me:) </p> <p>Lets's imagine, I have a *.txt file with only one column which looks like: </p> <pre><code> Column-1 row-1 0 row-2 25.00 row-3 27.14 row-4 29.29 row-5 31.43 row-6 ...
<p>I believe this would do what you asked:</p> <pre><code>INPUT = 'file.txt' OUTPUT = 'calc.txt' def main(): with open(INPUT, 'r') as reader, open(OUTPUT, 'a') as writer: last_value = 0 for line in reader: column_1, *remaining_columns = map(float, line.split()) column_2 = c...
python|python-2.7|python-3.x|numpy
5
12,332
40,641,166
How to add an id column to identify read_html() tables?
<p>Consider the following sites (<a href="http://pastebin.com/vpnGqn5X" rel="nofollow noreferrer">site1</a>, <a href="http://pastebin.com/FbAFGbfR" rel="nofollow noreferrer">site2</a>, <a href="http://pastebin.com/LqZWxFSP" rel="nofollow noreferrer">site3</a>) which have a number of different tables.</p> <p>I am using...
<p>try to change your <code>process_url()</code> function as follows:</p> <pre><code>def process_url(url): return pd.concat([x.assign(table_num=i) for i,x in enumerate(pd.read_html(url))], ignore_index=False) </code></pre>
python|python-3.x|pandas|iteration
1
12,333
18,688,948
numpy, how do I find total rows in a 2D array and total column in a 1D array
<p>Hi apologies for the newbie question, but I'm wondering if someone can help me with two questions. Example say I have this, </p> <p>[[1,2,3],[10,2,2]]</p> <p>I have two questions. </p> <ul> <li>How do I find total columns: </li> <li>How do I find total rows: </li> </ul> <p>thank you very much. A</p>
<p>Getting number of rows and columns is as simple as:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.array([[1,2,3],[10,2,2]]) &gt;&gt;&gt; num_rows, num_cols = a.shape &gt;&gt;&gt; print num_rows, num_cols 2 3 </code></pre>
python|numpy
46
12,334
61,755,012
How to use gpu in .py files Google Colab?
<p>I have a notebook in GC with configured gpu computing. When I run in this notebook:</p> <pre><code>from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) </code></pre> <p>I can see GPU in devices:</p> <pre><code>[name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 loca...
<p>I am actually not sure why this is happening but still, I think the file you are running does not demand GPU use and hence no GPU are used. Please correct me if I am wrong.</p>
python|tensorflow|gpu|google-colaboratory
0
12,335
61,750,341
Convert int64 column to datetime column in python
<p>I have a dataframe with one column 'time', which is the object <code>int64</code> and looks like this:</p> <pre><code>time 202003180001043 202003180001044 </code></pre> <p>And which should be converted to a datetime column:</p> <pre><code>time 2020-03-18 00:01:043 2020-03-18 00:01:044 </code></pre> <p>When I run...
<p>Problem is <code>%I</code> is for hour in 12hours format, so failed. Need <code>%H</code> for hours in 24hours format:</p> <pre><code>df['time'] = pd.to_datetime(df['time'], format='%Y%m%d%H%M%S%f') print (df) time 0 2020-03-18 00:01:04.300 1 2020-03-18 00:01:04.400 </code></pre>
python|pandas
5
12,336
61,674,479
DataFrame.to_csv Error, is there any way to locate the character causing error in the DataFrame?
<p>I have a DataFrame with shape 330000, 70, when I try to save it as csv a got the following error:</p> <p>UnicodeEncodeError: 'charmap' codec can't encode character '\uff91' in position 110: character maps to </p> <p>Is there any way to locate the character at position 110 in the DataFrame?</p> <p>Thanks in advanc...
<p>If you google what \uff91 is, you may be able to filter on it, or replace it with something else</p> <p>Another option - export it to excel and locate it that way. </p> <p>Not elegant but it will probably get you the answer</p>
python|pandas
0
12,337
58,097,192
Separate street name strings with street number and letter python
<p>I have a column in a pandas dataframe with street names such as </p> <pre><code>88 SØNDRE VEI 54 89 UTSIKTVEIEN 20B 92 KAARE MOURSUNDS VEG 14 A 94 OKSVALVEIEN 19 96 SLEMDALSVINGEN 33A 97 GAMLESTRØMSVEIEN 59 10...
<p>IIUC, you can use this regex:</p> <pre><code>df[1].str.extract('(\D+)\s+(\d+)\s?(.*)') </code></pre> <p>Output:</p> <pre><code> 0 1 2 0 SØNDRE VEI 54 1 UTSIKTVEIEN 20 B 2 KAARE MOURSUNDS VEG 14 A 3 OKSVALVEIEN 19 4 SLEMDALSVINGEN 33 A 5 G...
python|pandas|list|join
3
12,338
58,112,528
How to change my pandas dataframe output format such as auto adjust column size
<p>I newly installyed pandas and python, and my pandas dataframe result is not like the usual type. I tried to upgrade pandas and ipython, but none of these worked.<a href="https://i.stack.imgur.com/Z79E4.png" rel="nofollow noreferrer">This is my desired dataframe format for displaying</a></p> <p><a href="https://i.st...
<p>Try this:</p> <pre><code>import pandas as pd pd.set_option('display.max_columns', 200) # increase the number of visible columns in output to 200 pd.set_option('display.max_rows', 200) # increase the number of visible rows in output to 200 </code></pre> <p><strong>EDIT:</strong></p> <p>Paste the following code in ...
python|pandas|dataframe|format
0
12,339
34,243,488
How to merge two grouped-by Pandas Dataframes by a common column(ID) together?
<p>I'm learning data analysis with pandas. </p> <p>I have two grouped-by dataframes, looking like below.</p> <p>df1:</p> <pre><code> count1 count2 rate id 958 34 34 1.000000 2822 41 41 1.000000 5193 180 184 0.978261 5841 35 35 1.000000 5858 104 104 1.000000 </code></pre> <p>...
<p>You could use <code>join</code></p> <pre><code>In [226]: df1.join(df2) Out[226]: count1 count2 rate price id 958 34 34 1.000000 170 2822 41 41 1.000000 138 5193 180 184 0.978261 160 5841 35 35 1.000000 181 5858 104 104 1.000000 250 </co...
python|pandas|merge|group-by
4
12,340
36,916,343
How do you use matplotlib function fill_between with pandas dataframe
<p>I have a stock price line graph which works,however I wanted to use the fill between function. I have tried passing in the values directly from the series and also creating lists etc. and nothing works. Is this possible? </p> <pre><code>myDF = pd.read_csv('C:/Workarea/OneDrive/PyProjects/Learning/stocks_sentdex/GOO...
<pre><code>import pandas as pd import pandas_datareader.data as pdata import matplotlib.pyplot as plt # myDF = pd.read_csv('C:/Workarea/OneDrive/PyProjects/Learning/stocks_sentdex/GOOG-LON_TSCO.csv') # myDF = myDF.set_index('Date') myDF = pdata.get_data_google('LON:TSCO', start='2009-01-02', end='2009-12-31') fig, a...
python-3.x|pandas|matplotlib
1
12,341
36,712,578
How to extract a 1d profile (with integrated width) from a 2D array in an arbitrary direction
<p>i have the following problem: I would like to extract a 1D profile from a 2D array, which is relatively simple. And it is also easy to do this in an arbitrary direction (see <a href="https://stackoverflow.com/questions/7878398/how-to-extract-an-arbitrary-line-of-values-from-a-numpy-array">here</a>).</p> <p>But i wo...
<p>As another option, There's now a scipy measure function that does exactly this (get profile between arbitrary points in a 2d array, with optional width specified):<a href="https://scikit-image.org/docs/dev/api/skimage.measure.html?highlight=profile#skimage.measure.profile_line" rel="nofollow noreferrer">skimage.meas...
python|numpy|image-processing|scipy
3
12,342
37,107,223
How to add regularizations in TensorFlow?
<p>I found in many available neural network code implemented using TensorFlow that regularization terms are often implemented by manually adding an additional term to loss value.</p> <p>My questions are:</p> <ol> <li><p>Is there a more elegant or recommended way of regularization than doing it manually?</p></li> <li>...
<p>As you say in the second point, using the <code>regularizer</code> argument is the recommended way. You can use it in <code>get_variable</code>, or set it once in your <code>variable_scope</code> and have all your variables regularized.</p> <p>The losses are collected in the graph, and you need to manually add them...
python|neural-network|tensorflow|deep-learning
70
12,343
36,748,184
Averaging numpy masked array over multiple dimensions
<p>It is possible to compute the average of a numpy array over multiple dimensions, as in eg. <code>my_ndarray.mean(axis=(1,2))</code>. </p> <p>However, it does not seem to work with a <strong>masked array</strong>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.randint(0, 10, (2, 2, 2)) &g...
<p>I found out that though <code>np.ma.mean</code> does not works, <code>np.ma.average</code> gives the expected result:</p> <pre><code>&gt;&gt;&gt; np.ma.average(ma, axis=(1,2)) masked_array(data = [7.0 7.0], mask = [False False], fill_value = 1e+20) </code></pre> <p>This is confusing since for r...
python|numpy|masked-array
2
12,344
37,065,512
Fully Convolution Net (FCN) on Tensorflow
<p>I'm trying to reimplement FCN on tensorflow. I have implemented the deconvolution layer as such.</p> <pre><code>up8_filter = tf.Variable(tf.truncated_normal([64, 64, 21, 21])) prob_32 = tf.nn.conv2d_transpose(score, up8_filter, output_shape = [batch_size, 224, 224, 21], strides = [1, 32, 32, 1]) tf.histogram_summar...
<p>Also have a look at my Tensorflow <a href="https://github.com/MarvinTeichmann/tensorflow-fcn" rel="noreferrer">FCN implementation</a>. Training works when using this <a href="https://github.com/MarvinTeichmann/tensorflow-fcn/blob/86645753421a6b045182b69d6c68b6720670a3b8/loss.py" rel="noreferrer">loss function</a> in...
tensorflow
5
12,345
55,128,814
How can I make a neural network that has multiple outputs using pytorch?
<p>Is my question even right? I looked everywhere but couldn't find a single thing. I'm pretty sure this was addressed when I learned keras, but how do I implement it in pytorch?</p>
<p>Multiple outputs can be trivially achieved with pytorch. </p> <p>Here is one such network.</p> <pre class="lang-py prettyprint-override"><code>import torch.nn as nn class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.linear1 = nn.Linear(in_features = 3, out_fea...
pytorch
27
12,346
54,709,248
data frame with answers, how to keep only the top 100 answers
<p>I have a data frame with answers (the internet color survey). the data frame is like this:</p> <p>I have a data frame with answers (the internet color survey). the first five rows look like this:</p> <pre><code>id user r g b colorname 0 1 72 100 175 pastel blue 1 2 204 177 246 faint violet 2 3 ...
<p>Can you try the following:</p> <pre class="lang-py prettyprint-override"><code>data[data.colorname.isin(data.colorname.value_counts()[:100].index)] </code></pre>
python|pandas|dataframe
2
12,347
54,766,956
manipulating pandas dataframe - conditional
<p>I have a pandas dataframe that looks like this:</p> <pre><code>ID Date Event_Type 1 01/01/2019 A 1 01/01/2019 B 2 02/01/2019 A 3 02/01/2019 A </code></pre> <p>I want to be left with:</p> <pre><code>ID Date 1 01/01/2019 2 02/01/2019 3 02/01/2019 </code></pre> <p>W...
<p>I believe you need first convert values to datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, then get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.htm...
python-3.x|pandas
3
12,348
54,725,038
Numpy optimized reshape : 2D array to 3D
<p>I was wondering if there is a more pythonic/efficient way of reshaping my 2d-array into a 3d-array ? Here is the following working code :</p> <pre><code>import numpy as np # # Declaring the dimensions n_ddl = 2 N = 3 n_H = n_ddl*N # # Typical 2D array to reshape x_tilde_2d = np.array([[111,112,121,122,131,132],[211...
<pre><code>In [337]: x=np.array([[111,112,121,122,131,132],[211,212,221,222,231,232],[311,3 ...: 12,321,322,331,332]]) In [338]: x.shape Out[338]: (3, 6) In [339]: x Out[339]: array([[111, 112, 121, 122, 131, 132], [211, 212, 221, 222, 231, 232], [311, 312, 321, 322, 331, 332]]) </code></pre> <p>Th...
python|python-3.x|numpy|reshape|numpy-ndarray
2
12,349
49,717,231
Error in pandas read_csv function
<p>I am new to data science. I want to apply preprocessing to my dataset in Jupyter Notebook. Here is what I have done so far:</p> <pre><code>import pandas as pd import numpy as np from sklearn import preprocessing country = pd.read_csv('data.csv', encoding='utf_8') </code></pre> <p>But it gives me this error:</p> ...
<p>There is problem need omit first 4 lines by parameter <code>skiprows</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>:</p> <pre><code>df = pd.read_csv('data.csv', skiprows=4) print (df.head()) Country Name Country C...
python-3.x|pandas
1
12,350
49,682,655
How to read the data ignoring the comma in columns using pd.read_csv
<p>I used the follow way to read my data:</p> <pre><code>df=pd.read_csv("file.dat",delim_whitespace=True,header=None,skiprows=None) df.head() </code></pre> <p>and then I obtained:</p> <pre><code>0, 1, 0, 1, 0, 0, 0, 0, 0, 0.5 1, 1, 0, 1, 0, 0, 0, 0, 0, 1.5 ... </code></pre> <p>It is shown t...
<p>Your option <code>delim_whitespace=True</code> is equivalent to <code>sep='\s+'</code> if your file has value separeted with commas ommit the line <code>delim_whitespace=True</code>, you don't need the <code>sep = ','</code> as it is the default value. try:</p> <pre><code>df = pd.read_csv("file.dat", header=None,...
python|pandas|import-from-csv
0
12,351
73,242,286
Pandas merge duplicate rows
<p>I am trying to merge two dataframes on Origin, Destination and Service. The first df is</p> <pre><code>df = {'Origin': ['London','London','London','Geneva','Amsterdam','Amsterdam','Mardid'], 'Destination': ['Paris','Paris','Paris','Vienna','Berlin','Berlin','Barcelona'], 'Service': ['Express','Express','...
<p>Use <code>drop_duplicates</code> with <code>keep=&quot;first&quot;</code> (keep is &quot;first&quot; by default) on <code>df1</code>.</p> <p>before <code>drop_duplicates</code>, sort by price.</p> <pre class="lang-py prettyprint-override"><code>cols = [&quot;Origin&quot;, &quot;Destination&quot;, &quot;Service&quot;...
python|pandas
2
12,352
73,473,063
How to append new values in a pandas dataframe and save it to a csv file?
<p>I have made a stock trading code, mainly for paper trading...I want to save the output to a csv file. Below is my code. I can't save that to CSV file. How to fix that???</p> <pre><code>columns = [&quot;Datetime&quot;,&quot;Symbol&quot;,&quot;Trade_price&quot;,&quot;Trade_type&quot;] trade = pd.DataFrame(columns = co...
<p>I propose you make a dictionary object of your input data and then simply append the dictionary object to your data frame; I am pretty sure, it is the best way you append new data row to pandas data frame. For example:</p> <pre><code>output = pd.DataFrame() output = output.append(dictionary, ignore_index=True) print...
python|pandas|dataframe|csv
0
12,353
73,492,487
Subsetting pandas dataframe where at least two columns are true
<p>If I have a pandas dataframe that I want to subset based on if at least two out of three columns are &gt; specific values, what would be the best way to do so?</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [50, 0, 0, 30, 10], 'c': [0, 1000, 2000, 0, 0]}) a b c 0 1 50 0 1 2 0 1000 2 3 0 2000 3 4 30 0 4 5 10 0 </code></pre> <pre class="lang-py prettyprint-...
pandas|dataframe|subset
0
12,354
73,327,621
Replace Pandas NaN with Data from Different DF Based on Multiple Conditions
<p>I have a datafrmae &quot;dfnan&quot; that has NaN values and I need to replace those values with data from a different dataframe &quot;dffill&quot; with specific row insert position requirements by &quot;name&quot; and &quot;month&quot;. My data looks like this for dfnan:</p> <pre><code>index result result resul...
<p>here is one way to do it, which is to make use of df.update assuming its ok to set the index and rename the df2 columns</p> <pre><code>#set the index on both the DF df.set_index(['name','month'], inplace=True) df2.set_index(['name','month'], inplace=True) #match the columns names b/w df and df2, by taking df column...
python|pandas|group-by|nan|fillna
1
12,355
30,941,425
Updating Pandas MultiIndex after indexing the dataframe
<p>Suppose I have the following dataframe:</p> <pre><code>arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) s = pd.DataFrame(np.random.rand...
<p>Two points. First, I think you may want to do something that is actually bad for you. I know it's annoying that you have a lot of extra cruft in your filtered indices, but if you rebuild the indices to exclude the missing categorical values, then your new indices will be incompatible with each other and the original...
python|indexing|pandas|multi-index
2
12,356
31,148,543
Transforming data for kmeans and PCA
<p>I have a dataset that looks like this:</p> <pre><code>search_term = ['computer','usb port', 'phone adaptor'] clicks = [3,2,1] bounce = [0,0,2] conversion = [4,1,0] </code></pre> <p>I want to feed it into a kmeans model however i am having trouble transforming the lists into a matrix format so that it can be ingest...
<p>The following code should work. Let me know if this is not the case.</p> <pre><code>import numpy as np from sklearn.decomposition import PCA from sklearn.cluster import KMeans search_terms = ['computer','usb port', 'phone adaptor'] clicks = [3,2,1] bounce = [0,0,2] conversion = [4,1,0] X = np.array([clicks, bounc...
python|numpy|scipy|scikit-learn|k-means
3
12,357
31,162,701
Getting rid of frame and axis labels
<p>I have done some research, but every solution I found didn't work for what comes with 'Anaconda-2.2.0-Linux-x86_64.sh'... Can someone tell me how to get rid of the frame and the axis labels?</p> <pre><code>boros = GeoDataFrame.from_file('nybb/nybb.shp') boros.plot() </code></pre> <p><img src="https://i.stack.imgu...
<p>Here is a way to remove spines and tick labels:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x = np.linspace(-np.pi, np.pi, 100) y = 2*np.sin(x) ax.plot(x, y) ax.patch.set_visible(False) ax.grid('off') [ax.spines[spine].set_visible(False) for spine in ax.spines] ...
python|pandas|matplotlib
1
12,358
67,322,586
Pandas duplicate rows replacing one column value
<p>I have a dataframe <em>train_df</em> that looks like this (this is an example, I have a lot more rows):</p> <pre><code>term text_snippet abbr label Operatiekamer De OK is open OK 1 </code></pre> <p>I have another dataframe <em>abbr_df</em> that looks like this:</p> <pre><code>a...
<p>You can use <code>pd.merge</code> to populate <code>abbr_df</code> with the matching values of <code>train_df</code>. Of course the labels will not be populated correctly, but you can use <code>apply</code> to set the labels to <code>0</code> if the <code>terms</code> of the two dataframes do not match:</p> <pre><co...
python|pandas|dataframe|nlp
1
12,359
67,506,935
pd.ExcelWriter, writer.save(), download file locally
<p>I am using Python 3.7.5 in a databricks environment.</p> <p>I have a pretty simple function written that concatenates multiple dataframes into one excel spreadsheet. <strong>The main issue is that I can't access the file to download to my local machine.</strong></p> <pre><code># function def dfs_tabs(df_list, shee...
<p>per <a href="https://docs.databricks.com/data/databricks-file-system.html#local-file-api-limitations" rel="nofollow noreferrer">https://docs.databricks.com/data/databricks-file-system.html#local-file-api-limitations</a> - I had to append the entire local address to the filename variable - complete working script bel...
python|excel|pandas|dataframe
1
12,360
34,428,730
In python convert day of year to month and fortnight
<p>I want to convert day (say 88) and year (say 2004) into its constituent month and nearest number out of 2 possibilities:</p> <p>If the day of month ranges from 1 to 14, then return 1, else return 15</p> <p>I am doing this:</p> <pre><code>datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1) </code></pre> ...
<p>You can use the replace method:</p> <pre><code>In [11]: d Out[11]: datetime.datetime(2004, 3, 28, 0, 0) In [12]: d.replace(day=1 if d.day &lt; 15 else 15) Out[12]: datetime.datetime(2004, 3, 15, 0, 0) In [13]: t = pd.Timestamp(d) In [14]: t.replace(day=1 if t.day &lt; 15 else 15) Out[14]: Timestamp('2004-03-15 0...
python|datetime|pandas
3
12,361
34,666,424
Access Violation (0xC0000005) NumPy array
<p>I have this simple NumPy/Python code below:</p> <pre class="lang-py prettyprint-override"><code>from numpy import zeros, float32 v = 3039345 d = 400 i = 354993 j = 0 var1 = zeros((v,d), dtype=float32) var1[i, j] = 0 #the problem pops here </code></pre> <p>when the last line is interpreted, I have this:</p> <blockq...
<p>It is caused by the 32 bit version of numpy binaries. Numpy does calculate the size of the allocated memory region using platform-specific integers, and the size of the array measured in bytes does not fit in 2**32. It sounds like a bug, as it should raise an error at array creation in my opinion.</p> <p>You can in...
python|arrays|numpy|limit|memory-access
2
12,362
59,954,377
Can only compare identically-labeled Series objects error with if statement - Python
<p>I'm attempting to run an if statement to match the country of origin of marathon winners to theirs countrie's gdp data. I am getting the error 'Can only compare identically-labeled Series objects'. </p> <pre><code>if df['Winner Country'] == gdp_data['Country']: if df['YEAR'] == 1970 : df['gdp'] = gdp...
<p>I am not quite sure what you are asking but i think you are trying to create a gdp column that matches with the year column.</p> <p>If that is the case i think this should work.</p> <pre><code>df_gdp['gdp'] = df_gdp.apply(lambda x: x.loc[(x['YEAR'])], axis=1) </code></pre> <p>Here is how i tested it.</p> <pre...
python|pandas|if-statement
0
12,363
65,156,174
how to group by multiple columns
<p>I want to group by my dataframe by different columns based on UserId,Date,category (frequency of use per day ) ,max duration per category ,and the part of the day when it is most used and finally store the result in a .csv file.</p> <pre><code> name duration UserId category part_of_day Date Settings ...
<p>It looks like you might be wanting to calculate statistics for each group.</p> <pre class="lang-py prettyprint-override"><code>grouped = df.groupby([&quot;UserId&quot;, &quot;Date&quot;,&quot;category&quot;]) result = grouped.agg({'category': 'count', 'duration': 'max'}) result.columns = ['group_count','duration_ma...
python|pandas|csv
1
12,364
65,355,986
Indexing error: Unalignable boolean series
<p>I am getting Indexing error in following code</p> <pre><code>data.loc[data.loc[sub_df_idx, 'A'] == data.loc[sub_df_idx, 'A'].min(), 'B'] </code></pre> <p>sub_df_idx is just</p> <pre><code>Int64Index([25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], ...
<p>Index of mask has to be same length like original, so compare original column <code>A</code> and then filter only index values from <code>sub_df_idx</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a>:</p> <pre><co...
python|pandas
0
12,365
65,463,792
How to compare 2 columns of unordered lists in 2 separate dataframes?
<p>I have 2 dataframes that have the same structure. Below is the code for dummy data:</p> <pre><code>col1=[1,2,3] col2=[['a','b','c'],['d','e','f'],['g','h','i']] col3=[['b','a','c'],['e','d','f'],['i','m','g']] d1={ &quot;col1&quot;:col1, &quot;col2&quot;:col2, } d2={ &quot;col1&quot;:col1, &quot;col2...
<p>The lists need to be treated without ordering, and in order to test for membership, they must be hashable.</p> <p>One structure that fits these descriptions is a <code>frozenset</code>, this works assuming your lists don't have duplicates. We can filter on B in this manner:</p> <pre><code>B[~B['col2'].map(frozenset)...
python|python-3.x|pandas|dataframe
3
12,366
49,806,587
OLS in Python: dimension of estimated coefficient matrix is not OK
<p>I have written a Python code to estimate the parameter from (univariate) linear regression model, but the dimension of the estimated coefficient matrix is not ok. The dimension of vector 'beta_estimated' (reported below) should be (1-by-1) but is (n-by-n). Any thougths? </p> <pre><code># Linear regression in Python...
<p>I'm not sure what you want to do, but if I had to guess the product is the reason why you don't have the dimensions you are looking for. In your case:</p> <pre><code>x # has a shape of (1, 100) x.T # has a shape of (100, 1) np.dot(x.T, x) # produces an array with shape (100, 100) np.dot(x, x.T) # would produce a...
python|numpy
1
12,367
50,206,526
apply conditions to df.groupby() to filter out duplicates
<p>I need to groupby and filter out duplicates in a pandas dataframe based on conditions. My dataframe looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID':[1,1,2,2,3,4,4],'Date':['1/1/2001','1/1/1999','1/1/2010','1/1/2004','1/1/2000','1/1/2001','1/1/2000'], 'type':['yes','yes','yes','yes','no'...
<p>This will need <code>pd.concat</code></p> <pre><code>grouped = df.groupby(['type'])['Date'].transform(max)# I change this line seems like you need groupby type s = df.loc[df['Date'] == grouped].index #here we split the df into two part , one need to drop the not match row , one should keep all row pd.concat([d...
python|pandas|numpy
2
12,368
63,850,014
Python/ Pandas: Conditional summation
<p>i'm working with a large dataset and having trouble coding the conditions for the following task:</p> <p>The following is an example similar to my own problem. I'm trying to calculate how quickly a substance travels through a medium. Each year and for each id, a substance is inserted into the medium. The goal is to ...
<p>I'm not aware of any pandas built-in method that targets this specific case. But here's a solution with <code>apply</code> and some numpy handling.</p> <pre><code>def rolling_fwd_idx_over(df, group_by_cols, value_col, target_col, cutoff=100): def find_cross(group): travel = group[value_col].to_numpy() ...
python|pandas|conditional-statements
1
12,369
64,100,096
Input fixed length sequence of frames to CNN
<p>I want my pytorch CNN to take as input a sequence of length <code>SEQ_LEN</code> of 32x32 RGB images concatenated along channels dimension. Therefore, a single input of the network has shape <code>(32, 32, 3, SEQ_LEN)</code>. How should I define my CNN input layer?</p> <p>The common way</p> <pre class="lang-py prett...
<p>Given your comments, it sounds like your data is not fit for a <em>2D</em> convolutional neural network at all, and that a <em>3D</em> one (<a href="https://pytorch.org/docs/stable/generated/torch.nn.Conv3d.html" rel="nofollow noreferrer"><code>Conv3d</code></a>) would be more appropriate. As you can see from its do...
python|pytorch|tensor|conv-neural-network
1
12,370
47,050,382
Pandas: Dynamically add a row and columns and input values to it
<p>I am working with a large dataset that iteratively fetches n number of child URLs for a particular parent URL. </p> <p>I initially used excel to record the data (test the working my code actually). But later found out that the idea is not worth it as the output data were huge.</p> <p>for example: i have two set of...
<p>Hope this would help:</p> <pre><code>xx = { 'amazon.com': ['a','b','c','d','e'], 'a' : ['k','j','e','f'] } all_vals = [item for key,items in xx.items() for item in items] all_vals = sorted(set(all_vals)) df = pd.DataFrame(index=xx.keys(),columns=all_vals) def is_exist(idx,col): ret = col in xx[...
python|pandas
2
12,371
32,989,376
Timeseries forecasting in Python with datetime indexes
<p>I'm trying to forecast a time serie using both SVR and GP. The time serie is in fact a <code>pandas.Series</code> with <code>pandas.DatetimeIndex</code> as indexes.</p> <p>Both of the algorithms are implemented in scikit-learn. Whereas SVR actually accepts to predict with X axis after a modification :</p> <pre><c...
<p>Obviously the timestamp data types are unacceptable. They should be converted to float.</p>
python|pandas|scikit-learn|time-series|gaussian
0
12,372
33,050,136
Replace missing values in list from second list using python/pandas
<p>Consider you have two lists (or columns in a pandas DataFrame), each containing some null values. You want a single list that replaces the null values in one list with the corresponding non-null values of the other if one exists.</p> <p>Example:</p> <pre><code>s1 = [1, NaN, NaN] s2 = [NaN, NaN, 3] ## some function...
<p>You can use pandas fillna functionality to fill missing values from other columns.</p> <pre><code>df = pd.DataFrame([[1,np.nan],[np.nan,np.nan],[np.nan,3]],columns=['c1','c2']) df['c1'].fillna(df['c2']) </code></pre>
python|pandas
1
12,373
38,737,134
Loss of precision while converting floats to strings in pandas
<p>I am converting in Python some floats (some shorter some longer) to strings and getting unexpected (?) results:</p> <p><strong>Case 1</strong></p> <pre><code>pd.options.display.float_format = '{:.2f}'.format pd.DataFrame({'x': [12345.67]}) x 0 12345.67 </code></pre> <p><strong>Case 2</strong></p> <...
<p>I'm afraid this "issue" happens in the Python (instead of pandas) side. When you have some instant values like <code>1234589890878708980.67</code> it's recognized as <code>float</code> and loses precision instantly, e.g.:</p> <pre><code>&gt;&gt;&gt; 1234589890878708980.67 1.234589890878709e+18 &gt;&gt;&gt; 12345898...
python|string|pandas|floating-point
3
12,374
38,666,040
TensorFlow: AttributeError: 'Tensor' object has no attribute 'shape'
<p>I have the following code which uses TensorFlow. After I reshape a list, it says </p> <blockquote> <p>AttributeError: 'Tensor' object has no attribute 'shape'</p> </blockquote> <p>when I try to print its shape.</p> <pre><code># Get the shape of the training data. print "train_data.shape: " + str(train_data.shap...
<p><strong>UPDATE:</strong> Since TensorFlow 1.0, <code>tf.Tensor</code> now has a <a href="https://www.tensorflow.org/api_docs/python/tf/Tensor#shape" rel="noreferrer"><code>tf.Tensor.shape</code></a> property, which returns the same value as <a href="https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape" rel...
python|neural-network|tensorflow
26
12,375
63,170,518
Assertion failed: predictions must be >= 0, Condition x >= y did not hold element-wise
<p>I am running a multi-class model(total 40 class in total) for 2000 epochs. The model is running fine till 828 epoch but at 829 epoch it is giving me an InvalidArgumentError (see the screenshot below)</p> <p><a href="https://i.stack.imgur.com/O7yv8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O7yv8.png" ...
<p>I think that this error is due to the setting of the AUC metric.(see <a href="https://www.tensorflow.org/api_docs/python/tf/keras/metrics/AUC" rel="noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/metrics/AUC</a>) The predictions should be all non-negative values instead of [-nan, -nan, ...] as your m...
python-3.x|tensorflow2.0|multiclass-classification
19
12,376
63,093,510
Error while installing tensorflow(AVX support) and cpuid python
<p>While I was trying to setup <code>tensorflow</code> (both, using venv and without it) on <code>import</code> I got the following error:</p> <blockquote> <p><code>ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.</code></p> </blockquote> <p>I went to the official site's error p...
<p>I've managed to resolve all the issues:</p> <ol> <li>Problem with <code>cpuid</code> and Microsoft Visual C++ 14.0 is required:</li> </ol> <blockquote> <p><a href="https://visualstudio.microsoft.com/visual-cpp-build-tools/" rel="nofollow noreferrer">VS BuildTools needed</a>, I installed all the marked items but I fo...
python|tensorflow
1
12,377
63,139,598
Convert 100k row pyspark df to pandas df
<p>I have a pyspark df with 100k rows. I am using spark</p> <pre><code>df = pandas_df.toPandas() </code></pre> <p>which takes lot of time to execute this syntax. Is there any other way to do this operation within seconds? Also to save the pyspark dataframe in <code>.csv</code> format it takes lot of time. Why is it so?...
<p>Try to repartition your datafram first before converting to pandas df</p> <pre><code>df = df.repartition(1) df = df.toPandas() </code></pre>
python|pandas|pyspark
0
12,378
63,143,261
Pandas distinguish between "date" and "string" columns both with "object" type
<p>This seems like a straightforward question, but I've been stuck for a while on it now. Apologies if this has been asked already. I have the following pandas dataframe:</p> <pre><code>import pandas as pd zed = pd.DataFrame({'gameDate': {0: datetime.date(2019, 12, 12), 1: datetime.date(2019, 12, 12), 2: datetime.d...
<p>You have two options:</p> <p>1- Use pd.datetime in the construction of your 'gameDate' dictionary as follow:</p> <pre><code>zed = pd.DataFrame( {'gameDate': { 0: pd.datetime(2019, 12, 12), 1: pd.datetime (2019, 12, 12), 2: pd.datetime(2019, 12, 12), 3: pd.datetime(2019, 12, 12), ...
python|pandas|dataframe|validation|datetime
1
12,379
62,936,421
Python Pandas: Repeat the column name based on the value in a cell
<p>I have the below dataframe</p> <pre><code>import pandas as pd dfx = pd.DataFrame({'A': [100, 100, 100, 102, 102], 'B': [1, 2, 3, 0, 0],'C': [0, 2, 1, 0, 0],'D': [0, 0, 4, 1, 0] }) print(dfx) A B C D 0 100 1 0 0 1 100 2 2 0 2 100 3 1 4 3 102 0 0 1 4 102...
<p>You can try <code>dot</code></p> <pre><code>s=df.loc[:,'B':] df['New Col']=s.dot(s.columns+',').str.split(',').str[:-1] Out[70]: 0 [B] 1 [B, B, C, C] 2 [B, B, B, C, D, D, D, D] 3 [D] 4 [] dtype: object </code></pre>
python|pandas
2
12,380
67,780,172
Cannot convert datetime values to a necessary format
<p>I am struggling with datetime format... This is my dataframe in pandas:</p> <pre><code>Datetime Date Field 2020-01-12 00:00:00 2020-12-01 6.543916 2020-01-12 00:10:00 2020-12-01 6.505547 2020-01-12 00:20:00 2020-12-01 7.047578 2020-01-12 00:30:00 2020-12-01 6.070998 2020-01-12 00:40:00 20...
<p>I think you'll get what you want with <code>&quot;%Y-%d-%m %H:%M:%S&quot;</code> instead of <code>&quot;%Y-%m-%d %H:%M:%S&quot;</code> on your last line.</p> <p><strong>EDIT:</strong> Or better even, simply replace the last 2 lines of your code by the following:</p> <pre class="lang-py prettyprint-override"><code>df...
python|pandas|dataframe|datetime
0
12,381
67,723,390
I'm trying to predict probability of X_test and getting 2 values in an array. I need to compare those 2 values and make it 1
<p><strong>I'm trying to predict probability of X_test and getting 2 values in an array. I need to compare those 2 values and make it 1.</strong></p> <p>when I write code</p> <pre><code>y_pred = classifier.predict_proba(X_test) y_pred </code></pre> <p>It gives output like</p> <pre><code>array([[0.5, 0.5], [0.6, ...
<p>Compare the two columns to create a boolean index then convert to <code>int</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html#pandas-series-astype" rel="nofollow noreferrer"><code>astype</code></a>:</p> <p>Option 1:</p> <pre><code>df['output'] = (df['pred_0'] ...
python|pandas|dataframe|loops|sklearn-pandas
0
12,382
67,981,104
OSError: SavedModel file does not exist at: cnnCat2.h5\{saved_model.pbtxt|saved_model.pb}
<p><a href="https://i.stack.imgur.com/EUWbJ.png" rel="nofollow noreferrer">Sublime Text Project Structure</a></p> <p><strong>Error Displaying</strong></p> <pre><code>2021-06-15 11:48:41.978235: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cu...
<p>in your code try to use <code>&quot;&quot;</code> and not <code>''</code> in specifying the directory</p> <p>for example</p> <pre><code>model_path = os.path.join(join(dirname(realpath(__file__))), &quot;example.h5&quot;) </code></pre>
python|tensorflow|keras
1
12,383
41,314,324
Sum large pandas dataframe based on smaller date ranges
<p>I have a large pandas dataframe that has hourly data associated with it. I then want to parse that into "monthly" data that sums the hourly data. However, the months aren't necessarily calendar months, they typically start in the middle of one month and end in the middle of the next month. </p> <p>I could build ...
<p><strong><em><code>pd.merge_asof</code> only available with pandas 0.19</em></strong><br> combination of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html#pandas.merge_asof" rel="nofollow noreferrer"><code>pd.merge_asof</code></a> + <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas
3
12,384
41,324,143
Handle missing values in pandas using dtype to read files
<p>I'm reading a bunch of CSV files using dtype to specify the type of data of each column:</p> <pre><code>dict_tpye = {"columns_1":"int","column_2":"str"} pd.read_csv(path,dtype=dict_tpye) </code></pre> <p>the problem I'm facing with at doing this that columns with non-float values have missing rows, which rise and...
<p>Consider the <em>converters</em> argument which uses a dictionary, mapping results of a user-defined function to imported columns. Below user-defined methods uses the built-in <a href="https://docs.python.org/3.4/library/stdtypes.html#str.isdigit" rel="nofollow noreferrer"><code>isdigit()</code></a> that returns <co...
python|pandas|missing-data
4
12,385
41,364,790
Group by a column and return multiple aggregates as a dataframe
<p>I have a csv having multiple columns. As an example, here is the header and the first 2 rows of the file:</p> <pre class="lang-none prettyprint-override"><code>ACC;SYM;SumRealPNL;Count;MinAVG;PerLotPNL;SumOneLotPNL;ProfitOnly;ProfitOnlyCount;ProfitOnlyMinAVG;LossOnly;LossOnlyCount;LossOnlyMinAVG;Period;-;P;Q;R;S;T...
<p>Once you have your dataframe <code>df</code> and group on the <code>AS</code> column as you have already in your post, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="noreferrer">agg</a> function to obtain the desired output.</p> <pr...
python|pandas|group-by
11
12,386
27,809,175
no module called numpy
<p>I'm using ubuntu 14.04 and just installed python 3.4. And on terminal I entered:</p> <p>sudo apt-get install python-numpy</p> <p>sudo apt-get install cython</p> <p>sudo apt-get install python-scipy</p> <p>sudo apt-get install python-matplotlib</p> <p>when I tried to run something on idle, it showed the massage...
<p>Can you try </p> <pre><code>sudo apt-get install python3-numpy </code></pre> <p>Because what you did should install it for python 2.x </p>
ubuntu|numpy|installation|python-3.4
1
12,387
27,733,230
What is this issue of variable affectation in python?
<p>I have this problem in python. I have a function which take the following inputs</p> <pre><code>import numpy; from numpy import *; def GetInf(G, X, m, n): g = G[m - 1, :].T; Y = X; Y[m - 1, :] = 0; Y[:, n - 1] = 0; # Here I modify Y. The problem is that X is modified too. Why...
<p>it because of that you assign <code>X</code> to <code>Y</code> . that means <code>Y</code> is a reference to where <code>X</code> refer ! if you don't want that you have to make a copy of <code>X</code> :</p> <pre><code>Y=np.copy(X) </code></pre>
python|arrays|numpy|matrix
2
12,388
61,502,843
Pandas - match a column of string with a column of regular expressions
<p>The problem: I have two dataframes - one with a bunch of product titles that are not normalized, and one with a bunch of regular expressions that are tied to normalized product titles. I need to match the non-normalized titles to some regular expressions which are tied to normalized titles. It should make more sens...
<p>There are many ways to do this, but the simplest is to test each of the regexes on each of the titles and return the first match you find. First, we'll define a function that will return two values: the manufacturer and model of the regex row, if we match, two <code>None</code>s otherwise:</p> <pre><code>def find_m...
pandas|dataframe
0
12,389
61,591,470
How can i Load local images to train model in tensorflow
<p>I am trying to build a CNN to differentiate between a car and a bicycle. However i saw the same example of a horse and a human in the Laurence's example here. But instead of loading the data from some library, i have downloaded close to 5000 images of cars and bicycle and segregated them as the folders suggested in ...
<p>You can't access files which are on your computer directly from colab. If you have enough space on your google drive, you can upload them to your google drive and mount it like <a href="https://colab.research.google.com/notebooks/io.ipynb" rel="nofollow noreferrer">here</a> or with the "Mount Drive" button on the fi...
python-3.x|tensorflow2.0
0
12,390
61,263,796
Use a numpy mask to determine indices for imshow
<p>Using the small reproducible example below, I create mask that I would then like to programatically determine the min and max x and y indices of where the mask is false (i.e., where the values are not masked). In this and the larger 'real-world' example, the masked values will always be spatially continuous - there...
<p>The following code should work:</p> <pre class="lang-py prettyprint-override"><code>y, x = np.where(~mask) # ~ negates the boolean array x_min = x.min() x_max = x.max() y_min = y.min() y_max = y.max() plt.imshow(arr1[y_min:y_max+1, x_min:x_max+1]) </code></pre> <p><a href="https://i.stack.imgur.com/Bmw0y.png" rel...
python|numpy
1
12,391
61,581,658
module 'tensorflow.python.keras.utils.generic_utils' has no attribute 'populate_dict_with_module_objects'
<p>When trying to import tensorflow I keep on getting this error. I have tried reinstalling tensorflow but I still revive this problem on this statement:</p> <p>import tensorflow as tf</p> <p>Does anyone have advice? Tensorflow worked on my system before I originally reinstalled it but now I have no luck. Thanks.</p>
<p>I ended up deleting my python and re downloading it</p>
python|tensorflow
0
12,392
61,414,186
How do I create a for loop here?
<p>I want to take names from a name list, look those up in an excel sheet, and return both the name and a value in another column (column 'Unnamed: 4'). This is what I have right now, and it works to lookup one name, but I want to look up every name in the list. How do I make a for loop here?</p> <pre><code>file = '/m...
<p>You haven't given much context but i guess it would be something like this: A for loop for the names and a list 'rows' to store the results</p> <pre><code>file = '/mnt/c/python/Iban programmatje/testsheet.xlsx' f = open('namelist.txt', 'r') namestring = f.read() f.close() namelist = namestring.split(",") df = pd...
python|excel|pandas
0
12,393
61,524,370
How can I count the presence of different values in a long list of specific columns with Python?
<p>I have 25 columns and 5 rows here. I need to count the values in specific columns only once per row. Was the value '1' present in this row of data between these columns? If yes, then count it. And so on with the other values. </p> <p>There are other columns that also contain these values, but they should not be cou...
<p>The strategy here is melt your data down into row, value pairs, and then count the distinct sets of these. First, get the columns you want to keep as a list:</p> <pre><code>cols = [f"Column {x} {y}" for y in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for x in [1, 2]] </code></pre> <p>Then, transpose your data so that you hav...
python|pandas|dataframe|count
1
12,394
68,694,768
AttributeError: module 'keras.engine.sequential' has no attribute 'add'
<p>AttributeError: module 'keras.engine.sequential' has no attribute 'add'</p> <p>I am working on an image classification in this a problem keras.engine.sequential has no attribute add</p>
<p>Please use from Keras.models import Sequential for image classification. and also if you could more elaborate the problem with your code snippets.</p>
tensorflow|tf.keras|keras-layer
0
12,395
68,453,045
Problem with variable when working with python
<p>Hello everyone im trying to work with the Digit tactile sensor with the PyTouch library so when i try to run the contact area code example i get this error</p> <pre><code>DigitSensor with SensorDataSources.RAW data source Traceback (most recent call last): File &quot;contactarea.py&quot;, line 31, in &lt;module&gt; ...
<p>Seems like the condition <code>len(contour) &gt; contour_threshold</code> inside <code>_compute_contact_area</code> is never matched so the variable <code>poly</code> is never defined.</p> <p>I recommend trying to <code>print</code> the length of <code>contour</code> before the <code>if</code> statement to check the...
python|pytorch|arguments|python-3.7|python-3.8
1
12,396
36,614,427
Use between_time() on MultiIndex?
<p>Suppose I have a DataFrame with a MultiIndex as follows:</p> <pre><code> col col col col ... tstp pkt 2016-04-14 04:05:32.321 0 ... ... ... ... 25 ... ... ... ... 2016-04-14 04:05:...
<p>There are multiple ways to get the result you want:</p> <h1>Option 1</h1> <p><strong>Probably the best is to use</strong> <code>DataFrame.loc</code> <strong>to index directly into the</strong> <code>MutliIndex</code>:</p> <pre><code>df.loc[beg:end] </code></pre> <h1>Option 2</h1> <p>If you need to use <code>bet...
python|pandas
3
12,397
52,918,337
R Keras: Convert tensorflow tensor to R array
<p>I am using R Keras. I can obtain the output of an intermediate layer by for example executing:</p> <pre><code>layer_output &lt;- get_layer(mymodel, index=1)$output </code></pre> <p>where mymodel is a Keras model. The problem is that layer_output is a tensor.</p> <pre><code>class(layer_output) [1] "tensorflow...
<p>One option is to create a new model which will only output your layer of interest.</p> <p>First create the original model:</p> <pre><code>model &lt;- ... # create original model </code></pre> <p>Then create the new model and use predict to get the output:</p> <pre><code>layer_name &lt;- 'my_layer' intermediate_...
r|tensorflow|keras
1
12,398
53,330,908
Python - Quick Upscaling of Array with Numpy, No Image Libary Allowed
<p><strong>Note on duplicate message:</strong></p> <p>Similar themes, not exactly a duplicate. Esp. since the loop is still the fastest method. Thanks.</p> <p><strong>Goal:</strong> </p> <p>Upscale an array from [small,small] to [big,big] by a factor quickly, don't use an image library. Very simple scaling, one smal...
<p>I did some benchmarks about this using a <code>512x512</code> byte image (10x upscale):</p> <pre><code>a = np.empty((512, 512), 'B') </code></pre> <h3>Repeat Twice</h3> <pre><code>&gt;&gt;&gt; %timeit a.repeat(10, 0).repeat(10, 1) 127 ms ± 979 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) </code></pre> ...
python|arrays|numpy|scaling
4
12,399
65,866,526
Tensorflow MNIST Sequential - ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have
<p>I am trying a simple network on MNIST dataset from Tensorflow. I hit this error and am trying to understand where the issue lies.</p> <pre><code>mnist_ds, mnist_info = tfds.load( 'mnist', split='train', as_supervised=True, with_info=True) def normalize(image, label): n = tf.cast(image, tf.float32) / 255.0 ...
<p>Problem is with this line layers.Dense(units=64, activation='relu', input_shape=[28*28])</p> <p>Find the sample working code</p> <pre><code>(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # train set / data x_train = x_train.reshape(-1, 28*28) x_train = x_train.astype('float32') / 255 #...
tensorflow|keras|mnist
0