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
18,400
52,387,440
mege two csv files using python or pandas
<pre><code>**csv file 1** date yearMonth deviceCategory channelGrouping eventCategory Totalevents 20160719 201607 desktop Direct _GW_Legal_RM_false 149 20160719 201607 desktop Direct _GW_Risk_RM_false 298 20160719 201607 desktop Direct _GW_Risk_RM_true 149 20160719 201607 desktop Direc...
<pre><code>df1 = pd.read_csv("csv1.csv") df2 = pd.read_csv("csv2.csv") df = pd.merge(df1, df2, on='eventCategory', how='left') </code></pre> <p>some modification to @FrankZhu 's answer.</p>
python|pandas|csv
1
18,401
60,604,844
How to formatting list of text into 2 column
<p>I have this code below to process text data using tf idf in python. </p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import glob files = glob.glob("Text/*.txt") with open("all_data.txt","wb") as outfile: for f in files: with open(f,"rb") as infile: outfile.write(infile.read()) ...
<p>The Pandas <code>.head()</code> method will print the dataframe with the number of rows you specify. You can try using this method and inserting the number of rows you would like to see. For example to see 150 rows, you can try</p> <p><code>print(test.head(150))</code></p>
python|arrays|numpy
0
18,402
60,424,873
Why does `idxmax` throw an error when I try to find the column name which has the maximum value for each row?
<p>I'm working with the UK parliamentary election dataset from <a href="https://researchbriefings.parliament.uk/ResearchBriefing/Summary/CBP-8647" rel="nofollow noreferrer">researchbriefings.parliament.uk</a>, which for some reason has thought it worth including the vote share as a proportion as well as a number, but n...
<p>Because some columns were string, not float:</p> <pre><code>&gt;&gt;&gt; parties = pd.Series(['con','lib','lab','natSW','oth']) &gt;&gt;&gt; elections[parties + '_votes'].dtypes con_votes float64 lib_votes object lab_votes object natSW_votes float64 oth_votes float64 dtype: object </code><...
python|pandas
1
18,403
60,580,248
Search a Pandas Dataframe having hierarchical indexing by a single column
<p>I'm working with this dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame([['A', 'one', 105], ['A', 'two', 101], ['A', 'three', 103], ['B','one', 101], ['B','two', 1102], ['B','three', 1050]], columns=['c1', 'c2', 'c3']) df = df.set_index(['c1', 'c2']) df <...
<p>IIUC you can do:</p> <pre><code>out = (df.sort_values(['c3','c1'],ascending=False) .reindex(df.index.get_level_values(0).unique(),level=0)) </code></pre> <hr> <pre><code> c3 c1 c2 A one 105 three 103 two 101 B two 1102 three 1050 one 101 </code></pre>
pandas|search|indexing|hierarchical
4
18,404
60,399,562
How to count choices in (3, 2000) ndarray faster?
<p>Is there a way to speed up the following two lines of code?</p> <pre><code>choice = np.argmax(cust_profit, axis=0) taken = np.array([np.sum(choice == i) for i in range(n_pr)]) </code></pre> <pre><code>%timeit np.argmax(cust_profit, axis=0) 37.6 µs ± 222 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) ...
<p>The first line seems pretty straightforward. Unless you can sort the data or something like that, you are stuck with the linear lookup in <code>np.argmax</code>. The second line can be sped up simply by using numpy instead of vanilla python to implement it:</p> <pre><code>v, counts = np.unique(choice, return_counts...
python|numpy
2
18,405
60,641,166
write lists as columns in a txt file
<p>I would like to write lists as columns in a txt file. I tried to do this like so:</p> <pre><code>lst_h_names=['name_1','namenamename','nam3','4'] lst_h_1_cont=[1,2,3000,4] lst_h_2_cont=[1,2000,3,4] lst_scaling_factor=[10,2,3,4] array_h_names=np.array(lst_h_names) array_h_1_cont=np.array(lst_h_1_cont) array_h_2_cont...
<p>You are trying to write an array with string dtype:</p> <pre><code>In [11]: norm_factors Out[11]: array([['name_1', '1', '1', '10'], ['namenamename', '2', '2000', '2'], ['nam3', '3000', '3', '3'], ['4', '4', '4', '4']], ...
python|numpy
1
18,406
72,749,651
append rows with if statement in for loop to a dataframe using python with very large files
<p>After updating anaconda-navigator, I am receiving this message on a code I wrote:</p> <p><strong>'The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.'</strong></p> <p>I'm conducting an artificial star experiment and using three files. I have included ...
<p>Here is a more vectorized way to do what you've described in your question:</p> <pre class="lang-py prettyprint-override"><code>start = time.time() distThreshold = 2000 def getIdxWithMinDist(row): dist = np.sqrt((row.x - biart.x)**2 + (row.y - biart.y)**2) idxMn = dist.idxmin() return biart.loc[idxMn].I...
python|pandas|dataframe|for-loop|if-statement
1
18,407
72,721,348
Error in backward(), pytorch, lstmcell. "Trying to backward through the graph a second time"
<p>Error, could you show me where is the problem for this error?</p> <p>pytorch is latest version. Tried to change inputs and initial hidden state into Variable(), but it dose not work.</p> <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx</p> <pre><code> *Trace...
<p>Detach the hidden/cell state before passing as input again.</p> <pre><code>outputs, hx, cx = net(inputs, hx.detach(), cx.detach()) </code></pre> <p>Also, Variable is <a href="https://pytorch.org/docs/stable/autograd.html#variable-deprecated" rel="nofollow noreferrer">deprecated</a>, in your case just remove the Var...
python|pytorch|lstm
0
18,408
72,737,645
How to aggregate all values in a pandas dataframe columns in 2 values
<p>I have a Pandas dataframe contains some columns. Each columns have some differents values. See the image.</p> <p><a href="https://i.stack.imgur.com/3WTty.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3WTty.png" alt="enter image description here" /></a></p> <p>In col1 I have that the value 1 is m...
<p>Try clip function on column:</p> <pre><code>df[&quot;col1&quot;].clip(upper=2) 0 1 1 2 2 2 3 2 4 1 5 2 6 2 7 1 8 1 9 1 10 1 11 2 12 1 </code></pre>
python|pandas|dataframe
3
18,409
59,903,808
Expected 2D array, got scalar array instead error
<p>I am working on python 3.7. I get the error when I execute the code below. How can I solve it?</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression data = pd.read_csv("hw_25000.csv") regression = LinearRegression() boy= data.Height.values.reshape(-1,1...
<p>You can't predict on an int, it must be an array</p> <pre><code>reg.predict(np.array(70).reshape(-1, 1)) array([[141.94045785]]) </code></pre>
python|sklearn-pandas
0
18,410
59,524,226
How to manipulate data in arrays using pandas
<p>Have data in dataframe and need to compare current value of one column and prior of value of another column. Current time is row 5 in this dataframe and here's the desired output:</p> <p>target data is streamed and captured into a DataFrame, then that array is multiplied by a constant to generate another column, ho...
<p>Let's try this, I think this will capture your intended logic:</p> <pre><code>df = pd.DataFrame({'col0':[1,2,3,4,5] ,'col1':[5,4.9,5.5,3.5,6.3] ,'col2':[2.5,2.45,2.75,1.75,3.15] }) df['col3'] = df['col2'].shift(-1).cummax().shift() print(df) </code></pre> <p>...
pandas|python-3.6
1
18,411
59,857,635
Numpy matrix power function and matrix multiplication
<p>What is the difference between the calculation in numpy.linalg.matrix_power and directly multiplying the matrix by itself those many times? This is what I observed and was confused about. </p> <pre><code>&gt;&gt; Matrix A: [[2 4 5], [4 4 5], [8 3 1]] &gt;&gt; numpy.linalg.matrix_power(A, 3) [[556 501 530] [676...
<pre><code>In [1]: from sklearn.preprocessing import normalize </code></pre> <p>Start with a numpy array:</p> <pre><code>In [2]: A = np.array([[2,4,5],[4,4,5],[8,3,1]]) </code></pre> <p>make a <code>np.matrix</code> from it:</p> <pre><code>In [3]: M = np.matrix(A)...
python|numpy|matrix
0
18,412
32,363,500
Apply string.format() to row in Pandas DataFrame
<p>I would like to represent a row in a pandas DataFrame with a formatted string referencing the columns. The best method I have found is to cast the row to a dict and then string.format()</p> <p>Assuming a <code>pd.DataFrame</code> <code>df</code> with the columns 'specimen' and 'date':</p> <pre><code>r = df.loc[0]...
<p>You can just use the row itself. It is a <code>Series</code> which supports dict-like access to the items:</p> <pre><code>&gt;&gt;&gt; d A B C 0 1 This One 1 2 is Two 2 3 crud Three &gt;&gt;&gt; "{A} then {B} and also {C}".format(**d.iloc[0]) '1 then This and also One' </code></pre>
python|pandas
7
18,413
32,334,966
Pandas Bad Lines Warning Capture
<p>Is there any way in Pandas to capture the warning produced by setting error_bad_lines = False and warn_bad_lines = True? For instance the following script:</p> <pre><code>import pandas as pd from StringIO import StringIO data = StringIO(&quot;&quot;&quot;a,b,c 1,2,3 4,5,6 ...
<p>I think it isn't implemented to pandas.<br> <a href="https://github.com/pydata/pandas/issues/2842" rel="noreferrer">source1</a>, <a href="https://github.com/pydata/pandas/issues/5686" rel="noreferrer">source2</a></p> <p>My solutions:</p> <p><strong>1. Pre or after processing</strong></p> <pre><code>import pandas ...
python-2.7|pandas
9
18,414
40,594,660
Add data to retrained Inception net
<p>I did few experiments with Google's Inception-v3 net from the tutorial (<a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html</a>)</p> <p>If I have a large enough data set, then it...
<p>There are <a href="https://www.tensorflow.org/programmers_guide/variables#saving_and_restoring" rel="nofollow noreferrer">checkpoints</a> in TensorFlow if you want to pause and resume. Another option is to train different categories on different layers. It's possible to use your outputs from image retraining as inpu...
machine-learning|tensorflow
0
18,415
40,390,474
Attributing multidimensional KDTree output in pandas
<p>I have created multidimensional arrays with KDTree from finding up to 100 B points within 5 cm of a set of A points.</p> <p>I'm left with up to 100 values for each row of my array. For example:</p> <pre><code>0 0.1 0.5 nan nan nan nan nan 1 0.4 0.2 0.1 2.0 6.0 0.2 0.2 2 0.3 nan 0.3 nan nan nan nan 3 0.2 0.5 0.6 5....
<p>This should work - you'll have to figure out how to handle column naming at the end. Not sure if you want to keep nan values, you'd have to replace them first, they get lost in the stacking.</p> <pre><code>import pandas as pd df = pd.DataFrame([[1,2,np.nan,'A'],[5,np.nan,np.nan,'B']], columns = ['col1','col2','col...
python|arrays|pandas|numpy
0
18,416
61,780,845
Sorting a dataframe by another
<p>I have an initial dataframe X:</p> <pre><code> x y z w 0 1 a b c 1 1 d e f 2 0 g h i 3 0 k l m 4 -1 n o p 5 -1 q r s 6 -1 t v à </code></pre> <p>with many columns and rows (this is a toy example). After applying some Machine Learning procedures, I get back a similar dataframe, but wit...
<p>If you can't trust just sorting the indexes (e.g. if the first <code>df</code>'s indexes are not sorted, or if you have something other than <code>RangeIndex</code>), just use <code>loc</code></p> <pre><code>df2.loc[df.index] </code></pre> <hr> <pre><code> x y z w 0 1 a b c 1 1 d e f 2 0 g h i 3 ...
python|pandas|dataframe|sorting
1
18,417
61,990,437
Problems with CSV output using Pandas for webscraping
<p>Early today with the help of an user i could get this nobbie webscraping project work. But the final CSV has all the information in just one column (Photo Attached). How can i put each class in one particular column with the respective row?</p> <p>Thanks guys in advance.</p> <p><a href="https://i.stack.imgur.com/Q...
<p>I'm getting the information in different columns only, there is no mistake in your code. The issue is in excel.</p> <p>Go to Data, then select the column, then In data tools, click on Text to Columns and click on delimited and use comma as delimiter</p>
python|pandas|selenium|csv|dataframe
2
18,418
61,667,967
How can I swap axis in a torch tensor?
<p>I have a torch tensor of size <code>torch.Size([1, 128, 56, 128])</code></p> <p>1 is channel, 128 is the width, and height. 56 are the stacks of images.</p> <p>How can I resize it to <code>torch.Size([1, 56, 128, 128])</code> ?</p>
<p>You could simply use <code>permute</code> or <code>transpose</code>.</p>
python|pytorch|permutation
3
18,419
61,642,339
Given a start date and number of months, work out end date P
<p>I'm trying to work out the end date and have succeeded but code takes long to run. How can I improve the following code? Also <code>df['end_date']</code> is a new variable? i tried: <code>df['end_date'] = []</code>, and appending it but getting a length error. I therefore wrote the below Many thanks, d </p>...
<p>Assuming 'end_date' is a datetime, something like this should work:</p> <pre><code>df['end_date'] = df['start_date'] + pd.to_timedelta(df['term']*365/12, unit='d') </code></pre> <p>However, the proper way of handling month offsets would be to use <code>pd.DateOffset</code>:</p> <pre><code># if the offset was the ...
python|pandas|datetime
2
18,420
57,912,126
How to merge label columns into a single tag based on column names?
<p>I'm working with a dataset that has a text comment and individual columns for each label that the comment could be categorized under. Each comment can have multiple labels assigned. From these label columns, I'd like to create a single column summarizing all applicable labels.</p> <p>For example, using movie genres...
<p>Here's my approach with <code>melt</code> and <code>groupby</code></p> <pre><code>s = sample_df.melt('Movie Title', var_name='genres') new_df = s[s['value'].eq(1)].groupby('Movie Title').genres.apply(list) sample_df.merge(new_df, on='Movie Title') </code></pre> <p>Output:</p> <pre><code> Movie Title action com...
python|pandas|scikit-learn
1
18,421
58,159,181
Weird error in converting a numpy array to a tensor due to tensor id
<p>I wrote a code to synthesize some face images and I have a custom layer which its task is to extract FaceNet embeddings so I can use these embeddings in addition to the images itself in my loss function but I get this error:</p> <pre><code>tensorflow.python.framework.errors_impl.InvalidArgumentError: transpose expe...
<p>As I mentioned, there must be something related to the id of tensor. So I edited my_func this way:</p> <pre><code>def my_func(x): y1 = x y2 = x x = x.numpy() y2 = tf.convert_to_tensor(x, dtype=tf.float32) + y2 - y1 return y2 </code></pre> <p>So, as we already set the id of y2 to the same of x s...
python|numpy|tensorflow|keras-layer
0
18,422
58,043,679
read_csv shifting columns and skipping wrong rows
<p>I'm using Pandas to <code>read_csv</code> to import a CSV file into a Jupyter notebook.</p> <p>You can find the <a href="https://drive.google.com/open?id=1Eobd9FBEp-aUshpuq4aEYKrfHR79fjL1" rel="nofollow noreferrer">CSV file at this link</a>. It has two empty rows before the header row. When I use:</p> <pre><code>...
<p>Your first version of code is OK. Two initial rows are empty and should be skipped.</p> <p>But note that one of column names in your input file (see <em>DATA</em> view - for some time your post contained it) contains <em>%2C</em>, which is a hex code for a <strong>comma</strong>.</p> <p>So apparently your heading ...
pandas|csv
1
18,423
58,001,493
Dask Grouby Performance for nunique is too slow. How to improve the performance?
<p>I have large files of size more than 5GB. I have stored them in parquet format. When I do groupby operation as shown below code for small sample set of 600k+ records, Dask is taking more than 6 mins, whereas pandas took only 0.4 seconds. Though I understand pandas is faster if the dataset fits in memory, my question...
<p>I believe that there is an open issue for an approximate groupby nunique algorithm for dask dataframe. You might look into that if you're particularly interested. Dask dataframe's non-groupby nunique algorithm is quite a bit faster.</p>
pandas|dask
0
18,424
58,125,364
Is there a way to join two lists with the corresponding information from an xarray data variable?
<p>I have two lists, list1 and list2.</p> <pre><code>list1 = [wind_speed_0, wind_speed_1, wind_direction_0, wind_direction_1] list2 = [serial_num_0, serial_num_1] </code></pre> <p>The items in these lists are actually the names of data variables that belong to an xarray dataset.</p> <p>Essentially, if the...
<p>I would suggest using the matching sequence as an index for a reference dictionary which stores each value under a key (column):</p> <pre><code>import pandas as pd import re # build the regular expression pattern = re.compile('_([0-9]+)') # build a lambda to use in for loop f = lambda x: int(pattern.findall(x)[0]...
python|pandas|numpy|python-xarray
0
18,425
58,121,772
How can I seperate my dataframe according to a column values and export it to excel file?
<p>I want to separate my df according to client_id column. Then, I want to export each of them in different excel files. For example, I'd like to have an Excel file which only includes clients with id number 100. Also, the same for 200, 300 etc. How can I do that?</p> <pre><code> id employee_id company_name clie...
<p>You can take advantage of groupby.</p> <pre><code>group = df.groupby('client_id') for key, df in group: df.to_excel(f'{key}.xlsx') </code></pre>
python|pandas
4
18,426
57,777,578
pandas drop_duplicates() "keep" parameter gives very different answers - how does it work?
<p>I have a CSV dataset of olympic athletes participated in games.</p> <p>the features are: id,Name,Sex,Age,Games,Year,Sport</p> <p>I need to find:</p> <blockquote> <p>What was the percentage of male basketball players among all the male participants of the 2012 Olympics? Round the answer to the first decimal.</p> </bl...
<p>keep defines which duplicate value you want to keep.</p> <p>1) First specifies to keep the first duplicate value and drop the rest.</p> <p>2) Last specifies to keep the last duplicate value and drop the rest.</p> <p>3) False specifies to drop all duplicates.</p> <p>Consider the example:</p> <pre><code>df = pd.D...
python|pandas
2
18,427
58,039,192
Reversing the view of a numpy array twice in a jitted function makes the function run faster
<p>So I was testing the speeds of two versions of the same function; one with reversing the view of a numpy array twice and one without. The code is as follows:</p> <pre><code>import numpy as np from numba import njit @njit def min_getter(arr): if len(arr) &gt; 1: result = np.empty(len(arr), dtype = arr....
<p>TL;DR: It's probably just a lucky coincidence that the second code was faster.</p> <hr> <p>Inspecting the generated types reveals there's one important difference:</p> <ul> <li>In the first example your <code>arr</code> is typed as <code>array(int32, 1d, C)</code> a C-contiguous array.</li> </ul> <pre class="lan...
python|performance|numpy|numpy-ndarray|numba
2
18,428
57,909,773
Dropping any row with identical cell values across columns
<p>I couldn't find anything addressing this issue; <a href="https://stackoverflow.com/questions/51182228/python-delete-duplicates-in-a-dataframe-based-on-two-columns-combinations">this is the closest I guess, but I can't figure out how to implement the ideas here.</a></p> <p>Somehow I found myself looking at a datafra...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html" rel="nofollow noreferrer"><code>df.nunique()</code></a> along <code>axis=1</code> and check for rows which has more than 1 unique value for all columns.:</p> <p>Per docs: <code>nunique()</code></p> <block...
python|pandas
3
18,429
34,028,511
skipping unknown number of lines to read the header python pandas
<p>i have an excel data that i read in with python pandas:</p> <pre><code>import pandas as pd data = pd.read_csv('..../file.txt', sep='\t' ) </code></pre> <p>the mock data looks like this:</p> <pre><code>unwantedjunkline1 unwantedjunkline2 unwantedjunkline3 ID ColumnA ColumnB ColumnC 1 A ...
<p>If you know what the header startswith:</p> <pre><code>def skip_to(fle, line,**kwargs): if os.stat(fle).st_size == 0: raise ValueError("File is empty") with open(fle) as f: pos = 0 cur_line = f.readline() while not cur_line.startswith(line): pos = f.tell() ...
python|pandas
12
18,430
37,015,551
Updating a numpy array using multiprocessing module
<p>I have a simple Jaccard like similarity calculation on a list of n-gram sets as shown below. This code executes fine using a relatively smaller list, yet memory usage starts becoming a concern when the list size get larger, say 10k or more. Instead of appending results in a list, if I can populate a Numpy zero-alloc...
<p>Here is a self-solution, which is not the most efficient one, yet does the job done. I used ideas from a few related SO questions. The key here is <strong>imap</strong> which lowers the memory consumption and also running the code on Linux.</p> <pre><code>if __name__ == '__main__': m = len(lines) dma = np.z...
python|numpy|multiprocessing
0
18,431
37,010,212
What is the fastest way to upload a big csv file in notebook to work with python pandas?
<p>I'm trying to upload a csv file, which is 250MB. Basically 4 million rows and 6 columns of time series data (1min). The usual procedure is:</p> <pre><code>location = r'C:\Users\Name\Folder_1\Folder_2\file.csv' df = pd.read_csv(location) </code></pre> <p>This procedure takes about 20 minutes !!!. Very preliminary I...
<p>Here are results of my read and write comparison for the DF (shape: 4000000 x 6, size in memory 183.1 MB, size of uncompressed CSV - 492 MB).</p> <p>Comparison for the following storage formats: (<code>CSV</code>, <code>CSV.gzip</code>, <code>Pickle</code>, <code>HDF5</code> [various compression]):</p> <pre><code>...
python|csv|pandas|dataframe
74
18,432
54,814,812
how to convert an array of dimension three to five in keras
<p>I have an array of shape <code>(?, ?, 128)</code> and I want to convert it to <code>(?, ?, 128,1,1)</code>.</p> <p>I tried to search it but I did not find any good thing or maybe I did not use correct words for finding what I am looking for. is there any efficient way I can do that?</p> <p><a href="https://stackov...
<p>With Numpy, you can do <code>reshape</code></p> <pre><code>a = np.random.rand(2, 3, 128) b = a.reshape(a.shape + (1, 1)) </code></pre> <p>With <a href="https://keras.io/backend/#expand_dims" rel="nofollow noreferrer">Keras</a>, you can do <code>keras.backend.expand_dims(x, axis=-1)</code> to add a 1-sized dimensio...
python|numpy|machine-learning|keras|reshape
1
18,433
54,697,281
How to do a heatMap on python
<p>The first time I'll do a heatMap in python 3 using Pandas and Matplotlib. I tried to use the plugin gmaps in jupyter notebook. I uploaded a csv file that conatin 2 columns (long,lat).</p> <pre><code>import gmaps import gmaps.datasets gmaps.configure(api_key=os.environ["GOOGLE_API_KEY") locations = gmaps.datasets.lo...
<p>There are points to correct in your code. I will provide a list of what I had to do in order to put this to work in my environment (jupyter notebook).</p> <p>1) Make sure to have the gmaps installed in your environment. You can achieve this by using something like:</p> <pre><code>pip install gmaps </code></pre> <...
python|python-3.x|pandas
1
18,434
49,668,252
Returning strings in tf.data.Dataset map method
<p>In Tensorflow 1.4.1 the map method in tf.data.Dataset could return strings so I could return something like this my map function:</p> <pre><code>return filename, image, one_hot_label </code></pre> <p>where <code>filename</code> is string. This doesn't work anymore in TF1.5+:</p> <pre><code> dataset = dataset.m...
<p>As discussed in the comments, this seems to be a bug in TF 1.5 up to at least 1.6, likely also 1.7. I have opened a Github issue on this at <a href="https://github.com/tensorflow/tensorflow/issues/18355" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/18355</a></p> <p>Until the issue is ad...
python|tensorflow|tensorflow-datasets
1
18,435
28,257,167
Pandas join: Does not recognize joining column
<p>I have no idea what's happening, the title is just a first-order approximation. I'm trying to join two data frames:</p> <pre><code>&gt;&gt;&gt; df_sum.head() TUCASEID t070101 t070102 t070103 t070104 t070105 t070199 \ 0 20030100013280 0 0 0 0 0 0 1 20030...
<p><code>df.join</code> generally calls <code>pd.merge</code> (except in a special case when it calls <code>concat</code>). Therefore, anything <code>join</code> can do, <code>merge</code> can do also. Although perhaps not strictly correct, I tend to use <code>df.join</code> only when joining on the index and use <cod...
python|join|pandas|inner-join
2
18,436
73,492,747
Replace missing value in a row if there's a match in two columns from another row using Pandas
<p>I'm working on a data analysis project and I have the following dataframe that looks like this.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">id</th> <th style="text-align: center;">store</th> <th style="text-align: center;">long</th> <th style="text-align: ...
<p>You can use:</p> <pre><code>df['store'] = df.groupby(['long', 'lat'], sort=False).bfill()['store'] </code></pre> <p>Output:</p> <pre><code> id store long lat 0 1 A 1 -4 1 2 D 2 3 2 3 C 4 5 3 4 D 2 3 </code></pre>
python|pandas|dataframe|data-analysis
0
18,437
35,049,628
In Python Pandas using cumsum with groupby
<p>I am trying to do a pandas cumsum(), where want to initialize the value to 0 every time group changes. Say I have below dataframe where after group by I have col2(Group) and expect col3(cumsum) while using the function</p> <pre><code>Value Group Cumsum a 1 0 a 1 1 a 1 2 b 2 0 b 2 1 b 2 ...
<p>Hmm, this turned out more complicated than I imagined, due to getting the groups' keys back in. Perhaps someone else will find something shorter.</p> <p>First, imports</p> <pre><code>import pandas as pd import itertools </code></pre> <p>Now a DataFrame:</p> <pre><code>df = pd.DataFrame({ 'a': ['a', 'b', 'a',...
pandas
0
18,438
67,323,296
Python: scipy.sparse / pandas Null values in sparse matrix is being converted to large negative integer
<p>I am trying to work with scipy sparse COO matrix but I am running into weird errors with null values being converted to large negative integers. Here is what I am doing:</p> <pre><code>import pickle5 as pk5 from scipy import sparse import pandas as pd with open('some_file.pickle', 'rb') as f: df = pk5.load(f) <...
<p>Thanks to @hpaulj for the hint! The problem was that my dtype was an int. So recasting it to float solves the issue. Example:</p> <p><code>df.iloc[0:5, 0:4].astype(float).T</code></p> <pre><code> 0 1 2 3 4 1028799.3_nuc_coding 1.0 NaN NaN NaN NaN 1156994.3_nuc_coding NaN 1.0 Na...
python|pandas|scipy|null|integer-overflow
0
18,439
67,262,296
How to append value_counts() values to new column in pandas
<p>How to count repeated values in a column(df1) and add it to a new dataframe(df2) with two modified columns. I tried with drop_duplicates(), value_counts() and assigned to new dataframe but value_counts() showing NaN values . How to convert dataframe from df1 to df2. Thank You.</p> <pre><code>df1: A 0 Del...
<p>You can <code>.reset_index()</code> after <code>.value_counts()</code>:</p> <pre><code>print(df.value_counts().reset_index().rename(columns={0: &quot;B&quot;})) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> A B 0 Dell 2 1 Lenovo 2 2 Acer 1 3 Apple 1 </code></pre...
python-3.x|pandas|dataframe
1
18,440
67,583,661
extracting existing dataframe to dataframe array
<p>I have an original dataframe read as df. I want to separate the df to several parts and each one saved to a individual csv.<br /> my code:</p> <pre><code>df = pd.read_csv('text.csv') for i in range(1, 10): df[i] = df.iloc[257*(i-1):256+257*(i-1), : ].copy() df[i].to_csv('%d.csv' % i, index=None, hea...
<pre><code>df = pd.read_csv('text.csv') for i in range(1, 10): df.iloc[257*(i-1):256+257*(i-1), : ].to_csv(f'{i}.csv', index=None, header = False) </code></pre> <p>This should work. No need to copy the splitted dataframe to a separate variable.</p>
python|pandas|dataframe|csv
2
18,441
67,243,652
Loop by Quantity from two dataframe
<p>I have two dataframes, one shows buys and the other shows sell. I need to pull sale date for each buy lot. Sometimes, the buy is sold in different sale lots, I need to be able to split shares for that(or if not possible, no need to split shares, just pull the selldate). This is what I have:</p> <pre><code>df1 = pd.D...
<p>This solution is a little messy, but what you're asking is a little complicated, so here comes a working prototype:</p> <pre><code># Sort values by date. df1 = df1.sort_values(by='Buydate').reset_index() # id_jumps will be used for ignoring items you already subtracted from. id_jump = {} for id_ in df1['ID']: ...
python|pandas|dataframe
1
18,442
67,573,652
How to remove columns based on user input in python (pandas)?
<p>How to write code so that the dataframe remove column based on user input of the column name?</p> <pre><code>amend_col= input(&quot; would u like to 'remove' any column?:&quot;) if amend_col == &quot;yes&quot;: s_col= input(&quot;Select the column you want to add or remove:&quot;) if s_col in df.columns: ...
<p>You can amend your codes as follows:</p> <pre><code>amend_col= input(&quot; would u like to 'remove' any column?:&quot;) if amend_col == &quot;yes&quot;: s_col= input(&quot;Select the column you want to add or remove:&quot;) if s_col in df.columns and amend_col ==&quot;yes&quot;: print(&quot;Column is fo...
python|pandas|dataframe|data-science|drop
2
18,443
67,267,374
Is there a way to stop scikit learn from truncating my (large) output data in a document term matrix?
<p>I am trying to build and store a document term matrix (DTM) from a large corpus of text data. Everything seems to be working except that when I store the to .tsv it takes only saves the first and last 24 entries like this:</p> <p>(0, 256) 2</p> <p>(0, 272) 1</p> <p>(0, 286) 1</p> <p>: :</p> <p>(0, 12351) 4</p...
<p>I ended up working around this problem by saving the Compressed Sparse Matrix as a pickle byte string file, as suggested by bindu madhavi.</p> <p>All my data is preserved this way.</p>
python|pandas|scikit-learn|nlp|sparse-matrix
0
18,444
67,406,377
How to map values from another column in python
<p>Having 2 columns , I want to map values from <strong>column3 to column1</strong> if there is no value in column1, if column3 is also blank then no value will be mapped.</p> <p><strong>Input Data</strong></p> <pre><code>column1 column2 column3 2225 India 2227 UK 35604 32578 ...
<p>You can also try <code>np.where</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame({'column1': {0: 2225, 1: np.nan, 2: 32578, 3: np.nan, 4: 7528, 5: np.nan}, 'column2': {0: 'India', 1: 'UK', 2: 'USA', 3: 'Dubai', 4: 'Bhutan', 5: 'In...
python|pandas
1
18,445
34,669,622
Algorithm to parse file where redundant index values are selected by maximum and minimum values
<p>I am trying to write a Python program which reads in a file in the following format:</p> <pre> ID chrom txStart txEnd score strand ENSMUSG00000042429 chr1 1 100 0 - ENSMUSG00000042429 chr1 110 500 0 - ENSMUSG00000042500 chr2 12 40 0 - ENSMUSG00000042500 chr2 200 10000 0 - ENSMUS...
<p>Your idea to use a dictionary, with the record IDs as the keys, seems to be a good one. Here's a general outline.</p> <pre><code>records = {} # Open file and deal with the header line. with open(...) as fh: header = next(fh) # Process the input data. for line in fh: # Parse the line and get t...
python|algorithm|parsing|pandas
3
18,446
34,590,037
Updating excel spreadsheet with python
<p>I'm keeping track of a rather large inventory database of various instruments. I need a good way to update said inventory system. The system is made up of many spreadsheets, one for each instrument, essentially. The main methods of organization I've been using is the instrument and the part number. As of right now, ...
<p>Idea for your first question -- this acts likes a sql <code>select</code> statement:</p> <pre><code>nozeros_finaldata = finaldata[finaldata['ColumnName'] != 0] </code></pre> <p>replace <code>'ColumnName'</code> with the name of your column that went from four to zero; it will return a new dataframe. Then use <cod...
python|excel|pandas
0
18,447
60,226,753
Apply filtering on dataframe based on the input from other sheet
<p>I am trying to filter main dataset(Pandas Dataframe) by applying filters (inputs from the another spreadsheet).</p> <p><strong>Main data set:</strong></p> <pre><code>+---------+--------+-----+-----------+-------------+-------+-------------+-------------+----------+ | Cust Id | gender | Age | Indicator | X Indicato...
<p>I came up with a solution but you'll have to alter the input spreadsheet slightly. It should look like the table below:</p> <pre><code> Label Operator Condition Value 0 gender == F 1 gender | == M 2 Age &amp; &gt;= 75 3 Age...
python|pandas|dataframe|filtering
0
18,448
60,104,990
combine row values in all consecutive rows that contains NaN and int values using pandas
<p>I need your help: I want to merge consecutive rows like this:</p> <p><strong>Input:</strong></p> <pre><code>Time ColA ColB Time_for_test[sec] 2020-01-19 08:51:56.461 NaN B NaN 2020-01-19 08:52:15.405 NaN NaN 18.95 2020-01-19 08:52:40.923 A NaN NaN 2020-01-19 0...
<p><code>stack</code> and <code>unstack</code> are your friends. Assuming your dataframe index is unique:</p> <pre><code>df[['ColA', 'ColB']].stack() \ .reset_index(level=1) \ .reindex(df.index) \ .ffill() \ .set_index('level_1', append=True) \ .unstack() \ .droplevel(0, axis=1) </code></pre> ...
python-3.x|pandas|dataframe
0
18,449
59,974,209
Reading unstructured dictionaries in pandas dataframe
<p>I am trying to create a pandas dataframe from a collection of dictionaries that I read from a json file. The dictionaries are as follows - </p> <pre><code>d1 = {"DisplayName": "Test_drive", "permissions": {"read": True, "read_acp": True, "write": True, "write_acp": True}} d2= {"DisplayName": "Log delivery","URI": "...
<p>Create dataframe by appending and then reshape to the structure you need using pivot</p> <pre><code>df = pd.DataFrame.from_dict(d1).append(pd.DataFrame.from_dict(d2)) df.reset_index().pivot(index='DisplayName', columns='index', values='permissions') </code></pre> <p>To include URI</p> <pre><code>&gt;&gt;&gt; df.r...
python|pandas|dataframe|dictionary
2
18,450
60,127,656
Replace numpy arrays of arrays with values
<p>I am trying to convert a numpy array of arrays. An example input is this:</p> <pre class="lang-py prettyprint-override"><code>np.array([[[0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0]]], np.uint8) </code></pre> <p>I want to replace all arrays with values <code>[0, 0, 0]</code> with <code>0</code> and the...
<pre><code>X_new = np.mean(X, axis=2) X_new array([[ 0., 255.], [255., 0.]]) </code></pre>
numpy|replace
2
18,451
59,976,705
AttributeError: module 'tensorflow.compat' has no attribute 'v1' Tensorflow v: 1.10.0
<p>I got that error when I'm trying to train my model:</p> <pre><code>(tensorflow1) C:\tensorflow1\models\research\object_detection&gt;python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config Traceback (most recent call last): File "train.py", line 52, ...
<p>Providing the solution here (Answer Section), even though it is present in the Comment Section for the benefit of the community.</p> <p>This code <code>tf.compat.v1.GraphKeys.UPDATE_OPS</code> is not available on <code>Tensorflow==1.10.0</code></p> <p>If you are using an older version of TensorFlow, <a href="https...
python|tensorflow|object-detection
1
18,452
65,245,549
How to plot labels for some cites on the map? using cartopy
<p>I have an excel file with the information of some cites, now I want to plot those cites with their name on the map. I wrote the following codes, however, I can't get the name of the cites properly. For each cite I get a label with the whole list of 'name'.Any suggestion is welcome. <a href="https://i.stack.imgur.com...
<p>From your for-loop, I'm 99% certain you should be using <code>ne</code> in place of <code>name</code>:</p> <pre><code>zip_object = zip(lon, lat, name) for (lg, lt, ne) in zip_object: ax.text(lg - .05, lt + .05, ne, va='center', ha='right', transform=ccrs.Geodetic(), fontwei...
python|excel|pandas|dictionary|cartopy
2
18,453
64,048,850
Dataframe replace() not replacing '-'s with with assigned value
<p>I have a dataset that has been formatted to be entirely objects regardless of the content of the individual columns. I want to use this dataset for some basic linear regression modelling so need to get the dataset into a workable input. Most of the columns in the dataset are numeric and where they are missing a valu...
<p>Your apply function is doing something but you are not storing it as a new dataframe, so it doesn't get returned back to you.</p> <p>If you want to fill na rows with the mean you can do this:</p> <pre><code>df = pd.DataFrame({'Name': ['Mick', 'Alice', 'Bob', 'Mary'], 'Age': [17, 27, 37, np.nan]}) ...
python|pandas|replace|missing-data
0
18,454
63,841,890
How to do np.dot in specific axis
<p>If I have two arrays <code>a #25x25x3x5</code> and <code>b #25x25x5x3</code>, how can I get dot product of <code>a</code> and <code>b</code> with the output <code>25x25x3x3</code>?</p>
<p>What you want is not the dot product but matrix multiplication. For two matrices with shapes (A,B) and (B,C) it is defines as:</p> <p>(A,B) * (B,C) = (A,C)</p> <p>This corresponds to your last two dimensions and the desired output (3,5)*(5,3)=(3,3).</p> <p>You can use <a href="https://numpy.org/doc/stable/reference/...
numpy
1
18,455
63,832,352
How to serialize empty pandas dataframe into list of dictionaries
<p>I have a dataframe output and I would like to be able to serialize it as a list of dictionaries and convert the date timestamps to string. I know i can do <code>to_json(orient='records', data_format='iso) </code> but it is getting converted to a string and <code>json.loads(to_json_df)</code> throws</p> <pre><code> F...
<p>It was a no brainer</p> <pre><code> import json columns = ['project_number', 'people_manager', 'quality_manager', 'inserted_at'] projects = get_projects_info(project_ids) # returns pd.DataFrame(columns=columns) serialized_projects = projects.to_json(orient='records', date_format='iso') serialized_projects = json.loa...
python|json|pandas|serialization
0
18,456
46,657,349
Cannot Find the Correct Working Directory in Python Spyder
<p>I'm having trouble with the working directory in Spyder console. I'm trying to convert an xlsx file into a pandas array, but I keep getting the same error. I've changed the <code>Run</code> Directory in preferences and it should be the correct one. </p> <p><a href="https://imgur.com/qhR2mcH" rel="nofollow noreferre...
<p>The path at the top right of the screen in Spyder will change the working directory of the IPython console. Set it to the desired working directory. Hit Ctrl+F6 to check the run configuration of your script and make sure it is set to run at the current work directory. See if that fixes the problem.</p> <p>As others...
python-3.x|pandas|numpy|spyder
6
18,457
46,751,581
list of lists to pandas dataframe
<p>I'm trying to parse a list of nested lists to a pandas dataframe.</p> <p>This is a sample of the list:</p> <pre><code>&gt;&gt;&gt;result[1] { "account_currency": "BRL", "account_id": "1600343406676896", "account_name": "aaa", "buying_type": "AUCTION", "campaign_id": "aaa", "campaign_name": ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a>, something like this:</p> <pre><code>pd.io.json.json_normalize(df.unique_actions) </code></pre>
python|pandas
1
18,458
32,621,677
pandas rename column if contains string
<p>I would like to go through all the columns in a dataframe and rename (or map) columns if they contain certain strings.</p> <p>For example: rename all columns that contain 'agriculture' with the string 'agri'</p> <p>I'm thinking about using <code>rename</code> and <code>str.contains</code> but can't figure out how ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.15.2/generated/pandas.core.strings.StringMethods.replace.html" rel="noreferrer"><code>str.replace</code></a> to process the columns first, and then re-assign the new columns back to the DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFram...
python-2.7|pandas
8
18,459
32,747,772
How to do join of multiindex dataframe with a single index dataframe?
<p>The single index of df1 matches with a sublevel of multiindex of df2. Both have the same columns. I want to copy all rows and columns of df1 to df2.</p> <p>It is similar to this thread: <a href="https://stackoverflow.com/questions/17451843/copying-a-single-index-dataframe-into-a-multiindex-dataframe">copying a sing...
<p>This feels a little too manual, but in practice I might do something like this:</p> <pre><code>In [46]: mult[:] = sngl.loc[mult.index.get_level_values(2)].values In [47]: mult Out[47]: one two three four 10 1 a 1.175042 0.044014 1.341404 -0.223872 b 0.216168 -0.748194 -0.54600...
python|pandas
1
18,460
32,873,263
return indices from filtered, sorted array with numpy
<p>What is the most straightforward way to do the following in python/numpy?</p> <ul> <li>begin with random array <code>x</code></li> <li>filter out elements <code>x &lt; .5</code></li> <li>sort the remaining values by size</li> <li>return indices of (original) <code>x</code> corresponding to these values</li> </ul>
<p>Finding the mask of <code>x &lt; 0.5</code> and <code>x.argsort()</code> seemed like compulsory here. Once you have those two, you can sort the mask array using the sort indices and use this mask on the sort indices to get back the indices corresponding to sorted indices that satisfy the masked condition. Thus, you ...
python|arrays|sorting|numpy|indexing
10
18,461
38,706,196
Pandas Dataframe - Lookup Error
<p>I am attempting to lookup a row in a pandas (version 0.14.1) dataframe using a date and stock ticker combination and am receiving a strange error.</p> <p>My pandas dataframe that looks like this:</p> <pre><code> AAPL IBM GOOG XOM Date 2011-01-10 16:00:00 340.99 143.41 614...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow"><code>df.lookup</code></a> expects 2 array-likes (instead of scalars) as arguments:</p> <pre><code>In [25]: df.lookup(row_labels=[DT.datetime(2011,1,10,16,0)], col_labels=['AAPL']) Out[25]: array([ 340.99]) <...
python|pandas
4
18,462
38,876,816
Change Value of a Dataframe Column Based on a Filter
<p>I have a Dataframe that consists of 2 columns: </p> <ol> <li>"Time Spent on website"</li> <li>"Dollars spent on the website"</li> </ol> <p>I want to perform some classification analysis on this dataset and I only care whether a user made a purchase or not. So I want to run through the "Dollars spent on the websit...
<pre><code>df['purchase'] = 0 df.loc[df['dollars_spent'] &gt; 0, 'purchase'] = 1 </code></pre> <p>or</p> <pre><code>df['purchase'] = df['dollars_spent'].apply(lambda x: 1 if x &gt; 0 else 0) </code></pre>
python|pandas|dataframe
72
18,463
38,728,366
Pandas cannot load data, csv encoding mystery
<p>I am trying to load a dataset into pandas and cannot get seem to get past step 1. I am new so please forgive if this is obvious, I have searched previous topics and not found an answer. The data is mostly in Chinese characters, which may be the issue.</p> <p>The .csv is very large, and can be found here: <a href="h...
<p>It seems that there's something very wrong with the input file. There are encoding errors throughout.</p> <p>One thing you <em>could</em> do, is to read the CSV file as a binary, decode the binary string and replace the erroneous characters.</p> <p>Example (<a href="https://stackoverflow.com/a/20014805/3165737">so...
python|pandas|chardet
3
18,464
38,556,573
Shortest Path between two matrices
<p>I have two distance matrices with overlapping variable names.</p> <p>dfA:</p> <pre><code> Start A1 A2 A3 A4 … A150 Location A 12 4 12 2 9 B 5 2 19 4 3 C 1 4 8 7 12 </code></pre> <p>dfB:</p> <pre><code> A B C ...
<p>I added <code>D</code> so that the axis lengths will be different (<code>dfB</code> won't be square matrix) just for my convenience (it works with square matrices too).</p> <pre><code>import pandas as pd import numpy as np df_a = pd.read_csv('dfA.csv', delim_whitespace=True, index_col=0, decimal=",") df_b = pd.read...
python-2.7|numpy|pandas|matrix|networkx
0
18,465
63,127,701
Botocore error: HTTP Client raised an unhandled exception: sys.meta_path must be a list of import hooks
<p>I am running this small snippet to upload a panda dataframe to s3 using parquet. But I get the error:</p> <p><code>Exception botocore.exceptions.HTTPClientError: HTTPClientError(u'An HTTP Client raised an unhandled exception: sys.meta_path must be a list of import hooks',) in &lt;bound method S3File.__del__ of &lt;...
<p>Was using the wrong ( or probably low level ) function</p> <p>Instead of pq.write_table(table, s3file) Do pq.write_to_dataset(table=table, root_path=bucket_uri, filesystem=fs )</p> <p><a href="https://www.jitsejan.com/interacting-with-parquet-on-s3.html" rel="nofollow noreferrer">https://www.jitsejan.com/interacting...
python|pandas|amazon-s3|parquet|pyarrow
1
18,466
63,058,144
How to assign random values from list to new column that doesn't exist in another column of the same row?
<p>I have a data set about 50k~ rows that has a certain Job ID and the User ID of the person that performed the job. It is represented by this sample I've created:</p> <pre><code>df = pd.DataFrame(data={ 'job_id': ['00001', '00002', '00003', '00004', '00005', '00006', '00007', '00008', '00009', '00010', '00011', '0...
<p>The simplest way I can think of is to keep changing the reviewer until no one reviews their own works:</p> <pre><code>users = df['user_id'].unique() df['reviewer_id'] = df['user_id'] self_review = lambda: df['reviewer_id'] == df['user_id'] while self_review().any(): reviewers = np.random.choice(users, len(df)) ...
python|pandas|random
1
18,467
67,724,673
How to plot seaborn with pandas multi index
<p>I am trying to efficiently plot the number of orders in a seaborn line plot. Here the x-axis should be the date, the y-axis the number_of_orders and there should be a total of 12 lines that correspond to each individual group.</p> <p>The data I'm working with looks like this. It is a multi index pandas dataframe, wh...
<p>try something like this:</p> <pre><code>sns.lineplot(data=yourDF, x=&quot;Date&quot;, y=&quot;number of orders&quot;, hue=&quot;Group&quot;) </code></pre>
pandas|seaborn
1
18,468
67,805,950
How to change the for loop in the code to give me an additional column in my dataframe?
<p>I have two dataframes. df1['column'] has 70k unique text values. df2['column'] has 20 unique text values.</p> <p>I want to find the closest synonym for all the 70k values by looking at the 20 values in df2['column']. and want an additional column in df1, which has the best synonym for that word.</p> <p>I found a cod...
<p>Assuming we are adding a column called &quot;Match&quot; to <code>df_test</code>:</p> <pre><code>matches = dict() #dictionary to save the mappings top_k=1 #because we only want the top match for query in queries: query_embedding = embedder.encode(query, convert_to_tensor=True) cos_scores = util.pytorch_cos_s...
python|python-3.x|pandas|dataframe
0
18,469
41,339,823
Initialization of RMSPropOptimizer
<p>In TensorFlow (Python), when adding to the graph a <code>tf.train.RMSPropOptimizer</code>, are any additional variables added that need initialization? If yes, how can I get access to them and initialize them manually? (I'd rather not use <code>tf.global_variables_initializer</code>). In other words: (1) How can I d...
<blockquote> <p>In TensorFlow (Python), when adding to the graph a tf.train.RMSPropOptimizer, are any additional variables added that need initialization? </p> </blockquote> <p>Yes.</p> <blockquote> <p>If yes, how can I get access to them and initialize them manually? (I'd rather not use tf.global_variables_initi...
tensorflow
0
18,470
41,276,407
get data from xml using pandas
<p>I'm trying to get some data from xml using pandas. Currently I have "working" code, and by working i mean it almost work.</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url = "http://degra.wi.pb.edu.pl/rozklady/webservices.php?" response = requests.get(url).content soup = Beauti...
<p>You can add <code>ignore_index=True</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>append</code></a> for avoid duplicated <code>index</code> and then need select column <code>sem</code> by <code>[]</code>, because function <a hre...
python|pandas|web|service
1
18,471
41,481,482
How can I delete rows/items of pandas series with indices' labels not in a list?
<p>I have a list of labels. </p> <p>I also have a pandas series that has multiple rows/items, some of which have their index labels in that list and some others have index labels not in that list. </p> <p>I want to delete the rows/items of that series that have labels not in that list. </p> <p>The only way I could c...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>Index.intersection</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.loc.html" rel="nofollow noreferrer"><code>loc</code></a>:</p> <pr...
python|python-2.7|python-3.x|pandas|series
3
18,472
41,527,069
Fast row removal and addition in pandas.DataFrame without reallocation
<p>I'm using <code>pandas.DataFrame</code> to store 3 hours of sensor data sampled at the second interval. So each second, I'm adding a row and dropping rows older than 3 hours.</p> <p>Currently, I'm doing it very inefficiently:</p> <pre><code>record = pd.DataFrame.from_records([record], index='Date') if self.data.em...
<h1>work in progress</h1> <p>See comments below. I'll leave answer as it is until I can work something out. I don't want anyone to think that this solves the problem. </p> <hr> <p>Consider the dataframe <code>df</code> with timeseries index <code>tidx</code>. <code>tidx</code> starts off with 70 days worth of dates...
python|pandas|optimization|memory-efficient
0
18,473
41,488,930
Date Range using frequency and periods
<p>I built a routine that creates me a list of dates using different frequencies and also periods, the only thing I cannot get working is using the periods while using 'M' for end of the month entries.</p> <pre><code>def run_date_creator(start_date, end_date, steps, interval): #Interval: Days(d or D), Weeks (w or ...
<p>You can specify steps in <code>freq</code>.</p> <pre><code>dates = pd.date_range(start_date, end_date, freq='%dM' % steps) </code></pre>
python|datetime|pandas|date-range
1
18,474
61,283,630
How to use tensorflow model for predicting my own images
<p>I've just started with tensorflow. I wrote a program that uses Fashion_MNIST dataset to train the model. And then predicts the labels using 'test_images'and it's working good so far. But what I am curious how can I use my own image of a shoe or shirt for prediction. Because all the test images are of shape 28*28. H...
<p>The task you are engaged in is the task of data preparation and preprocessing. Among the things you must do already having a directory with images is the tagging of the images, for this task I recommend <a href="https://github.com/tzutalin/labelImg" rel="nofollow noreferrer">labelImg</a>. If you also need the dimens...
python|tensorflow|tensorflow-datasets
1
18,475
61,283,382
Pandas Profiling error within google colab
<p>I'm trying to use <code>Pandas_Profiling.ProfilingReport</code> within my Google Colab notebook. This is my code:</p> <pre><code> import pandas_profiling profile = pandas_profiling.ProfileReport(df) </code></pre> <p>and get that error:</p> <pre><code>" concat() got an unexpected keyword argument 'join_axes' " </...
<p>Unfortunately <code>join_axes</code> function is deprecated in pandas version installed in google colab. If you downgrade pandas library version you can use Pandas Profiling. Just use in your colab:</p> <pre class="lang-py prettyprint-override"><code>! pip install pandas==0.25 </code></pre> <p>Then restart the kerne...
python|pandas|google-colaboratory|data-analysis
3
18,476
61,192,242
Distance between points in two data frames
<p>I'm new to python and I tried searching but could not find a solution. </p> <p>I have two dataframes with Cartesian coordinates.</p> <pre><code>node x y value abc 645 714 8 def 187 754 11 location x y value ijk 621 744 1 lmn 202 720 -5 </code></pre> <p>I wan...
<p>Here's a way to do it from scratch:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df1 = pd.DataFrame({'node': ['abc', 'def'], 'x': [645, 187], 'y': [714, 754], 'value': [8, 11]}) df2 = pd.DataFrame({'locati...
python|pandas|geographic-distance
0
18,477
61,224,570
Splitting up an array in python into sub arrays
<p>I have an array which is 1 -> 160. I want to split this into 10 arrays that are split every sixteen numbers. This is what I have so far:</p> <pre><code>amplitude=[] for i in range (0,160): amplitude.append(i+1) print(amplitude) #split arrays up into a line for each sample traceno=10 #number ...
<p>You are nesting the loops. So you consistently fill the new array with the same number from the first one, and end with the last one <code>160</code> repeated everywhere.</p> <p>You only need to copy the list into a 1D numpy array, and then reshape it:</p> <pre><code>amplitude_split=np.array(amplitude, dtype=np.in...
python|numpy|numpy-ndarray
2
18,478
68,734,966
How to groupby date in pandas?
<p>I have a data frame created from a spreadsheet and I need to split the Data Frame into multiple Dataframes based on column value. The following code works fine:</p> <pre><code>df = pd.read_excel(&quot;20210720.xlsx&quot;) # print (df) grouped = df.groupby(df.Store) ninth = grouped.get_group(&quot;B&quot;) print...
<p>You need to ensure that your column is using the datetime type:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) </code></pre> <p>Then the possible group values will be in <code>df['Date'].unique()</code></p> <p>To get an idea of your groups:</p> <pre><code>for group, d in df.groupy('Date'): print('group:'...
python|pandas
1
18,479
36,460,368
How to calculate quantiles in a pandas multiindex DataFrame?
<p>I have a pandas multiindex DataFrame, and I want to calculate the quantiles of its values over a specific index level. It's better to explain with an example. </p> <p>First, let's create the DataFrame:</p> <pre><code>import itertools import pandas as pd import numpy as np item = ('A', 'B') item_type = (0, 1, 2) l...
<p>Apply the <code>quantile</code> function by first grouping by your multiindex levels:</p> <pre><code>df.groupby(level=[0,1]).quantile() </code></pre> <p>The same result will work for the <code>median</code> function, so the following line is equivalent to your code <code>df.median(level=[0,1])</code>:</p> <pre><c...
python|pandas
6
18,480
36,600,476
Pandas: Create dataframe of rows where the median of a groupby object column is above a threshold
<p>I've got a dataframe with columns <code>gene_name</code>, <code>sample_name</code>, <code>value</code>, and <code>e_id</code>. I want to create a dataframe containing only the rows where the median <code>value</code> of all the <code>sample_name</code> in a <code>gene_name</code> is above a threshold. </p> <p>E.g. ...
<p>Let <code>cond</code> be a boolean dataframe showing which medians are above threshold:</p> <pre><code>cond = df.groupby(["gene_name", "sample_name"])["value"].median() &gt;= 22 </code></pre> <p>We can <code>groupby</code> again to find out which genes have all medians above threshold:</p> <pre><code>cond.groupby...
python|pandas
2
18,481
4,992,040
python, numpy boolean array: negation in where statement
<p>with:</p> <pre><code>import numpy as np array = get_array() </code></pre> <p>I need to do the following thing:</p> <pre><code>for i in range(len(array)): if random.uniform(0, 1) &lt; prob: array[i] = not array[i] </code></pre> <p>with array being a numpy.array.</p> <p>I wish I could do something sim...
<p>I suggest using</p> <pre><code>array ^= numpy.random.rand(len(array)) &lt; prob </code></pre> <p>This is probably the most efficient way of getting the desired result. It will modify the array in place, using "xor" to invert the entries which the random condition evaluates to <code>True</code> for.</p> <blockquo...
python|numpy
33
18,482
65,605,881
Pseudo code conversion into python for csv
<p>I have some pseudocode that I am trying to convert into Python and was hoping for some help. I have a csv that I would like to import into Python and essentially split up into smaller csv's based on a conditional statement. I have an example of the spreadsheet structure and how the split looks. I was thinking the be...
<p>Based on @RufusVS idea from comments:</p> <pre><code># create dataframe foo = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9,10,11,12,13], 'B': [0,0,1,2,3,0,0,0,4,5,5,0,0]}) foo['C'] = 0 # add new column with 0s group = 0 collecting = False #boolean flag for i in range(foo.shape[0]): if foo['B'][i] != ...
python|pandas|for-loop
1
18,483
65,817,496
Conditional update of pandas dataframe from another dataframe
<p>I have a master dataframe with two sets of values:</p> <pre><code>df1 = pd.DataFrame({'id1': [1, 1, 2, 2], 'dir1': [True, False, True, False], 'value1': [55, 40, 84, 31], 'id2': [3, 3, 4, 4], 'dir2': [True, False, False, True], 'value2': [60,...
<p>I agree with Thales' answer. First, you merge df2 with df1 based on id1:</p> <pre><code>df = df1.merge(df2, left_on='id1', right_on='id') </code></pre> <p>Then, you replace <code>value1</code> based on <code>dir1</code> with <code>value</code>:</p> <pre><code>df.value1 = np.where(df.dir1 == True, df.value, df.value1...
python|pandas
1
18,484
65,608,173
Create a permuted shallow copy of a numpy array
<p>I am looking to have two different views of the same data with the rows in a different order such that changes done through one view will be reflected in the other. Specifically, the following code</p> <pre><code># Create original array A = numpy.array([[0, 1, 2], [3, 4, 5], [6, 7, ...
<p>An array has a <code>shape</code>, <code>strides</code>, <code>dtype</code> and 1d data_buffer. A <code>view</code> will have its own <code>shape</code>, <code>strides</code>, <code>dtype</code>, and pointer to some place in the base's data_buffer. Indexing with a <code>slice</code> can be achieved with just these...
python|numpy|numpy-slicing|numpy-indexing
2
18,485
63,600,228
when i execute pandas-profiling package it won't return min, max and mean values
<p>When i profiling the following data using <strong>pandas-profiling==2.8.0</strong> it won't return min, max and mean values.</p> <blockquote> <p>CSV data</p> </blockquote> <p><strong>a,b,c<br></strong> 12,2.5,0<br> 12,4.7,5<br> 33,5,4<br> 44,44.21,67</p> <blockquote> <p>python code</p> </blockquote> <pre><code>impor...
<p>For a dataset with less elements than a given number (say 5), pandas-profiling assumes that your variable is categorical instead of interval.</p> <p>Use the <code>vars.num.low_categorical_threshold</code> parameter to change this (<a href="https://pandas-profiling.github.io/pandas-profiling/docs/master/rtd/pages/adv...
python-3.x|pandas|python-3.6|pandas-profiling|data-profiling
1
18,486
63,382,022
Is there any scripts available to import multiple csv files and stitch the data in terms of dates and export it to n excel file
<p>I want to write a python script to plot a graph from daily data ( temperature, humidity vs time (15 mins interval) stored in multiple csv files (daily basis). I want to read the entire monthly data (30 csv files), filter the columns and store the entire monthly data in a single file, in terms of Time and date to plo...
<p>You can read all your .csv files and combine them in one .csv or .xlsx file by below code: (as you did not mention which type of filtering do you need I cannot provide any solution for that part):</p> <pre><code>import os import glob import pandas as pd import sys import csv maxInt = sys.maxsize while True: # decre...
python|numpy|csv|matplotlib
0
18,487
63,606,300
Getting: 'IndexError: index 1 is out of bounds for axis 0 with size 0' but can't tell why
<p>I get an index error when trying to fill values to my array, but I can't see why this error would occur.</p> <pre><code> Hist = HistData[:pos, :] if Hist.shape[0] != 0: for y in range(2012, 2019): hist_pos = 0 YearHist = np.zeros((150000, 1)) for k in range(His...
<p>The problem lies in the last line, you accidently put it in the for-k-Loop, but it belongs to the for-y loop. Delete one Tab and you should be fine.</p> <pre><code> YearHist = YearHist[:hist_pos] </code></pre> <p>becomes</p> <pre><code> YearHist = YearHist[:hist_pos] </code></pre>
python|python-3.x|numpy
0
18,488
63,721,936
Get nth and mth elements of a numpy array
<p>A very basic question but I cannot find similar question in here og by googling.</p> <pre><code>tmp = np.array([1,2,3,4,5]) </code></pre> <p>I can extract 2 by <code>tmp[1]</code> and 2 to 4 by <code>tmp[1:4]</code></p> <p>Suppose I want to extract 2 AND 4. What is the easiest way to do that?</p>
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.take.html" rel="nofollow noreferrer">.take()</a></p> <pre><code>import numpy as np tmp = np.array([1,2,3,4,5]).take([1,4]) # Out[4]: (2, 5) </code></pre>
python|numpy
1
18,489
63,405,079
Find in what polygon is each point
<p>I am new to Python, so I apologize for the rudimentary programming skills, I am aware I am using a bit too much &quot;loop for&quot; (coming from Matlab it is dragging me down).</p> <p>I have millions of points (timestep, long, lat, pointID) and hundreds of irregular non-overlapping polygons (vertex_long,vertex_lat,...
<p>Have you tried Geopandas Spatial join?</p> <p>install the Package using pip <code>pip install geopandas</code> or conda <code>conda install -c conda-forge geopandas</code></p> <p>then you should able to read the data as GeoDataframe</p> <pre><code>import geopandas df = geopandas.read_file(&quot;file_name1.csv&quot...
python|numpy|dataframe|polygon|point
1
18,490
63,415,752
pythonic way to identify and remove sub strings from strings
<p>I have a large numpy array of strings, where some elements of the array are good strings, some have special characters (typically at the start of the string and some have substrings in various quotes inside of it). I want to identify the elements which have a string inside of the string, store the string inside and ...
<p>try this</p> <pre><code>import re corrected_array = [re.sub('&quot;[^&quot;]*&quot;', '', s.replace(&quot;'&quot;, '&quot;')) for s in my_array] </code></pre>
python|regex|pandas|string|numpy
2
18,491
29,911,212
pandas: replacing categorical values with counts of multi class label
<p>Lets assume I have a data frame:</p> <pre><code>df = pd.DataFrame({'label': [0, 1, 2, 0, 1, 2], 'cat_col': [1, 1, 2, 2, 3, 3]}) cat_col label 0 1 0 1 1 1 2 2 2 3 2 0 4 3 1 5 3 2 </code></pre> <p>I want to transform this data frame to the f...
<p>You can use a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>In [11]: df.pivot_table(index="cat_col", columns="label", aggfunc=len, fill_value=0) Out[11]: label 0 1 2 cat_col 1 1 1 0 2 ...
python|pandas
0
18,492
53,721,756
Year wise cumsum based on condition on other column Python 3+ Pandas data frame
<p>I have a dataframe with three columns as Year, Price, PV. I want a cumulative sum of column PV getting reset as per Year column, if values in Price column not equal to zero.</p> <pre><code>df = pd.DataFrame({"Year": [2000] * 3 + [2001] * 3, "Value": [0,100,0,0,100,100], "PV": [...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.cumsum</cod...
python-3.x|pandas|cumsum
0
18,493
53,781,596
Combine two columns, ignore empty cells and add a separator
<p>I need to combine column <code>1</code> and <code>2</code> in <code>3</code> with separator <code>,</code> but ignore empty cells. So I have this dataframe:</p> <pre><code> 1 2 0 A, B, B D 1 C, D 2 B, B, C D, A </code></pre> <p>And need to create column <code>3</code> (desired output):...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>str.strip</code></a> for possible removing <code>,</code> from both sides:</p> <pre><code>(df["1"] + ", " + df["2"]).str.strip(', ') </code></pre>
python|pandas|dataframe|concatenation
3
18,494
53,434,489
Replacing multiple value names in a panda dataframe
<p>I have a column <code>colA</code> that has multiple values in a pandas dataframe. I want every value that starts with <code>spare1</code> in this column to be replaced with the words <code>email_petition</code>. e.g. <code>spare1signed</code>, <code>spare1not</code> signed yet' etc. will all be converted to just <co...
<p>Try this:</p> <pre><code>df.colA.replace({'spare1':'email_petition'}, regex=True) </code></pre> <p>For complete removal:</p> <pre><code>df['colA'].replace({'spare1signed':'email_petition','spare1notsigned':'email_petition'}) </code></pre>
python|pandas
0
18,495
53,765,593
Is this a bug in using Keras with tensorflow Datasets?
<p>Or maybe the tutorial has a typo somewhere. Or maybe there's a bug just in my version (see notes; cannot upgrade online via <code>pip</code>). Or maybe I'm doing something wrong. <strong>I'd like to know which and what to do about it.</strong></p> <p><a href="https://www.tensorflow.org/guide/keras#input_tfdata_data...
<p>I had the same issue and I updated <code>tensorflow</code> to <code>2.1.0</code> and importing <code>keras</code> not directly but <code>import tensorflow.keras</code>. Doing this the same broken code using <code>Dataset</code> now works</p>
python-3.x|tensorflow|keras
2
18,496
17,390,928
Selecting Pandas dataframe records based on the content of a series field
<p>======================== UPDATE #2 =============================================</p> <p>What a day. I am very slowly making progress. But while PANDAS is very fast and powerful it has a steep learning curve and there are not very good examples (at least for what I am trying to do). </p> <p>The latest issue i...
<p>Hopefully I'm understanding your particular use-case well enough to provide a decent answer.</p> <p>Given some data:</p> <pre><code>data = """ dtu_docid|dtu_topic_split 9|2010-0185|['Financial Services Industries'] 17|2010-0152|['Financial Services Industries', 'International'] 46|2012-1421|['Financial Services In...
pandas
2
18,497
17,545,626
how to create an interlaced rows images with python and openCv
<p>I have two images with the same size. I would like to create a new interlaced image where the odd rows belong to one image and the even rows to the other image. Like a 3d image. I am trying to do that with python and openCv and numpy! Reading the two images and with a loop i try to write the values in the odd and ev...
<p>This should be much faster than your approach:</p> <pre><code>def interlace(imgL, imgR, h, w): inter = np.empty((h, w, 3), imgL.dtype) inter[:h:2, :w, :] = imgL[:h:2, :w, :] inter[1:h:2, :w, :] = imgL[1:h:2, :w, :] return inter.astype(np.float32) / 255 </code></pre> <p>As general rules, try to avoi...
image|opencv|python-2.7|numpy
3
18,498
17,369,854
Python creating a smaller sub-array from a larger 2D NumPy array?
<p>So I have a large NumPy array that takes the following form:</p> <pre><code>data = [[2456447.64798471, 4, 15.717, 0.007, 5, 17.308, 0.019, 6, 13.965, 0.006], [2456447.6482855, 4, 15.768, 0.018, 5, 17.347, 0.024, 6, 14.001, 0.023], [2456447.648575, 4, 15.824, 0.02, 5, 17.383, 0.024, 6, 14.055, 0.023]...
<p>You could do this:</p> <pre><code>&gt;&gt;&gt; data[:, [1, 2, 4, 5, 7, 8]] array([[ 4. , 15.717, 5. , 17.308, 6. , 13.965], [ 4. , 15.768, 5. , 17.347, 6. , 14.001], [ 4. , 15.824, 5. , 17.383, 6. , 14.055]]) </code></pre>
python|arrays|numpy|indexing
7
18,499
12,155,137
pyqt : Convert numpy array to QImage
<p>I need to convert a numpy array to a QtGui.QImage. But I don't know how to do that. I've find this : <a href="http://kogs-www.informatik.uni-hamburg.de/~meine/software/qimage2ndarray/" rel="nofollow">http://kogs-www.informatik.uni-hamburg.de/~meine/software/qimage2ndarray/</a> but when I try to install this I get an...
<p>The traceback shows that you are trying to install the package using the <code>easy_install</code> installed under the <a href="http://docs.python.org/library/site.html#site.USER_BASE" rel="nofollow"><code>USER_BASE</code></a> directory (<code>~/.local/bin/easy_install</code>).</p> <p>This is in turn using the pyt...
python|qt|numpy|pyqt|easy-install
0