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
1,400
25,197,052
Is there a numpy function to convert from log(e) to log(10)?
<p>Is there a single numpy function convert log(e) numbers to log(10) numbers? If so, would the single function be faster than this code?</p> <pre><code>y = np.array([1, 2, 3, 4]) np.log10(np.exp(y)) </code></pre>
<p>I do not think there is a <code>numpy</code> function (and I hope to be corrected), but the standard mathematical way is faster than what you have shown.</p> <p>That is, you would simply divide <code>log_e(n)</code> by the constant <code>log_e(10)</code> to obtain <code>log_10(n)</code>.</p>
python|numpy
2
1,401
39,275,533
Select row from a DataFrame based on the type of the object(i.e. str)
<p>So there's a DataFrame say:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({ ... 'A':[1,2,'Three',4], ... 'B':[1,'Two',3,4]}) &gt;&gt;&gt; df A B 0 1 1 1 2 Two 2 Three 3 3 4 4 </code></pre> <p>I want to select the rows whose datatype of particular ...
<p>This works:</p> <pre><code>df[df['A'].apply(lambda x: isinstance(x, str))] </code></pre>
python|pandas
47
1,402
39,018,107
Convert non-strict JSON Amazon SNAP metadata to Pandas DataFrame
<p>I am trying to convert <a href="http://snap.stanford.edu/data/amazon/productGraph/categoryFiles/meta_Grocery_and_Gourmet_Food.json.gz" rel="nofollow">this Amazon sample Snap grocery JSON data</a> to a Pandas dataframe in IBM Bluemix (using Python 2.x) and then analyze it with Apache Spark.</p> <p>I have unzipped th...
<p>Let me answer this in two parts:-</p> <ol> <li><p>You can install ijson in your bluemix spark service using below command and then user <code>import ijson</code> to further use it as per your use.</p> <p><code>!pip install --user ijson</code></p></li> <li><p>You can use <code>sqlContext.jsonFile</code> to read the...
python-2.7|pandas|apache-spark|ibm-cloud
0
1,403
39,200,644
numpy 3 dimension array middle indexing bug
<p>I seems found a bug when I'm using python 2.7 with numpy module:</p> <pre><code>import numpy as np x=np.arange(3*4*5).reshape(3,4,5) x </code></pre> <p>Here I got the full 'x' array as follows:</p> <pre><code>array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16...
<p>No, it's not a bug.</p> <p>When you use <code>[:]</code> you are using slicing notation and it takes all the list:</p> <pre><code>l = ["a", "b", "c"] l[:] #output: ["a", "b", "c"] </code></pre> <p>and in your case:</p> <pre><code>x[1][:] #output: array([[20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [...
python|arrays|numpy
3
1,404
39,218,768
Find numpy vectors in a set quickly
<p>I have a numpy array, for example:</p> <pre><code>a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) </code></pre> <p>and I also have a set</p> <pre><code>b = set((1,2),(6,4),(9,9)) </code></pre> <p>I want to find the index of vectors that exist in set b, he...
<p>You can use filter:</p> <pre><code>In [8]: a = np.array([[1,2], [3,4], [6,4], [5,3], [3,5]]) In [9]: b = {(1,2),(6,4)} In [10]: filter(lambda x: tuple(a[x]) in b, range(len(a))) Out[10]: [0, 2] </code></pre>
python|numpy|set|vectorization|lookup
1
1,405
19,456,239
Convert python list with None values to numpy array with nan values
<p>I am trying to convert a list that contains numeric values and <code>None</code> values to <code>numpy.array</code>, such that <code>None</code> is replaces with <code>numpy.nan</code>.</p> <p>For example:</p> <pre><code>my_list = [3,5,6,None,6,None] # My desired result: my_array = numpy.array([3,5,6,np.nan,6,np...
<p>You simply have to explicitly declare the data type:</p> <pre><code>&gt;&gt;&gt; my_list = [3, 5, 6, None, 6, None] &gt;&gt;&gt; np.array(my_list, dtype=np.float) array([ 3., 5., 6., nan, 6., nan]) </code></pre>
python|numpy
55
1,406
12,957,593
Pandas: reshape data with duplicate row names to columns
<p>I have a data set that's sort of like this (first lines shown):</p> <pre><code>Sample Detector Cq P_1 106 23.53152 P_1 106 23.152458 P_1 106 23.685083 P_1 135 24.465698 P_1 135 23.86892 P_1 135 23.723469 P_1 17 22.524242 P_1 17 20.658733 P_1 17 21.146122 </...
<p>It looks like what you may be looking for is a hierarchical indexed dataframe<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#hierarchical-indexing-multiindex"> [link]</a>.</p> <p>Would something like this work?</p> <pre><code>#build a sample dataframe a=['P_1']*9 b=[106,106,106,135,135,135,17,17...
python|pandas
5
1,407
13,215,525
How to extend an array in-place in Numpy?
<p>Currently, I have some code like this</p> <pre><code>import numpy as np ret = np.array([]) for i in range(100000): tmp = get_input(i) ret = np.append(ret, np.zeros(len(tmp))) ret = np.append(ret, np.ones(fixed_length)) </code></pre> <p>I think this code is <strong>not efficient</strong> as <code>np.append</...
<p>Imagine a numpy array as occupying one contiguous block of memory. Now imagine other objects, say other numpy arrays, which are occupying the memory just to the left and right of our numpy array. There would be no room to append to or extend our numpy array. The underlying data in a numpy array always occupies a <em...
python|arrays|numpy|scipy
69
1,408
29,287,943
pandas groupby for multiple data frames/files at once
<p>I have multiple huge tsv files that I'm trying to process using pandas. I want to group by 'col3' and 'col5'. I've tried this:</p> <pre><code>import pandas as pd df = pd.read_csv('filename.txt', sep = "\t") g2 = df.drop_duplicates(['col3', 'col5']) g3 = g2.groupby(['col3', 'col5']).size().sum(level=0) print g3 </co...
<p>This is a nice use case for <a href="http://blaze.pydata.org" rel="noreferrer"><code>blaze</code></a>.</p> <p>Here's an example using a couple of reduced files from the <a href="http://www.andresmh.com/nyctaxitrips/" rel="noreferrer">nyctaxi dataset</a>. I've purposely split a single large file into two files of 1,...
python|csv|pandas|group-by
8
1,409
29,291,279
Group and average NumPy matrix
<p>Say I have an arbitrary numpy matrix that looks like this:</p> <pre><code>arr = [[ 6.0 12.0 1.0] [ 7.0 9.0 1.0] [ 8.0 7.0 1.0] [ 4.0 3.0 2.0] [ 6.0 1.0 2.0] [ 2.0 5.0 2.0] [ 9.0 4.0 3.0] [ 2.0 1.0 4.0] [ 8.0 4.0 4.0...
<p>A compact solution is to use <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="noreferrer">numpy_indexed</a> (disclaimer: I am its author), which implements a fully vectorized solution:</p> <pre><code>import numpy_indexed as npi npi.group_by(arr[:, 2]).mean(arr) </code></pre>
python|numpy|matrix|grouping|average
9
1,410
33,728,831
Remove bracket of a array python
<p>In here, i want to ask how to remove bracket of a array in python. This is my following code:</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv('data.csv', index_col=0, header=0) X = np.array(df.ix[:,0:29]) Y = np.array(df.ix[:,29:30]) Y Out[55]: array([[ 1], [ 2], [ 3], .....
<p>Check if it works</p> <pre><code>X = np.array(df.ix[:,0:29]) Y = np.array(df.ix[:,29:30]) Y = Y[0] </code></pre>
python|numpy|pandas
4
1,411
33,622,481
"The truth value of a Series is ambiguous. " Series vs Element Fuction
<p>I have a dataframe and I have written the following function to populate a new column:</p> <pre><code>df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b']) def perc(a,b): if a/b &lt; 0: n = 0 elif a/b &gt; 1: n = 1 else: n = a/b return n df['c']=perc(df['a'],df['b'...
<p>What you're actually asking for is a bit hard to describe in words, but the following example captures it:</p> <blockquote> <p>If <code>a</code> is the series <code>[-1, 1, 3, 5]</code> and <code>b</code> is <code>[2, 2, 3, 3]</code>, then <code>a/b</code> will be a series like <code>[-0.5, 0.5, 1, 1.6666667]</co...
python|pandas|series
0
1,412
33,576,758
Creating a pandas DataFrame with counts of categorical data
<p>I have a bunch of survey data broken down by number of responses for each choice for each question (multiple-choice questions). I have one of these summaries for each of several different courses, semesters, sections, etc. Unfortunately, all of my data was given to me in PDF printouts and I cannot get the digital da...
<p>One hacky way to get the information out is to first split by ----- and then use regex.</p> <p>For each course so something like the following:</p> <pre><code>In [11]: s Out[11]: 'Semester: Spring\nSection: 01\nQuestion 1\n----------\nOption A: 27\nOption B: 30\nOption C: 0\nOption D: 2\n\nQuestion 2\n----------\n...
python|excel|pandas|categorical-data
0
1,413
23,628,503
Finding indices in Python lists efficiently (in comparison to MATLAB)
<p>I have got difficulties to find an efficient solution to find indices in Python lists. All the solutions I have tested so far are slower than the 'find' function in MATLAB. I have only just started to use Python (therefore, I am not very experienced). </p> <p>In MATLAB I would use the following:</p> <pre><code>a =...
<p>Try <code>numpy.searchsorted</code>:</p> <pre><code>&gt;&gt; a = np.array([0, 1, 2, 3, 4, 5, 6, 7]) &gt;&gt; b = np.array([1, 2, 4, 3, 1, 0, 2, 9]) % sorting b "into" a &gt;&gt; np.searchsorted(a, b, side='right')-1 array([1, 2, 4, 3, 1, 0, 2, 9]) </code></pre> <p>You might have to apply a little special treatment...
python|matlab|list|numpy
5
1,414
15,194,468
How to generate n dimensional random variables in a specific range in python
<p>I want to generate uniform random variables in the range of <code>[-10,10]</code> of various dimensions in python. Numbers of 2,3,4,5.... dimension. </p> <p>I tried random.uniform(-10,10), but that is only one dimensional. I do not know how to do it for n-dimension. By 2 dimension I mean,</p> <pre><code>[[1 2], [3...
<p>Since <code>numpy</code> is tagged, you can use the random functions in <code>numpy.random</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random.uniform(-10,10) 7.435802529756465 &gt;&gt;&gt; np.random.uniform(-10,10,size=(2,3)) array([[-0.40137954, -1.01510912, -0.41982265], [-8.1266...
python|numpy|scipy
11
1,415
15,072,626
Get group id back into pandas dataframe
<p>For dataframe</p> <pre><code>In [2]: df = pd.DataFrame({'Name': ['foo', 'bar'] * 3, ...: 'Rank': np.random.randint(0,3,6), ...: 'Val': np.random.rand(6)}) ...: df Out[2]: Name Rank Val 0 foo 0 0.299397 1 bar 0 0.909228 2 foo 0 0.517700 3 ba...
<p>A lot of handy things are stored in the <code>DataFrameGroupBy.grouper</code> object. For example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'Name': ['foo', 'bar'] * 3, 'Rank': np.random.randint(0,3,6), 'Val': np.random.rand(6)}) &gt;&gt;&gt; grouped = df.groupby(["Name",...
python|pandas|group-by
39
1,416
29,730,488
Setting columns for an empty pandas dataframe
<p>This is something that I'm confused about...</p> <pre><code>import pandas as pd # this works fine df1 = pd.DataFrame(columns=['A','B']) # but let's say I have this df2 = pd.DataFrame([]) # this doesn't work! df2.columns = ['A','B'] # ValueError: Length mismatch: Expected axis has 0 elements, new values have 2 ele...
<p>Update: <a href="https://github.com/pydata/pandas/pull/9939" rel="nofollow">as of Pandas version 0.16.1</a>, passing <code>data = []</code> works:</p> <pre><code>In [85]: df = pd.DataFrame([], columns=['a', 'b', 'c']) In [86]: df Out[86]: Empty DataFrame Columns: [a, b, c] Index: [] </code></pre> <p>so the best ...
python|pandas
3
1,417
29,381,271
How to make array into array list in python
<p>from this array </p> <pre><code>s = np.array([[35788, 41715, ... 34964], [5047, 23529, ... 5165], [12104, 33899, ... 11914], [3646, 21031, ... 3814], [8704, 7906, ... 8705]]) </code></pre> <p>I have a loop like this</p> <pre><code>end =[] for i in range(len(s)): for...
<p>You need to loop differently in at least <strong>two</strong> ways:</p> <pre><code>end =[] for s1 in s: end.append([mahalanobis(s1, s2, invcov) for s2 in s]) </code></pre> <p>The most important thing is that the inner loop needs to be on the whole <code>s</code> again, else you will never get a square but <cod...
python|arrays|numpy
6
1,418
62,392,798
Tensorflow 2.x: How to assign convolution weights manually using numpy
<p>In tensorflow 1.x this can be done using a <a href="https://stackoverflow.com/questions/39555256/tensorflow-how-can-i-assign-numpy-pre-trained-weights-to-subsections-of-graph">graph and a session</a>, which is quite tedious.</p> <p>Is there an easier way to manually assign pretrained weights to a specific convoluti...
<p>If you are working with Keras inside Tensorflow 2.x, every layer has a method called <code>set_weights</code> that you can use to substitute weights or assign new ones from Numpy arrays.</p> <p>Say, for example, that you are doing distillation knowledge. Then you could assign weights of the teacher to the student by...
tensorflow|tensorflow2.0|onnx
1
1,419
62,327,529
Pandas DataFrame data types change unexpectedly
<p>I am working on a script that solves sudoku puzzles. I use a <code>pandas.DataFrame</code> for the sudoku itself and the numbers are integers.</p> <p>When I check which numbers are possible in a box and multiple numbers fit the requirements, I put the numbers as a <code>list</code> within the box. Because of this, ...
<p>I saw such issue in practice. This is because you insert NaNs into your DataFrame, ie.:</p> <pre><code>df = pd.DataFrame([range(3), range(3)]) df.dtypes </code></pre> <p>Output:</p> <pre><code>0 int64 1 int64 2 int64 dtype: object </code></pre> <p>Then:</p> <pre><code>df.iloc[0,0] = np.nan df.dtypes ...
python|python-3.x|pandas|dataframe
1
1,420
62,062,539
Transform with sum of values of the same column
<p>I have the following dataframe:-</p> <pre><code>traffic_type date unique_visitors region total_views desktop 01/04/2018 72 aug 50 mobileweb 01/04/2018 1 aug 60 total 01/04/2018 sum(mobileweb+desktop) aug 100 de...
<p>You can use go row by row and check and sum as below </p> <pre class="lang-py prettyprint-override"><code> import pandas as pd df = pd.DataFrame([["desktop","01/04/2018",72,"aug",50], ["mobileweb","01/04/2018",1,"aug",60], ["total","01/04/2018","","aug",100], ["deskt...
python|python-3.x|pandas|numpy|dataframe
3
1,421
62,162,677
Slicing lists based on several parameters
<p><strong>I have posted a similar question several times but it was closed or redirected to another post that wasn't answering my question. I hope this time this post stays.</strong></p> <p>I have a df with US census data. I grouped states with their correspondent counties. There's also another column with population...
<p>I am guessing what you are looking for is <code>cdf.groupby('STNAME').head(3)</code> after you sort the cdf?</p> <p>P.S. perhaps your questions keep getting closed because of duplicate questions? like: <a href="https://stackoverflow.com/questions/20069009/pandas-get-topmost-n-records-within-each-group">Pandas get t...
python|pandas|greatest-n-per-group
0
1,422
62,438,764
Adding rows at a specific column
<p>I have a dataframe-</p> <pre><code> DATE CITY_NAME WEEK_NUM 0 2019-12-01 Bangalore 48 1 2019-12-01 Delhi 48 2 2019-12-02 Bangalore 49 3 2019-12-02 Delhi 49 </code></pre> <p>Now I want to add a new column to the dataframe and add a row to the new column in a...
<pre><code>import random df['Hi'] = [random.randrange(10) for _ in range(len(df))] print(df) </code></pre> <p>Prints (for example):</p> <pre><code> DATE CITY_NAME WEEK_NUM Hi 0 2019-12-01 Bangalore 48 2 1 2019-12-01 Delhi 48 9 2 2019-12-02 Bangalore 49 0 3 2019-12-02...
python|pandas
1
1,423
62,274,746
How to convert mat file to numpy array
<p>I want to convert a mat file with size 600 by 600 to numpy array and I got this error "float() argument must be a string or a number, not 'dict'" I am wondering how can I fix it.</p> <pre><code> import numpy as np import scipy.io as sio test = sio.loadmat('Y7.mat') data=np.zeros((600,600)) data[:...
<pre><code>In [240]: from scipy.io import loadmat </code></pre> <p>Using a test mat file that I have from past SO questions:</p> <pre><code>In [241]: loadmat('test.mat') Out[241]: {'__header__': b...
arrays|numpy|scipy
1
1,424
62,341,554
How to assign value to new column based on other column string?
<p>I have a trade data of the country with the following column names </p> <pre><code>Index(['TNVED', 'Product_Name', 'Export_Value', 'Import_Value', 'Year', 'Country', 'Region', 'Total_Export_XLS', 'Total_Import_XLS', 'Export_Sum', 'Import_Sum', 'Type', 'Nonraw_Type'], </code></pre> <p>Now I am trying ...
<p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> along with regex pattern to create a boolean mask, then substitute values in <code>Type</code> column using this mask:</p> <pre><code>pattern = r'^...
python-3.x|pandas
0
1,425
62,341,053
validation accuracy not improving
<p>No matter how many epochs I use or change learning rate, my validation accuracy only remains in 50's. Im using 1 dropout layer right now and if I use 2 dropout layers, my max train accuracy is 40% with 59% validation accuracy. And currently with 1 dropout layer, here's my results:</p> <pre><code>2527/2527 [========...
<p>The size of the training dataset is less than 3K. While the amount of the trainable parameters is around 3 million. The answer to your question is classical overfitting - the model is so huge, that just remember the training subset instead of a generalization.</p> <p>How to improve the current situation:</p> <ul> <l...
python|tensorflow|machine-learning|keras|neural-network
10
1,426
51,291,053
How to append to a column in a DataFrame containing time sequences
<p><a href="https://i.stack.imgur.com/gC8ak.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gC8ak.png" alt="enter image description here"></a></p> <p>How do I append another list to the column df_final['time_seq'] which is stored in timeseq=[xyz,xyz...,xyz]</p>
<p>For your particular question:</p> <pre><code>additional_time_seq = [1234567, 1234568] # i the index of the row you want # the line below gives you the time_seq list time_seq_to_append = df_final.loc[df_final.index[i], 'time_seq'] # the line below extends the time_seq list with the additional_time_seq time_seq_to_ap...
python|pandas
2
1,427
51,344,660
How to use pandas at?
<p>I am often confused about pandas slice operation, for example, </p> <pre><code>import pandas as pd raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1...
<p>Problem is with the line,</p> <pre><code>des = df['postTestScore'].groupby(df['categories']).apply(get_stats).unstack() </code></pre> <p>after doing a group by over 'postTestScroe' you are getting <strong>"Series"</strong> not <strong>"DataFrame"</strong> as shown below.</p> <p><a href="https://i.stack.imgur.com/...
python|pandas|dataframe
0
1,428
48,285,160
Write 1s faster to col-rows based on positions in a list
<p>I'm new to pandas. I'm using a dataframe to tally how many times two positions match. </p> <p>Here is the code in question...right at the start. The "what am I trying to accomplish" below...</p> <pre><code>def crossovers(df, index): # Duplicate the dataframe passed in _dfcopy = df.copy(deep=True) # Set...
<p>I'd organize it with numpy slice assignment and the handy <code>np.triu_indices</code> function. It returns the row and column indices of the upper triangle. I make sure to pass <code>k=1</code> to ensure I skip the diagonal. When I slice assign, I make sure to use both <code>i, j</code> and <code>j, i</code> to ...
python-3.x|list|pandas|dataframe
3
1,429
48,269,372
Tensorflow serving_input_receiver_fn with arguments
<p>I want to add some arguments to the function serving_input_receiver_fn, because the size of the feature array depends of the model. The problem is that the oficial definition of serving_input_receiver_fn is: </p> <blockquote> <p>serving_input_receiver_fn: A function that takes no argument and returns a Serving...
<p>How about using a nested function or closure?</p> <pre><code>&gt;&gt;&gt; def create_serving_fn(size, feature, inputs): def serving_input_receiver_fn(): serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_tensors') receiver_tensors = {inputs: serialized...
python|tensorflow|machine-learning
5
1,430
48,015,191
How to extrapolate a function based on x,y values?
<p>Ok so I started with Python a few days ago. I mainly use it for DataScience because I am an undergraduate chemistry student. Well, now I got a small problem on my hands, as I have to extrapolate a function. I know how to make simple diagrams and graphs, so please try to explain it as easy to me as possible. I start ...
<p>Taking a quick look at your data,</p> <pre><code>from matplotlib import pyplot as plt from matplotlib import style style.use('classic') x1 = [0.632455532, 0.178885438, 0.050596443, 0.014310835, 0.004047715] y1 = [114.75, 127.5, 139.0625, 147.9492188, 153.8085938] plt.plot(x1, y1) </code></pre> <p><a href="https:/...
python|numpy|matplotlib|extrapolation
5
1,431
48,613,671
slice pandas dataframe to get noncontiguous columns
<p>I have a <code>pandas.DataFrame</code>: <code>wordvecs_df</code>, with columns labeled <code>'word'</code>, <code>'count'</code>, <code>'v1'</code> through <code>'v50'</code> and <code>'norm1'</code> through <code>'norm50'</code> in that order. I want to create a new pandas df with just the columns for <code>'word'...
<p>You can build up a list of column names like:</p> <pre><code>columns = ['word', 'count'] + ['norm%d' % i for i in range(1, 51)] wordvecs_df.loc[:,columns] </code></pre>
python|pandas|dataframe|slice
4
1,432
48,445,748
group the same consecutive values in pandas and store: values, indices, and column slices
<p>I have a dataframe</p> <pre><code>import pandas as pd import numpy as np v1=list(np.random.rand(30)) v2=list(np.random.rand(30)) mydf=pd.DataFrame(data=zip(v1,v2),columns=['var1','var2']) </code></pre> <p>then I apply some boolean conditions on some variables</p> <pre><code>mydf['cond1']=mydf['var1']&gt;0.2 mydf[...
<p>I think you can use <a href="https://stackoverflow.com/questions/40802800/pandas-dataframe-how-to-groupby-consecutive-values">this SO answer</a>. <code>i</code> gives you the group number, and the <code>index</code> of <code>g</code> can be used to get the <code>var</code> values.</p> <pre><code>v1=list(np.random.r...
python|pandas
1
1,433
48,839,618
High training accuracy but low prediction performance for Tensorflow's official MNIST model
<p>I'm new to machine learning and I was following along with the Tensorflow official MNIST model (<a href="https://github.com/tensorflow/models/tree/master/official/mnist" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/official/mnist</a>). After training the model for 3 epochs and getting a...
<p>The MNIST images are white-on-black; the images you've linked are black-on-white.</p> <p>Unless there's a conversion step I missed, you'll want to invert the colors before attempting detection.</p>
python|tensorflow|machine-learning|conv-neural-network|mnist
5
1,434
48,639,183
pandas dataframe get NaN when mapping
<p>Can anyone answer me why I always get NaN ?<a href="https://i.stack.imgur.com/MIcl5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MIcl5.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/N5jHh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com...
<p>It seems there are some whitespaces, so is necesary remove them first.</p> <p>You can check it by:</p> <pre><code>print(Xtrain['Sex'].head().tolist()) </code></pre> <p>So use:</p> <pre><code>Xtrain = pd.read_csv('train.csv', skipinitialspace=True) Xtrain['Sex'] = Xtrain['Sex'].map(sex_mapping) </code></pre> <p>...
pandas|csv|dictionary
0
1,435
48,553,070
python: handle out of range numpy indices
<p>I am using the following code to rotate an image along it's y-axis.</p> <pre><code>y, x = np.indices(im1.shape[:2]) return im1[y, ((x-im1.shape[1]/2)/math.cos(t*math.pi/2)+im1.shape[1]/2).astype(np.int)] </code></pre> <p>Some of the values are intentionally out-of-range. I would like for out of range pixels to be...
<p>Just mask them:</p> <pre><code># transform &gt;&gt;&gt; x2 = ((x-im1.shape[1]/2)/np.cos(t*np.pi/2)+im1.shape[1]/2).astype(np.int) # check bounds &gt;&gt;&gt; allowed = np.where((x2&gt;=0) &amp; (x2&lt;im1.shape[1])) # preallocate with zeros &gt;&gt;&gt; res = np.zeros_like(im1) # fill in within-bounds pixels &gt;&g...
python|numpy|indexing
1
1,436
70,909,233
Numpy: replace RGB color at specific indexes
<p>I have a Numpy Array of an image and I need to only replace the RGB color of specific elements.</p> <p>E.G.: If I have 10 elements in the Array with the color rgb(16, 16, 16), I want to replace the color of the 2nd and 7th elements only.</p> <p>How to do this?</p> <h1>What I have so far replace them all:</h1> <pre><...
<p>It's a bit hard to check without a working example img_array. But if I'm not mistaken, you should be able to get the indeces of the masked values like so :</p> <pre><code>masked_indeces = np.where(img_array[:,:,:3][mask]) </code></pre> <p>And then you can choose which of the indeces you want to change in the img_ar...
python|numpy|image-processing
0
1,437
70,823,496
reset cumulative sum base on condition pandas and return other cumulative sum
<p>I have this dataframe -</p> <pre><code> counter duration amount 0 1 0.08 1,235 1 2 0.36 1,170 2 3 1.04 1,222 3 4 0.81 1,207 4 5 3.99 1,109 5 6 1.20 1,261 6 7 4.24 1,068 7 8 3.07 1,098 8 9 ...
<p>I would first go through the 2 columns once for their cumulative sums.</p> <pre><code>cum_amount = df['amount'].cumsum() cum_duration = df['duration'].cumsum() </code></pre> <p>Get a list ready for the results</p> <pre><code>results = [] </code></pre> <p>Then loop through each index (equivalent to counter)</p> <pre>...
python|pandas|dataframe|cumsum
0
1,438
51,954,912
Adding header/column to my .csv file
<p>My current code:</p> <pre><code>file='filelocation.sav' finalfile = 'filelocation.csv' s=spio.readsav(file, python_dict=True, verbose=True) amf=np.asarray(s["amf"]) d=[amf] df=pd.DataFrame(data=d) df=df.T df.to_csv(finalfile,sep= ' ', encoding = 'utf-u', header=True) </code></pre> <p><a href="https://i.stack.img...
<p>The problem is that your are wrapping amf between brackets <code>df=[amf]</code> making it a list of arrays, change it to <code>df=amf</code>, for instance:</p> <pre><code>data = [np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70])] result = pd.DataFrame(data=data) print(result.shape) </code></pre> <p>returns: <c...
python|pandas
0
1,439
51,987,076
Avoiding overfitting while training a neural network with Tensorflow
<p>I am training a neural network using Tensorflow's object detetction API to detect cars. I used the following youtube video to learn and execute the process.</p> <p><a href="https://www.youtube.com/watch?v=srPndLNMMpk&amp;t=65s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=srPndLNMMpk&amp;t=65s</a></p> ...
<p>You should use a validation test, different from the training set and the test set.</p> <p>At each epoch, you compute the loss of both training and validation set. If the validation loss begin to increase, stop your training. You can now test your model on your test set.</p> <p>The Validation set size is usually t...
tensorflow|machine-learning|neural-network|tensorboard|training-data
2
1,440
42,003,177
Merge text into datetime column
<p>I have a dataframe with 2 columns. <code>col1</code> is <code>date</code> and <code>col2</code> is <code>bigint</code>. There are dummy values <code>1970-01-01 00:00:00</code> and <code>19700101000000</code></p> <pre><code>col1 col2 2012-01-12 18:09:42 19700101000000 1970-01-01 00:00:00 201407010000...
<p>You need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a>, last...
python|pandas|datetime
1
1,441
64,321,843
Divide rows in two columns with Pandas
<p>I am using Pandas.</p> <ol> <li>For each row, regardless of the County, I would like to divide &quot;AcresBurned&quot; by &quot;CrewsInvolved&quot;.</li> <li>For each County, I would like to sum the total AcresBurned for that County and divide by the sum of the total CrewsInvolved for that County.</li> </ol> <p>I ju...
<p>This is very simple with Pandas. You could create a new col with these operations.</p> <pre><code>df['Acer_per_Crew'] = df['AcersBurned'] / df['CrewsaInvolved'] </code></pre> <p>You could use a groupby clause for viewing the sum of AcersBurned for a county.</p> <pre><code>df_gb = df.groupby(['counties']) ['AcersBurn...
pandas|division
0
1,442
47,856,852
Estimator predict infinite loop
<p>I don't understand how to make a single prediction using TensorFlow Estimator API - my code results in an endless loop that keeps predicting for the same input.</p> <p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#predict" rel="noreferrer">documentation</a>, the predict...
<p>That's because input_fn() needs to be a generator. Change your function to (yield instead of return):</p> <pre><code>def make_predict_input_fn(filename): queue = [ filename ] def _input_fn(): if len(queue) == 0: raise StopIteration image = model.read_and_preprocess(queue.pop()) ...
python|tensorflow|google-cloud-ml
0
1,443
49,171,911
How to select column for a specific time range from pandas dataframe in python3?
<p>This is my pandas dataframe</p> <pre><code> time energy 0 2018-01-01 00:15:00 0.0000 1 2018-01-01 00:30:00 0.0000 2 2018-01-01 00:45:00 0.0000 3 2018-01-01 01:00:00 0.0000 4 2018-01-01 01:15:00 0.0000 5 2018-01-01 01:30:00 0.0000 6 2018-01-01 01:4...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>between_time</code></a> working with <code>Datetimeindex</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="...
python|python-3.x|pandas|python-datetime
2
1,444
48,932,611
Insert seam into a numpy matrix
<p>I have a numpy matrix with values in it. They won't be all the same, but the example is easier if I show it like this:</p> <pre><code>input = np.array([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1] ]) </code></pre> <p>Now I have another matrix of the same size. There is a "seam" of numbers, one number per column...
<p>Here is the straight-forward way using a mask to rearrange the input values:</p> <pre><code>&gt;&gt;&gt; m, n = seam.shape &gt;&gt;&gt; output = np.empty((m, n+1), input.dtype) &gt;&gt;&gt; mask = np.ones((m, n+1), dtype=bool) &gt;&gt;&gt; nz = np.where(seam) &gt;&gt;&gt; mask[nz] = False &gt;&gt;&gt; output[mask]=...
python|numpy
2
1,445
49,075,726
Compare values/strings in two columns in python pandas
<p>Python Pandas: I want to compare values/strings in two columns in an excel and return a string/value in new column based on a condition given. i tried this below code.. but the output is lengthier than the actual array..</p> <p>could someone help me to sort it out</p> <pre><code>Resource = [] for x in df['Categor...
<pre><code> Resource = [] for i, x in enumerate(df['Category']): y = df['Service_Line'][ i ] if x=='low space'and y=='Intel': Resource.append('Rhythm') elif x=='log space' and y=='Intel': Resource.append('Blue') elif x=='CPU usage' and y=='Intel': Resource.append('Jazz') ...
python|pandas
0
1,446
49,053,080
Python Pandas Don't Repeat Item Labels
<p>I have a table: <a href="https://i.stack.imgur.com/ZP6Gx.png" rel="nofollow noreferrer">Table</a></p> <p>How would I roll up Group, so that the group numbers don't repeat? I don't want to pd.df.groupby, as I don't want to summarize the other columns. I just want to not repeat item labels, sort of like an Excel pivo...
<p>In your dataframe it appears that 'Group' is in the index, the purpose of the index is to label each row. Therefore, is unusual and uncommon to have blank row indexes.</p> <p>You you could so this:</p> <pre><code>df2.reset_index().set_index('Group', append=True).swaplevel(0,1,axis=0) </code></pre> <p>Or if you r...
python|pandas
0
1,447
58,607,480
In tensorflow V.2 Astroid error during TensorFlow installation and AttributeError: module tensorflow has no attribute Session
<p>anaconda3.7버전을 다운받고 tensorfow gpu버전을 다운 받았습니다(그 전에 CUDA v.10,cuDNN도 다운 받았어요.)</p> <p>그런데 tensorflow설치 과정에서 에러가 하나 발생했네요.</p> <pre><code>ERROR: astroid 2.3.1 requires typed-ast&lt;1.5,&gt;=1.4.0; implementation_name == "cpython" and python_version &lt; "3.8", which is not installed. </code></pre> <p>위 문제가 중요한가요? 중...
<p>In tf2, get get session with the compatible interface.</p> <pre><code>sess = tf.compat.v1.Session() </code></pre>
tensorflow
0
1,448
58,714,618
Numba Invalid use of BoundFunction on np.astype
<p>I'm trying to compile a function that does some computation on an image patch using numba. Here is part of the code:</p> <pre><code>@jit(nopython=True, parallel=True) def value_at_patch(img, coords, imgsize, patch_radius): x_center = coords[0]; y_center = coords[1]; r = patch_radius s = 2*r+1 xvec =...
<p>Use <code>np.int64</code> in place of <code>int</code> in following places:</p> <pre><code>xvec = xvec.astype(np.int64) yvec = yvec.astype(np.int64) </code></pre>
python-3.x|numpy|jit|numba
6
1,449
59,006,469
What does ":" do in Python
<p>I was trying to the understand basic Tensorflow functions in <code>cifar10.py</code> keras lib, function <code>load_batch</code>:</p> <pre><code>for i in range(1, 6): fpath = os.path.join(path, 'data_batch_' + str(i)) (x_train[(i - 1) * 10000:i * 10000, :, :, :], y_train[(i - 1) * 10000:i * 10000]) = ...
<p>The <code>x_train</code> etc are numpy array or similar structure which implement their interface. Here you can read about slicing in numpy <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a></p> <p>...
python|tensorflow
1
1,450
58,716,539
How can I create a pandas data frame in a certain way?
<p>I need to create a pandas dataframe that contains all of the required information where each row of the dataframe should be one track. I also need to sort the dataframe by popularity score, so that the most popular track is at the top and the least popular is at the bottom. I tried many ways but they did not work. Y...
<p>There are definitely more efficient ways, but here's a solution</p> <pre><code>import pandas as pd def gen_artist_frame(d): categories = [c for c in d.keys()] for idx, artist in enumerate(d['Artist name']): artist_mat = [d[j][idx] for j in categories[1:]] artist_frame = pd.DataFrame(arti...
python|pandas|nested-loops
0
1,451
70,144,331
TypeError: Expected float32, but got auto of type 'str'. Tensorflow error , tell me how to fix it?
<p>I got <em><strong>TypeError: Expected float32, but got auto of type 'str'.</strong></em> error while fitting the sequential model. I checked my inputs both are numpy.ndarray.</p> <pre><code>type(xtrain),type(ytrain) (numpy.ndarray, numpy.ndarray) model = tf.keras.Sequential() model.add(tf.keras.layers.Flatten(inpu...
<p>The error may be in this part of the code:</p> <pre><code>model.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy,optimizer = tf.keras.optimizers.Adam(learning_rate=.0001),metrics = ['accuracy']) </code></pre> <p>Try changing the loss parameter from <code>tf.keras.losses.SparseCategoricalCrossentropy</cod...
python|tensorflow|deep-learning|typeerror|tensorflow2.0
2
1,452
70,133,911
How to extract a word and its next 2 digit?
<p>I have this pandas dataframe</p> <p><a href="https://i.stack.imgur.com/7hRKD.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I want to extract word id and nid and its next 2 digit from log column using python. The output should be like this:</p> <p><a href="https://i.stack.imgur.com/VbLr0.png"...
<p>Using <code>str.extract</code> we can try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;log&quot;] = df[&quot;log&quot;].str.extract(r'\b(n?id \d+)') </code></pre> <p>Here is a <a href="https://regex101.com/r/9XI3Zx/1" rel="nofollow noreferrer">regex demo</a>.</p>
python|python-3.x|pandas|dataframe
1
1,453
70,222,006
Need to use apply or broadcasting and masking to iterate over a DataFrame
<p>I have a data frame that I need to iterate over. I want to use either apply or broadcasting and masking. This is the pseudocode I am trying to improve upon.</p> <p>2 The algorithm Algorithm 1: The algorithm <em>initialize</em> the population (of size n) uniformly randomly, obeying the bounds; <strong>while</strong> ...
<p>I'm not sure I'm implementing your formula correctly, but hopefully this helps</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.uniform(-5.0, 10.0, size = (20, 5)), columns = list('ABCDE')) #while portion of pseudocode f_func = np.square(df).sum(axis=1) final_func = np.square(f_fun...
python|pandas|numpy|apply|array-broadcasting
0
1,454
70,273,929
Fix the color order in a plotly gantt chart
<p>Trying to plot a gantt chart using plotly and a pandas dataframe. The plot comes fine, except the colors are in a different order.</p> <p>Here is the dataframe</p> <pre><code> Goss got timestamp 16-01-21 10:00:09 M Item1 04-02-21 20:28:30 T Item2 06-02-21 00:45:57 ...
<p>You can update the colors after the figure is created.</p> <pre><code>cmap = {'T':'#FFFF00','G':'#A0522D','M':'#808000','D':'#008000','V':'#FF0000', 'K':'#00CED1',&quot;I&quot;:'#00FFFF'} gfig.for_each_trace(lambda t: t.update(fillcolor=cmap[t.name]) if t.name in cmap.keys() else t) </code></pre>
pandas|plotly-python|gantt-chart
0
1,455
70,257,040
pandas dataframe columns to a single cell
<p>I have the dataframe:</p> <pre><code>df = A B l1 l2 l3 1 1 2 3 4 1 1 3 5 7 1 1 1 2 9 1 2 2 7 8 </code></pre> <p>I want to groupby A,B , per columns, and put the values as a series in a cell. So the output will be:</p> <pre><code>df = A B l1 l2 l3 1 1 2,3,1 3,5,2 4,7,...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with lambda function with cast to strings and <code>join</code>:</p> <pre><code>df1 = df.groupby(['A','B']).agg(lambda x: ','.join(x.astype(str))).reset_...
python|pandas|dataframe|pandas-groupby
3
1,456
56,433,820
How to groupby one column with 3 conditions in multiple columns
<p>I have dataframe, where i need to apply below condition</p> <ol> <li>Check if colA > 0</li> <li>If it is, search for string "recycled" in colB and compare if its present in colC</li> <li>If it satisfies, its true else false</li> </ol> <p>dataframe:</p> <pre><code> Temp colA colB colC ...
<p>Try using Rank function</p> <pre><code>data['Rank'] = data.groupby('Temp')['output'].rank(method='dense',ascending=True) data['Final'] = data.groupby('Temp')['Rank'].rank(method='first',ascending=True) </code></pre>
python-3.x|string|dataframe|pandas-groupby
1
1,457
56,380,114
Python Loop, Need to / Can't Retain Value from Original Dataframe
<p>I'm attempting to loop through groups of phrases to match and score them among all the members in each group. Even if some of the phrases are the same, they may have different Codes which is what I'm trimming from the loop inputs - but need to retain in the final <code>df2</code>. I have to make the comparison in th...
<p>In case anyone else runs into a similar issue - figured it out - instead of filtering the inputs at the beginning of the second level loop, I'm bringing the full value into the second loop and stripping it there:</p> <pre><code>a2 = a[6:] b2 = b[6:] </code></pre> <p>So:</p> <pre><code>import pandas as pd from fuz...
python|pandas|loops|dataframe
0
1,458
55,835,671
How to Perform a Complicated Join in Pandas with Interaction Terms from Statsmodel output
<p>This is an extension of this quetion: <a href="https://stackoverflow.com/questions/55767468/to-join-complicated-pandas-tables/55770736?noredirect=1#comment98224838_55770736">To join complicated pandas tables</a></p> <p>I have three different interactions in a <code>statsmodels</code> GLM. I need a final table that...
<pre><code>df = {'variable': ['CLded_model','CLded_model','CLded_model','CLded_model','CLded_model','CLded_model','CLded_model','married_age','married_age','married_age'], 'level': [0,100,200,250,500,750,1000, 'M_60', 'M_61', 'S_62'], 'value': [460955.7793,955735.0532,586308.4028,12216916.67,48401773.87,147...
python-3.x|pandas|join|data-manipulation
1
1,459
56,004,287
Loaded keras model in flask always predict same class
<p>Weird thing is happening to me. I trained a sentiment analysis model using keras as follows: </p> <pre><code>max_fatures = 2000 tokenizer = Tokenizer(num_words=max_fatures, split=' ') tokenizer.fit_on_texts(data) X = tokenizer.texts_to_sequences(data) X = pad_sequences(X) with open('tokenizer.pkl', 'wb') as fid: ...
<p>You are saving the model architecture but not it's weights!</p> <p>Given that you are using Keras and its tokenizer, I have found that the best way to load and reuse your models is to use the json representation for the architecture and the tokenizer and save the weights with h5:</p> <pre><code>def save(model): ...
python|tensorflow|machine-learning|flask|keras
0
1,460
55,870,502
TensorFlow function to check whether a value is in given range?
<p>I know there is <code>tf.greater(x,y)</code> which will return true if x > y (element-wise). Is there a function that returns true if lower_bound &lt; x &lt; upper_bound (element-wise) for a tensor x?</p>
<p>There's not a specific function for that, but you can use a combination of <code>tf.greater</code>, <code>tf.less</code>, and <code>tf.logical_and</code> to get the same result.</p> <pre><code>lower_tensor = tf.greater(x, lower) upper_tensor = tf.less(x, upper) in_range = tf.logical_and(lower_tensor, upper_tensor) ...
python|tensorflow
3
1,461
55,673,302
Convert pandas column of lists into matrix representation (One Hot Encoding)
<p>I have a pandas column with lists of values of varying length like so:</p> <pre><code> idx lists 0 [1,3,4,5] 1 [2] 2 [3,5] 3 [2,3,5] </code></pre> <p>I'd like to convert them into a matrix format where each possible value represents a column and each row populates a 1 if the value exists and 0 ot...
<p>If performance is important use <code>MultiLabelBinarizer</code>:</p> <pre><code>test_hot = pd.Series([[1,2,3],[3,4,5],[1,6]]) from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df = pd.DataFrame(mlb.fit_transform(test_hot),columns=mlb.classes_) print (df) 1 2 3 4 5 6 0 1 ...
python|pandas|list
3
1,462
64,955,021
How can I add info from one row to another row multiple times before a specific word?
<p>Suppose I have a table as following:</p> <pre><code>ID Description 1 code: xyz; code:axy 2 code: 238a; code: 34u; code: 482m 3 code: 24sd 4 code: 3edn; code: 3n23 </code></pre> <p>And I want the following table:</p> <pre><code>ID Description 1 co...
<p>You could try (I'm assuming your DataFrame is named <code>fhand</code>, as in your code example):</p> <pre><code>fhand['Description'] = fhand['Description'].str.split(';') fhand = fhand.explode('Description') </code></pre> <p><strong>EDIT</strong>: You might want to add an <code>lstrip</code> afterwards:</p> <pre><c...
python|pandas|database|csv|python-re
1
1,463
64,634,902
Best Loss Function for Multi-Class Multi-Target Classification Problem
<p>I have a classification problem and I don't know how to categorize this classification problem. As per my understanding,</p> <blockquote> <p>A Multiclass classification problem is where you have multiple mutually exclusive classes and each data point in the dataset can only be labelled by one class. For example, in ...
<blockquote> <p>What Loss function (preferably in PyTorch) can I use for training the model to optimize for the One-Hot encoded output</p> </blockquote> <p>You can use <a href="https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html#torch.nn.BCEWithLogitsLoss" rel="nofollow noreferrer">torch.nn.BCEWit...
pytorch|classification|multilabel-classification|multiclass-classification
4
1,464
64,991,547
Compute and broadcast a count in pandas (with groupby transform)
<p>How can I compute and broadcast a count in pandas?</p> <p>To compute a count:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('field').size() </code></pre> <p>To broadcast an aggregation to the original dataframe:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('field')['field_to_aggreg...
<p>You could try:</p> <pre><code>result = df.groupby('field')['field_to_aggregate'].transform('size') </code></pre> <p>Note that <code>'field_to_aggregate'</code> can be the same as <code>'field'</code>.</p>
python|pandas|aggregation|split-apply-combine
1
1,465
64,752,451
How to count number of characters in string for the column values and group rows by count of those as a result using pandas?
<p>I have .csv file with column name:</p> <pre><code>id name 1 sample1 2 sample3 3 sample four 4 sample.five 5 sample.six.com </code></pre> <p>I need to print result as below (ordered by number of rows descending):</p> <pre><code>chars(str_len_count) rows(id_count) 7 2 1...
<p>First new column is not necessary, you can pass <code>str.len</code> to <code>groupby</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> for count:</p> <pre><code>df1 = df.groupby(df['name']....
python|pandas
1
1,466
64,648,964
Get number of elements of array satisfying a list of conditionsin Python/Numpy
<p>I have two arrays of the same size N, <code>array1</code> and <code>array2</code>. You can essentially think of it as a single array with shape (N,2). The entries are all numbers. I have a list of conditions and I want to see how many entries satisfy all these conditions, ideally using vectorization. For example, th...
<p>You could do the following:</p> <pre><code>x = np.array(array1&gt;2) y = np.array(array1&lt;5) z = np.array(x == y) sum(z) </code></pre>
python|arrays|numpy|vectorization
0
1,467
40,275,756
How can I add a extra roll of each columns' mean?
<p>When I was using <code>df['mean'] = df.mean(axis = 1)</code>, it always added an extra COLUMN of average of each rows. But now I need an extra ROW to get each COLUMNS' mean. So I switch to <code>df['mean'] = df.mean(axis = 0)</code> but it still has an extra column but with all NaN. How can I get the row of each col...
<p>IIUC</p> <pre><code>df = pd.DataFrame(np.arange(16).reshape(-1, 4), list('abcd'), list('ABCD')) df.loc['mean', :] = df.mean(0) df.loc[:, 'Mean'] = df.mean(1) df.loc['mean', 'Mean'] = np.nan df </code></pre> <p><a href="https://i.stack.imgur.com/SRRwZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/SRRwZ....
python|python-2.7|python-3.x|pandas|dataframe
1
1,468
44,355,229
Can I use `tf.nn.dropout` to implement DropConnect?
<p>I (think) that I grasp the basics of DropOut and the <a href="https://stackoverflow.com/a/34597667/656912">use of the TensorFlow API in implementing it</a>. But the normalization that's linked to the dropout probability in <code>tf.nn.dropout</code> seems not to be a part of <a href="http://cs.nyu.edu/%7Ewanli/dropc...
<h1>Answer</h1> <p>Yes, you can use <strong>tf.nn.dropout</strong> to do <strong>DropConnect</strong>, just use <strong>tf.nn.dropout</strong> to wrap your weight matrix instead of your post matrix multiplication. You can then <em>undo</em> the weight change by multiplying by the dropout like so</p> <pre><code>dropC...
machine-learning|tensorflow|neural-network
10
1,469
44,213,626
How to get substring in panda data frame when certain characters exist in the row?
<p>I have a data frame where certain rows contains a special character '#'. </p> <p>Here's my data and I can find the index positions of '#' : </p> <pre><code>import pandas as pd df = pd.DataFrame(data=['fig#abc', 'strawberry', 'applepie#efg'], columns=['fruitname']) ind= df.fruitname.str.find("#") df['col1'].str.fin...
<pre><code>#use apply to split fruitname and then check the length before setting the new fruitname column. df['fruitname_new'] = df.apply(lambda x: x.fruitname if len(x.fruitname.split('#')[0])&lt;=4 else x.fruitname.split('#')[0], axis=1) df Out[484]: fruitname fruitname_new 0 fig#abc fig#abc 1 ...
python-2.7|pandas|dataframe|substring
0
1,470
69,631,477
How do you groupby with pandas that sums values in the same column but is offset by a set number of rows
<p>I have a table that looks like the table below. I want to group by id, start_time, and approach so I can add the right, thru, left, and u-turn for each similar timestamp.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">intersection_id</th> <th style="text-align:...
<p>You could use:</p> <pre><code>df['volume'] = (df.groupby(['intersection_id', 'start_time', 'approach']) ['volume'].transform('sum') .where(df['movement'].eq('Right')) ) </code></pre> <p>output:</p> <pre><code> intersection_id start_time approach movement ...
python|pandas|group-by
3
1,471
69,506,993
Json to excel using python
<p>Json code:Below we have json data format which I am pulling from site using API</p> <pre class="lang-py prettyprint-override"><code>response={ &quot;result&quot;: [ { &quot;id&quot;: &quot;1000&quot;, &quot;title&quot;: &quot;Fishing Team View&quot;, &quot;sharedWithOrgani...
<p>Try:</p> <pre><code>df = pd.Series(response).explode().apply(pd.Series).reset_index(drop=True) df = df.join(df['filters'].explode().apply(pd.Series)).drop(columns=['filters']) df['sharedWithUsers'] = df['sharedWithUsers'].str.join('|') </code></pre> <p>Output:</p> <pre><code> id title sharedWithOrg...
python|python-3.x|excel|pandas|dataframe
2
1,472
69,297,998
How can I delete rows from dictionaries using pandas
<p>If I have a data set like this one.</p> <pre><code>date PCP1 PCP2 PCP3 PCP4 1/1/1985 0 -99 -99 -99 1/2/1985 0 -99 -99 -99 1/3/1985 0 0 -99 -99 1/4/1985 0 0 -99 -99 1/5/1985 1 -99 1 1 1/6/1985 0 -99 -99 -99 1/7/1985 0 1 -99 0 1/8/1985 0 2 -99 3 1/9/1985 ...
<p>You can create in dictioanry comrehension DataFrames:</p> <pre><code>d = {k: v[v != -99].reset_index() for k,v in df.set_index('date').to_dict('series').items()} </code></pre> <p>Create variables by name is not <a href="https://stackoverflow.com/a/30638956">recommended</a>, but possible:</p> <pre><code>for i, (k, v)...
python|pandas|dataframe|for-loop
1
1,473
41,066,853
Tensorflow - How to manipulate Saver
<p>I am working with the Boston housing data tutorial for tensorflow, but am inserting my own data set:</p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) COL...
<p>The <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/contrib.learn.html#DNNRegressor" rel="nofollow noreferrer"><code>tf.contrib.learn.DNNRegressor</code></a> initializer takes a <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/contrib.learn.html#RunConfig" rel="nofollow noreferre...
tensorflow
0
1,474
40,909,024
how to output the states of lstm gates in tensorflow?
<p>I want to see the activation states of lstm gates, but it seems that it is not easy to get the gates states and output them to a file. <br></p> <p>I can use "tf.Print" function like following in BasicLSTM:<br> <code>gate = tf.Print(gate, [sigmoid(gate)])</code> <br>But "tf.Print" displays this gate in terminal like...
<p><a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/control_flow_ops.html#Print" rel="nofollow noreferrer">tf.Print</a> supports a special parameter "summarize" to control the number of printed elements: E.g. you can use</p> <pre><code>tf.Print(gate, [sigmoid(gate)], summarize=10000000) </code></pre...
tensorflow|recurrent-neural-network|lstm
0
1,475
54,103,661
Identify pandas column that contains None value
<p>I have a geopandas dataframe <code>gdf</code> that looks like the following:</p> <pre><code> Id text float geometry 0 0 1.65 0.00 POINT (1173731.7407 5354616.9386) 1 0 None 2.20 POINT (1114084.319 5337803.2708) 2 0 2.25 6.55 POINT (1118876.2311 5307167.5724) 3 0 ...
<pre><code>print(gdf.isna().any()) </code></pre> <p>will give output which column contains null in terms of <code>true</code> or <code>false</code></p> <pre><code>Id False text True float False geometry False </code></pre> <hr> <p>So use this</p> <pre><code>print(gdf.columns[gdf.isna().any()].tolist()...
python|pandas|nonetype|geopandas
1
1,476
53,836,882
write an array to the next column in a CSV file
<pre><code>landData = [] landData = pd.read_csv('Agriculture land area.csv') landData = landData.drop(landData.columns[[0]], axis=1) </code></pre> <p>I currently have a CSV file that only have 1 column:</p> <p><img src="https://i.stack.imgur.com/IiElU.png" alt="only the first column is filled with years">\</p> <p>I ...
<p>You might convert the landData DataFrame (read by read_csv) to a Series, then making that Series the column of the other DataFrame. </p> <pre><code>landData = pd.read_csv('Agriculture land area.csv') landData = landData.drop(landData.columns[[0]], axis=1) landData_Series = landData.loc[:,landData.columns.values[0]...
python|pandas|csv|data-science
0
1,477
66,130,516
Pandas: select column with the highest percentage from a frequency table
<p>Hi I have a dataframe that I'd like to select the column with the highest percentage from a frequency table.</p> <pre><code>d = {'c1':['a', 'a', 'b', 'b', 'c', 'c'], 'c2':['Low', 'High', 'Low', 'High', 'High', 'High']} dd = pd.DataFrame(data=d) dd.groupby('c1')['c2'].value_counts(normalize=True).mul(100) </code></pr...
<p>Lets try reset_index and drop level=1 and then find the maximum index using idxmax</p> <pre><code>dd.groupby('c1')['c2'].value_counts(normalize=True).mul(100).reset_index(level=1, drop=True).idxmax() </code></pre>
pandas
4
1,478
52,797,062
'Tensor' object has no attribute '_keras_history' Keras with no Tensorflow tensor
<p>This code:</p> <pre><code>a = Input(ish) for i in range(a.shape[1]): x=Conv2D(filters=50, kernel_size=3, padding='same', activation=rl)(a[:,i]) x=MaxPooling2D(pool_size=2)(x) x=Dropout(0.5)(x) x=Conv2D(filters=100, kernel_size=5, padding='same', activation=rl)(x) x=MaxPooling2D(pool_size=2)(x) x=Dropout...
<p>You have to do the indexing inside a Lambda layer, in order to keep the Keras metadata:</p> <pre><code>a = Input(ish) for i in range(a.shape[1]): x=Lambda(lambda x: x[:, i])(a) x=Conv2D(filters=50, kernel_size=3, padding='same', activation=rl)(x) x=MaxPooling2D(pool_size=2)(x) x=Dropout(0.5)(x) x=Conv2D(f...
python|tensorflow|keras|deep-learning
1
1,479
52,731,563
Vectorising a loop based on the order of values in a series
<p>This question is based on a <a href="https://stackoverflow.com/questions/52730234/descending-filtering-for-dataframe">previous question</a> I answered.</p> <p>The input looks like:</p> <pre><code>Index Results Price 0 Buy 10 1 Sell 11 2 Buy 12 3 Neutral 13 4 Buy ...
<p>By using <code>cumcount</code> to find the pair:</p> <pre><code>s=df.groupby('Results').cumcount() df['Diff']=df.Price.groupby(s).diff().loc[df.Results.isin(['Buy','Sell'])] df Out[596]: Index Results Price Diff 0 0 Buy 10 NaN 1 1 Sell 11 1.0 2 2 Buy 12 NaN 3 ...
python|pandas|performance|numpy|dataframe
4
1,480
52,737,258
how can we merge csv as column side by side using python pandas?
<p>If I have three CSV files:</p> <p>file1.csv<br> file2.csv<br> file3.csv</p> <p>Each CSV file has a first column (A) containing values as below: </p> <p>file1.csv </p> <pre><code>A asd zxc qwe </code></pre> <p>file2.csv </p> <pre><code>A iop jkl bnm </code></pre> <p>file3.csv </p> <pre><code...
<pre><code># Read files data_1 = pd.read_csv(file1.csv) data_2 = pd.read_csv(file2.csv) data_3 = pd.read_csv(file3.csv) # Assuming the name A for the first column of each csv is not a typo data_2.rename(columns={'A': 'B'}) data_3.rename(columns={'A': 'C'}) # Order columns new_columns = [] for i in range(len(dat...
python|pandas
1
1,481
52,584,035
Keyerror when adding a column to a Dataframe (Pandas)
<p>Pandas DataFrame is not really accepting adding a second column, and I cannot really troubleshoot the issue. I am trying to display Moving Averages. The code works fine just for the first one (MA_9), and gives me error as soon I try to add additional MA (MA_20).</p> <p>Is it not possible in this case to add more th...
<p>Please update your code as below and then it should work:</p> <pre><code>google_close['MA_9'] = google_close.Close.rolling(9).mean() google_close['MA_20'] = google_close.Close.rolling(20).mean() </code></pre> <p>Initially there was only one column data of Close so your old code <code>google_close['MA_9'] = google_...
python-3.x|pandas|dataframe|matplotlib
3
1,482
46,434,765
kernel dies when performing optimization with scikit
<p>I'm performing some optimization with scikit on machine learning problem working with 75 mb file that has 42k rows and 784 columns containg numbers. Working on jupyter notebook.</p> <p>But kernel dies when I run the code. The same working with terminal.</p> <p>Is there any way to handle this problem?</p> <p>def t...
<p>I ran into the same issue, my research tell me that it's a memory outage.</p> <p>A lot of people on <a href="https://stackoverflow.com/questions/32573948/ipython-notebook-kernel-getting-dead-while-running-kmeans">stackoverflow and github</a> of recommend using a <code>.py</code> script instead of a jupyter notebook...
numpy|machine-learning|jupyter-notebook
0
1,483
58,480,223
How to read a list from an excel cell
<p>I put a list into an excel cell, and when I read it with pandas, it did not return me a list, it returned me a string, is there anyway I can get a list in return instead?</p> <p>eg. in the cell: ['a', 'b', 'c'] output from pandas: '['a', 'b', 'c']'</p> <p>here is my code:</p> <pre><code>df = pd.read_excel('exampl...
<p>In excel are lists converted to string repr of lists.</p> <pre><code>df = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,['a', 'b', 'c']], 'E':[5,3,6,9,2,4], 'F':list('aaabbb') }) print(df.iloc[5, 3]) ['a', 'b', 'c'] df....
python|excel|string|pandas|list
3
1,484
58,473,700
is there a way to combine multiple columns with comma separated
<p>I have a dataframe with 1 million+ records and I am looking to combine two columns to one row with a separator, anyone help me how to do it ?</p> <pre><code>def chunk_results(df): n =0 for i in range(len(df)): data_frame = df.iloc[n:n+5] # code for combie n=n+5 My Dataframe: ID Val...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> whatever the rows you want and just aggregate them</p> <pre><code>chunksize = 5 df.astype(str).groupby(df.index // chunksize).agg(','.join) </code></pre> <p><strong>...
python-3.x|pandas
2
1,485
68,967,904
Suppression tool help. Need to know how to not delete a row if it is empty
<p>So in my code I am deleting duplicates. The problem is some of my data has no entry's. because it deletes duplicates the ones with no entrys get deleted. The problem with this is I am running millions of entrys so I couldnt just go in and add a fake entry to the data. I need a line of code that will ignore the blank...
<p>You could filter empty rows, drop duplicates and after concat both.</p> <pre><code>df = pd.DataFrame({'col1': ['1','1 2','2 3','3 4','','5','5 6','','1','1 2','2']}) dfempty = df.loc[df.col1 == &quot;&quot;] df2 = df.loc[df.col1 != &quot;&quot;].drop_duplicates() pd.concat([dfempty, df2]).sort_index() col1 0 ...
python|arrays|pandas|sql-delete|suppression
0
1,486
68,970,873
How do i concat csv files to end up with the one csv file with stacked data using pandas
<p>I want to concat csv files on top of each other vertically/stacked and save that to a new csv. The testing.csv file should just have the 2 csv files data stacked. The images below show the original csv files for both msft and adbe, but once concat is used, it comes out with one horizontal line of data. How to do thi...
<pre class="lang-py prettyprint-override"><code>import pandas as pd csv_files = ['path/to/file1.csv', 'path/to/file2.csv'] concat_csvs = [] for filename in csv_files: df = pd.read_csv(filename, index_col=None, header=0) concat_csvs.append(df) frame = pd.concat(concat_csvs, axis=0, ignore_index=True) frame.to...
python|pandas|csv|merge|concatenation
0
1,487
69,063,716
In python pandas, How to apply loop to create rows for multiple columns?
<pre><code>import pandas as pd import numpy as np column_names = [str(x) for x in range(1,4)] df= pd.DataFrame ( columns = column_names ) new_row = [] for i in range(3): new_row.append(i) df = df.append(new_row , ignore_index = True) print(df) </code></pre> <hr /> <p>output:</p> <pre><code> 1 2 ...
<p>I know it's weird but you can use <code>.loc</code> to do that:</p> <pre><code>df.loc[len(df.index)+1] = new_row </code></pre> <pre><code>&gt;&gt;&gt; df 1 2 3 1 0 1 2 </code></pre>
python|pandas|dataframe
0
1,488
61,104,122
Converting long dataframe and extracting string
<p>Hi I have Dataframe like this:</p> <pre><code> Date A_2002 B_2003 C_2004 D_2005 Type 03-2002 20 30 12 42 X 04-2002 12 321 12 23 X 03-2002 10 31 2 3 Y </code></pre> <p>I want to convert it to long version and extract the string type from it so the end result...
<p>you can do <code>stack</code> after <code>set_index</code> and <code>str.split</code>:</p> <pre><code>m = df.set_index(['Date','Type']) m.columns = m.columns.str.split('_',expand=True) out = (m.stack([0,1]).rename('Value').reset_index() .rename(columns={'level_2':'NewCol','level_3':'Extracted'})) </code></pre>...
python|pandas|dataframe
5
1,489
60,891,442
Pandas dataframe problem. Create column where a row cell gets the value of another row cell
<p>I have this pandas dataframe. It is sorted by the "h" column. What I want is to add two new columns where: The items of each zone, will have a max boundary and a min boundary. (They will be the same for every item in the zone). The max boundary will be the minimum "h" value of the previous zone, and the min boundary...
<p>First group-by zone and find the minimum and maximum of them</p> <pre><code>min_max_zone = df.groupby('zone').agg(min=('h', 'min'), max=('h', 'max')) </code></pre> <p>Now you can use apply:</p> <pre><code>df['maxB'] = df['zone'].apply(lambda x: min_max_zone.loc[x-1, 'min'] if x-1 i...
python|pandas|loops|dataframe|operation
2
1,490
61,038,783
pd.read_csv has issues with differing number of columns between csv files
<p>I have number of csv files that have differing numbers of columns.<br/> Majority of the csv files are 4 columns wide and gets read and concatenated.<br/> However, when it encounters files that exceeds 4 columns the script errors out.<br/></p> <p>I get the following error message:<br/><code>Error tokenizing data. C...
<p>The issue here is with pandas.concat, not pandas.read_csv. The concat function does not allow you to concatenate DataFrame objects with differing number of columns.</p> <p>The only way I can think of solving this is to find out the DataFrames that have lesser number of columns (than the DataFrame with max number of...
python|pandas|csv|concatenation
0
1,491
61,041,820
Plotting latitude / longitude from Excel spreadsheet using Cartopy
<p>Trying to plot a survey transect on a map using Cartopy, a library seriously lacking in online information compared to others. My lat/long data is in two seperate columns of an Excel spreadsheet.</p> <p>I have managed to build a basemap, and my script for that is as follows:</p> <pre><code>import cartopy.feature a...
<p>I'm not sure what you mean exactly as plot them as transects, but you can plot lon/lat lines in CartoPy with:</p> <pre><code>ax.plot(df_lon, df_lat, linestyle='-', color='orange', transform=ccrs.PlateCarree()) </code></pre>
python|pandas|mapping|gis|cartopy
1
1,492
42,367,281
Tensorflow Android : retrained Inception v3 take too much time
<p>I have retrained the Inception-V3 final layer with my own 20 categories. When I am using retrained model in android demo app it takes 6 to 8 seconds to predict.</p> <p>Running on</p> <ul> <li>LG G4 Stylus -&gt; 6-8 sec</li> <li>S6, -&gt; 3-4.5 sec</li> </ul> <p>I have done <code>optimize_for_inference</code> it t...
<p>Comparing your debug output to the normal TF Classify app on my phone I see that you have a much larger node count which would suggest that, for some reason, your graph is a lot larger than it should be. I'm not too familiar with the quantize method but it looks like you have more conv2D layers than normal as well.<...
android|tensorflow
0
1,493
42,495,155
Two pandas MultiIndex frames multiply every row with every row
<p>I need to multiply two MultiIndexed frames (say <code>df1, df2</code>) that have the same highest level index, such that for each of the highest level index each row of <code>df1</code> is multiplied to each row of <code>df2</code> elementwise. I have implemented the following example that does what I want, however ...
<p>I created the following solution that seems to work and provide the right outcome. While Stephen's answer remains the fastest solution, this is close enough but provides a big advantage, it works for arbitrary MultiIndexed frames, as opposed to the ones where the index is a product of lists. This was the case I need...
python|python-3.x|pandas|numpy|multi-index
2
1,494
69,799,699
Substract Two Dataframes by Index and Keep String Columns
<p>I would like to subtract two data frames by indexes:</p> <pre><code> # importing pandas as pd import pandas as pd # Creating the second dataframe df1 = pd.DataFrame({&quot;Type&quot;:['T1', 'T2', 'T3', 'T4', 'T5'], &quot;A&quot;:[10, 11, 7, 8, 5], &quot;B&quot;:[21, 5, 32, 4,...
<p>You could handle NaN using:</p> <pre><code>df1.subtract(df2).combine_first(df1).dropna(how='all') </code></pre> <p>output:</p> <pre><code> A B C D Type 2001 10.0 21.0 11.0 1.0 T1 2002 9.0 3.0 19.0 2.0 T2 2003 5.0 28.0 16.0 1.0 T3 2004 6.0 1.0 4.0 7.0 T4 2005 5.0 6...
python|pandas
2
1,495
69,897,567
Numpy numbers arent integers?
<p>Can someone explain why some Numpy numbers aren't whole integers? When I run this:</p> <pre><code>print(np.sqrt(2.)**2) </code></pre> <p>I get:</p> <pre><code> 2.0000000000000004 </code></pre> <p>And why is it that I get</p> <pre><code>[ 0. 1.11111111 2.22222222 3.33333333 4.44444444 5.55555556 6.6666...
<p>From numpy's documentation:</p> <pre><code> dtype : dtype, optional The type of the output array. If `dtype` is not given, the data type is inferred from `start` and `stop`. The inferred dtype will never be an integer; `float` is chosen even if the arguments would produce an array...
python|numpy
2
1,496
43,195,133
Are there packages to register/identify schemas for a Pandas data analysis workflow?
<p>I'm using Pandas to automate analysis of a variety of different <em>3rd party reports</em>. Most are in <code>csv</code> format. </p> <p>Assuming only correct files are loaded into the program, I need to:</p> <ul> <li>identify the origin of the report (3rd party), based on <ul> <li>schema</li> <li>predictable col...
<p>I've taken a first pass solution which I'll offer as answer. I've implemented a class-based solution with <code>defaultdict</code>. Here's the basic outline:</p> <ul> <li><a href="https://martinfowler.com/eaaCatalog/registry.html" rel="nofollow noreferrer">Register</a> class oop structure to handle and access <stro...
pandas|schema|workflow
0
1,497
43,067,338
Tensor multiplication in Tensorflow
<p>I am trying to carry out tensor multiplication in NumPy/Tensorflow.</p> <p>I have 3 tensors- <code>A (M X h), B (h X N X s), C (s X T)</code>. </p> <p>I believe that <code>A X B X C</code> should produce a tensor <code>D (M X N X T)</code>.</p> <p>Here's the code (using both numpy and tensorflow).</p> <pre><code...
<p>Try</p> <pre><code>tf.tensordot(A_tf, B_tf,axes = [[1], [0]]) </code></pre> <p>For example:</p> <pre><code>x=tf.tensordot(A_tf, B_tf,axes = [[1], [0]]) x.get_shape() TensorShape([Dimension(5), Dimension(2), Dimension(3)]) </code></pre> <p>Here is <a href="https://www.tensorflow.org/api_docs/python/tf/tensordot" ...
python|numpy|matrix|tensorflow|matrix-multiplication
8
1,498
72,452,858
Displaying data from summarization dataset in TensorFlow (using TensorFlow datasets)
<p>I'm new to Machine Learning and a newbie when it comes to utilizing the TensorFlow Module in Python.</p> <p>I'm currently working with summarization and the dataset library in TensorFlow has many convenient datasets available for training the summarizers. However, I wanted to take a look at their contents before cho...
<p>That is the source code for the Opinosis dataset. You don't need to copy it over to your code. <a href="https://www.tensorflow.org/datasets/overview" rel="nofollow noreferrer">This</a> should give you a good idea of how to use tensorflow datasets. Opinosis doesn't make much sense displayed as a table, so to get an i...
python|tensorflow|tensorflow-datasets|summarization
1
1,499
72,443,457
Pandas - dataframe to BigQuery
<p>I have a df like the attached one:</p> <p><a href="https://i.stack.imgur.com/Kwm8X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kwm8X.png" alt="enter image description here" /></a></p> <p>I'd like to iter over this df and write data into bq, the table's schema is something like: |coicop|unit|ge...
<p>Use <code>df.melt</code>:</p> <pre><code>In [965]: df = df.melt(id_vars=['coicop', 'unit', 'geo\time'], var_name='period') In [966]: df Out[966]: coicop unit geo\time period value 0 CP03 I15 AT 2021M05 108.36 1 CP03 I15 BE 2021M05 106.66 2 CP03 I15 BG 2021M05 97.33 3 CP03 ...
python|pandas|dataframe|google-bigquery
0