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
370,100
51,051,745
Teradata - Pandas TypeError: 'NoneType' object is not iterable
<p>I am trying to run the following code to create a Teradata table using the teradata python library:</p> <pre><code>import teradata import pandas as pd udaExec = teradata.UdaExec (appName="Hello", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", system="tdprod", username="xxx", pass...
<p>Your SQL (sqlStr) is a DDL (CREATE Table) -> it will NOT deliver any Resultset that can be placed into the Pandas Dataframe (pd.read_sql).</p> <p>If you just want to create the table, you don't need pandas:</p> <pre><code>session.execute(sqlStr); </code></pre> <p>If you want to read from the table "TEST123":</p> ...
python|pandas|teradata
1
370,101
50,938,144
Resampling (upsampling, interpolating) a series of numbers
<p>I have a comma separated series of integer values that I'd like to resample so that I have twice as many, where a new value is added half way between each of the existing values. For example, if this is my source:</p> <pre><code>1,5,11,9,13,21 </code></pre> <p>the result would be:</p> <pre><code>1,3,5,8,11,10,9,1...
<p>Since the interpolation is simple, you can do it by hand:</p> <pre class="lang-python prettyprint-override"><code>import numpy as np a = np.array([1,5,11,9,13,21]) b = np.zeros(2*len(a)-1, dtype=np.uint32) b[0::2] = a b[1::2] = (a[:-1] + a[1:]) // 2 </code></pre> <p>You can also use <code>scipy.signal.resample</co...
python|pandas|numpy|interpolation|resampling
3
370,102
51,058,614
split list elements into sub-elements in pandas dataframe
<p>I have a dataframe as:-</p> <pre><code>Filtered_data ['defence possessed russia china','factors driving china modernise'] ['force bolster pentagon','strike capabilities pentagon congress detailing china'] [missiles warheads', 'deterrent face continued advances'] ...... ...... </code></pre> <p>I just want to split...
<p>Use list comprehension with <code>split</code> and flatenning:</p> <pre><code>df['Filtered_data'] = df['Filtered_data'].apply(lambda x: [z for y in x for z in y.split()]) print (df) Filtered_data 0 [defence, possessed, russia, china, factors, d... 1 [force, bolster, pentagon...
python|arrays|python-3.x|pandas
1
370,103
50,755,238
Merging list of list into a dataframe pandas
<p>I am trying to merge a list of list which consists of Date index as every list into a single dataframe on axis=1. Please find the code below:</p> <pre><code>d=[] for i in range(0,Alpha.shape[0]-1): d.append(pd.date_range(start=Alpha.iloc[i]['Month_year'], end=Alpha.iloc[i+1]['Month_year']-pd.DateOffset(days=1),...
<p>I think need <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>numpy.concatenate</code></a>:</p> <pre><code>df = pd.DataFrame(index=np.concatenate(d)) </code></pre>
python|pandas|numpy|datetime|merge
2
370,104
51,045,848
Improve pandas filter speed by storing indices?
<p>I have the following df:</p> <pre><code>df = pd.DataFrame({'ID1':[1,2,3,4,5,6],'ID2':[2,6,6,2,1,2],'AREA':[1,1,1,1,1,1]}) ... ID1 ID2 AREA 0 1 2 1 1 2 6 1 2 3 6 1 3 4 2 1 4 5 1 1 5 6 2 1 </code></pre> <p>I accumulate the AREA column as so:</p> <pre><code>for id_ in df.ID1:...
<p>One way to do it is like this:</p> <pre><code>df = df.set_index('ID1') for row in df.join(df.groupby('ID2')['AREA'].apply(lambda x: x.index.tolist()),rsuffix='_').dropna().itertuples(): df.loc[row[0],'AREA'] += df.loc[row[3],'AREA'].sum() df = df.reset_index() </code></pre> <p>and you get the result expected ...
python|postgresql|pandas|dataframe
1
370,105
50,723,072
Stop Tensorflow from reloading model per request
<p>I've inherited some TF code that does the following per request:</p> <pre><code>def predict_tf(ml_wrapper, prediction_row_df): log.debug('request POST {}'.format(prediction_row_df)) prediction_row_df, _, _ = ml_wrapper._engineer_features(prediction_row_df) # As method says; delete stuff we don't want a...
<p>If you're using <code>Estimator</code> then you can try this one: <a href="https://github.com/marcsto/rl/blob/master/src/fast_predict2.py" rel="nofollow noreferrer">https://github.com/marcsto/rl/blob/master/src/fast_predict2.py</a> This basically prevents reloading the graph.</p>
python|tensorflow|tensorflow-serving|tensorflow-estimator
0
370,106
50,971,123
converty numpy array of arrays to 2d array
<p>I have a pandas series <code>features</code> that has the following values (<code>features.values</code>)</p> <pre><code>array([array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), ..., array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), ar...
<p>In response your comment question, let's compare 2 ways of creating an array</p> <p>First make an array from a list of arrays (all same length):</p> <pre><code>In [302]: arr = np.array([np.arange(3), np.arange(1,4), np.arange(10,13)]) In [303]: arr Out[303]: array([[ 0, 1, 2], [ 1, 2, 3], [10, 1...
python|pandas|numpy|multidimensional-array
52
370,107
50,970,476
Comparing values from Pandas data frame column using offset values from another column
<p>I have a data frame as:</p> <pre><code>Time InvInstance 5 5 8 4 9 3 19 2 20 1 3 3 8 2 13 1 </code></pre> <p><code>Time</code> variable is sorted and <code>InvInstance</code> variable denotes the number of rows to the end of a <code>Time</code>...
<p>I don't see/know how to use internal vectorized Pandas/Numpy methods for shifting Series/Array using a <strong>non-scalar / vector</strong> step, but we can use <a href="https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html#using-numba" rel="nofollow noreferrer">Numba</a> here:</p> <pre><code>from numba i...
python|performance|pandas|dataframe
4
370,108
20,555,996
Can't Select A Cell In Pandas
<p>This is a simple noob question, but it is vexing me. Following a tutorial, I want to select the first value in column "A". The tutorial says run <code>print(df[0]['A'])</code> but Python3 gives me an error. However, it works perfectly if I use <code>print(df[0:1]['A'])</code>. Why is that?</p> <p>Here is the full c...
<p>See the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#slicing-ranges" rel="nofollow">selecting ranges</a> section of the docs. As mentioned:</p> <blockquote> <p>With DataFrame, slicing inside of <code>[]</code> slices the rows. This is provided largely as a convenience since it is such a comm...
python|python-3.x|pandas
3
370,109
20,522,785
Aggregating dataframe to give sum of elements and string of grouped indices
<p>I'm trying to use groupby to give me the sum or mean of a number of elements, and a string of the original row indices for each group. So for instance, the dataframe:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1,2,3],[1,3,4],[2,3,4],[2,5,6],[7,8,3],[11,12,13],[11,2,3]],index = ['p','q','r','s','t','u','v'],col...
<p>The way aggregation works is that you give a key and a value, where the key is a <strong>pre existing</strong> column name and the value is a function to map on the column.</p> <p>So to get the sums the way you want, you do the following:</p> <pre><code>&gt;&gt;&gt; grouped = df.groupby('a') &gt;&gt;&gt; grouped.a...
python|pandas
3
370,110
20,577,019
how to extract required dimension from a numpy array
<p>Given that I have a numpy array of three dimension [3,500,500], how can I extract one dimension as [1,500,500]?</p> <pre><code>import numpy as np my_array = np.ones((3,500,500),dtype=int,order='C') print (my_array) </code></pre>
<p>Those ones?</p> <pre><code>&gt;&gt;&gt; my_array[0,:,:] array([[1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1], ..., [1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1]]) &gt;&gt;&gt; my_array[0,:,:].shape (500, 500) </code></...
python|numpy
4
370,111
33,349,623
Exporting DataFrame Containing Lists To Excel
<p>So I am trying to export a Pandas DataFrame to an .xlsx file using the 'to_excel' method; I've scoured SO and not found any questions that seem to answer this completely. The problem is that individual elements within the dataframe are themselves lists, let me illustrate:</p> <p>Say we have the following dataframe:...
<p>Not sure about efficiently but a cleaner method is to call <code>apply</code> and pass <code>' ,',join</code> as the func to call:</p> <pre><code>In [75]: data = [[['a','b','c']],[['a']],[[]],[['a', 'b']],[['a']]] df = pd.DataFrame(data=data) df[0].apply(' ,'.join) Out[75]: 0 a ,b ,c 1 a 2 3...
python|excel|pandas|dataframe
1
370,112
33,370,982
Replacing minimum element in a numpy array subject to a condition
<p>I need to replace an element of a numpy array subject to the minimum of another numpy array verifying one condition. See the following minimal example:</p> <pre><code>arr = np.array([0, 1, 2, 3, 4]) label = np.array([0, 0, 1, 1, 2]) cond = (label == 1) label[cond][np.argmin(arr[cond])] = 3 </code></pre> <p>I would...
<p>You are triggering <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow"><code>NumPy's advanced indexing</code></a> with that <em>chaining of indexing</em>, so the assigning doesn't go through. To solve this, one way would be to store the indices corresponding to t...
python|arrays|numpy
2
370,113
33,509,478
Add new column elements to explicitly to existing row in Pandas DataFrame (Python 2)
<p>I'm trying to add columns to a row like in <a href="https://stackoverflow.com/questions/12555323/adding-new-column-to-existing-dataframe-in-python-pandas">Adding new column to existing DataFrame in Python pandas</a></p> <pre><code>I want to go from: a b c A 1 2 3 B -1 -2 -3 a b c d e f g A 1 2 ...
<p>If all you're wanting to do is add some random ints with some new columns then you can just do:</p> <pre><code>In [16]: pd.concat([DF, pd.DataFrame(columns=list('defg'), data=np.random.randint(0, 4,(2,4)), index=DF.index)], axis=1) Out[16]: a b c d e f g A 1 2 3 0 2 1 3 B -1 -2 -3 3 0 3 3 </cod...
python|pandas|append|dataframe|series
1
370,114
33,380,810
Elegant way to mask out intervals between events containing nan in numpy/pandas
<p>Suppose I have some data containing certain events and I want to measure the time between events. But sometimes I have nan values because there was no measurement. I don't want to include those intervals since I don't really know what happened there.</p> <p>For instance, given:</p> <pre><code>import numpy as np a ...
<p>Try simply</p> <pre><code>idx, = np.where(a==1) nanidx, = np.where(np.isnan(a)) intervals = np.diff(idx) good_intervals = np.delete(intervals, np.searchsorted(idx, nanidx)-1) </code></pre> <p>This simply looks up where the 1s are and where the <code>nan</code>s are, then deletes the intervals which contain <code>...
python|numpy|pandas
2
370,115
33,115,058
customized map function with multiple variable input in pyspark return wrong results
<p>As a part of my project, I am trying to implement parallelized normalization operation on a bulk of matrice by using a map function with the matrix to processed and vectors encapsulating min and max value of each dimension as input variables. The codes are listed below:</p> <pre><code>import numpy as np from functo...
<p>I run this code (python 2.7):</p> <pre><code>import numpy as np from functools import partial def cf(A,MinValues,MaxValues): #print "Result is " + str((A-MinValues)/(MaxValues-MinValues)) A=(A-MinValues)/(MaxValues-MinValues) return A AMatrix=np.matrix([[1,5,9],[4,8,3],[7,2,6]]) MinMatrix=np.matrix([...
python-3.x|numpy|matrix|parallel-processing|pyspark
0
370,116
33,106,396
Print format using NumPy in Python
<p>I want to create a 2d dimensional array in NumPy of size <code>128x2</code> and store in it long integers (each integer has 128-bit size). </p> <p><strong>CODE:</strong> </p> <pre><code>keys = np.zeros(shape=(128, 2)) for i in range(0, 128): key1 = random.randrange(1 &lt;&lt; 127, 1 &lt;&lt; 128) key2 = r...
<p>There are two issues you're having with your code.</p> <p>The first is that your using an inappropriate <code>dtype</code> for your array of long integers. The default <code>dtype</code> of the array returned by <code>np.zeros</code> is <code>float64</code>, which means you're going to be losing a lot of precision ...
python|arrays|python-3.x|numpy
0
370,117
33,505,245
How to change order of plots in pandas hist command
<p>I'm trying to plot a set of histograms for a dataframe with 25 columns named <code>"Feature_1","Feature_2",...."Feature_25"</code>. When I use <code>df.hist()</code> it sorts individual histograms by their names so they are plotted in the following order: <code>"Feature_1",""Feature_10","Feature_11"..."Feature_2","...
<p>You could instead make repeated calls to hist with individual columns. Not sure if that fits all of your needs. </p> <pre><code>import pandas as pd df = pd.DataFrame({'a':[1,1,1,1,3], 'b':[1,1,2,1,3], 'c':[2,2,2,1,3], }) df[['c']].hist() df[['a']].hist() df[['...
python|pandas|matplotlib
2
370,118
33,169,701
Pandas Multiindex from array => TypeError: unhashable type: 'dict'
<p>I'm trying to create the dataframe from the array with following structure:</p> <pre><code>df = [[{'date_time': Timestamp('2015-05-22 05:37:59'), 'name': 'Tom', 'value': '129'}, {'date_time': Timestamp('2015-05-22 05:37:59'), 'name': 'Kate', 'value': '0'}, {'date_time':...
<p>I am still not sure what exactly you want to do with the MultiIndex, but here is one way to "flatten" your dictionary in your multi-level arrays and load your data into the dataframe properly:</p> <p><strong>Updated with "list" and "index" as MultiIndex</strong></p> <pre><code>In [100]: data = [[{'date_time': Time...
python|pandas|dataframe|multi-index
3
370,119
33,483,704
Counting arithmetic operations
<p>Is there a way to evalute the number of numeric operations (+, -, /, *) in a function/expression? </p> <p>In example, lets take a simple linear algebra problem (<code>Ax = b</code>):</p> <pre><code>A_data = np.array([[1, -4, 1], [1, 6, -1], [2, -1, 2]], dtype=float) b_data = np...
<p>I am assuming you are trying to reduce the complexity here for performance. Listed in this post is an approach to <em>kill</em> the inner loop of <code>Gauss-elimination</code> with <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> giving us a partia...
python|numpy|recursion|scipy
1
370,120
9,250,796
Cross product of a vector in NumPy
<p>Consider the following vectors (essentially<code>2x1</code> matrices):</p> <pre><code>a = sc.array([[1], [2], [3]]) &gt;&gt;&gt; a [[1] [2] [3]] b = sc.array([[4], [5], [6]]) &gt;&gt;&gt; b [[4] [5] [6]] </code></pre> <p>The cross product of these vectors can be calculated using <code>numpy.cross()</code>. Wh...
<p>To compute the cross product using <code>numpy.cross</code>, the dimension (length) of the array dimension which defines the two vectors must either by two or three. To quote the documentation:</p> <blockquote> <p>If <code>a</code> and <code>b</code> are arrays of vectors, the vectors are defined by the las...
python|numpy
24
370,121
6,032,781
python+numpy: why does numpy.log throw an attribute error if its operand is too big?
<p>Running </p> <pre><code>np.log(math.factorial(21)) </code></pre> <p>throws an <code>AttributeError: log</code>. Why is that? I could imagine a <code>ValueError</code>, or some sort of <code>UseYourHighSchoolMathsError</code>, but why the attribute error?</p>
<p>The result of <code>math.factorial(21)</code> is a Python long. numpy cannot convert it to one of its numeric types, so it leaves it as <code>dtype=object</code>. The way that unary ufuncs work for object arrays is that they simply try to call a method of the same name on the object. E.g.</p> <pre><code>np.log(np.a...
python|numpy
32
370,122
6,094,957
High Pass Filter for image processing in python by using scipy/numpy
<p>I am currently studying image processing. In Scipy, I know there is one median filter in Scipy.signal. Can anyone tell me if there is one filter similar to high pass filter?</p> <p>Thank you</p>
<p>"High pass filter" is a very generic term. There are an infinite number of different "highpass filters" that do very different things (e.g. an edge dectection filter, as mentioned earlier, is technically a highpass (most are actually a bandpass) filter, but has a very different effect from what you probably had in ...
python|numpy|image-processing|scipy|fft
52
370,123
66,541,985
'WANDB_MODE' is not recognized as an internal or external command, operable program or batch file
<p>I am trying to run the custom <a href="https://github.com/ultralytics/yolov5" rel="nofollow noreferrer">yolo model</a> on my data set in my local machine. I am following some reference code from the kaggle platform. Here first time I encounter the <code>wandb</code> frame work. while doing so I use the following to ...
<p>Can you share the kernel that you're following? The official kernel has been updated and you can now easily authenticate using the prompter. If you'd still like to disable wandb from syncing data to the cloud, you can do either of these:</p> <ol> <li>Use environment variable: In a kernel execute this.</li> </ol> <pr...
python-3.x|windows|pytorch|wandb
0
370,124
66,474,616
Unable to retrieve data for all pages using beautiful soup while writing to CSV
<p>I'm web scraping a particular website which scrapes different currency information. I'm unable to retrieve all data when i write to csv file. Please let me know ho to go about it</p> <p>Code</p> <pre><code> lista = [&quot;eur-usd-historical-data&quot;,&quot;usd-jpy-historical-data&quot;,] listb=[] link = &q...
<p>Try appending to csv may be like:</p> <pre><code>final_df.to_csv('result.csv', mode='a', header=False) </code></pre>
python|python-3.x|pandas|web-scraping|beautifulsoup
0
370,125
66,633,121
How do I create a new dataframe column based on certain conditons as it gives me a TypeError: where() takes from 1 to 3 pos args but 4 were given?
<p>I am trying to create a new dataframe using pandas using a few values. This is how I have created a dataframe:</p> <pre><code>dataframe['ON/OFF'] = np.where((dataframe['Height'] == median_height) &amp; ( dataframe['State Hash'] == most_common_state_hash) &amp; (dataframe['File Name']!= name_of_file),...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p> <pre><code>dataframe['ON/OFF'] = np.select([(dataframe['Height'] == median_height), (dataframe['State Hash'] == most_common_state_hash), ...
python|python-3.x|pandas
1
370,126
66,489,488
Splitting the values of column in csv and write in new column using Pandas
<p>I have an excel column as shown below :-</p> <pre><code>FileName Coordinates abc.text 0 0.41, 0.42, 0.43, 0.44 </code></pre> <p>I want the output to be in this fashion :-</p> <pre><code>FileName Coordinates Label X-1 Y-1 X-3 X-4 abc.txt ...
<p>replace <code>df[['Label', 'x1','y1', 'x2', 'y2']] = df['Coordinates'].str.split(&quot; &quot;,expand=True)</code></p> <p>with <code>df[['Label', 'x1','y1', 'x2', 'y2']] = df['Coordinates'].str.split(&quot;, &quot;,expand=True)</code></p>
python-3.x|pandas|dataframe|csv
1
370,127
66,723,167
Create an array from Dataframe comumn
<p>I'm beginning with Python. I want to create an new array which will contains all words store from one columns in a dataframe.</p> <p>This column already contains array with words :</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>df['Body_A'].values[0] </code></pre> <p>the output:</p> <...
<p>you can flat the list using nested list comprehension</p> <pre><code>df = pd.DataFrame({&quot;a&quot;:[['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]}) flat_list = [item for sublist in df['a'] for item in sublist] df:: a 0 [Hello, I, am, fine] 1 [How, are, you, ?] </code></pre> <p>Output:</p> <p...
python|arrays|pandas|dataframe
0
370,128
66,608,578
Is there a way in Python to read one column in a CSV file and randomly select one value to put into a string variable?
<p>So I have CSV file which has the following: | Task 1 | Task 2 | | -------- | -------------- | | First | row | | Second | row | I want to select a random value from Task 1 column and then write a string variable.</p> <p>I have the following:</p> <pre class="lang-py prettyprint-ove...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randint.html" rel="nofollow noreferrer"><code>numpy.random.randint</code></a></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.read_csv('activities.csv', header=0, squeeze=...
python|pandas|csv
0
370,129
66,556,392
Python convert lists of unequal length into dictionaries, and then columns
<p>I have a pandas dataframe with a column of lists with a value and count that I need to convert into a dictionary: For example:</p> <pre><code>[['a:4', 'b:3', 'd:5'], ['b:1'], ['a:2', 'c:5']] </code></pre> <p>I would then like each item to have a column with the corresponding value as the row value.</p> <pre><code>a ...
<p>If you can change that data format just slightly, so it looks like a list of dicts:</p> <pre><code>x = [{'a':4, 'b':3,'d':5'}, {'b':1}, {'a':2,'c':5}] </code></pre> <p>Then pd.DataFrame(x) will do this automatically:</p> <pre><code>&gt;&gt;&gt; pd.DataFrame(x) a b d c 0 4.0 3.0 5.0 NaN 1 NaN 1.0 ...
python|pandas
1
370,130
66,706,684
Reindex with multiindex and create empty dates
<p>How can I create empty rows from 7 days before 2016-01-01 going to January 2015 for each country? I tried reindexing. I need to retain the multiindex df</p> <pre><code> value date uk 2016-01-01 4.0 2016-01-08 5.0 us 2016-01-01 1.0 2016-01-08 ...
<p>I try modify previous answer for working with <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>MultiIndex.from_product</code></a> for get same datetimes for each category in first level:</p> <pre><code>r...
python|python-3.x|pandas|datetime
3
370,131
66,424,131
Replace part of text from column in dataframe
<p>I need to replace this following</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Numeric Route</th> <th style="text-align: center;">Alphanumeric Route</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1571</td> <td style="text-align: center;">T5...
<p>You can use look-behind utility of regex:</p> <pre><code>import pandas as pd evaluate2 = pd.DataFrame({'Numeric Route':['1571','2212','3123','421','2473']}) evaluate2['Alphanumeric Route'] = evaluate2['Numeric Route'] mapping = { 1:'T', 2:'P', 3:'A', 4:'E'} mapping2 = { 1:'A', 2:'B', 3:'C', 4:'D', 5:'E'} for k, ...
python|pandas
0
370,132
66,749,616
Pandas dataframe: summing cell data from a group of rows, storing in a new column
<p>As a part of a treatment for a health related issue, I need to measure my liquid intake (along with some other parameters), registring the amount of liquid every time I drink. I have a dataframe, of several months of such registration. I want to sum my daily amount in an additional column (in red, image below) As yo...
<ul> <li>use fact <code>False==0</code></li> <li>first row of date will be where <strong>data</strong> is not equal to <code>shift()</code> of date</li> <li><code>merge()</code> to sum</li> </ul> <pre><code>## construct a data set d = pd.date_range(&quot;1-jan-2021&quot;, &quot;1-mar-2021&quot;, freq=&quot;2H&quot;) A ...
python|pandas|dataframe
1
370,133
66,548,133
Set sequential number on entries with specific condition
<h2>Situation</h2> <p>I'm preparing the migration of user data and I have a list of user subscriptions, for which I try to give every user a member id.</p> <p>We only want to migrate active subscriptions, which are identified with the value 1 in the row &quot;active&quot;. The oldest user should get the lowest number ...
<p>Create sample dataset:</p> <pre><code>df = pd.DataFrame({ &quot;member_id&quot;:[1,2,3,4,5,6], &quot;active&quot;:[0,0,1,1,1,1], &quot;date&quot;: [&quot;Jan 2020&quot;,&quot;Feb 2020&quot;,&quot;Mar 2020&quot;,&quot;Apr 2020&quot;,&quot;Jan 2021&quot;,&quot;Feb 2021&quot;], &quot;mail&quot;: [&quot;one@user.com&quo...
pandas
1
370,134
66,563,727
How to make boxplot using matplotlib when i already have all the information?
<p>Can you guys help me for my statistics problem? I'm trying to make Box Plot exactly like this :</p> <p><a href="https://i.stack.imgur.com/n7Vc5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n7Vc5.png" alt="1" /></a></p> <p>I have all the information to make like :</p> <pre><code># Median media...
<p>You can call matplotlib's <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bxp.html" rel="nofollow noreferrer"><code>ax.bxp(...)</code></a> directly. It accepts a list of dictionaries as its first parameter. Here is an example to get you started:</p> <pre class="lang-py prettyprint-override">...
pandas|numpy|matplotlib|anaconda
1
370,135
66,554,730
How do I put data from one column into separate columns
<p>I've got a column of data:</p> <pre><code>Item NaN item_a description_a price_a NaN item_b description_b price_b NaN item_c description_c price_c </code></pre> <p>This is all in the same column <code>Item</code>. Everywhere there's a NaN in the column, I want to put the data below it in a separate column.</p> <p>Lik...
<p>A few boolean statements and a <code>unstack()</code> should do the trick.</p> <pre><code>df['item'] = np.where(df['Item'].str.contains('item',case=False),df['Item'],np.nan) df['item'] = df['item'].ffill() df1 = df.loc[df['item'].ne(df['Item'])].dropna() df1['item_2'] = df1['item'].factorize()[0] + 1 df2 = df1.se...
python|pandas|dataframe
0
370,136
66,730,734
Select min from subgroup pandas
<p>I get such table via following query:</p> <pre class="lang-py prettyprint-override"><code>df_netflix.groupby(by=['year_added','quarter_added'])['quarter_added'].count() </code></pre> <pre><code>year_added quarter_added 2008 Q1 2 2009 Q4 2 2010 Q4 ...
<p>You can try something like below for your grouped object.</p> <pre><code>grouped = pd.DataFrame(grouped) grouped.columns = ['count'] grouped = grouped.reset_index() grouped.iloc[grouped .groupby('year_added').idxmin()['count']] </code></pre>
python-3.x|pandas|pandas-groupby
2
370,137
66,395,321
pandas: groupby using specific class without filtering the rows
<p>I'm trying to calculate farming growth probability with groupby, however, is it possible to have a specific class(state: WA) without filtering the rows?</p> <p>i was able to calculate the probability with the codes below, however, it will filter the rows that are not WA, which makes it impossible to do further calcu...
<p>Not sure if I understand your question well, but if you want to keep all the states in the calculation, just remove the following part in square brackets from the equation:</p> <pre><code>df[df[&quot;state&quot;]==&quot;WA&quot;] </code></pre> <p>would become simply</p> <pre><code>df </code></pre> <p>or for the full...
python|pandas|dataframe
0
370,138
66,441,412
most efficient way to set dataframe column indexing to other columns
<p>I have a large Dataframe. One of my columns contains the name of others. I want to eval this colum and set in each row the value of the referenced column:</p> <pre><code>|A|B|C|Column| |:|:|:|:-----| |1|3|4| B | |2|5|3| A | |3|5|9| C | </code></pre> <p>Desired output:</p> <pre><code>|A|B|C|Column| |:|:|:|:-...
<p>For better performance, use <code>df.to_numpy()</code>:</p> <pre><code>In [365]: df['Column'] = df.to_numpy()[df.index, df.columns.get_indexer(df.Column)] In [366]: df Out[366]: A B C Column 0 1 3 4 3 1 2 5 3 2 2 3 5 9 9 </code></pre>
pandas|performance|dataframe|indexing|eval
1
370,139
66,515,491
how to convert lists/array entries in a column to one row with different columns for each entry
<p>I have a dataframe where one column called <code>features</code> has its entries as lists of numbers over 1064 rows. So each row contains 6 to 7 columns with the <code>features</code> column where over each row it contains a list of numbers. I want to take this list, and spread it over the columns till while the num...
<p>You can generate another dataframe which contains the values you have in the lists of the column <code>features</code> by using the last row of the following code (first three rows are used to generate data):</p> <pre><code>import numpy as np df = pd.DataFrame(columns = ['features']) df['features'] = list(np.rando...
python|pandas|list|dataframe|multiple-columns
0
370,140
66,715,318
Fine tune Universal Sentence Encoder with Keras
<p>I am trying to fine tune <a href="https://tfhub.dev/google/universal-sentence-encoder-large/5" rel="nofollow noreferrer">Universal Sentence Encoder</a> and use the new encoder layer for something else.</p> <pre><code>import tensorflow as tf from tensorflow.keras.models import Model, Sequential from tensorflow.keras....
<p>Hoping this will help someone, I ended up solving this by using <a href="https://tfhub.dev/google/universal-sentence-encoder/4" rel="nofollow noreferrer">universal-sentence-encoder-4</a> instead of <a href="https://tfhub.dev/google/universal-sentence-encoder-large/5" rel="nofollow noreferrer">universal-sentence-enco...
python|tensorflow|keras|tensorflow-hub
0
370,141
66,698,828
How to take difference between datetime.times in a pandas DataFrame column
<p>I have a df with some times:</p> <pre><code>import datetime as dt import pandas as pd data = [dt.time(0,0,10), dt.time(0,24,30), dt.time(4,20,12)] df = pd.DataFrame(data, columns=['times']) </code></pre> <p>How can I use the logic from .diff() to take the difference for datetimes like below where the first entry i...
<p>You have to convert <code>data</code> to a list of <code>datetime.datetime</code>'s:</p> <pre><code>data = [dt.time(0,0,10), dt.time(0,24,30), dt.time(4,20,12)] data = [dt.datetime.combine(dt.date.today(), d) for d in data] df = pd.DataFrame(data, columns=['times']) df.times.diff() </code></pre> <p><strong>Output</...
python|pandas|datetime|python-datetime
1
370,142
66,350,248
Is there any way to inverse tensorflow predicted variable to origin value?
<p>I have run tensorflow 2.0 algorithm where my dependent variable is y in label format</p> <pre><code>array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
<p>Use <code>tf.argmax()</code> to get indices:</p> <pre><code>ind = tf.argmax(y_pred, -1) </code></pre>
python-3.x|encoding|tensorflow2.0
0
370,143
66,718,694
Fail to rebuild npm rebuild @tensorflow/tfjs-node build-addon-from-source
<p>I have no idea whats happening here. I've seen solutions with electron but it does not apply to this context.</p> <p>My node -v is v10.16.3</p> <p>My package.json is:</p> <pre><code>&quot;@tensorflow-models/mobilenet&quot;: &quot;^2.0.4&quot;, &quot;@tensorflow/tfjs&quot;: &quot;^1.7.4&quot;, &quot;@tensorflow/tfjs-...
<p>Try running this:</p> <pre><code>xcode-select --install npm i node-pre-gyp -g npm rebuild @tensorflow/tfjs-node --build-from-source </code></pre>
tensorflow|tensorflow.js|tfjs-node
0
370,144
66,395,587
How do I display the row number for pandas dataframe while using groupby?
<p>I have a dataframe with results using groupby. I want the output to display a row number for the output that I can use for reference</p> <pre><code>df.groupby(&quot;Class&quot;).agg({&quot;Avg. B. Ranking&quot;: np.mean,&quot;Class&quot;: np.size}).sort_values(&quot;Avg. B. Ranking&quot;,ascending=True) Avg. B. Ra...
<p>Just use <code>as_index</code> parameter in <code>groupby()</code> method</p> <p>By default <code>as_index</code> parameter in <code>groupby()</code> is <code>True</code> so make it <code>False</code></p> <p>Use this:-</p> <pre><code>df.groupby(&quot;Class&quot;,as_index=False).agg({&quot;Avg. B. Ranking&quot;: np.m...
python|pandas
2
370,145
66,508,183
Split 2 csv files into smaller sets of files based on unique values in python
<p>Sorry if this question has been asked before, I just couldn't find a simple example.</p> <p>I have 2 large CSV files that I would like to split based on the unique values in the <code>Location</code> &amp; <code>LocationType</code> Column. I would like to store the split csv files into sub-directories for each value...
<blockquote> <p>would like to know the workflow for this type of project</p> </blockquote> <ul> <li>open the file</li> <li>sort the contents on the desired column</li> <li>group by the desired column</li> <li>write each group to a new file</li> </ul>
python|python-3.x|pandas|csv|split
0
370,146
66,755,774
How to vectorize a for loop with conditions instead of iterating over a Pandas DataFrame
<p>I have some code that ingests two .csv files: <em>employee.csv and schedule.csv</em>. The employee.csv has properties '<strong>ID</strong>' and '<strong>Building</strong>' which I use together as a '<strong>key</strong>' to gather entries in the schedule file with the same ID/Building pair based on conditionals.</p>...
<p>What you're doing is manually performing a &quot;merge&quot;</p> <pre><code>key_cols = ['Building', 'ID'] output_df = employee_df.merge( schedule.drop(columns=['Name', 'Op Date', 'Rev', 'Start Time']), on=key_cols, how='outer' ) </code></pre> <p>You can <code>.drop()</code> whatever columns are not needed ...
python|pandas|optimization|vectorization
1
370,147
66,364,117
Python: how can I treat the currency pair same as the one formed in reversed order?
<p>I would like to group the rows by currency pairs but I got some problem. From the inputs, for the first two rows, USDGBP and GBPUSD are actually referring to the same currency pair but the order of currencies is reversed. How can I treat them as the same and sum the VR column by same currency pair? Many thanks!</p> ...
<p>You can try to make a <code>tuple</code> after sirting the currencies like</p> <pre class="lang-py prettyprint-override"><code>df['grpupable'] = df['Qualifier'].apply(lambda x: tuple(sorted([x[:3], x[3:]]))) </code></pre> <p><strong>Example:</strong> Now you can group them like</p> <pre><code>df.groupby(['grpupable'...
python|pandas|database|dataframe
1
370,148
66,744,229
How to explode columns with multiple (dictionary like) json objects in each row in pandas?
<p>I have a csv file that contains some columns. The columns of interest have multiple json objects in a single row. it looks something like this:</p> <pre><code>IN: df=read_csv('filename.tsv',sep='\t') IN: df OUT: name RSN model version dt si2 si3 pi1 wi20 wi28 li1 ci1 ai1 ai2 ai3 ad1 wi19 wi27 wan2 w...
<p>Let's use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>df.explode()</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply()</code></a> + <a href="https://pandas.py...
python|pandas
0
370,149
66,625,945
huggingface's ReformerForMaskedLM configuration issue
<p>I'm trying to pass the all of the huggingface's ...ForMaskedLM to the FitBert model for fill-in-the-blank task and see which pretrained yields the best result on the data I've prepared. But in the Reformer module I have this error says that I need to do 'config.is_decoder=False' but I don't really get what this mean...
<p>You can override certain model configurations by loading the model config separately and providing it as parameter for the <code>from_pretrained()</code> method. This will assure that you are using the proper model configuration with the changes you have made:</p> <pre class="lang-py prettyprint-override"><code>from...
nlp|bert-language-model|huggingface-transformers
2
370,150
66,586,351
Unexpected numpy sum behaviour with where parameter
<p>As an example, have a look at these numpy arrays:</p> <pre><code>&gt;&gt;&gt; a array([[1, 2, 3], [4, 5, 6]]) &gt;&gt;&gt; b array([[ True, False, True], [False, False, True], [ True, True, False]]) </code></pre> <p>Say I want the sum of each row of <code>a</code> including the elements spec...
<p>So what you have been doing is make a (2,3,3) array, and summing on the last axis:</p> <pre><code>In [216]: np.where(b, a[:,None], 0) Out[216]: array([[[1, 0, 3], [0, 0, 3], [1, 2, 0]], [[4, 0, 6], [0, 0, 6], [4, 5, 0]]]) In [217]: np.sum(_, axis=2) Out[217]: array([[ 4, 3,...
python|numpy|sum|where-clause|array-broadcasting
1
370,151
66,653,723
TensorFlow custom loss ValueError: "No gradients provided for any variable: [....'Layers'....]"
<p>I am trying to use the inbuilt TensorFlow function as a loss function to compile my model. Is it because of the changing from numpy array to tensor, or is it something about the function. My code:</p> <pre><code>import numpy as np from pandas import read_csv from keras.utils import to_categorical import matplotlib.p...
<p>The edit distance is not differentiable, so you cannot use it as a loss function. You can only use differentiable functions as loss.</p>
python-3.x|tensorflow|sequence|loss-function|levenshtein-distance
0
370,152
66,458,592
pandas rolling over irregular dataset with irregular window size
<p>I want to calculate a median over an irregular pandas series.</p> <p>In particular, I want to calculate the median first based on the first X-days and later based on the following X-days.</p> <p>I did code the following working example. In there, I generate two columns, one <code>median_-2days</code> which lists the...
<p>You can use <code>rolling</code> with a window of 3D as you want to include the boundary with <code>&gt;=</code> and <code>&lt;=</code>. to do the left and right, you can reverse the series with <code>[::-1]</code> so it is done with:</p> <pre><code>df[&quot;median_-2days_r&quot;] = df.loc[:,'l'].rolling('3D').media...
python|pandas
1
370,153
66,546,739
How differently do matplotlib.pyplot and seaborn treat numpy arrays?
<p>Turns out that when trying to plot the same synthetically generated numpy arrays of 2D points (one with 12 data points and another with just 1) in both pyplot and seaborn, I have to change the array dimension of the single-point array so that the program does not yield an error:</p> <pre><code>points = np.array([[1,...
<p>You have an inconsequence in the way you define the point <code>p</code>. You can either define <code>p</code> as a <code>points</code> array of length = 1:</p> <pre><code>p = np.array([[2.5,2]]) </code></pre> <p>Then use it in pyplot as follows:</p> <pre><code>plt.plot(p[:,0],p[:,1], &quot;bo&quot;) </code></pre> <...
python|arrays|numpy|matplotlib|seaborn
1
370,154
66,726,476
How to calculate the average true range - scipy
<p>Im working with OHLC data and I want to implement the formula below in my script <a href="https://i.stack.imgur.com/qiSAZ.png" rel="nofollow noreferrer">ATR formula</a></p> <p>Here is how I used to do it in Excel <a href="https://i.stack.imgur.com/oI1MA.png" rel="nofollow noreferrer">1D ATR excel formula</a></p> <p>...
<p>Please check the documentation.</p> <p>In your example it would be</p> <pre><code>mean = df['True Range'].mean() print(mean) </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/referenc...
python|pandas|numpy|scipy
0
370,155
66,620,848
When and Whether should we normalize the ground-truth labels in the multi-task regression models?
<p>I am trying a multi-task regression model. However, the ground-truth labels of different tasks are on different scales. Therefore, I wonder whether it is necessary to normalize the targets. Otherwise, the MSE of some large-scale tasks will be extremely bigger. The figure below is part of my overall targets. You can ...
<p>I've been working on a Multi-Task Learning problem where one head has an output of ~500 and another between 0 and 1. I've tried Uncertainty Weighting but in vain. So I'd be grateful if you could give me a little clue about your studies.(If there is any progress) Thanks.</p>
pytorch|regression|normalization|tensorflow-datasets|multitasking
-1
370,156
66,502,423
How to highlight the first row of this python code (to_excel)?
<p>Is it possible to highlight the first row of these dataframes so when they are stacked vertically into excel they highlight in yellow.</p> <p>import pandas as pd</p> <pre><code>data1 = &quot;&quot;&quot; class precision recall &lt;18 0.0125 12 18-24 0.0250 16 25-34 0.0035...
<p>Yes, you have full control over the formatting. Pandas uses a package called XlsxWriter for that. <a href="https://xlsxwriter.readthedocs.io/working_with_pandas.html" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/working_with_pandas.html</a></p>
python|excel|pandas|xlwings
0
370,157
66,548,156
scipy and numpy not error with as_matrix function
<p>This is a &quot;working example&quot; that does not work. Why does this not run? scipy seems to not work.</p> <p>i get this error:</p> <p>File &quot;display_map.py&quot;, line 35, in rot_cw = R.from_quat(keyframe[&quot;rot_cw&quot;]).as_matrix() AttributeError: 'Rotation' object has no attribute 'as_matrix'</p> <p...
<p>In scipy.spatial.Rotation methods from_dcm, as_dcm were renamed to from_matrix, as_matrix respectively.</p>
python|numpy|scipy
0
370,158
66,360,645
Changing values of one column based on the other three columns in pandas dataframe
<p>I have a following Pandas dataframe, where I want to change a value of 'fmc' column based on 'time', 'samples' and 'uid' columns.</p> <p>Concept is as following:</p> <p>For the same <code>date</code>, <code>if df.samples == 'C' &amp; df.uid == 'Plot1'</code>, then corresponding row value of <code>fmc * 0.4</code></p...
<p>This code:</p> <pre><code>import pandas as pd data = [ ['2015-10-11', 'C', 'Plot1', 98.226352 ], ['2015-10-11', 'C', 'Plot2', 132.984817 ], ['2015-10-11', 'E', 'Plot1', 114.147964 ], ['2015-10-11', 'E', 'Plot2', 110.083699 ], ['2015-10-11', 'ns', 'Plot1', 113.258977 ], ['2015-10-11', 'ns', '...
python|pandas
1
370,159
66,552,454
how to import a torch 1.7.1 when torch 1.4.0 is also installed
<p>how to import a torch 1.7.1 when torch 1.4.0 is also installed</p> <p>When I run the command: ! pip list It lists all libraries with : torch 1.7.1</p> <p>Now when I run:</p> <pre><code>&gt;&gt;&gt;import torch &gt;&gt;&gt;torch.__version__ '1.4.0' </code></pre> <p>How Do I import torch==1.7.1 in the python progra...
<p>Slightly different way to answer your question, but if you want to have two versions of <code>torch</code> installed simultaneously for different purposes (e.g. running different programs), my recommendation would be to use <code>torch 1.7.1</code> and <code>torch 1.4.1</code> in separate <strong>virtual environment...
python-3.x|pytorch
1
370,160
66,708,665
Pick a list of values from one CSV and get the count of the values of the list in a different CSV
<p>i am working on python code to calculate the occurrences of few values in a column within a CSV.</p> <p>Example - CSV1 is as below</p> <pre><code>**Type Value** Simple test complex problem simple formula complex theory simple idea simple task </code></pre> <p>I need to get the content of value for type simple a...
<p>Use:</p> <pre><code>df2['cat'] = df2['Category'].map(df1.set_index('Value')['Type']) df2 = df2['cat'].value_counts().rename_axis('a').reset_index(name='b') print (df2) a b 0 simple 18 1 complex 6 </code></pre>
python|python-3.x|pandas|dataframe
2
370,161
66,606,991
python dask to_csv delimiter
<p>I have a question to setup delimiter with <code>python dask</code>.</p> <pre><code>import dask.dataframe as dd df_out.to_csv(&quot;path/out.csv&quot;, single_file = True) </code></pre> <p>How can I set a <code>delimiter</code>? It seems that there is no parameter for delimiter.</p> <p>I got the error:</p> <pre><cod...
<p>You can pass <code>sep</code> option:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(zip(range(10), range(10)), columns=list('ab')) import dask.dataframe as dd ddf = dd.from_pandas(df, npartitions=3) ddf.to_csv('test.txt', sep='|', single_file=True, index=False) </code></...
python|pandas|dask|delimiter|dask-dataframe
1
370,162
66,721,622
Plotting a histogram with data intervals
<p>I tried to import a data file and then plot a histogram with this data. I was able to read the data file however I cannot turn this into a proper histogram with intervals. I imported the data with the following code:</p> <p><code>data = np.loadtxt(&quot;data.dat&quot;, delimiter =';', dtype = str)</code></p> <p>I am...
<p>Bins takes the number of intervals into which you want to evenly divide your data. So in your case, bins=2. You can use the range argument to indicates you want the range between 0 and 100 to be divided into 2 bins. Also that data for the histogram would be just the grades. Here is an example:</p> <pre><code>grades...
python|numpy|matplotlib|data-science|histogram
0
370,163
66,744,324
How to compare two data frame and get the unmatched rows using python?
<p>I have two data frames, df1 and df2. Now, df1 contains 6 records and df2 contains 4 records. I want to get the unmatched records out of it. I tried it but getting an error <code>ValueError: Can only compare identically-labelled DataFrame objects</code> I guess this is due to the length of df as the df1 has 6 and df2...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="noreferrer"><code>df.merge</code></a> with <code>indicator=True</code> and pick all rows except <code>both</code>:</p> <pre><code>In [173]: df = df1.merge(df2, indicator=True, how='outer').query('_merge != &quot;both&quot;')....
python|pandas|dataframe|indexing|rows
5
370,164
66,411,722
pandas pivot or groupby multiple columns and control columns
<p>Need to modify the following df</p> <pre><code>gears milesbefore milesafter model_car safety_car gears milesbefore milesafter model_truck safety_truck 1 10 20 honda NTSB 5 100 200 volvo NTSB 1 10 20 honda NTFD ...
<p>Your raw dataframe has some duplicate columns and appears to really be a &quot;cars&quot; dataframe and &quot;trucks&quot; dataframe. You can start by splitting the raw dataframe and working on each one separately, then merging them at the end. You can do it without groupby.</p> <h3>Split raw data into two similar d...
python-3.x|pandas|pandas-groupby|pivot-table
0
370,165
66,450,965
Interpolate between two matrices with numpy
<p>I have two HxW matrices <code>A</code> and <code>B</code>. I'd like to get an NxHxW matrix <code>C</code> such that <code>C[0]=A</code>, <code>C[-1]=B</code>, and each of the remaining <code>N-2</code> slices are linearly interpolated between <code>A</code> and <code>B</code>. Is there a single numpy function I can ...
<p>Just use linspace if you are looking for linear interpolation between just 2 points.</p> <pre><code>A = np.array([[0,1], [2,3]]) B = np.array([[1, 3], [-1,-2]]) C = np.linspace(A,B,4) #&lt;- Change this to H+2, which is H linearly interpolated values between the 2 points C </code></p...
python|numpy
2
370,166
66,759,261
From dictionary to organized Excel
<p>Good Morning,</p> <p>I have a dictionary: organized this way below; And What I want to do is use the dictionary values as the column number for the Key. As showed below:</p> <p>My first idea was to loop through the dictionary and create a text file where dico_values = tabs and then transform this new file into an ex...
<p>You could perhaps try this:</p> <pre class="lang-py prettyprint-override"><code>new_dico = {value: [] for value in dico.values()} # {1: [], 2: [], 3: [], ...} for key, value in dico.items(): new_dico[value].append(key) for otherkey in new_dico.keys(): if otherkey == value: continue ...
pandas|dictionary|export-to-excel
0
370,167
66,350,684
How to create loop only through existing pairs in Data Frame in Python Pandas?
<p>I have Data Frame like below:</p> <pre><code>t = pd.DataFrame() t[&quot;value1&quot;] = [10, 20] t[&quot;value2&quot;] = [1, 2] </code></pre> <p>How can I create loop which will go only through existing pairs of values so: 10 1 and 20 2, how to diallow loop to create non existing combinations like: 10 2 and 20 1 ?</...
<pre><code>for v1, v2 in zip(t[&quot;value1&quot;], t[&quot;value2&quot;]): print(v1, v2) 10 1 20 2 </code></pre>
python|pandas|dataframe|loops
0
370,168
66,490,715
How can I get a specific value from a pandas DataFrame?
<p>I have a <code>.df</code> that looks something like this(<code>df = pandas.read_csv(main_db)</code>):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>itemName</th> <th>itemBrand</th> <th>itemCode</th> <th>itemStock</th> </tr> </thead> <tbody> <tr> <td>some name</td> <td>some brand</td> <...
<p>If you use:</p> <pre><code>result2 = result['itemStock'] </code></pre> <p>it returns you a data series so you see also the index and not only the value you want. You can check it using</p> <pre><code>type(result2) </code></pre> <p>You can find what you want using .values attribute</p> <pre><code>result2 = result['it...
python|pandas
1
370,169
66,479,494
Adding missing rows and setting column value to zero based on current dataframe
<pre><code>dic= {'distinct_id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'first_name': {0: 'Joe', 1: 'Barry', 2: 'David', 3: 'Marcus', 4: 'Anthony'}, 'activity': {0: 'Jump', 1: 'Jump', 2: 'Run', 3: 'Run', 4: 'Climb'}, 'tasks_completed': {0: 3, 1: 3, 2: 3, 3: 3, 4: 1}, 'tasks_available': {0: 3, 1: 3, ...
<pre><code>idx_cols = ['distinct_id', 'first_name', 'activity'] tasks.set_index(idx_cols).unstack(fill_value=0).stack().reset_index() distinct_id first_name activity tasks_completed tasks_available 0 1 Joe Climb 0 0 1 1 Joe Jump ...
python|pandas|dataframe|pandasql
2
370,170
66,679,603
Python self defined function with None argument
<p>I want to define my own function as below:</p> <pre><code>def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2): tmp = df tmp['NEWADD'] = (tmp['ADD1'] + ' ' + tmp['ADD2']).str.strip() return tmp </code></pre> <p>I know this is incorrect so I can add <code>if</code> statement in the function...
<p>You can accomplish this by using loops and lists like this:</p> <pre><code>def myown(df, add_args, OtherArgument_1, OtherArgument_2): tmp = df new_add = '' for i in add_args: new_add = new_add + tmp[i].str.strip() + '' tmp['NEWADD'] = new_add </code></pre> <p>Your add_args parameter must ...
python|pandas|function
1
370,171
66,509,523
How can I reed this text data using pandas, each category in a separate column?
<p>I need to put auth_name, univ, department on columns of df from the following text data:</p> <p><a href="https://i.stack.imgur.com/SOIzN.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>import pandas as pd data = '[Bashiri, Fahad A.; Hamad, Muddathir H.; Kentab, Amal Y.; Salih, Mustafa A.; Al Nasser, Mohammad N.] King Saud Univ, King Khalid Univ Hosp, King Saud Univ Med City, Div Neurol, Riyadh, Saudi Arabia; [Hamad, Muddathir H.; Amer, Yasser S.; Abouelkheir, Manal M.; Mohamed, Sarar; Al...
python|pandas|database|dataframe|statistics
2
370,172
66,725,357
Python pandas: find if string contains any of the row values
<p>Say we have pandas dataframe:</p> <pre><code> Country 0 United Kingdom 1 Bosnia and Herzegovina 2 France 3 United States 4 Ukraine </code></pre> <p>And we have a String for example like this:</p> <p><code>'The U...
<p>One way to start is by using an <code>apply()</code> on the sentences column - where you apply a lambda function that checks for what you need. You can read about <code>apply()</code> in <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">the pandas documentat...
python|pandas|database|dataframe
1
370,173
66,609,357
I have no idea why I am getting "can only concatenate str (not "int") to str" ERROR here
<p>Code:</p> <pre><code>import pandas as pd app = pd.read_excel(&quot;/Users/michaelblack/Downloads/Applicants with Interest/Applicants with Interests 2020.xlsx&quot;) app = app.replace(',',' ', regex=True).replace('/','', regex=True).replace('-','',regex=True).replace(';',' ',regex=True) pd.set_option('display.max_col...
<p>Try adding .astype(str) to each column:</p> <pre><code>while ct &lt;= 9: if ct == 0: app['new'+str(ct)] = app['Interest Description'].astype(str) +' '+ app['Interest Role'].astype(str) else: app['new'+str(ct)] = app['Interest Description' + '.' + str(ct)].astype(str) + ' '+ app['Interest Role...
python-3.x|pandas
0
370,174
66,502,184
changing index of dataframe: getting attribute error
<p>So I am working in Python trying to change the index of my dataframe. Here is my code:</p> <pre><code>df = pd.read_csv(&quot;data_file.csv&quot;, na_values=' ') table = df['HINCP'].groupby(df['HHT']) print(table.describe()[['mean', 'std', 'count', 'min', 'max']].sort_values('mean', ascending=False)) </code></pre> <p...
<pre><code>&gt;&gt;&gt; df = pd.DataFrame(columns = [&quot;HHT&quot;, &quot;HINC&quot;], data = np.transpose([[2,3,2,2,2,3,3,3,4], [1,1,3,1,4,7,8,9,11]])) &gt;&gt;&gt; df HHT HINC 0 2 1 1 3 1 2 2 3 3 2 1 4 2 4 5 3 7 6 3 8 7 3 9 8 4 11 &gt;&gt;&gt; table ...
python|pandas
0
370,175
66,403,356
Creating a custom piecewise loss function in tf.keras with three variables
<p>I am using the following code to try and train a model using a custom piecewise loss function that incorporates three variables but I am unable to get it to work. I am new to tensorflow so if anyone has any suggestions that would be helpful.</p> <p>I want to incorporate a third variable &quot;p&quot; into the loss f...
<p>Loss function is a part of computation graph built by keras. You can not use python <code>len()</code> function within it. This function don't support backpropagation of gradient. Replace it by <code>tf.shape()</code>.</p>
tensorflow|keras|loss-function
0
370,176
66,483,538
Searching in numpy array
<p>I have a 2D numpy array, say A sorted with respect to Column 0. e.g.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Col.0</th> <th style="text-align: center;">Col.1</th> <th style="text-align: center;">Col.2</th> </tr> </thead> <tbody> <tr> <td style="text-al...
<h1>Pure numpy solution:</h1> <p>My intuition is that I take the difference <code>c</code> between <code>a[:,1:]</code> and <code>b</code> by broadcasting, such that <code>c</code> is of shape <code>(11, 4, 2)</code>. The rows that match will be all zeros. Then I do <code>c == False</code> to obtain a mask. I do <code>...
python|arrays|pandas|numpy
1
370,177
66,439,210
Join numpy arrays of different dimensions and shapes
<p>I have 2 <code>arrays</code>, one has a shape of <code>(2,2)</code> and the other has a shape of <code>(2,2,2)</code>. I want to stack them together so that my final result can have a shape of <code>(3,2,2)</code>. I'll put an illustration of what I'm talking about</p> <pre><code>Array 1 -&gt; [ 1,2 ] -&gt;...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.dstack.html" rel="nofollow noreferrer"><code>numpy.dstack</code></a>, to stack your arrays along the <strong>d</strong>epth (third) axis:</p> <pre><code>import numpy as np a = np.arange(1, 5).reshape(2, 2) b = np.arange(5, 13).reshape(2, 2, 2) c =...
python|numpy|data-analysis
0
370,178
66,639,616
Python search string contains characters
<p>I have a data below:</p> <pre><code>col1 086945159 549615853 589ac2546 GED456231 F56hy8W12 </code></pre> <p>I want to find whether <code>col</code> has non-numeric value and return.</p> <pre><code>col1 col2 086945159 086945159 549615853 549615853 589ac2546 Nan GED456231 Nan F56hy8W12 Na...
<p>You can use <code>mask</code> with conditional pattern:</p> <pre><code># first part to match any non-digit # second part to match identical characters df['col2'] = df.col1.mask(df.col1.str.contains(r'\D|^(.)\1*$')) </code></pre> <p>Output:</p> <pre><code> col1 col2 0 086945159 086945159 1 549615853 ...
python|regex|pandas|data-manipulation|python-re
5
370,179
66,567,596
Plot word count on x axis and its occurrence on y axis from pandas df
<p>The goal is to plot something like this:</p> <p><a href="https://i.stack.imgur.com/9BXeb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BXeb.png" alt="plot" /></a></p> <p>I have the following dummy df. Note that data = number of words = x axis</p> <pre><code>data = [13,2,2,13,14,5,6,2,2,2,1,1,1,...
<p>I used set and count method. The loop iterate over set(data) and count method count the number of occurrences of an item in the list. I use the sorted function . b is the zero item and c is the first item in the nested list. b is x-axis and c is y-axis in plot.</p> <pre><code>d = sorted([[x,data.count(x)] for x in s...
python|pandas|dataframe|matplotlib
1
370,180
66,643,031
numpy Tries to Allocate More Memory than Available in Windows
<p>When <code>numpy</code> is asked to allocate memory for an array, it makes a call to <code>malloc</code>. If the call returns a NULL pointer, then <code>numpy</code> reports an exception like this:</p> <pre><code>np.random.randn(1000000 * 1000 * 1000) MemoryError: Unable to allocate 7.28 TiB for an array with shape ...
<p>I reviewed the <code>numpy</code> code and verified that it relies on <code>malloc</code> to determine whether an array can be allocated. <code>malloc</code> is a function in the C standard library. In Windows 10, it is implemented as a wrapper around <code>HeapAlloc</code>. See <a href="https://docs.microsoft.com/e...
python|c|numpy|memory-management|malloc
1
370,181
66,716,767
Scipy.Curve fit struggling with exponential function
<p>I'm trying to fit a curve of the equation:</p> <pre><code>y = ( (np.exp(-k2*(t+A))) - ((k1/v)*Co) )/ -k2 where A = (-np.log((k1/v)*Co))/k2 </code></pre> <p>given to me by a supervisor to a dataset that looks like a rough exponential that flattens to a straight horizontal line at its top. When I fit the equation i ...
<p>I think the problem maybe in the optimization function, in the sense that maybe a mistake.</p> <p>For instance:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.optimize import differential_evolution xData_forfit = [1.07683e+13, 1.16162e+13, 1.24611e+...
python|numpy|scipy|curve-fitting|scipy-optimize
1
370,182
66,402,679
How to use the output of argmin as index with Numpy
<p>I want to find the location of minima along a given axis in a rank-3 numpy array. I have obtained these locations with <code>np.argmin</code>, however I'm not sure how to &quot;apply&quot; this to the original matrix to get the actual minima.</p> <p>For example:</p> <pre><code>import numpy as np a = np.random.randn...
<p><code>a[min_loc]</code> does <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow noreferrer">integer array indexing</a> on the first dimension, i.e. it will pick up <code>(5, 2)</code> shaped array for each index in <code>min_loc</code>. Since <code>min_loc</cod...
python|numpy|array-broadcasting
1
370,183
66,498,585
How to import a .log file(s) with space in the columns and space separating the columns from each other?
<p>I have multiple .log files that look similar to the example down below. I can't seem to import them correctly in python. If I use space as delimiter then most of the columns break into multiple ones. The first row shows the names of the columns I want to add. I tried turning the log files into .csv but it did not he...
<p>This will preprocess the file into an acceptable CSV format:</p> <pre><code>columns = [1,11,25,74,78,131] colpairs = [(a-1,b-1) for a,b in zip(columns,columns[1:]+[999])] for ln in open('log.txt'): parts = [ ln[a:b].rstrip() for a,b in colpairs ] print( '&quot;' + '&quot;,&quot;'.join(parts) + '&quot;' ) </...
python|pandas
1
370,184
16,097,984
Fitting arbitrary gaussian functions, massive memory consumption in python
<p>I'm trying to (in python) fit a series of an arbitrary number of gaussian functions (determined by a simple algorithm still being improved) to a data set. For my current sample data set, I have 174 gaussian functions. I have a procedure for doing the fit, but it's basically complicated guess-and-check, and consumes ...
<p>Yes, it can likely be done better (easier) using scipy. But firstly, refactor your code into smaller functions; it justs makes it a lot easier to read and understand what's going on.</p> <p>As for the memory consumption: you're probably overextending a list far too much somewhere (<code>others</code> is a candidate...
python|numpy|scipy
2
370,185
16,408,851
Checking existence of an array inside an array of arrays python
<p>I have a numpy array of arrays:</p> <pre><code>qv=array([[-1.075, -1.075, -3. ], [-1.05 , -1.075, -3. ], [-1.025, -1.075, -3. ], ..., [-0.975, -0.925, -2. ], [-0.95 , -0.925, -2. ], [-0.925, -0.925, -2. ]]) </code></pre> <p>And I want to determine if an array ...
<p>This should do the trick,</p> <pre><code>import numpy as np np.where((qv == qt).all(-1)) </code></pre> <p>Or</p> <pre><code>import numpy as np tol = 1e-8 diff = (qv - qt) np.where((abs(diff) &lt; tol).all(-1)) </code></pre> <p>The second method might be more appropriate when floating point precision issues come ...
python|arrays|numpy
3
370,186
16,082,835
Calculating Midprice in pandas
<p>I'm working with intraday time and quote data in pandas, and struggling to find a good way to calulate a weighted mid-price. I currently have the data represented as four dataframes (bid_price, bid_quantity, ask_price, ask_quantity), with the columns of each dataframe being individual instruments, and the index bein...
<p>As I tried to convey in the comments, you can't vectorize an <code>if</code> branch the way you're trying, and so while the code wouldn't have raised an exception in the past, it almost certainly wasn't doing what you want it to. That's why <code>array</code>s (and now <code>DataFrame</code>s) error out instead whe...
python|pandas
1
370,187
16,180,534
I want to create headings relative to a single point from a list of points with angles between the points. Is there a function for this?
<p>I have a list of points and their angles relative to each other from one central point. Because of how the list is generated there is no order to the list nor is there a guarantee that an angle between two points will or will not exist. There is also no way of guaranteeing that the angle is clockwise or anticlockwis...
<p>This can be made into a graph theory problem: given a list of nodes and edges, calculate the distance between them based on the edge plus the distance from the starting node to the current edge. The orientation can be encoded by making the graph directed.</p> <p>In the above example, it's assumed you want to rotate...
python|numpy
2
370,188
16,562,080
How to count number of index or Null values in Pandas dataframe group
<p>Its always the things that seem easy that bug me. I am trying to get a count of the number of non-null values of some variables in a Dataframe grouped by month and year. So I can do this which works fine</p> <pre><code>counts_by_month=df[variable1, variable2].groupby([lambda x: x.year,lambda x: x.month]).count() <...
<pre><code>df.isnull().sum() </code></pre> <p>Faster, and doesn't need a custom function :)</p>
pandas
8
370,189
57,598,011
How to save a Keras model consisting of feature layer?
<p>I am trying a save a Keras model trained using Sequential and having a feature_layer. feature_layer is created using feature_columns consisting of numerical and categorical features. While saving I get error "Layer sequential_2 is not connected, no input to return."</p> <p>I followed the tutorial provided on tenso...
<p>In addition to commenting the <code>try</code> and <code>except</code> block, since you are using Tensorflow Version 1.14, adding the below line of code will resolve your issue.</p> <pre><code>tf.enable_eager_execution() </code></pre> <p>Please find the below screenshot:</p> <p><a href="https://i.stack.imgur.com/...
python|tensorflow|keras|feature-selection|tensorflow-serving
-1
370,190
57,583,109
sklearn - why is this not rescaling properly?
<p>I'm using <code>MinMaxScaler()</code> currently, but the same thing is happening to me with <code>StandardScaler()</code>. What am I doing wrong? The same is happening for my feature list as well. Some of them aren't even close?</p> <pre><code>test_labels array([[1100. , 0.05, 0.69], [1095. , 0.1...
<p>If i run the same script on an empty notebook:</p> <pre><code>import numpy as np test_labels = np.array([[1100. , 0.05, 0.69], [1095. , 0.15, 1.2 ], [1097. , 0.13, 1.14], [1094. , 0.12, 1.15]]) from sklearn.preprocessing import MinMaxScaler MinMax_scaler = MinMaxScal...
python|numpy|scikit-learn
1
370,191
57,373,851
Pivot table sorting pandas
<p>My initial df is:</p> <pre><code> ordinal id_easy latitude longitude 1 141 45.0714 7.6187 2 141 45.0739 7.6195 ... </code></pre> <p>After applying Pivot table my it looks like:</p> <pre><code>latitude ... ...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>DataFrame.sort_index</code></a> by second level:</p> <pre><code>df = df.sort_index(axis=1, level=1) </code></pre>
python|pandas|pivot-table
2
370,192
57,419,464
How to write to separate columns based on function output
<p>I have an internal function which returns two different values, and I want to be able to write that to separate columns of the same dataframe</p> <pre><code>df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}]) def test(a): return a*2, a*3 </code></pre> <p>...
<p>Adding <code>pd.Series</code> should do the work.</p> <pre><code>df[['Two Times', 'Three Times']] = df.apply(lambda row: pd.Series(test(row['a'])), axis=1) </code></pre> <p>OR </p> <pre><code>#create function like this def test(a): return pd.Series((a*2,a*3)) </code></pre> <p>Both should work</p>
python|pandas
1
370,193
57,729,067
How to find whether a value is occurring in sequence or time order?
<p>I have given two dataframes below for you to test</p> <pre><code>df_1 = pd.DataFrame({ 'subject_id':[1,1,1,1,1,1,1,1,1,1,1], 'time_1' :['2173-04-03 10:00:00','2173-04-03 10:15:00','2173-04-03 10:30:00','2173-04-03 10:45:00','2173-04-03 11:01:00','2173-04-04 12:00:00','2173-04-05 16:00:00','2173-04-05 22:00:00','217...
<p>You're doing a little too much overhead. Stuff these steps into a one-line command:</p> <ol> <li>Shift ["val"] one position left ...</li> <li>... compare that shifted sequence to ["val"] with &lt;= ...</li> <li>That gives you a sequence of Booleans; apply <code>all()</code> to that</li> </ol> <p>The result of <co...
python|python-3.x|pandas|datetime|python-datetime
0
370,194
57,682,123
dataframe to hierarchical xml
<blockquote> <p>Read csv to dataframe and then convert that to xml using lxml library</p> </blockquote> <p>This is my first time handling xml and it appears that there is partial success. Any help will be highly appreciated. </p> <p>CSV File used to create dataframe:</p> <hr> <pre><code>Parent,Element,Text,Attrib...
<p>You've made a great start! Thought it would be easiest to go through your code bit-by-bit and explain where it needs tweaking, and suggest some improvements:</p> <h2>Reading and cleaning the Data</h2> <pre class="lang-py prettyprint-override"><code># Read the csv file dfc = pd.read_csv('test_data_txlife.csv').fill...
python|xml|pandas|lxml
1
370,195
57,696,200
Tensorboard. Duplicated graph node: one unconnected with placeholders and one connected
<p>I'm trying to visualize my model graph on TensorBoard. I'm using Keras 2.1.5 and tensorflow-gpu 1.13.1. My model is a concatenation of convolutional layers and, at the end, a custom layer where I make some operations with tensors. Everything works fine, although I defined some prints at the end and at the beggining...
<p>This issue happens when you are using multiple tf scope. </p> <p>For each scope it creates a new op with "op_{integer}". </p> <p>You need to make use of "absolute_name_scope(scope)" to resolve your issue. </p> <p>Please refer to below link on how to make use of it. </p> <p><a href="https://github.com/tensorflow/...
python-3.x|tensorflow|tensorboard
0
370,196
57,627,463
Data type transfering/converting
<p><code>a</code> = </p> <pre><code>array([[0.093949 ], [4.71874039], [4.72334459], [4.8183138 ], [4.89309171]]) </code></pre> <p><code>df['b']</code> = </p> <pre><code>0 45.1076 1 45.0533 2 44.9566 3 45.0386 4 45.0292 </code></pre> <p>How to transfer from <strong>"b"</st...
<p>Convert one column <code>DataFrame</code> with <code>[[]]</code> to numpy array by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_numpy.html" rel="nofollow noreferrer"><code>Series.to_numpy</code></a>:</p> <pre><code>b = df[['b']].to_numpy() #older pandas versions #b = df[['b']]...
python|pandas|numpy
1
370,197
57,484,180
Generate Z-Stack of images and create a 2D top-down view of the stacked image using python
<p>I have n number of images with same size that need to be stacked along Z-Axis as shown in figure creating a sort of 3D Model. I have tried doing this using Z-Stack with different libraries (like <a href="https://stackoverflow.com/questions/31978698/how-to-make-a-tiff-z-stack-conserving-or-adding-metadata">here</a>) ...
<p>Every image in OpenCV is 3-dimensional tensor, the last dimension being number of channels, 3 usually. Stacking them along another new dimension requires a 4-dimensional tensor.</p> <pre><code>W, H, n = 300, 200, 5 num_channels = 3 # shape is (height, width, channels) im = np.zeros((H, W, num_channels), dtype=np.u...
python|numpy|image-processing
1
370,198
57,642,144
How do I create the decoder part of the Autoencoder?
<p>I am trying to copy the layers from the Encoder to create the decoder but I'm getting "Index Error".</p> <pre><code>input_img =Input(25425,) encoded1 = Dense(75,activation=tf.nn.relu)(input_img) encoded = Dense(50,activation=tf.nn.relu)(encoded1) decoded = Dense(25425, activation='sigmoid')(encoded) autoencoder...
<p>You have several mistakes in you code. See my comments in the working snippet:</p> <pre><code># Random input for testing purposes X = np.random.rand(10, 25425) input_img =tf.keras.layers.Input(25425,) encoded1 = tf.keras.layers.Dense(75,activation=tf.nn.relu)(input_img) encoded2 = tf.keras.layers.Dense(50,activati...
python|tensorflow|keras|autoencoder
0
370,199
57,610,473
Fast selection and assignment using Hierarchical indexing (MultiIndex)
<p>I work with a large dataset in Pandas (over 18000000 rows, 8 columns) and want to assign one of the columns in certain rows to True. I use Hierarchical indexing and have my DataFrame Structured as follows: </p> <pre class="lang-py prettyprint-override"><code> col1 col2 ... col8 ...
<p>As every <code>name</code> part of the multiIndex is going to be selected, maybe trying indexing by <code>get_level_values(1)</code>, where (1) indicates <code>position</code>:</p> <pre><code>df.loc[df.index.get_level_values(1).isin(positions), 'col1'] = True </code></pre> <p>Try and see if that offers any speedup...
python|pandas
3