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
9,200
68,131,987
Unify different separators in column
<p>I have a dataframe df with ~450000 rows and 4 columns like &quot;HK&quot; as in the example:</p> <pre><code>df = pd.DataFrame( { &quot;HK&quot;: [ &quot;19000000-ac-;ghj-;qrs&quot;, &quot;19000000- abcd-&quot;, &quot;19000000 -abc;klm-&quot;, &quot;19000000...
<p>Using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>pd.Series.str.replace</code></a> with a regular expression:</p> <pre><code>&gt;&gt;&gt; df['HK'].str.replace(r'(?&lt;=\d{8})[\s-]+(?=\w)', ' - ', regex=True) 0 19000000 - ac-;ghj-;qrs 1 ...
python|pandas
1
9,201
59,443,435
Stacked bar plot - percentage
<p>I want to represent this information in a stacked bar plot in percentage On the x axis I want the age groups and on the y axis and the values that represent percentage of Gender in each age group Age is represented by bins in the dataset I have this so far <a href="https://i.stack.imgur.com/QKIum.png" rel="nofollow ...
<p>I created a test data frame:</p> <pre><code> df = pd.DataFrame({'Gender': ['F','M','F','F','F','M','M','M','F','F','M','F','F','M','M','M','M','F','F','M','M','M'], 'Age': [17,10,20,51,53,15,50,60,43,28,35,67,33,17,20,40,43,47,48,51,53,54]}) </code></pre> <p>You can use <a href="https://pandas.pydata.org/pandas-do...
pandas|stacked-chart
0
9,202
57,239,426
Pandas showing only the unique instances of a value in a dataframe for a given id
<p>This is the dataframe I'm working with.</p> <pre><code>df = pd.DataFrame({'id' : ['45', '45', '45', '45', '46', '46'], 'description' : ['credit score too low', 'credit score too low', 'credit score too low', 'high risk of fraud', 'address not verified', 'address not verified']}) print(df) </code><...
<p>You can remove the duplicates with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><strong><code>.drop_duplicates()</code></strong> [pandas-doc]</a>. For example:</p> <pre><code>&gt;&gt;&gt; df id description 0 45 cr...
python|pandas|dataframe
2
9,203
50,913,520
How can I use multiple datasets with one model in Keras?
<p>I am trying Forex prediction with Keras and Tensorflow using a LSTM Network. I of course want it to train on many days of trading but to do that I would have to give it sequential data with big jumps and phases without movement... when the market is closed... This isn't ideal as it gets "confused" because of these j...
<p>If you plan on fitting multiple datasets as data slices, sequentially, something like this would work:</p> <pre><code>for _ in range(10): #somehow cut the data into slices and fit them one by one model.fit(data_slice, label_slice ......) </code></pre> <p>As successive calls to <strong>fit</strong> will train the...
tensorflow|neural-network|keras|artificial-intelligence|forecasting
1
9,204
50,904,053
Tensorflow Intel MKL Optimization with NHWC data format
<p><strong>TensorFlow</strong> is compiled with the <strong>Intel MKL</strong> optimizations, many operations will be optimized and support NCHW.</p> <p>Can someone please explain, why does Intel MKL support NCHW format more than NHWC?</p>
<p>TensorFlow default NHWC format is not the most efficient data layout for CPU and it results in some additional conversion overhead.Hence Intel MKL support NCHW format</p>
tensorflow|intel-mkl|intel-tensorflow|intel-ai-analytics
2
9,205
66,415,572
"ValueError: No gradients provided for any variable" Custom function in layer present
<p>Im facing some problems with my code. Im giving the nn 2 Coordinates, it has to convert these to 3 variables (angles). These angels are used to calculate the position of some vectors that should end in the given point. When i trie to run the code, i get the above described error.</p> <pre><code>import tensorflow as ...
<p>Probably related with the fact that the method <code>robot_arm.calculate_point</code> is doing calculations outside of tensorflow, hence de backpropagation cannot be done because the gradient tape cannot &quot;keep track&quot; of the calculations to go from <code>x</code> to <code>r.calculate_point(x)</code>. See <a...
python|tensorflow|tensorflow2.0
0
9,206
57,693,908
find column value in dataframe
<p>Have 2 dataframes. First has 1 column. </p> <p><code>test1: 1,2,3,4,5</code></p> <p>Second has 2 columns. </p> <p><code>test2: 0 1 1 1 1. test3: 2 2 3 3 4</code></p> <p>I need to create new column in First dataframe that with search row value exist in whole dataframe2 (simple ctrl+F). As result I need to get t...
<p>You can check with <code>isin</code> with values flatten </p> <pre><code>test1['col2']=test1['col1'].isin(test2.values.ravel()) </code></pre>
python|pandas|dataframe|vlookup
1
9,207
57,419,094
Keras: display model shape in Jupyter Notebook
<p>I have the following code which I used to view my Network architecture. </p> <p><a href="https://i.stack.imgur.com/D2fpi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/D2fpi.png" alt="enter image description here"></a></p> <p>However, I also want to see the shape of each layer, so I tried to use the fol...
<p>since the resulting image is not a svg file anymore you should replace <code>SVG</code> with <code>Image</code> use </p> <pre><code>from IPython.display import Image ... plot_model(model, show_shapes=True, show_layer_names=True, to_file='model.png') Image('model.png') </code></pre>
python-3.x|tensorflow|keras
7
9,208
73,145,527
How to drop one level of a multiindex in pandas
<p>Im trying to drop a level of my multi index using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer">drop</a>, but I cant get it to work.</p> <pre><code>iterables = [[&quot;bar&quot;, &quot;baz&quot;], [&quot;bar&quot;, &quot;baz&quot;]] index = pd.MultiIndex....
<p>you use <a href="https://pandas.pydata.org/docs/reference/api/pandas.MultiIndex.droplevel.html#pandas.MultiIndex.droplevel" rel="nofollow noreferrer">pd.MultiIndex.droplevel</a></p> <pre><code>df=df.droplevel(level=1) or df=df.droplevel('second') df </code></pre> <pre><code>first bar 1 bar 2 baz 3 baz ...
pandas
1
9,209
70,565,880
Adding a moving formula to excel using python
<p>I am writing multiple <code>dfs</code> to excel and I am trying to add a formula to cells. The problem is that my assigned formula is static for the whole row, for example:</p> <pre><code># df 2019 2020 2021 2022 A 40 40 51 58 B ...
<p>You have to depend it on the number of the column. In the most brutal way, you can use loop:</p> <pre><code>df.loc['test'] = [f'=SUM(sheet_1!D{c+1}:sheet_1!D{c+6})' for c in range(0, len(df.columns)] </code></pre>
python|excel|pandas
1
9,210
70,701,975
I already have a CUDA toolkit installed, why is conda installing CUDA again?
<p>I have installed cuda version 11.2 and CUDNN version 8.1 in ubuntu</p> <pre><code>cnvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2020 NVIDIA Corporation Built on Mon_Nov_30_19:08:53_PST_2020 Cuda compilation tools, release 11.2, V11.2.67 Build cuda_11.2.r11.2/compiler.29373293_0 </code></pre> <p>When I in...
<blockquote> <ol> <li>Why is it happening?</li> </ol> </blockquote> <p>Conda expects to manage any packages you install <em>and</em> all their dependencies. The intention is that you literally never have to install anything else by hand for any packages they distribute in their own channel. If a GPU accelerated package...
tensorflow|cuda|conda|tensorflow2.0|cudnn
3
9,211
70,592,132
Update/merge dataframes based values in each row
<p>I have two dataframes:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ &quot;id&quot;: [1,2,3,4,5,6], &quot;c1&quot;: [1,2,3,4,5,6], &quot;c2&quot;: [1,2,3,4,5,6], &quot;c3&quot;: [1,2,3,4,5,6] }) </code></pre> <p>and</p> <pre><code>df2 = pd.DataFrame({ &quot;id&quot;: [1,2,3,4,5,6], &quot;column&quo...
<p>We can reshape <code>df2</code> using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>, then use it to substitute values in <code>df1</code></p> <pre><code>df1.replace(df2.pivot(*df2.columns)).fillna(df1) </code></pre> <hr /> <pre><co...
python|pandas|dataframe
2
9,212
51,382,175
Setting values of a tensor at the indices given by tf.where()
<p>I am attempting to add noise to a tensor that holds the greyscale pixel values of an image. I want to set a random number of the pixels values to 255.</p> <p>I was thinking something along the lines of:</p> <pre><code>random = tf.random_normal(tf.shape(input)) mask = tf.where(tf.greater(random, 1)) </code></pre> ...
<p><code>tf.where()</code> can be used for this too, assigning the noise value where mask elements are <code>True</code>, else the original <code>input</code> value:</p> <pre><code>import tensorflow as tf input = tf.zeros((4, 4)) noise_value = 255. random = tf.random_normal(tf.shape(input)) mask = tf.greater(random...
python|tensorflow|image-processing|noise
2
9,213
70,759,976
pyspark- how to add a column to spark dataframe from a list
<p>I'm looking for a way to add a new column in a Spark DF from a list. In pandas approach it is very easy to deal with it but in spark it seems to be relatively difficult. Please find an examp</p> <pre><code>#pandas approach list_example = [1,3,5,7,8] df.new_column = list_example #spark ? </code></pre> <p>Could you p...
<p>You could try something like:</p> <pre><code>import pyspark.sql.functions as F list_example = [1,3,5,7,8] new_df = df.withColumn(&quot;new_column&quot;, F.array( [F.lit(x) for x in list_example] )) new_df.show() </code></pre>
python|pandas|apache-spark|pyspark|rdd
0
9,214
70,880,328
Pandas dataframe manipulation/re-sizing of a single-column count file
<p>I have a file that looks like this:</p> <pre><code>gRNA_A gene_a 140626 gene_b 227598 gene_c 115781 gRNA_B gene_a 125003 gene_b 102000 gene_c 200300 </code></pre> <p>I want to read this into a pandas dataframe and re-shape it so that it looks like this:</p> <pre><code> gene_a gene_b gene_c gRNA_A 140626 2275...
<p>Not sure if this is the cleanest way, but this works for the given example.</p> <p>I created a file <code>data.txt</code> with provided sample.</p> <p>I assumed the count is always a number.</p> <pre><code>def file_parser(f_path): data_dict = {} my_gRNA = None my_gene = None with open(f_path, &quot;r...
python|pandas|dataframe|reshape
1
9,215
71,067,544
CNN Transfer Learning Takes Too Much Time
<p>I'm trying to train my model with transfer learning with Vgg16 via Google Colab(using GPU) but it takes too time and validation and test accuracy is low. Additional informations; Train data is 16057 , test data is 4000, validation data is 2000 with different sized rgb images. Classes facial mood expressions (Happy,S...
<p>Issue most likely related to &quot;ImageDataGenerator&quot;, try using workers=8 in your fit_generator.</p>
tensorflow|keras|conv-neural-network|transfer-learning
1
9,216
51,843,209
Use fields with NA values for model training with tensorflow
<p>I am trying to create a machine learning model with tensorflow using dataset available at <a href="https://www.kaggle.com/imnikhilanand/heart-attack-prediction" rel="nofollow noreferrer">https://www.kaggle.com/imnikhilanand/heart-attack-prediction</a></p> <p>The csv file looks like below (please note I have replace...
<p>Looking at the <a href="https://www.kaggle.com/imnikhilanand/heart-attack-prediction" rel="nofollow noreferrer">data</a>, and realizing that the <em>vast majority</em> of the values in the three attributes <code>scope</code>, <code>ca</code>, and <code>thal</code> are missing, the most certain thing you should do is...
pandas|tensorflow|machine-learning
0
9,217
51,657,128
How to access the adjacent cells of each elements of matrix in python?
<p>Here two cells are considered adjacent if they share a boundary. For example :</p> <pre><code>A = 5 6 4 2 1 3 7 9 8 </code></pre> <p>Here adjacent elements to index 0,0 is at index [0,1] and [1,0] and for index 1,1 the adjacent elements are at index [0,1],[1,0],[2,1] and [1,2].</p>
<p>Supposed you have <code>m</code>x<code>n</code> matrix, and you want to find the adjacent indices of the cell (<code>i</code>, <code>j</code>):</p> <pre><code>def get_adjacent_indices(i, j, m, n): adjacent_indices = [] if i &gt; 0: adjacent_indices.append((i-1,j)) if i+1 &lt; m: adjacent_...
python|python-3.x|algorithm|numpy|implementation
6
9,218
36,015,409
moving average with time offset pandas
<p>I looking for a vectorized solution to calculating a moving average with a date offset. I have an irregularly spaced times series of costs for a product and for each value I would like to calculate the mean of the previous three values, with a date offset of 45 days. For example if this were my input dataframe:</p> ...
<p>Try something like this:</p> <pre><code>#Set up DatetimeIndex (easier to just load in data with index as OrDate) df = df.set_index('OrDate', drop=True) df.index = pd.DatetimeIndex(df.index) df.index.name = 'OrDate' #Save original timestamps for later idx = df.index #Make timeseries with regular daily interval df ...
python|pandas|time-series
0
9,219
35,917,281
Iterate over 'zipped' ranges of a numpy array
<p>I often work with numpy arrays representing critical times in a time series. I then want to iterate over the ranges and run operations on them. Eg:</p> <pre><code>rngs = [0, 25, 36, 45, ...] output = [] for left, right in zip(rngs[:-1], rngs[1:]): throughput = do_stuff(array[left:right])... output.appen...
<p>You might use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">enumerate</a> generator</p> <pre><code>rngs = [0, 25, 36, 45, ...] output = [] for index, _ in enumerate(rngs[:-1]): throughput = do_stuff(array[index:index+1])... output.append(throughput) </code></pre> <...
python|arrays|numpy
0
9,220
35,940,114
Write a pandas df into Excel and save it into a copy
<p>I have a pandas dataframe and I want to open an existing excel workbook containing formulas, copying the dataframe in a specific set of columns (lets say from column A to column H) and save it as a new file with a different name.</p> <p>The idea is to update an existing template, populate it with the dataframe in a...
<p>The below should work, assuming that you are happy to copy into column A. I don't see a way to write into the sheet starting in a different column (without overwriting anything).</p> <p>The below incorporates @MaxU's suggestion of copying the template sheet before writing to it (having just lost a few hours' work o...
python|excel|pandas
2
9,221
37,445,334
Pandas Cannot Create a DataFrame from a Numpy Array Of Timestamps
<p>I have a numpy array of Pandas Timestamps:</p> <pre><code>array([[Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T')], [Timestamp('2016-05-02 17:10:00+0000', t...
<p>I think you can use <code>list</code> comprehension:</p> <pre><code>import pandas as pd import numpy as np a =np.array([[pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC...
python|arrays|numpy|pandas|dataframe
1
9,222
42,119,434
ipython notebook view wide pandas dataframe vertically
<p>In Pandas 0.18.1, say I have a dataframe like so:</p> <pre><code>df = pd.DataFrame(np.random.randn(100,200)) df.head() 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 </code></pre> <p>What if I wanted to view this vertica...
<p>If you want to see just a few records, try this.</p> <pre><code>df.head(3).transpose() </code></pre>
python|pandas|jupyter-notebook
12
9,223
37,797,325
Using Pandas, How to replace the last word of the string with an empty strings without distorting rest of the string?
<p>I can't share the actual data. So I am taking an example. Suppose I have a list of suffixes - </p> <pre><code>Suffix_List = ["Ltd.", "Inc.", "Limited", "Corp.", "AG"] </code></pre> <p>I have a data frame with a column containing company names. I want to replace the suffixes of the company name with an empty strin...
<p>You can use regex to substitute out the suffix:</p> <pre><code>In [11]: re.sub("\s?(" + "|".join(Suffix_List) + ")$", "", "CAGE AG") Out[11]: 'CAGE' </code></pre> <p><em>This looks whether any (<code>|</code>) of the suffixes ends (<code>$</code>) the string.</em></p> <p>On the Series/column you can use <a href="...
python|pandas
2
9,224
37,733,225
Explaining the difference between sklearn's scale() and multiplying by STD and adding the mean
<p>I'm running sklearn's PCA <code>fit_transform()</code> function on some data I'm looking to analyze, and I'm having trouble figuring out how exactly I need to transform scaled data back into numbers that make sense within the context of what I'm running. More specifically, when I run:</p> <pre><code>import pandas ...
<p>sklearn uses zero degrees of freedom in their standard deviation calculation:</p> <pre><code>import pandas as pd import numpy as np from sklearn.preprocessing import scale np.random.seed([3,1415]) otr_df = pd.DataFrame(np.random.rand(10, 10)) X_scaled = scale(otr_df) X_scaled2 = otr_df.sub(otr_df.mean()) X_scale...
python|numpy|pandas|scikit-learn
2
9,225
31,655,929
Does spark dataframe have a "row name" for each row like pandas?
<p>I am trying to use Spark DataFrames to operate on two DataFrames indexing by row name. In pandas, we can do </p> <pre><code>df.loc(['aIndex', 'anotherIndex']) </code></pre> <p>to select two rows in the df by the index (or name of the row). How to achieve this in Spark DataFrame? Thanks. </p>
<p>No, there is no row indexing in Spark. Spark Data Frames are more like tables in relational database so if you want to access specific row you have to filter:</p> <pre><code>df = sqlContext.createDataFrame( [("Bob", 5), ("Alice", 6), ("Chuck", 4)], ("name", "age")) df.where("name in ('Bob', 'Alice')") df.where...
python|pandas|apache-spark|pyspark|apache-spark-sql
4
9,226
64,447,637
Creating masks for duplicate elements in Tensorflow/Keras
<p>I am trying to write a custom loss function for a person-reidentification task which is trained in a multi-task learning setting along with object detection. The filtered label values are of the shape (batch_size, num_boxes). I would like to create a mask such that only the values which repeat in dim 1 are considere...
<p>This code works:</p> <pre><code>x = tf.constant([[0,0,0,0,12,12,3,3,4], [0,0,10,10,10,12,3,3,4]]) def mark_duplicates_1D(x): y, idx, count = tf.unique_with_counts(x) comp = tf.math.greater(count, 1) comp = tf.cast(comp, tf.int32) res = tf.gather(comp, idx) mult = tf.math.not_equal(x, 0) mult = tf.cast(mu...
python|tensorflow|keras|deep-learning
1
9,227
58,875,944
how can I write for loop in python for copy pandas dataframe
<p>I'm newbie in data engineer. now i try to write python code for duplicate data from from pandas dataframe. for example data : </p> <pre><code> A B C D E F G E 1 2 3 4 0 1 0 1 5 6 7 8 0 1 1 0 9 1 2 3 0 1 0 1 </code></pre> <p>I need to copy dataframe to</p> <pre><code>dfE = A B C D E ...
<p>Hi piyaphong welcome to stackoverflow,</p> <p>Basically pandas allow to select columns with column names, you can look at the code below which would probably solve your case.</p> <pre><code>from io import StringIO import pandas as pd data = """ A B C D E F G E 1 2 3 4 0 1 0 1 5 6 7 8 0 1 1 0 9 1 2 3 0 1 0 1 """ ...
python|pandas
0
9,228
70,347,202
converting float number into datetime format
<p>I have a file that contains DateTime in float format<br /> example <code>14052020175648.000000</code> I want to convert this into <code>14-05-2020</code> and leave the timestamp value.</p> <p>input ==&gt; <code>14052020175648.000000</code></p> <p>expected output ==&gt; <code>14-05-2020</code></p>
<p>Use <code>pd.to_datetime</code>:</p> <pre><code>df = pd.DataFrame({'Timestamp': ['14052020175648.000000']}) df['Date'] = pd.to_datetime(df['Timestamp'].astype(str).str[:8], format='%d%m%Y') print(df) # Output: Timestamp Date 0 14052020175648.000000 2020-05-14 </code></pre> <p>I used <code>ast...
python|pandas|datetime
2
9,229
70,204,990
NumPy filling values inside given bounding box coordinates for a large array
<p>I have a very large 3d array</p> <pre class="lang-py prettyprint-override"><code>large = np.zeros((2000, 1500, 700)) </code></pre> <p>Actually, <code>large</code> is an image but for each coordinate, it has 700 values. Also, I have 400 bounding boxes. Bounding boxes <strong>do not</strong> have a fixed shape. I stor...
<p>One big problem is that the input is really <em>huge</em> (~15.6 GiB). Another is that it is travelled up to 400 times in the worst case (resulting in up to 6240 GiB to be written in RAM). The thing is that <em>overlapping regions</em> written <em>multiple times</em>.</p> <p>A better solution is to iterate over the ...
python|arrays|numpy|performance|numpy-ndarray
4
9,230
56,180,685
How to load such [[a,b,c],[d,e,f]..........]data into python from csv file?
<p>Hi I have some date in the follwing format [[a,b,c],[d,e,f],.........] in a csv file.</p> <p>Its a 3x100 array. Please suggest me how to load the data to numpy arrray and I also want to perform one hot encoding upon it.</p>
<p>You have not shared the csv file correctly, here is my best guess</p> <p>first, read the data from file using simple file read operation next use json module to convert it to list</p> <pre><code>import json a= '[[1,11,1],[7,7,77],[5,6,7]]' a = json.loads(a) </code></pre> <p>it will give you list of list as <code...
python|machine-learning|numpy-ndarray
4
9,231
39,494,056
Progress bar for pandas.DataFrame.to_sql
<p>I want to migrate data from a large csv file to sqlite3 database.</p> <p>My code on Python 3.5 using pandas:</p> <pre><code>con = sqlite3.connect(DB_FILENAME) df = pd.read_csv(MLS_FULLPATH) df.to_sql(con=con, name="MLS", if_exists="replace", index=False) </code></pre> <p>Is it possible to print current status (pr...
<p>Unfortuantely <code>DataFrame.to_sql</code> does not provide a chunk-by-chunk callback, which is needed by tqdm to update its status. However, you can process the dataframe chunk by chunk:</p> <pre><code>import sqlite3 import pandas as pd from tqdm import tqdm DB_FILENAME='/tmp/test.sqlite' def chunker(seq, size):...
python|sqlite|pandas|dataframe|tqdm
34
9,232
39,706,277
Numpy: Why is difference of a (2,1) array and a vertical matrix slice not a (2,1) array
<p>Consider the following code:</p> <pre><code>&gt;&gt;x=np.array([1,3]).reshape(2,1) array([[1], [3]]) &gt;&gt;M=np.array([[1,2],[3,4]]) array([[1, 2], [3, 4]]) &gt;&gt;y=M[:,0] &gt;&gt;x-y array([[ 0, 2], [-2, 0]]) </code></pre> <p>I would intuitively feel this should give a (2,1) vector of zeros.</p>...
<p><code>numpy.array</code> indexes such that a single value in any position collapses that dimension, while slicing retains it, even if the slice is only one element wide. This is completely consistent, for any number of dimensions:</p> <pre><code>&gt;&gt; A = numpy.arange(27).reshape(3, 3, 3) &gt;&gt; A[0, 0, 0].sha...
python|arrays|numpy
1
9,233
39,646,480
numpy.savetxt() -- tuple index out of range when writing string to text file
<p>I am trying to write two strings into a .txt file using numpy.savetxt(). I want the strings to be on consecutive lines. However, when I run my code, I get the following error:</p> <pre><code>ncol = X.shape[1] IndexError: tuple index out of range </code></pre> <p>Which occurs at the first line I call np.savetxt(...
<p>According to the @moses-koledoye comment and @jvnna's answer, the following is the correct answer.</p> <p>The <code>hi</code> and <code>bye</code> variables are of type <code>string</code></p> <pre><code>hi = 'Hello {}'.format(name1) bye = 'Goodbye {}'.format(name2) </code></pre> <p>You are trying to save them t...
python|numpy
0
9,234
39,675,085
Generating normal distribution in order python, numpy
<p>I am able to generate random samples of normal distribution in numpy like this.</p> <pre><code>&gt;&gt;&gt; mu, sigma = 0, 0.1 # mean and standard deviation &gt;&gt;&gt; s = np.random.normal(mu, sigma, 1000) </code></pre> <p>But they are in random order, obviously. How can I generate numbers in order, that is, val...
<p>To (1) generate a random sample of x-coordinates of size n (from the normal distribution) (2) evaluate the normal distribution at the x-values (3) sort the x-values by the magnitude of the normal distribution at their positions, this will do the trick:</p> <pre><code>import numpy as np mu,sigma,n = 0.,1.,1000 def...
python|numpy|normal-distribution
1
9,235
44,021,986
Write ndarray with strings in first row followed by a matrix of numbers
<p>Let's say that I create a big matrix with np.vstack with a vector of strings as a first row followed by a matrix with numbers. How can I save/write in to a file? and in a nice aligned way?</p> <p>Simplifying:</p> <pre><code>names = np.array(['NAME_1', 'NAME_2', 'NAME_3']) floats = np.array([ 0.1234 , 0.5678 , 0....
<p>Apparently I found a solution following the kazemakase comments. It feels quite inefficient for big matrices but it does the work:</p> <pre><code>names = np.array(['NAME_1', 'NAME_2', 'NAME_3']) floats = np.array([[ 0.1234 , 0.5678 , 0.9123 ], [ 0.1234 , -0.5678 , 0.9123 ]]) with open('test....
numpy|python-3.6
2
9,236
69,452,672
Does "tf.keras.losses.SparseCategoricalCrossentropy()" work for all classification problems?
<p>For <code>tf.keras.losses.SparseCategoricalCrossentropy()</code>, the documentation of TensorFlow says</p> <p><code>&quot;Use this crossentropy loss function when there are two or more label classes.&quot;</code></p> <p>Since it covers two or more labels, including binary classification, then does it mean I can use ...
<p>BinaryCrossentropy ie like a special case of CategoricalCrossetropy with 2 classes, but BinaryCrossentropy is more efficient than CategoricalCrossentropy in calculation. With CategoricalCrossentropy loss you should take the outputs as 2 dimension, while with BinaryCrossentropy 1 dimension is enough. It means you can...
python|tensorflow|keras
1
9,237
69,386,912
Is there any way to use `.pkl` sklearn model in Pyspark DataFrame
<p>If dataframe using pandas, here's what I did</p> <pre><code>import joblib lgbm_v5 = joblib.load('model.pkl') b = lgbm_v5.predict_proba(X_test) </code></pre> <p>Is there any way to use <code>.pkl</code> sklearn model in Pyspark DataFrame?</p>
<p>Here is an example with a simple sentiment analysis to get you started.</p> <p>Once you get the hang of it, it can be become much more elaborated for even better performance (pandas_udf, preds over vectorized numpy arrays).</p> <pre><code>from functools import partial import joblib import numpy as np from pyspark....
python|pandas|dataframe|pyspark
1
9,238
69,544,827
Data frame: get row and update it
<p>I want to select a row based on a condition and then update it in dataframe.</p> <p>One solution I found is to update <code>df</code> based on condition, but I must repeat the condition, what is the better solution so that I get the desired row once and change it?</p> <pre><code>df.loc[condition, &quot;top&quot;] = ...
<p>Extract the boolean mask and set it as a variable.</p> <pre><code>m = condition df.loc[m, 'top'] = 1 df.loc[m, 'pred_text1'] = 2 df.loc[m, 'pred1_score'] = 3 </code></pre> <p>but the shortest way is:</p> <pre><code>df.loc[condition, ['top', 'pred_text1', 'pred_score']] = [1, 2, 3] </code></pre> <p><strong>Update</st...
pandas|dataframe
1
9,239
54,207,414
Is there a better way to deal with row dependency within a group when performing some calculations on a specific column?
<p>I have a dataframe and for some columns the one row is conditional on previous row's value. Also this dependence is only within a group identified by for example, 'gid'.</p> <p>What I did is basically create another dataframe and then transpose the column(s) used for calculations. The steps I used in the attached c...
<p>I think the following code will do the job, much simple.</p> <pre><code>def myfunc(df, id=0, column='x'): return np.fmax(df.loc[df['id'] == id, column], np.add(df.loc[df['id'] == id - 1, column], df.loc[df['id'] == id, 'y'])) for id in range(1, 5): df_1.loc[df...
python|pandas|numpy
0
9,240
53,824,556
How to install Numpy and Pandas for AWS Lambdas?
<p><strong>Problem:</strong> I wanted to use Numpy and Pandas in my AWS lambda function. I am working on Windows 10 with PyCharm. My function compiles and works fine on local machine, however, as soon as package it up and deploy on AWS, it breaks down giving errors in importing the numpy and pandas packages. I tried re...
<p>Like often there is more than one way to come to a solution.</p> <p>The preferred way imho is to use AWS lambda layers, because it separates the functional code from the dependencies. The basics are explained <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html" rel="noreferrer">here</a>....
python|pandas|amazon-web-services|numpy|aws-lambda
8
9,241
53,892,742
ndarray array2string output format
<p>I know this is a simple question, but can only find part of the answer on SO, and can't figure out how to do from Python or Numpy documentation. I'm sure it's documented, I just don't understand. </p> <p>I need to print/write using a fixed format (6 fields at 13.7e). The array I need to print might have 4, 8, 12...
<p>The output of <code>np.array2string</code> is just a string. You can format it using normal string methods. For instance, you can strip off the lead/tail brackets and replace spaces with nothing using:</p> <pre><code>foo = np.arange(12.) s = (np.array2string(foo, separator='', formatter={'floa...
python|numpy|numpy-ndarray
3
9,242
66,153,246
A str value changed over time & Customer dimension(s) in Pandas
<p>I have some customer data over dates and I want to see if for example they choose another product over time. Ideally, i'd like to copy the two columns where the changes occurred into a new column.</p> <p>So, if I had a table like</p> <pre><code>period, Customer , product 2020-01, Cust1, 12 TS 2020-02, Cust1, 12 TS 2...
<p>We can do this in a number of ways, I would suggest using <code>shift</code> and <code>groupby</code> to find the max record and then <code>.loc</code> to filter your query set appropriately.</p> <h3>setup.</h3> <pre><code>from io import StringIO import pandas as pd d = &quot;&quot;&quot;period, Customer, quantity...
python|pandas|dataframe|logic
1
9,243
66,248,368
How create a pandas dataframe for encoding nltk frequency-distributions
<p>Hej, I´m an absolute beginner in Python (a linguist by training) and don´t know how to put the twitter-data, which I scraped with Twint (stored in a <code>csv-file</code>), into a <code>DataFrame</code> in Pandas to be able to encode <code>nltk frequency-distributions</code>. Actually I´m even not sure if it is impo...
<p>You do not need to split your csv in a train and a test set. That's only needed if you are going to train a model, which is not the case. So simply load the original unsplit csv file:</p> <pre><code>import pandas as pd data = pd.read_csv(&quot;filename.csv&quot;) </code></pre> <p>The next step is to clean the tweet...
python|pandas|nltk
0
9,244
66,308,078
How to solve an Attribute Error -- no attribute 'register_op_list' in tensorflow?
<p>I'm trying to run this in jupyter and I get an AttributeError</p> <pre><code>%matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (12,8) import numpy as np import tensorflow as tf import keras import pandas as pd from keras_tqdm import TQDMNotebookCallback </code></pre> <p>I did a sear...
<p>Solution:</p> <pre><code>!pip install tensorflow==2.6.0 !pip install tensorflow-addons !pip install -q &quot;tqdm&gt;=4.36.1&quot; import tensorflow as tf import tensorflow_addons as tfa %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (12,8) import numpy as np import tensorf...
python|python-3.x|tensorflow|keras
0
9,245
52,822,548
How to convert a column with null values to datetime format?
<p>How I convert the df to pandas datetime datatype? (with null value)</p> <pre><code>datet = pd.DataFrame(['2018-09-07 00:00:00','2017-09-15 00:00:00',''],columns=['Mycol']) datet['Mycol'] = datet['Mycol'].apply(lambda x: dt.datetime.strptime(x,'%Y-%m-%d %H:%M:%S')) </code></pre> <p...
<p>Just do:</p> <pre><code>datet['Mycol'] = pd.to_datetime(datet['Mycol'], errors='coerce') </code></pre> <p>This will automatically convert the null to an <code>NaT</code> value.</p> <p>Output:</p> <pre><code>0 2018-09-07 1 2017-09-15 2 NaT </code></pre>
python|pandas|datetime|type-conversion
10
9,246
52,728,812
How to Animate multiple columns as dots with matplotlib from pandas dataframe with NaN in python
<p>I have a question that maybe is asked before, but I couldn't find any post describing my problem.</p> <p>I have two pandas dataframes, each with the same index, representing x coordinates in one dataframe and y coordinates in the other. Each colum represent a car that started a specific timestep, logged every step ...
<p>I've reformatted your code, but I think your main issue was that your dataframes start with a index of 1, but when you're calling your animation with <code>frames=4</code>, it's calling <code>update()</code> with <code>i=[0,1,2,3]</code>. Therefore when you do <code>get_data_x(0)</code> you raise a <code>KeyError: '...
python-3.x|pandas|dataframe|animation|matplotlib
1
9,247
52,720,467
Maximum between an array and a number
<p>When using:</p> <pre><code>import numpy as np A = np.array([1,2,-3,-1, 0,3,-1]) print [max(A[j], 0) for j in range(len(A))] </code></pre> <p>we get <code>[1, 2, 0, 0, 0, 3, 0]</code>, as desired.</p> <p><strong>How to get the same directly with a numpy function, such as <a href="https://docs.scipy.org/doc/numpy/r...
<p>It's just <code>np.maximum(A, 0)</code>. Contrary to <code>np.max</code> function, it accepts <em>two</em> arguments, and compares them element-wise. In your case, since the second argument is a scalar value, the comparison will happen by <em>broadcasting</em> it.</p>
python|arrays|numpy|max
2
9,248
46,503,087
Change Index and Reindex Pandas DataFrame
<p>I have a Python dictionary and I created a panda data frame like below:</p> <p><a href="https://i.stack.imgur.com/DH5Kg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DH5Kg.png" alt="enter image description here"></a></p> <p>I want to change the name of index column to <code>date</code> . But I...
<p><code>data.set_index('date')</code> here only assign the column with name 'date' as index for the dataframe <code>data</code>.</p> <p>You can rewrite the name of the column using <code>data.index.name = 'data'</code></p>
pandas
0
9,249
58,504,332
how to add a variable in a dictionary with several dataframes?
<p>I have a dictionary with several dataframes that looks like this:</p> <pre><code>dataframes = {'Df_20100101': DataFrame, 'Df_20100102': DataFrame, 'Df_20100103': DataFrame} </code></pre> <p>The keyname for each dataframe is composed by Df_ followed by the date 2010 [year], 01[month] and 01[day].</p> <p>For each d...
<p>Use dictionary comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>:</p> <pre><code>dataframes = {key:val.assign(Key = pd.to_datetime(key.split('_')[1])) for key, val ...
python|pandas|dictionary|for-loop|generate
1
9,250
58,459,189
Is there a minimum term length required for features in Sklearn TfidfVectorizer
<p>I have a pandas dataframe with sentences that I'm trying to calculate Tfidf on: </p> <pre><code>df['sentence'] = ['buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'buy donuts', 'purchase donuts', 'purchase donuts', 'purchase donuts', 'purc...
<p>Check out the regular expression used by your TfidfVectorizer which you do not explicitly set. This can be accessed (or changed) with the <code>token_pattern</code> parameter.</p> <p>It is <code>(?u)\b\w\w+\b</code> which you can see would prevent <code>2</code> or <code>I</code> from being recognized.</p> <p>I am ...
python|python-3.x|pandas|sklearn-pandas|tfidfvectorizer
0
9,251
58,389,161
Find and compare the last and the row before in a group it if it matches the criteria in python
<p>I have a dataframe that contains game data. For this game 2 players play a 90 minute game. However the game can last longer than 90 minutes for various reasons. What I want is to find games that player 1 won after the 90th minute mark. So I'd like the compare the end score for a game that: - lasted more than 90 minu...
<p>Edit: How about this?</p> <pre><code>endScores = games.loc[(games['time'] &gt; 90) &amp; (games['player 1'] &gt; games['player 2'])].groupby('game_id').nth(-1) beforeScores = games.loc[(games['time'] &lt;= 90) &amp; (games['player 1'] &lt;= games['player 2'])].groupby('game_id').nth(-1) compareGames = beforeScores....
python|pandas|dataframe|comparison
2
9,252
68,933,053
Why try/exception method is not working on my python?
<pre><code>import os.path from os import path import pandas as pd class ImportFiles: def __init__(self, pathname, file): self.pathname = pathname self.file = file def check(self): try: os.path.exists(self.pathname+'/'+self.file) print(f&quot;'{self.pathname}/{se...
<p><a href="https://docs.python.org/3/library/os.path.html#os.path.exists" rel="nofollow noreferrer">os.path.exists</a> returns True/False. It does not raise an exception. &quot;this file is valid to use&quot; will print regardless of whether the file exists because no exception stopped it.</p>
python|pandas|operating-system
3
9,253
44,480,208
Calling from a xlsx file I get attribute error but I do not when I create the dataframe pandas
<p>I am trying to do this with two dataframes:</p> <pre><code>df1 = df.copy() df1['emails'] = df1.emails.apply(lambda x: ','.join(set(map(str.strip, x.split(','))) - set(blacklisted.email))) df1 = df1[df1.emails != ''] </code></pre> <p>when I create the dataframe with the same information myself, and it returns the...
<p>Suppose you have:</p> <p>In <code>blacklisted.xlsx</code>:</p> <p><a href="https://i.stack.imgur.com/pLmZL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pLmZL.jpg" alt="enter image description here"></a></p> <p>In <code>customers.xlsx</code>:</p> <p><a href="https://i.stack.imgur.com/RXOxi.j...
python|csv|pandas|ipython
1
9,254
61,051,999
Dataframe value comparison
<p>I have data-frame like this</p> <p><a href="https://i.stack.imgur.com/PTwOy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PTwOy.png" alt="enter image description here"></a></p> <p>I want to compare a with c and b with d. When there is a nan or empty value, it will be considered as 0. <a href="...
<p><strong>ADDED ANSWER FOR YOUR 2ND QUESTION</strong></p> <p>To achieve what you want to do, simply compare the columns directly:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a':[1,3,5,7,9], 'b':[0,0,0,0,0], 'c':[1,3,5,7,9], 'd':[...
python|pandas|dataframe
3
9,255
60,831,188
Attribute 'getvalue' Error in Python (Pandas)
<p>I try to read .csv file using Pandas. When my programme starts to read a file it will get an error attribute not found. Output </p> <p><a href="https://i.stack.imgur.com/KDFma.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KDFma.png" alt="**This is my error**"></a></p> <p>here is my code.</p> ...
<p>It is most likely that you are asking pandas to read an empty file/ non-existent file. I face that problem in Open-CV too when I type in the wrong file name. Check your file name.</p> <p>The logic works like this: <code>variable = Non-Existant file</code> - so variable = NonType Object ie.Nothing so something to th...
python|python-3.x|pandas|csv|read.csv
0
9,256
71,641,351
Re-calibrate an existing regression model
<p>I have a pandas dataframe shown below (snapshot), I am trying to re-calibrate a regression equation. <code>Loss = (EXP(-1.01 + (-0.08 x mob)) x Price)</code> I wanted to fit regression on the new data available but not sure how I can input the new coefficients into the existing equation. Loss is my target variable ...
<p>You really have two choices about how to do the regression. One is to convert the exponential to a linear equation and solve with linear regression. (Note that your equation can be rewritten as <code>log(loss/price) = b1 + b2 * mob</code>, if you are unsure how, review your logarithm rules and prove it to yourself.)...
python|pandas|regression
1
9,257
42,280,506
How to replace items with their indices in a pandas series
<h3>Problem Statement</h3> <p>I have file containing a graph. The file is a csv with two columns, source name and target name. I'd like to generate a file/dataframe with source and target being numerical IDs instead of strings.</p> <p>I know this can be done in python, with something like</p> <pre><code>node_names =...
<p>I would opt for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow noreferrer"><code>pd.factorize()</code></a> across columns.</p> <pre><code>df.apply(lambda col: pd.factorize(col)[0]+1) </code></pre> <p>If you want unique ids in each column, you could just unstack ...
pandas
1
9,258
43,306,931
pandas: retrieve values post group by sum
<p>Pandas data frame(<strong>"df"</strong>) looks like :</p> <pre><code> name id time 1095 One 1 12:03:37.230812 1096 Two 2 10:56:29.314745 1097 Three 3 10:58:18.897624 1098 Three 3 09:45:38.755116 1099 ...
<p>I think you need convert column <code>time</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a> first.</p> <p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nof...
python|pandas
1
9,259
43,044,303
Using index arrays vs iterating in numpy
<p>I have many numpy arrays of about 50K elements. I want to compare them, using only certain positions of them (10% of them in the average), and performance matters. This looks like a good use case for index arrays. I can write this code:</p> <pre class="lang-py prettyprint-override"><code>def equal_1(array1, arra...
<p>For your purposes, you may want to use the just-in-time compiler <code>@jit</code> from <code>numba</code>. </p> <pre><code>import numpy as np from numba import jit a1 = np.arange(50000) a2 = np.arange(50000) # set some values to evaluation as false a2[40000:45000] = 1 indices = np.random.choice(np.arange(50000),...
python|numpy
1
9,260
72,245,113
How do I turn dataframe#1 into something i can properly graph, like dataframe#2?
<p>I have the following dataframe, based on data i pulled from my database:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">date</th> <th style="text-align: center;">event_type</th> <th style="text-align: right;">count</th> </tr> </thead> <tbody> <tr> <td style="te...
<pre><code>df.pivot(columns='event_type', index='date').fillna(0) </code></pre> <p>Output:</p> <pre><code> count event_type cart_add cart_remove page_view date 2022-05-10 0.0 0.0 3.0 2022-05-11 2.0 0.0 2.0 2022...
pandas|dataframe
0
9,261
72,186,680
Matplotlib and Pandas Plotting amount of numbers in certain range
<p>I have pandas Dataframe that looks like this:</p> <p><a href="https://i.stack.imgur.com/sCBp0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sCBp0.png" alt="DataFrame" /></a></p> <p>I am asking to create this kind of plot for every year [1...10] with the Score range of [1...10]. <strong>This mean...
<p>The following code works perfectly:</p> <pre><code>def visualize_yearly_score_distribution(ds, year): sns.set_theme(style=&quot;ticks&quot;) first_range = 0 second_range = 0 third_range = 0 fourth_range = 0 fifth_range = 0 six_range = 0 seven_range = 0 eight_range = 0 nine_range = 0 last_range = 0 score_list = [] ...
python|pandas|matplotlib|plot
0
9,262
50,663,135
Anchor boxes and offsets in SSD object detection
<p>How do you calculate anchor box offsets for object detection in SSD? As far as I understood anchor boxes are the boxes in 8x8 feature map, 4x4 feature map, or any other feature map in the output layer.</p> <p>So what are the offsets?</p> <p>Is it the distance between the centre of the bounding box and the centre ...
<p>We need offsets because thats what we calculate when we default anchor boxes, In case of ssd for every feature map cell they will have predefined number of anchor boxes of different scale ratios on very feature map cell,I think in the paper this number is 6.</p> <p>Now because this is a detection problem ,we will a...
tensorflow|keras|deep-learning|object-detection|pytorch
1
9,263
50,498,525
python Tensorflow ImportError
<p>Please help me with this error:</p> <blockquote> <p>import tensorflow as tf Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in from tensorflow.python.pywrap_tensorflow_internal import * File "/home/user/anac...
<p>You could try that:</p> <ol> <li><p>Confirm the python interpreter path, is anaconda or system python?</p></li> <li><p>export python library <code>export PYTHONPATH=xxxxx:$PYTHONPATH</code> to solve some lib couldn't find before execute a python script in terminal. </p></li> </ol> <p>If you following two step, ab...
python|tensorflow
1
9,264
50,363,253
Insert array from csv using pymongo
<p>I have a csv file with array in string format as below:</p> <pre><code>date,name,criteria 2018-05-16,John,"[{'age':35},{'birthyear':1983}]" 2018-05-16,Jane,"[{'age':36},{'birthyear':1982}]" </code></pre> <p>I am using Python with pandas and numpy for processing this</p> <p>I need to import this file into MongoDB ...
<p>As noted the main issue is the JSON "like" data within the "string" for the <code>criteria</code> lacks quotes around the keys. With quotes properly in place you can parse the string into a list the data is structured how you want.</p> <p>You could actually run <a href="https://docs.python.org/3/library/functions.h...
python-3.x|mongodb|pandas|numpy
0
9,265
50,563,215
Zero all values except max in Tensorflow
<p>I have an array <code>[0.3, 0.5, 0.79, 0.2, 0.11].</code></p> <p>I want to convert all values to zero except the max value. So the resulting array would be: <code>[0, 0, 0.79, 0, 0]</code></p> <p>What would be the best way to do this in a Tensorflow graph?</p>
<p>If you want to keep all occurences of the maximum, you could use</p> <pre><code>cond = tf.equal(a, tf.reduce_max(a)) a_max = tf.where(cond, a, tf.zeros_like(a)) </code></pre> <p>If you want to keep only one occurrence of the maximum, you could use</p> <pre><code>argmax = tf.argmax(a) a_max = tf.scatter_nd([[argma...
python|tensorflow
4
9,266
45,492,678
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 3: invalid continuation byte
<p>I'm trying to load a csv file using <code>pd.read_csv</code> but I get the following unicode error:</p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 3: invalid continuation byte </code></pre>
<p>Unfortunately, CSV files have no built-in method of signalling character encoding.</p> <p><code>read_csv</code> defaults to guessing that the bytes in the CSV file represent text encoded in the UTF-8 encoding. This results in <code>UnicodeDecodeError</code> if the file is using some other encoding that results in b...
pandas|csv|unicode|load|python-unicode
18
9,267
62,592,434
Is it possible to replace specific piece of strings for a range of columns in Python?
<p>Here's first <a href="https://i.stack.imgur.com/jy0f0.png" rel="nofollow noreferrer">five rows</a> of a dataset: <code>df.head()</code></p> <p>All numbers here are objects and I want to convert them to numeric. However, I want to change all columns at once with minimum lines of code. Here what I did:</p> <pre><code>...
<p>Assuming we have the following data set:</p> <pre><code>df = pd.DataFrame({ 'median household income': dict(a='1,000', b='2,000'), 'number of households': dict(a='3,500', b='1,200') }) </code></pre> <p>You can write a function that will be applied to all elements of the dataframe using <a href="https://panda...
python|pandas|jupyter-notebook|jupyter
0
9,268
62,588,946
how to remove image refrences stored in numpy array as string based on some condition
<p>I wanted to avoid using for loops so I switched to numpy array...</p> <pre><code>#SOURCE is the path where images are actually stored content = np.array(os.listdir(SOURCE)) # content contains array of element type str_ </code></pre> <p>I want to apply condition on content and get new arrays containing removed label...
<p>You can use <code>filter</code> for this.</p> <h3>Demonstrated how to filter from <code>list</code> and <code>numpy array</code> in below</h3> <pre><code>import os import numpy as np SOURCE = &quot;test&quot; </code></pre> <p>Get the list of file using <code>os.listdir</code></p> <pre><code>## files is list object ...
python|arrays|numpy
0
9,269
62,478,528
Pandas - populate new column based on existing column values
<p>I have the following dataframe <code>df_shots</code>:</p> <pre><code> TableIndex MatchID GameWeek Player ... ShotPosition ShotSide Close Position ShotsDetailID ... ...
<p>It's bad form to store so many related variables outside of a container, lets use a dictionary that we map to your dataframe.</p> <pre><code>data_dict = {'the boxthe centre': {'y':random.randrange(25,45)...} df['Position'] = df['Position'].map(data_dict) print(df['Position']) 6 {'y': 35, 'x': 2} 8 ...
python|pandas
1
9,270
62,776,121
How to apply an operation on a vector with offsets
<p>Consider the following <code>pd.DataFrame</code></p> <pre><code>import numpy as np import pandas as pd start_end = pd.DataFrame([[(0, 3), (4, 5), (6, 12)], [(7, 10), (11, 90), (91, 99)]]) values = np.random.rand(1, 99) </code></pre> <p>The <code>start_end</code> is a <code>pd.DataFrame</code> of shape <code>(X, Y)<...
<h3>Prospective approach</h3> <p>Looking at your sample data :</p> <pre><code>In [64]: start_end Out[64]: 0 1 2 0 (1, 6) (4, 5) (6, 12) 1 (7, 10) (11, 12) (13, 19) </code></pre> <p>It is indeed non-overlapping for each row, but not across the entire dataset.</p> <p>Now, we have <a hr...
pandas|numpy|offset
5
9,271
54,316,729
Extremely long time (over 10 minutes) to load TensorRT-optimized TensorFlow graphs from .pb file
<p>I'm experiencing extremely long load times for TensorFlow graphs optimized with TensorRT. Non-optimized ones load quickly but loading optimized ones takes <strong>over 10 minutes</strong> by the very same code:</p> <pre><code>trt_graph_def = tf.GraphDef() with tf.gfile.GFile(pb_path, 'rb') as pf: trt_graph_def.P...
<p>OK, I think I got it sorted out. I left protobuf 2.6.1 almost untouched, just installed 3.6.1 from sources with cpp implementation next to it and set the symlinks in a way that 3.6.1 is the default one. Now after:</p> <pre><code>export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp </code></pre> <p>all models load in ...
python|tensorflow|protocol-buffers|tensorrt
4
9,272
54,644,113
Opencv fitellipse draws the wrong contour
<p>I want to draw the ellipse contour around the given figure append below. I am not getting the correct result since the figure consist of two lines. </p> <p><strong><em>I have tried the following:-</em></strong></p> <ol> <li>Read the Image</li> <li>Convert the BGR to HSV</li> <li>Define the Range of color blue</li>...
<p>I try to run your code on C++ and add erosion, dilatation and convexHull for result contour:</p> <pre><code>auto DetectEllipse = [](cv::Mat rgbImg, cv::Mat hsvImg, cv::Scalar fromColor, cv::Scalar toColor) { cv::Mat threshImg; cv::inRange(hsvImg, fromColor, toColor, threshImg); cv::erode(threshImg, thre...
python-3.x|numpy|opencv|computer-vision|cv2
-1
9,273
73,720,191
concat strings from different columns and get unique values in pandas df
<p>I have an issue while trying to concat and use <code>set</code> on multiple columns.</p> <p>This is an example df:</p> <pre><code>df = pd.DataFrame({'customer id':[1,2,3,4,5], 'email1':['ex11@email.com',np.nan,'ex31@email.com',np.nan, np.nan], 'email2':['ex11@email.com' ,np.na...
<p>Try work on the values directly instead of joining them then split again:</p> <pre><code>df['ALL_EMAILS'] = df.filter(like='email').apply(lambda x: set(x.dropna().str.lower()) or None, axis=1) </code></pre> <p>Output:</p> <pre><code> customer id email1 email2 email3 ...
python|python-3.x|pandas|concatenation
1
9,274
73,619,615
fill missing datetime pandas
<p>I have a following problem. I have this df with 10Min interval:</p> <pre><code>df_dict = {&quot;value&quot; : [1, 1, 2, 3], &quot;datetime&quot; : [&quot;2022-09-05 07:20:00&quot;, &quot;2022-09-05 07:30:00&quot;, &quot;2022-09-05 07:20:00&quot;, &quot;2022-09-05 07:20:00&quot;], &quot;expedice&quot; : [&...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> with DatetimeIndex created by minimal and maximal datetime:</p> <pre><code>df1 = df.set_index(['expedice', 'datetime']) df1 = (df1.reindex(pd.MultiIndex...
python|pandas|dataframe|datetime
1
9,275
73,790,671
Take dataframe with column that has values from 0 to 360 and wrap around to -180 to 180
<p>I have a dataframe <code>df</code> with a column <code>'lon'</code> that has values which range from 0 - 15 and 250 - 360. I would like to wrap the values around from -180 to 180 without a for loop. So, the input is this:</p> <pre><code>df['lon'] = [1,10,15,250,360] </code></pre> <p>and the output should look like t...
<p>Technically, you can add 180, get the modulo 360, subtract 180:</p> <pre><code>df['lon'].add(180).mod(360).sub(180) </code></pre> <p>Other approach:</p> <pre><code>df['lon'].mask(df['lon'].gt(180), df['lon'].sub(360)) </code></pre> <p>In place modification:</p> <pre><code>df.loc[df['lon'].gt(180), 'lon'] -= 360 </co...
python|pandas
5
9,276
73,732,700
What is the best way to transform unmerged cells to merged cells with Pandas?
<p>I have an excel file (top image) where I'm trying to essentially go from individual rows to merged rows and retain the order (bottom). I was thinking about using the groupby function but I don't really need to calculate anything just transform it. Any ideas would be greatly appreciated.</p> <p>Sample Code:</p> <pre>...
<p>This is 95% of the way there.</p> <p>I just forced everything to be a string, built a list, then &quot;\n&quot;.join()ed the string</p> <p>This would not function as merged cells (merged cells give me chills), but would be human-readable in a similar way. Good luck.</p> <pre class="lang-py prettyprint-override"><cod...
python|excel|pandas|dataframe
1
9,277
71,227,954
Aggregating by two different columns
<p>I'm trying to aggregate this using python pandas, I'm trying to find the Sum of spend and visitors for each network, but only aggregregate them if the months are the same</p> <p>for example</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">month</th> <th style="te...
<p>You can group your pandas dataframe by <strong>network</strong> and by <strong>month</strong> and then call the <code>sum</code> method.</p> <pre><code>df.groupby(['network', 'month']).sum() </code></pre> <p>Returns:</p> <pre><code>network month spend visitors BBC 9 10 2 BBC...
python|sql|pandas
3
9,278
71,416,293
Potential bug in GCP regarding public access settings for a file
<p>I was conversing with someone from GCS support, and they suggested that there may be a bug and that I post what's happening to the support group.</p> <p><strong>Situation</strong></p> <p>I'm trying to adapt this Tensorflow demo ... <a href="https://www.tensorflow.org/hub/tutorials/tf2_arbitrary_image_stylization" re...
<blockquote> <p>If I've set public access the way I have, do I still need code as in the example on the 'Access public data' article just above?</p> </blockquote> <p>No, you don't need to. I actually did some testing and I was able to pull images in GCS, may it be set to public or not.</p> <p>As what we have discussed ...
tensorflow|google-cloud-platform|google-cloud-storage
1
9,279
52,184,478
math_ops.floor equivalent in Keras
<p>I'm trying to implement a custom layer in Keras where I need to convert a tensor of floats <code>[a, 1+a)</code> to a binary tensor for masking. I can see that Tensorflow has a <code>floor</code> function that can do that, but Keras doesn't seem to have it in <code>keras.backend</code>. Any idea how I can do this?</...
<p>As requested by OP, I will mention the answer I gave in my comment and elaborate more:</p> <p><strong>Short answer:</strong> you won't encounter any major problems if you use <code>tf.floor()</code>.</p> <p><strong>Long answer:</strong> Using Keras backend functions (i.e. <code>keras.backend.*</code>) is necessary...
tensorflow|keras|keras-layer|floor
5
9,280
60,357,469
Increase brightness of specific pixels in an image using python
<p>I would like to increase the brightness/vividness of the purple color in the following image:</p> <p><a href="https://i.stack.imgur.com/vf1Gn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vf1Gn.png" alt="enter image description here"></a></p> <p>Here is the color palette</p> <p><a href="https...
<p>Note you have converted the image from RGB (to HSV) and need to convert it from BGR (to HSV). </p> <p>If you only want to increase the brightness of the purple, then use cv2.inRange() for the purple color to create a mask. Then modify the input image everywhere with your current method. Then use the mask to combine...
python|image|numpy|opencv
2
9,281
60,357,990
Are these images too 'noisy' to be correctly classified by a CNN?
<p>I'm attempting to build an image classifier to identify between 2 types of images on property sites. I've split my dataset into 2 categories: [Property, Room]. I'm hoping to be able to differentiate between whether the image is of the outside of some property or a room inside the property.</p> <p>Below are 2 exampl...
<p>You are not post-processing the output of the classifier correctly, it outputs a probability in [0, 1], with <code>values &lt; 0.5</code> corresponding to the first class, and <code>values &gt;= 0.5</code> for the second class. You should change the code accordingly.</p>
tensorflow|machine-learning|image-processing|keras|neural-network
2
9,282
72,766,842
I am trying to find the time duration within a column with reference to change in activity status of a key column in python
<pre><code>Activity Schedule Activity Status Activity Date 1 Inactive 06/25/22 1 Inactive 06/21/22 1 Active 06/19/22 1 Inactive 06/18/22 2 Active 05/26/22 2 Active 05/23/22 2 Active 05/20/22 2 Inactive 04/14/22 3 Inactive 03/05/22 3 Inactive 02/28/22 3 Inactive 02/23...
<p>First, we have to sort the Dataframe values:</p> <pre><code>df = df.sort_values([&quot;Activity&quot;, &quot;Activity Date&quot;]) </code></pre> <p><strong>result:</strong></p> <pre><code>Activity Status Activity Date 1 Inactive 06/18/22 1 Active 06/19/22 1 Inactive 06/21/...
python|pandas
0
9,283
72,768,530
Transform Pandas DataFrame to custom JSON format
<p>I currently have a Python Pandas DataFrame that I would like to convert to a custom JSON structure. Does anyone know how I can achieve this? I'd love to hear it, thanks in advance!</p> <p>Current Pandas DataFrame structure:</p> <pre><code>ArticleNumber | Brand | Stock | GroupCode ----------------------------------- ...
<p>Use list with dict comprehension for custom format:</p> <pre><code>import json L = df.to_dict('records') df['DICT'] = [{&quot;Attributes&quot;:[{'Key':k,'Values':[v]} for k, v in x.items()]} for x in L] df['JSON'] = [json.dumps({&quot;Attributes&quot;:[{'Key':k,'Values':[v]} for ...
python|json|pandas
1
9,284
72,574,512
Is there a way to write a python function that will create 'N' arrays? (see body)
<p>I have an numpy array that is shape 20, 3. (So 20 3 by 1 arrays. Correct me if I'm wrong, I am still pretty new to python)</p> <p>I need to separate it into 3 arrays of shape 20,1 where the first array is 20 elements that are the 0th element of each 3 by 1 array. Second array is also 20 elements that are the 1st ele...
<p>Your array has shape (20, 3), this means it's a 2-dimensional array with 20 rows and 3 columns in each row.</p> <p>You can access data in this array by indexing using numbers or ':' to indicate ranges. You want to split this in to 3 arrays of shape (20, 1), so one array per column. To do this you can pick the column...
python|arrays|numpy
2
9,285
59,701,178
randomly select position in array with condition
<p>I have an array like this:</p> <pre><code>A = [[1,0,2,3], [2,0,1,1], [3,1,0,0]] </code></pre> <p>and I want to get the position of one of the cells with the value == 1 such as <code>A[0][0]</code> or <code>A[1][2]</code> and so on ...</p> <p>So far I did this:</p> <pre><code>A = np.array([[1,0,2,3], ...
<p>This should work for you.</p> <pre><code>A = np.array([[1,0,2,3], [2,0,1,1], [3,1,0,0]]) B = np.where(A == 1) C = [] for i in range(len(B[0])): Ca = [B[0][i], B[1][i]] C.append(Ca) D = random.choice(C) print(A[D[0]][D[1]]) </code></pre> <p>This gives the output.</p> <pre><c...
python|numpy
1
9,286
59,663,251
Why is SimpleImputer's fit_transform not working for dataframe in google colab?
<pre><code>imp = SimpleImputer(missing_values=np.nan, strategy='most_frequent') weather_test = imp.fit_transform(weather_test) </code></pre> <p>The above code is throwing error in google colab when weather_test is a pandas dataframe. But when I change weather_test to numpy array, it works.</p> <pre><code>imp = Simple...
<p>Scikit-learn's API methods generally assume the input will be a numpy array rather than a pandas dataframe. For an example of how to use this functionality with a dataframe, see <a href="https://stackoverflow.com/questions/35723472/how-to-use-sklearn-fit-transform-with-pandas-and-return-dataframe-instead-of-num">How...
pandas|scikit-learn|google-colaboratory
0
9,287
59,686,320
Filtering and Format dataframe from Webscrape
<p>I am new to Python, but know R decently. I am trying to webscrape stock price data from yahoo. I successfully retrieved the price data and able to create a dataframe. However, yahoo includes when dividends are paid out. For now, I would like to ignore dividends, but I am having trouble filtering the dataframe to rem...
<p><a href="https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas/38067805">This answer</a> should answer your date question. As for filtering, you should probably learn to use the <code>df.loc[]</code> functionality. <a href="https://www.kaggle.com/learn/pandas" rel="nofollow norefer...
python|pandas|dataframe|web-scraping
1
9,288
59,603,794
filtering pandas .isnull().any() output
<p>(This question can probably be generalized to filtering any Boolean Pandas series, but nothing that I can find on that subject addresses my issue.)</p> <p>Given this dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a': (1, None, 3), 'b': (4, 5, 6), 'c': (7, 8, None), 'd': (10, 11,...
<p>You can perform indexing on the columns with your mask:</p> <pre><code>&gt;&gt;&gt; df.columns[df.isnull().any()] Index(['a', 'c'], dtype='object') </code></pre> <p>Or if you want to show the data for the given columns:</p> <pre><code>&gt;&gt;&gt; df[df.columns[df.isnull().any()]] a c 0 1.0 7.0 1 NaN ...
python|pandas
4
9,289
59,721,654
Create a list where the even indexes have a path to a positive category and odd indexes have a path to the negative category
<p>I'm basically sorting my CNN images into a list with even and odd indexing. Even index will have positive images and odd index will have negative images. Here's my code so far:</p> <pre><code>from PIL import Image import matplotlib.pyplot as plt import os import glob import torch from torch.utils.data import Datas...
<p>Replace the code with:</p> <pre><code>directory=&quot;resources/data/&quot; </code></pre>
pytorch
0
9,290
59,565,756
Merge and delete rows according to two columns value
<p>I have a data frame with times and locations and I want to merge rows with the same date and location so the maximum time will move to "to" column and the row that I just used its time value will be removed. </p> <p>also, If the time difference is longer then 3 hours so the merge won't happen.</p> <pre><code>date...
<pre class="lang-py prettyprint-override"><code># sample dataframe df = pd.DataFrame( { "date": ["01", "01", "01", "01", "02", "02"], "time": ["01:02", "02:03", "04:05", "06:07", "08:09", "12:10"], "location": ["A", "A", "B", "B", "C", "C"], } ) # convert time column to datetime df["tim...
python|pandas
-2
9,291
40,717,614
Multiplication of tensors in a python list with a constant variable in tensorflow
<p>I have a 1D python list called <code>x</code>, of shape <code>(1000)</code> which contains tensor elements of shape <code>(3, 600)</code>. I also have a tensorflow variable <code>w</code> of shape <code>(600, 1)</code> which I would like to multiply to each tensor element of <code>x</code>. The result of each operat...
<p>Look into using tf.map_fn which maps a function along the first axis of a tensor. In you case you have x is a tensor of shape (1000, 3, 600). It does not matter that the first dim is a list. It will just act as a tensor.</p> <p><code>tf.map_fn(lambda x_: tf.matmul(x_, W), x)</code></p> <p>You could also use the...
matrix|tensorflow|product
0
9,292
18,626,709
How do I use k-means on time series data that has nans?
<p>I have a number of time series records that overlap at some times and don't necessarily have same start and end date. Each row represents a different time series. I made them all the same length to maintain the actual time of data collection.</p> <p>For example, at t(1,2,3,4,5,6):</p> <pre><code>Station 1: nan, na...
<p>K-means is not the best algorithm for this kind of data.</p> <p>K-means is designed to minimize within-cluster variance (= sum of squares, WCSS).</p> <p>But how do you compute variance with NaNs? And how meaningful is variance here anyway?</p> <p>Instead, you may want to use</p> <ul> <li>a similarity measure des...
python|numpy|time-series|cluster-analysis
2
9,293
18,569,408
Delete the elements of a array with a mask
<p>I want to delete the elements of an array with a mask. For example:</p> <pre><code>row = 24 col = 24 size = row * col a = numpy.ones((size)) mask = numpy.empty((col), dtype=numpy.bool) </code></pre> <p>The values of the <code>mask</code> are <code>False</code> or <code>True</code>. If <code>mask[x] = True</code>, ...
<p>Through this syntax you can delete the element of array</p> <pre><code>smaller_array =np.delete(array,index) </code></pre> <p>array indicates the array values index indicates the position of the elements</p>
python|numpy
1
9,294
61,917,777
3D object detection for custom objects; dataset creation
<p>How can I create a custom dataset for 3D object detection, I want to use the "Stanford3dDataset" or "Scannet" as baseline and add my object of interest in the dataset. I have the PCD files captured from the 3D camera [Realsense] and for 3D object detection, I am using the Pointnet model. </p> <p>I see the dataset ...
<p>import open3d as o3d</p> <p>import numpy as np</p> <h1>Load saved point cloud</h1> <p>pcd_load = o3d.io.read_point_cloud(&quot;try.ply&quot;)</p> <h1>convert PointCloud to numpy array</h1> <p>xyz_load = np.asarray(pcd_load.points)</p> <h1>Save points into a text file</h1> <p>np.savetxt('test.txt', xyz_load)`</p> <p>...
3d|object-detection|tensorflow-datasets|point-cloud-library|point-clouds
0
9,295
62,023,067
Python/Numpy - return slope for simple linear regression in a new array
<p>I'm searching for an answer for the following problem:</p> <p>I want to create a numpy array where all the intercepts and slopes are stored. The slope is the increase of <code>means</code> over the <code>years</code>. I have found multiple ways to calculate the intercept/slope, but I really miss the link to get the...
<p>You can simply calculate your slopes and intercepts in lists and add them in.</p> <pre><code>x = np.array([(2000, 'A', '1',5), (2001, 'A', '1', 10), (2002, 'A', '1',15), (2003, 'A', '1', 20), (2000, 'A', '2',1), (2001, 'A', '2', 2), (2002, 'A', '2', 3), (2003, 'A', '2', 4)]...
python|arrays|numpy|linear-regression
1
9,296
62,018,408
Applying a Numba guvectorize function over time dimension of an 3D-Array with Xarray's apply_ufunc
<p>I have some problems getting this to work properly and I'm also open to other suggestions as I'm not 100% sure if I'm going the right way with this.</p> <p>Here is some simple dummy data:</p> <pre><code>times = pd.date_range(start='2012-01-01',freq='1W',periods=25) x = np.array([range(0,20)]).squeeze() y = np.arra...
<p>I'd point you out to <a href="https://stackoverflow.com/questions/58719696/how-to-apply-a-xarray-u-function-over-netcdf-and-return-a-2d-array-multiple-new/62012973">How to apply a xarray u_function over NetCDF and return a 2D-array (multiple new variables) to the DataSet</a>, the immediate goal is not the same, but ...
python|numpy|numba|python-xarray|numpy-ufunc
1
9,297
61,904,939
numpy:Change values in array by randomly differently selecting index
<p>I am new in numpy, and I am having troubles with simple managment of numpy arrays.</p> <p>I am doing a task in which it said that randomly daily select different 12 items in a numpy by index to change its value.</p> <pre><code>import numpy as np import random N = 20 s = np.zeros([N]) for t in range(12): random...
<p>I'm having a little difficulty understanding what you're asking, but I think you want a way to be selecting different values in a randomized order. And the problem with the above code is that you may be getting duplicates. </p> <p>I have two solutions. One, you can use the <a href="https://coderslegacy.com/python/l...
python|arrays|numpy
0
9,298
61,735,110
File names on CSV with bad line errors
<p>I'm using the following code below to capture bad line errors when reading a csv through pandas. I'm having trouble getting the filename to be included. I tried using a list to append during the loop but resulted in every file showing an error instead of just the files with errors.</p> <p>How can I get the filename...
<p>I was able to get the following working code : </p> <pre><code>import os import sys import glob import pandas as pd from io import StringIO from pathlib import Path UnzipFilePoint = Path(str(os.getcwd()) + '/Unzipped/') def FindBadLines(zipPath): mylist = [] for f in glob.glob(zipPath): f_name = ...
python|pandas|csv|dataframe
0
9,299
57,950,035
FFT of np.cos has two peaks
<p>For some reason, the following snippet produces an FFT graph with two negative peaks, despite the fact that <code>wave</code> only consists of one <code>cos</code> and nothing else.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt scale1 = 1.0 scale2 = 1.0e-1 N...
<p>There are a couple of small mistakes in your script and your expectation:</p> <ol> <li><p>A cosine has two peaks in the FT at +freq and -freq because <code>cos fx = 1/2(exp ifx + exp -ifx)</code></p></li> <li><p>Where you are using <code>fftshift</code> you should be using <code>fftfreq</code> instead, since you ar...
python-3.x|numpy|fft
0