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
349,800
61,733,315
How to do I extract values from a pandas series
<p>Suppose I have a pandas series object where each value is a list. How do i change this series to DataFrame with columns say <code>[a,b,c,d,e,f]</code></p> <p>Series I have - <br><br></p> <pre><code>0 [0.7142, 0.833334, 1.0, 1.0, 1.0, 1.0] 1 [0.7142, 0.273924, 1.0, 1.0, 1.0, 1.0] </code></pre> <p>etc</p> <p>expec...
<p>IIUC:</p> <pre><code>pd.DataFrame(list(s), columns = ['a','b', 'c','d','e','f']) </code></pre>
python|pandas
4
349,801
61,859,500
Divide all numbers in dataframe for a constant
<p>I want to divide all my dataframe values by 2233 (with precision of 2 decimal places)</p> <p>How can I do that? I know that if it were a matrix, 2 nested loops could solve.</p> <p><a href="https://i.stack.imgur.com/7Z0kW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Z0kW.png" alt="My datafram...
<p>We can try </p> <pre><code>value=2233 df=(df/value).round(2) </code></pre>
python|pandas|dataframe
3
349,802
62,012,488
how do I interpret np.einsum("ijij->ij"
<p>I am trying to make sense of np.einsum, and there does not appear to be examples related to my specific context. There are many good examples in the <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer">numpy docs</a>, a <a href="https://ajcr.net/Basic-guide-to-einsum...
<p>There's no multiplication since there's only one argument:</p> <pre><code>In [25]: arr = np.arange(36).reshape(1,6,1,6) In [26]: arr Out[26]: array([[[[ 0, 1, 2, 3, 4, 5]], [[ 6, ...
python-3.x|numpy|array-broadcasting|numpy-einsum
1
349,803
61,736,348
How to create index and column for an Excel Dataset in Python
<p>I am doing data analysis with apriori algorithm in Python. I imported the Apriori algorithm into my code page, but the data I have cannot be processed. It is about the sales data of a company. However, the data is arranged so that one product corresponds to each line. As you can see in the visual, I want to change t...
<p>import pandas as pd import numpy as np import matplotlib.pyplot as plt </p> <p>from apyori import apriori</p> <p>market_basket = pd.read_excel("C:/Users/Lenovo/Desktop/Python_Programlama/reading_data/ornekcalısma.xlsx") market_basket.head()</p> <p>market_basket.shape</p> <p>yeni_veri = market_basket.pivot_tabl...
python|excel|pandas|numpy|apriori
0
349,804
61,725,306
Is there a quick method to project points onto an certain grid?
<p>I am now trying to project n points with 3 dimensional coordinates (x,y,z) onto a xy-grid with a certain size (like 64*64), of course the coordinate of such n points is restricted in this grid.</p> <p>The goal is to print z coordinate of points which are projected onto each of grid elements. I write two for-loops, ...
<p>To print all the entries of <code>Z_coordinate</code> that coorespond to a specific point in <code>X_coordinate</code> and <code>Y_coordinate</code> you can do:</p> <pre class="lang-py prettyprint-override"><code>for i in range(XY_grid.shape[0]): for j in range(XY_grid.shape[1]): print(Z_coordinate[np.l...
python|numpy
0
349,805
61,765,850
Convert UTC timestamp column but get ValueError: time data '-27' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
<p>Given a UTC timestamp column from dataframe, I want to convert them into format like <code>2018-10-07 06:59:05.162000</code>:</p> <pre><code> _source.@timestamp 0 2018-10-07T06:59:05.162Z 1 2018-10-07T06:59:05.075Z 2 2018-10-07T06:59:05.103Z 3 2018-10-07T06:59:05.093Z 4 2018-10-07T06:59:05.108Z 5 2018...
<p>The column name <code>'_source.@timestamp'</code> makes python think its an email hyperlink and not a string, hence you are getting a keyError.</p> <p>Do this instead -</p> <pre><code>df.iloc[:,0] = pd.to_datetime(df.iloc[:,0], format='%Y-%m-%dT%H:%M:%S.%fZ') </code></pre> <p>Output-</p> <pre><code>0 2018-10-0...
python-3.x|pandas|datetime
1
349,806
61,714,519
Keras Model.predict returns the error 'Matrix size-incompatible'
<p>I'm trying to use model.predict function for a keras NN model but it returns me the 'Matrix size-incompatible' error everytime. My training, validation and test dataset is based on 10 samples of 31 inputs and 45 targets. I'm trying to make predictions for 4 different input arrays (31 features). Any suggestions?</p>...
<p>Try this out while defining the model:</p> <pre><code>model = tf.keras.Sequential([ tf.keras.layers.Dense(hidden_layer_size,input_shape=(31,), activation='relu'), tf.keras.layers.Dense(hidden_layer_size, activation='relu'), tf.keras.layers.Dense(output_size, activation='linear') ]) </code></pre>
python|tensorflow|keras|neural-network
0
349,807
62,036,205
Plotting many columns from a csv file
<p>Imagine I have a very big csv file with 500 rows and 500 columns. Part of the data shown : <a href="https://i.stack.imgur.com/ya1Ex.png" rel="nofollow noreferrer">a small section of my data</a></p> <p>I cannot delete the first couple of rows from my file but I can omit them using "skiprows" while reading the file....
<p>If <code>df</code> is your DataFrame and the first column is named <code>x-data</code>, then you can plot all other columns vs <code>x-data</code> like so:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() df.iloc[:i+1,:].plot(x='x-data', ax=ax) </code></pre>
python|pandas|matplotlib
0
349,808
61,615,188
Split pandas dataframe column to new 4 columns
<p>I have this Pandas df and I would to spilt the Adress column (Last one) to 4 new columns Stree name + num, zipcode, City and land. </p> <p>test</p> <pre><code> ID Address 1.10065e+08 Bachgasse 39 \n69502 Hemsbach \nDeutschland 2.34115e+08 Am Friedensplatz 3\n68165 Mannheim\nDeutschland 2.36743e+08 A...
<p>Given that your column <code>Firmen Adresse Geschäftlich</code> is string, you can try the following:</p> <pre><code>df1=pd.DataFrame(test['Firmen Adresse Geschäftlich'].str.split(r"\n").tolist(),columns = ['street no.','zip','Land'],index=test['ID']) df1[['zip','Stadt']]=pd.DataFrame(df1['z...
python|pandas
0
349,809
61,981,413
How do I save a list of arrays (frames) to a video using OpenCV?
<p>I have tried to save a list of arrays to a video using the following code, but it isn't working.</p> <pre class="lang-py prettyprint-override"><code>out = cv2.VideoWriter("output.mp4", cv2.VideoWriter_fourcc(*'mp4v'), 30, (1280, 720)) for frame in frames: out.write(frame) # frame is a numpy.ndarray with shape (...
<p>Numpy array is (row,column) but OpenCV defines images by (width,height). So, in your numpy array <code>height=row=1080</code> and <code>width=column=720</code>. So, Change the frame size (1080,720) to (720,1080).</p> <pre><code>out = cv2.VideoWriter(&quot;output.mp4&quot;, cv2.VideoWriter_fourcc(*'mp4v'), 30, (720, ...
python|python-3.x|macos|numpy|cv2
2
349,810
61,667,325
How to print or display vertically a Python Numpy array/matrix
<p>I have a Numpy array called z:</p> <pre><code>pop = np.random.randint(4, size = (3, 3, 1, 5)) z = pop.reshape(tuple(d for d in pop.shape if d &gt; 1)) </code></pre> <p><a href="https://i.stack.imgur.com/tEd64.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tEd64.png" alt="enter image description...
<pre><code>In [277]: pop = np.arange(9*5).reshape(3,3,1,5) In [278]: pop Out[278]: array([[[[ 0, 1, 2, 3, 4]], [[ 5, 6, 7, 8, 9]], [[10, 11, 12, 13...
python|arrays|numpy|matrix
1
349,811
61,913,957
KeyError Python3.8.2
<p>I did get a KeyError and has never seen this before. Would someone be so kind to help me out with this? Thank you very much in advance!</p> <p>The output:</p> <pre><code>File "/home/maurits/freqtrade/user_data/hyperopts/BBRSI_hyperopts.py", line 55, in populate_indicators dataframe["bb_middleband1"] = bollinge...
<p>I think this error must be because there is no column with the name "middle". Change the name from "middle" to "mid"</p> <pre><code>dataframe["bb_middleband1"] = bollinger1["mid"] </code></pre>
python|pandas
1
349,812
62,035,429
Can I use python method without parentheses?
<p>I'm new to Python. I was using <em>head()</em> method to quickly check a dataframe. </p> <pre><code>import pandas as pd df = pd.DataFrame({"a": ['1', '3'], "b": ['1', '2'], "c": ['2', '4']}) df.head() </code></pre> <p>But I noticed that I can call it without parentheses too.</p> <pre><code>df.head </code></pre> ...
<p>head return a method head() return the top 5(default) row in your dataframe</p> <pre><code>type(df.head) &lt;class 'method'&gt; type(df.head()) &lt;class 'pandas.core.frame.DataFrame'&gt; </code></pre>
python|pandas|methods
1
349,813
61,763,885
Python / Pandas using pandas.io.json.json_normalize to drill down in json
<p>The following json (otherwise known as 'Cus_data') is what I am working on deciphering with the pandas.io.json.json_normalize package.</p> <p>I can get within the json at a base level by </p> <pre><code>cus_data = json_normalize(cus_data, 'data') </code></pre> <p>or</p> <pre><code>cus_data = json_normalize(cus_d...
<p>give <a href="https://github.com/jmespath/jmespath.py" rel="nofollow noreferrer">jmespath</a> a whirl; it can help with some intricate nested data. </p> <p>Key takeaways : if it is a dict, u can access it with the <code>.</code> notation; if it is an array/list, u access it with the <code>[]</code> notation. it cou...
python|json|pandas
1
349,814
58,034,840
Summing Row values together based on index value and conditional statement
<p>I am trying to automate a process where multiple items have similar indexes. </p> <p>For example, the index may be:</p> <pre><code>12345 - Banana - Green 12346 - Banana - Yellow 12347 - Banana - Brown 12348 - Orange - Orange </code></pre> <p>I need to be able to sum the rows of "banana" into 1 singular row that...
<p>If I understand your question correctly, the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> method is for you. See this example: </p> <pre><code>df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', ... ...
python|pandas|dataframe|jupyter
0
349,815
57,899,984
loop through a splited dataframe and write each of them in different excel sheets using Pandas
<p>Recently I have posted a problem regarding writing a spilted dataframe into different excel sheets <a href="https://stackoverflow.com/questions/57743568/loop-through-a-list-of-dataframes-in-python-and-wirte-each-df-into-different-exc/57743711?noredirect=1#comment101931861_57743711">this post</a>, and I somehow find ...
<p>Combining solutions from both the links that you posted, here is the solution</p> <pre><code># define an excel writer first writer = pd.ExcelWriter("output.xlsx", engine = 'xlsxwriter') df_split = np.array_split(promotion1, 4) for index, df_sub in enumerate(df_split): #print(df_sub.head()) # save each of yo...
python-3.x|pandas
1
349,816
57,968,291
what is mean this syntax using numpy.mean with condition
<pre><code>result = map(lambda x: (x&gt;0).mean(), np.array([[1,3], [2,4], [3,5]])) print result ## output: [1.0, 1.0, 1.0] </code></pre> <p>what is mean of (x>0) condition in this syntax, and why do i get result like [1.0, 1.0, 1.0] ?</p> <p>additional) If i use (x>0).mean((1,2)), what is mean of this (1,2)?</p>
<blockquote> <p>np.array > 0 return np.array of same shape but filled with boolean value which satisfy the given condition and if you take mean then true treated as 1.0 and false treated as 0 hence you got mean like 1.0 1.0.</p> </blockquote>
python|numpy
0
349,817
57,812,797
is there a simple method to smooth a curve without taking into account future values and without a time shift?
<p>I have a Unix time series (x) with an associated signal value (y) which is generated every minute, dropping the first value and appending a new one. I am trying to smooth the resulting curve without loosing time accuracy with a specific emphasis on the final value of the smoothed curve which will be written to a dat...
<p>This really depends on why you are smoothing the data. Every smoothing method will have side effects, such as letting some 'noise' through more than other. Research 'phase response of filtering'.</p> <p>A common technique to avoid the problem of missing data at the end of a symmetric filter is to just forecast your...
python|pandas|numpy|scipy|smoothing
0
349,818
57,759,351
Assign multi-index column while preserving the order of index level values
<p>I have the following data frame with multi-index columns:</p> <pre><code>df = pd.DataFrame(np.arange(6).reshape(2, 3), columns=pd.MultiIndex.from_tuples([('foo', 'a'), ('bar', 'a'), ('bar', 'b')])) foo bar a a b 0 0 1 2 1 3 4 5 </code></pre> <p>I would like to assign a new column <code>(...
<p>That is <code>insert</code> </p> <pre><code>df.insert(1, ('foo', 'b'), [10, 11]) df foo bar a b a b 0 0 10 1 2 1 3 11 4 5 </code></pre>
python|python-3.x|pandas
1
349,819
57,796,741
Creating function to filter and calculate division of rows based on filter?
<p>I have a df such as below:</p> <p>I am using simple code such as below: that filters columns in the <strong>df</strong> and then I calculate simple math based on value of the column, so if the column values is cancelled, processing, and complete; I want to calculate the % or number of rows that were cancelled of th...
<p>You can use groupby and len():</p> <pre><code>df.groupby(by='Status').apply(lambda x: len(x)/len(df)) Status Cancelled 0.666667 Processed 0.333333 dtype: float64 </code></pre> <p>Breakdown by both Status and Color:</p> <pre><code>cc = df.groupby(by='Color').ID.count() df.groupby(by=['Color', 'Status']).app...
python|python-3.x|pandas|function|data-science
1
349,820
57,772,334
Contraction along the last axe in numpy tensordot
<p>I am not very familiar with tensor algebra and I am having trouble understanding how to make <code>numpy.tensordot</code> do what I want.</p> <p>The example I am working with is simple: given a tensor <code>a</code> with shape <code>(2,2,3)</code> and another <code>b</code> with shape <code>(2,1,3)</code>, I want a...
<p>The way <a href="https://stackoverflow.com/a/41871402/"><code>tensordot</code> works</a>, it won't work here (not at least directly) because of the alignment requirement along the first axes. You can use <code>np.einsum</code> though to solve your case -</p> <pre><code>c = np.einsum('ijk,ilk-&gt;ij',a,b) </code></p...
python|python-3.x|numpy
1
349,821
57,741,190
Concat rows in pandas DataFrame with another text
<p>I need help with realisation of the following logic: While grouping a DataFrame I want certain columns to be concatenated with another text. For example:</p> <p>Input:</p> <pre><code>id | col1 | col2 ---|------|------ 1 | A | 12 1 | B | 43 ---|------|----- </code></pre> <p>After applying something like <c...
<p>One option could be the following:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('id').apply(lambda g: ';'.join('text_' + g.col1 + ':' + g.col2.astype(str))) </code></pre> <p>Output:</p> <pre><code>id 1 text_A:12;text_B:43 </code></pre>
python|pandas|dataframe|pandas-groupby
2
349,822
57,957,684
How to loop through a DataFrame containing 80k+ rows
<p>This question might have other answers but I could not figure out how to apply them on my current code.</p> <p>I have to iterate through the DataFrame and modify certain column values as shown below:</p> <p><strong>NOTE:</strong> All of the columns are strings. The ones with _Length contain the length in int of th...
<p>You can do it without looping:</p> <pre><code>df['Full_Input'] = df['Partial_Input'].str.cat(df['Input5'], sep=" ").str.cat(df['Input6'], sep=" ") df['Full_Input'] = np.where(df['Partial_Input_Length'].str.len() &gt; 50, df['Partial_Input'], df['Full_Input']) </code></pre>
python|pandas|loops
2
349,823
57,819,068
Reading Date times from Excel to Python using Pandas
<p>I'm trying to read from an Excel file that gets converted to python and then gets split into numbers (Integers and floats) and everything else. There are numerous columns of different types.</p> <p>I currently bring in the data with </p> <pre><code>pd.read_excel </code></pre> <p>and then split the data up with </...
<p>If your data contains only one column with dtype <code>object</code> (I assume it is a string) you can do the following:</p> <p>1) filter the column with dtype <code>object</code></p> <pre><code>import pandas as pd datatime_col = df.select_dtypes(object) </code></pre> <p>2) convert it to seconds</p> <pre><code>d...
python|excel|pandas|datetime|types
0
349,824
58,069,629
How does the LSTM know number of time steps and features in an Conv1D-LSTM network?
<p>I have a time series signal (n samples, each sample has 81 time steps and 3 features = n x 81 x 3). I am using an conv1D-LSTM network. n_timesteps = 81, n_features = 3. Normal LSTM specifies both n_timesteps and n_features, however when combined with conv1d, these are not specified. </p> <ol> <li><p>How does the ...
<h1>1 and 2</h1> <p>Everything is based on tensors (sort of like matrices, but with any number of dimensions). </p> <p>The tensors have shapes and everything is based on the shapes. Your data tensors are three-dimensional: <code>(samples, time_steps, features)</code>. </p> <p>It happens that 1D convolutions also u...
tensorflow|keras|conv-neural-network|lstm
3
349,825
58,105,241
How to find average of values in columns within iterrows in python
<p>I have a dataframe with 100+ columns where all columns after col10 are of type float. What I would like to do is find the average of certain range of columns within loop. Here is what I tried so far,</p> <pre><code>for index,row in df.iterrows(): a = row.iloc[col30:col35].mean(axis=0) </code></pre> <p>This unf...
<p>try:</p> <pre class="lang-py prettyprint-override"><code>df.iloc[:, 30:35].mean(axis=1) </code></pre> <p>You may need to adjust 30:35 to 29:35 (you can remove the .mean and play around to get an idea of how the .iloc works). Generally in pandas you want to avoid loops as much as possible. The .iloc method allows y...
python|pandas
0
349,826
57,949,866
What types of model files does Tensorflow support and how to load .ckpt + .pb
<p>I found TensorFlow supports various of model files, <code>.ckpt, .meta, .pb</code></p> <p>1) now I have a resnet50 model, with <code>.ckpt</code> 102MB and <code>.pb</code> 459KB, how to load them into memory by using TensorFlow?</p> <p>2) And how many types of model files does Tensorflow support? Could anyone pro...
<p>These files are not different file types to store complete models. Each contains different information and collectively they store a single model. </p> <p>The <code>.meta</code> file stores the bulk of the structure of the model, while the <code>.ckpt</code> file is a checkpoint file storing information about the v...
tensorflow
1
349,827
58,126,207
Pandas: fast reverse between()?
<p>Consider this df:</p> <pre><code>sample_df = pd.DataFrame({'begin': {0: pd.Timestamp('1999-11-18 00:00:00'), 1: pd.Timestamp('2016-11-01 00:00:00'), 2: pd.Timestamp('2014-10-02 00:00:00'), 3: pd.Timestamp('1987-05-07 00:00:00'), 4: pd.Timestamp('2005-09-27 00:00:00'), 5: pd.Timestamp('2012-12-13 00:00:00'), 6: pd....
<p>This can be done with broadcast:</p> <pre><code>mask = ((sample_df.begin.values&lt;=date_series.values[:,None]) &amp; (date_series.values[:,None]&lt;= sample_df.end.values)) np.where(mask, sample_df.index.values[None,:], np.nan) </code></pre> <p>Output:</p> <pre><code>array([[ 0., nan, 2., 3., 4.,...
python|pandas
2
349,828
58,149,401
Why pytorch needs much more memory than it should?
<p>I'm just playing around with pytorch and I'm wondering why it consumes so much memory of my GPU?</p> <p>I'm using Cuda 10.0 with pythorch 1.2.0 and torchvision 0.4.0.</p> <pre><code>import torch gpu = torch.device("cuda") x = torch.ones(int(4e8), device=gpu) y = torch.ones(int(1e5), device=gpu) </code></pre> <p>R...
<p>More information and testing done by <code>xymeng</code> in github could be seen in the given <a href="https://github.com/pytorch/pytorch/issues/12873" rel="nofollow noreferrer">link</a></p> <p>Referencing <code>xymeng</code>'s words : </p> <blockquote> <p>PyTorch has its own cuda kernels. From my measurement th...
python|memory|gpu|pytorch
2
349,829
58,002,668
Pandas groupby ewm
<p>I have labeled event (time series) data where the events occur at random intervals for a given label. I would like to compute the within group ewma and add it to the dataframe as a new column "X1_EWMA". Here's the code so far:</p> <pre><code>import pandas as pd import numpy as np import altair as alt n = 1000 df ...
<p>Let's fix the problem, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="noreferrer"><code>transform</code></a>:</p> <pre><code>t['ewm'] = ts.groupby(['C1'])['X1'].transform(lambda x: x.ewm(halflife=10).mean()).values() </code></pre>
python|pandas|time-series|pandas-groupby|rolling-computation
8
349,830
58,063,749
Functional API with mixed input data. Got this error: AttributeError: 'tuple' object has no attribute 'ndim'
<p>I have read and search the similar question but the answers did not work for me even If I try it in several ways. </p> <p>I have a data set that is this way 4.000.000 different string representing a Cell (categorical data) and 4.000.000 longitude, latitude, representing where those cells are here is a snippet of t...
<p>Since you did not paste the full error log, from what you shared I think the problem is with the round brackets you used to input the data(categorical , numerical). Try with square brackets like <code>model.fit([visible,device_id], X_trainY, batch_size=10, epochs=5, verbose=1)</code></p> <p><strong>EDIT</strong></...
python|tensorflow|keras|layer|categorical-data
1
349,831
58,000,160
Does PyTorch have a RandomState-like object for random number generation?
<p>in numpy i can</p> <pre><code>import numpy as np rs = np.random.RandomState(seed=0) </code></pre> <p>and then pass that object around, eg for dependency injection.</p> <p>Does PyTorch have a similar interface? I can't find anything in the docs, but maybe i'm missing something.</p>
<p>The closest thing would be <a href="https://pytorch.org/docs/master/torch.html?highlight=manual_seed#torch.manual_seed" rel="nofollow noreferrer"><code>torch.manual_seed</code></a>, which sets the seed for generating random numbers and returns a <code>torch.Generator</code>. This thread <a href="https://discuss.pyto...
numpy|random|pytorch|random-seed
2
349,832
58,011,087
Change index inside multi level hierarchy Pandas Dataframe
<p>I have a <code>DataFrame</code> that is multi level and having 2 levels named <code>Outer Groups, Inner Numbers</code>. I want to change the Index of <code>Inner Numbers</code>.</p> <pre><code>outside='g1 g1 g1 g2 g2 g2'.split() inside='1 2 3 1 2 3'.split() hier_index=list(zip(outside,inside)) hier_index= pd.MultiI...
<p>You can use <code>rename</code> with dictionary and specify levels, for change index names is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>DataFrame.rename_axis</code></a>:</p> <pre><code>df = df.rename({'g1':'X','...
python|pandas|dataframe
2
349,833
57,901,933
Want to check Intermediate Operations inside Keras Layer
<p>I am facing floating point resolution loss during convolution operation while porting the code on my embedded processor which supports only half precision, so I want to test the intermediate operations that are performed layer by layer in my Keras based model which is performing good while on Full precision on my de...
<p>You can disable the bias(<code>use_bias=False</code>) and activation functions(<code>activation=None</code>) when defining the <code>Conv1D</code> operation.</p> <pre><code>Input_sequence = keras.layers.Input(shape=(1500,3)) encoder_conv1 = keras.layers.Conv1D(filters=16, kernel_size=10, ...
tensorflow
0
349,834
58,003,161
Python pandas column to replace string boolean values to actual boolean type
<p>I want to replace string boolean type present inside a column with actual boolean values.</p> <pre><code>kdf = pd.DataFrame(data={'col1' : [True, 'True', np.nan], 'dt': [datetime.now(), ' 2018-12-12', '2019-12-12'], 'bool': [False, True, True], 'bnan': [False, True, np.nan]}) </code></pre> <p...
<p>Why not using <code>replace</code> </p> <pre><code>df.replace({'True':True,'False':False}) # df.replace({'True':True,'False':False}).applymap(type) Out[123]: bnan bool col1 dt 0 &lt;class 'bool'&gt; &lt;class 'bool'&gt; &lt;class 'bool'&gt; &lt;class 'str'&gt;...
python|pandas
1
349,835
58,123,573
Convert Keras model to quantized Tensorflow Lite model that can be used on Edge TPU
<p>I have a Keras model that I want to run on the Coral Edge TPU device. To do this, it needs to be a Tensorflow Lite model with full integer quantization. I was able to convert the model to a TFLite model:</p> <pre class="lang-py prettyprint-override"><code>model.save('keras_model.h5') converter = tf.lite.TFLiteConv...
<p>I believe <code>num_calibration_steps</code> is just the number of times the converter uses your rep set to determine the quantization levels. Just a guess, but maybe it subsamples from your rep set multiple times (bootstrapping or jackknifing). I'm still investigating the whole process myself, but it seems to work ...
python|tensorflow|keras|tensorflow-lite|tpu
3
349,836
57,790,841
Is there any way to read numpy array in Azure Blob Storage in python?
<p>I would like to read the numpy array stored in Azure Blob Storage from python code in Azure functions. I am not being able to do it. I tried with BlockBlobService but couldn't succeed. </p> <p>Looking for help/suggestions.</p>
<p>The simple solution is to use Azure Storage SDK for Python to download the blob content to memory, then to use the function <a href="https://numpy.org/doc/1.16/reference/generated/numpy.frombuffer.html" rel="nofollow noreferrer"><code>numpy.frombuffer</code></a> to load the memory content of the blob as a 1-dimensio...
python|azure-functions|azure-blob-storage|numpy-ndarray
0
349,837
57,757,611
Why does Pandas Dataframe.where method return NaN after calling dropna()?
<pre><code>import pandas as pd df = pd.read_csv('file.csv') df.dropna(inplace=True) filter1 = df['col1'] == 'some_value' filter2 = df['col2'] == 'some_other_value' df.where(filter1 &amp; filter2, inplace=True) df.head() localCountry localState remoteCountry remoteState ... col1 col2 col3 num_samples 1250 ...
<p>I think the problem is you are missing the default value of <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>DataFrame.where</code></a> for setting rows not matched by any of the conditions (<code>other</code>):</p> <pre><code>df = pd.D...
python|pandas
2
349,838
58,113,879
Remove parenthesis and contents in parenthesis if present in a df column
<p>I have a dataframe where the top scores/instances have parenthesis. I would like to remove the parenthesis and only leave the number. How would I do so?</p> <p>I have tried the code below, but it leaves me with nans for all other numbers that do not have paranthesis.</p> <pre><code>.str.replace(r"\(.*\)","") </cod...
<p>Reason is mixed values - numeric with strings, possible solution is:</p> <pre><code>df['a'] = df['a'].astype(str).str.replace(r"\(.*\)","").astype(int) print (df) a 0 1 1 3 2 2 3 4 4 5 5 6 6 8 7 7 8 11 9 13 </code></pre>
python|pandas|dataframe
1
349,839
57,975,706
Convert dictionaries with list of values into a dataframe
<p>Say I have three dictionaries</p> <pre><code>dictionary_col2 {'MOB': [1, 2], 'ASP': [1, 2], 'YIP': [1, 2]} </code></pre> <pre><code> dictionary_col3 {'MOB': ['MOB_L001_R1_001.gz', 'MOB_L002_R1_001.gz'], 'ASP': ['ASP_L001_R1_001.gz', 'ASP_L002_R1_001.gz'], 'YIP': ['YIP_L001_R1_001.gz', ...
<pre><code>pd.DataFrame({'col2': pd.DataFrame(col2).unstack(), 'col3': pd.DataFrame(col3).unstack(), 'col4': pd.DataFrame(col4).unstack()}).reset_index(level=0) </code></pre> <p>returns</p> <pre><code> level_0 col2 col3 col4 0 ASP 1 ASP_L001_R1_001....
python|pandas|dictionary
7
349,840
58,118,393
I am having trouble converting my nested json into a dataframe. I am getting the json from an API and want it in a dataframe
<p>This code is from Sportradar API. The API outputs the data as JSON or XML; below is my attempt at taking the JSON and making it into a dataframe.</p> <pre><code>import numpy as np import pandas as pd import http.client import json from pandas.io.json import json_normalize #API Call including my key conn = http.cli...
<p>Why not make use of a Python Wrapper that is publicly available and maintained. See <a href="https://github.com/johnwmillr/SportradarAPIs" rel="nofollow noreferrer">link</a>.</p>
json|python-3.x|pandas|api|dataframe
0
349,841
57,784,498
confusing result from pd .cut interval
<p>I need to create range for the interval by using the pd.cut. My minimum value is <code>0</code> and the maximum is <code>4412429728.0.</code> but the problem is the minimum value in the first interval start with <code>(-4412429.728, 44124297.28]</code> but it is should start with this interval <code>(0, 4412429...
<p>The best option might be to define your own bins and to specify that anything below 0 should get one single label. For example:</p> <pre><code>pd.cut(df_inputs_prepr['Pre_STANDARD_SALES'], bins=[np.NINF, 0, 5, 10, 15, np.PINF], labels=['&lt;=0', '0-5', '5-10', '10-15', '&gt;15']) </code></pre> <p>You might also wa...
python|pandas|intervals
1
349,842
57,931,210
Using a lambda expression for multiple columns in python
<p>I have this data: </p> <p><a href="https://i.stack.imgur.com/hkyh8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hkyh8.png" alt="enter image description here"></a></p> <p>I want to make a new column where if we have an 'X' in delinquency or Suspect LTV has a 'LTV &lt; 10%' Then I will have a '...
<p>The reason that isn't working is because your "exceptions" function needs /both/ columns in order to make a decision, and you're only passing it one of those columns. Instead, you can pass the entire row to your lambda function, and index the columns you need within that function.</p> <pre><code>def exceptions(row)...
python|pandas|lambda
1
349,843
57,837,376
How is Linear Regression model from sklearn predicting non-linearly in the following code?
<p>Since linear regression algorithms find the best fit line for the training data, so the forecast for the new data will always line on that best fit line. Then how is Linear Regression model from sklearn predicting data non-linearly as shown in this image. !(<a href="https://pythonprogramming.net/static/images/machi...
<p>The model produced by linear regression is linear in all of the predictive features, i.e. <code>X</code>. Your model appears to be trained with the features <code>'HL_PCT', 'PCT_change', 'Adj. Volume'</code>. However, the plot contains only one feature on the X-axis (as all 2D plots do), <code>Date</code>, which is ...
python|pandas|scikit-learn|linear-regression
1
349,844
57,961,706
how to append more than one list of time series correlation in python?
<p>I want to take correlation between two time series. I used np.correcoef to get the correlations as list. Now I introduced lag suppose 3, how to save 3 different list for 3 different lags.</p> <p>I tried</p> <pre><code> for k in range(0,4,1): corr_k= [] corr_k.append( np.corrcoef ( T[(365-k):(730-k)] ,...
<p>EDITED WITH MINIMUM EXAMPLE</p> <pre><code>import numpy as np T = np.random.rand(100) #defines a dummy T with size 100 corr = {} for k in range(4): corr[k] = np.corrcoef(T[50-k:100-k],T[50:100]) </code></pre> <p>returns a dictionary <code>corr</code> containing arrays. For instance :</p> <pre><code>corr[0] &gt...
python|list|numpy|correlation
0
349,845
57,871,463
Keras Sequential without providing input shape
<p>I currently have a keras model that looks like this:</p> <pre class="lang-py prettyprint-override"><code>model = keras.Sequential() model.add(keras.layers.Dense(100, activation=tf.nn.relu)) model.add(keras.layers.Dense(100, activation=tf.nn.relu)) model.add(keras.layers.Dense(len(labels), activation=tf.nn.softmax))...
<p>Nice observation - I believe the Keras documentation should be updated. When the input shape is not provided, Keras infers it from the argument <code>x</code> of <code>Model.fit</code> and only then it builds the whole model. Concretely, this is what's happening:</p> <ol> <li>When adding Keras layers in the <code>S...
python|tensorflow|keras
19
349,846
57,993,047
complex json to csv using python and pandas dataframe
<p>i know this problem has been asked many times but still i am not able to convert it to json.</p> <p>my json file look like this:</p> <pre><code>{ "itemCostPrices": { "Id": 1, "costPrices": [{ "costPrice": 83.56, "currencyCode": "GBP", "startDateValid": "2010-...
<p>Try this code: </p> <pre><code>import json import pandas as pd def flatten_dict(d, acc={}): for k, v in d.items(): if isinstance(v, dict): flatten_dict(v, acc) elif isinstance(v, list): for l in v: flatten_dict(l, acc) else: acc[k] ...
python|pandas|databricks
1
349,847
57,862,376
How to format a nice table with structured rows and columns, from a csv file?
<p>I found this dataset of fifa players and I am cleaning it, but I dont know a pandas function to specify it in columns and rows.</p> <p>The output is looking something like this:</p> <pre><code>id, name, rating, position, height, foot, rare, pace, shooting, passing, dribbling, defending, heading, diving, handling, ...
<pre class="lang-py prettyprint-override"><code>import pandas as pd fifa_df=pd.read_csv("FIFA.csv") #check the data is as you expect fifa_df.head() #Save to an excel file fifa_df.to_excel("output.xlsx") </code></pre>
python|pandas|jupyter
1
349,848
57,898,190
Efficient way of filtering groupby data in a Panda DataFrame
<p><strong>Issue</strong></p> <p>I have two dataframe <code>Frame A</code> (Holding some raw data) and <code>Frame B</code> (holding threshold data).</p> <p>My goal is for each id in <code>Frame B</code> I want to return the rows for the corresponding id in <code>Frame A</code> that are <code>&lt;= b['A']</code>.</p>...
<p>Using <code>map</code></p> <pre><code>s = df_a.id.map(dict(df_b[['id', 'A']].values)) df_a[df_a.A &lt;= s] Out[35]: id A B C D 0 123 2019-09-10 00:00:00 1 True False 1 123 2019-09-10 00:10:00 1 True False 3 456 2019-09-05 01:00:00 1 True False 5 789 2019-09-10 10:00:00 ...
python|pandas|bigdata
3
349,849
57,870,668
How to merge two dataframes with different length based on string contains
<p>I'm working with data augmentation in medical imaging. I have original 100 image names with their labels (0 and 1) in Pandas dataframe. I added new images and their name with some suffix. </p> <p>My original images have names such as: Image1, Image2, Image3, Image4 and my augmented data have names such as: Image1_1...
<pre><code>import pandas as pd #create dummy data data = pd.DataFrame([['Image1aa1'], ['Image1aa2'], ['Image2baa1'], ['Image2baasa2']], columns=['filename']) annotations = pd.DataFrame([['Image1',1],['Image2',0]], columns=['filename','label']) for name, l in zip(annotations.filename,annotations.label): temp = dat...
python|pandas
0
349,850
57,792,085
YOLO : Either overfits or underfits, increase batch or increase sample image pool?
<p>I'm trying to train my yolo model to identify fire extinguishers and to label it as "Fire Safety". Currently is either I get a overfit or underfit images(see below). </p> <p>My sample images size with annotations is around ~1500</p> <p>yolo-new.cfg config of width=608 and height=608</p> <p>And I have trained usin...
<p>Using Yolov3 to train my imageset solved my issue. <a href="https://github.com/AlexeyAB/darknet" rel="nofollow noreferrer">https://github.com/AlexeyAB/darknet</a></p> <p>One thing to note is not to leave any blanks during annotation, perhaps this might be one of the reasons why the detection did not work as planned...
python|tensorflow|image-processing|yolo
0
349,851
57,748,856
Standard deviation for the difference of two dataframes with group by
<p>I have two panda DataFrames:</p> <p>Dataframe Yahoo:</p> <pre><code>date ticker return 2017-01-03 CRM 0.018040121229614625 2017-01-03 MSFT -0.0033444816053511683 2017-01-04 CRM 0.024198086662915008 2017-01-04 MSFT -0.0028809218950064386 2017-01-05 CRM -0.0002746875429199269 2017-01-0...
<h2>Start by merging the data:</h2> <ul> <li><code>df1</code> is Yahoo data</li> <li><code>df2</code> is Quandl data</li> </ul> <pre><code>df = pd.merge(df1, df2, on=['date', 'ticker'], suffixes=('_yahoo', '_quandl')) </code></pre> <h2>Create <code>diff</code>:</h2> <pre><code>df['diff'] = df.return_yahoo - df.retu...
python|python-3.x|pandas|grouping|standard-deviation
1
349,852
58,171,333
compute symmetric function efficiently
<p>I have two dataframes. I need to apply a function to all possible couple of rows within the dataframe.</p> <pre><code>L=product(df.iterrows(),df.iterrows()) res=map(myfunc,L) </code></pre> <p>where myfunc(r1,r2)->float take two rows in input and returns one single value. now,myfunc is symmetric thus</p> <pre><co...
<p>IIUC, you can use <code>itertools.combinations</code> with the dataframe index:</p> <pre><code>np.random.seed(0) df = pd.DataFrame(np.random.randint(0,100,(10,10)), index=[*'abcdefghij'], columns=[*'ABCDEFGHIJ']) from itertools import combinations def addTwoRows(r1, r2): return r1.sum() + r2.sum() [(addTwoRo...
python|pandas|itertools
1
349,853
58,044,058
Numpy iteration and append
<p>I'm basically trying to loop through the array, substracting the first element from the second, the second from the third and so on and append my result into a new numpy array. </p> <pre><code>t = np.array([0, 10, 15, 35, 40, 24, 50, 90]) for i in np.nditer(t): dt = (t[int(i)] - t[int(i+1)] print(dt) n...
<p>You are probably looking for <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="nofollow noreferrer"><strong><code>np.diff(..)</code></strong> [numpy-doc]</a>, that each time subtracts an item from the previous one.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; np.diff(np.array([...
arrays|python-3.x|loops|numpy|iteration
3
349,854
57,948,003
How to increase Jupyter notebook Memory limit?
<p>I am using jupyter notebook with Python3 on windows 10. My computer has 8GB RAM and at least 4GB of my RAM is free.</p> <p>But when I want to make a numpy ndArray with size 6000*6000 with this command: <code>np.zeros((6000, 6000), dtype='float64')</code> I got this : <code>Unable to allocate array with shape (600...
<p>Jupyter notebook has a default memory limit size. You can try to increase the memory limit by following the steps:<br/> 1) Generate Config file using command:<br/> <pre><code>jupyter notebook --generate-config</code></pre> 2) Open jupyter_notebook_config.py file situated inside 'jupyter' folder and edit the foll...
python|numpy|memory|jupyter-notebook|ipython
41
349,855
57,941,858
Is there a faster method to calculate implied volatility using mibian module for millions of rows in a csv/xl file?
<p><strong>My situation:</strong></p> <p>The CSV file has been converted to a data frame <code>df5</code> and all the columns being used in the for loop below are of <code>float</code> type, this code is working but taking many many hours to just do <code>30,000</code> rows.</p> <p><strong>What I want from my situati...
<p>Your loop seems to take values from each row to build another column <code>IV</code>.<br> This can be done much faster by using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a> method, which allows to use a function on each row/c...
python|pandas|numpy
-1
349,856
57,739,039
IndexingError: Too many indexers while accessing multiindex dataframe
<p>I have a dataframe as below.</p> <pre><code>df Out[209]: a b User1 2019-07-01 [The Milky Way] 2019-07-02 NaN 2019-07-03 [Taken] 2019-07-04 NaN ...
<p>It looks like:</p> <ul> <li><em>User1</em> and <em>2019-07-13</em> are <em>MultiIndex</em> values (with levels named <em>a</em> and <em>b</em>, above respective index columns).</li> <li>The variable named <em>df</em> is actually a <em>Series</em> (your printout has no column name, not even the default name like <em...
python|pandas|dataframe|multi-index
0
349,857
58,107,348
Changing edgecolor in matplotlib legend markers
<p>I've checked the kwargs for matplotlibs legend but can't find this option available. When I plot the legend the color key beside the text will be correct, however there is a blue egdecolor to the key that I'd like to remove.</p> <p>Wondering if anyone knew how to get at this attributed.</p> <pre><code>cm = matplot...
<p>Due to <a href="https://github.com/geopandas/geopandas/blob/0f2ca1a802ad6814f5185b45288961b66f51a054/geopandas/plotting.py#L609" rel="nofollow noreferrer">this line</a> this shouldn't happen with the newest version. It's <a href="https://github.com/geopandas/geopandas/pull/807" rel="nofollow noreferrer">this fix</a>...
python|matplotlib|geopandas
2
349,858
57,773,287
iterating through data frame and addiing values if they are not present within that columns index
<p>I need to read data from a post gres server and put it into an array / data from. Each row has a source and and a destination field. I need to add these into an array cummulatively. As i iterate through the data frame, if the source and destination fields of are not in the accounts column, I need to add them into i...
<p>You could use <code>cumsum</code> on the <code>accounts</code> columns to create a cumulative concatenation of the accounts values. Then convert the accumulated list to <code>Set</code> in order to keep the unique values. </p> <p>There is a similar question answered here: <a href="https://stackoverflow.com/question...
python|pandas|numpy
1
349,859
58,008,032
Why is the results of groupby with mean aggregate is different between sample(frac=1) and original data?
<p>I don't know if this really a basic question..</p> <p>So I have been playing with Groupby, aggregating, and sampling using Pandas.. with this sample.csv file <a href="https://sendeyo.com/en/a36d65b2a7" rel="nofollow noreferrer">https://sendeyo.com/en/a36d65b2a7</a></p> <p>Here is a results of original data groupby...
<p>Thankyou @Chris for feedback!, this minimalistic plot shows that </p> <blockquote> <p>replace=True</p> </blockquote> <p>does give effects the sample distribution even a little bit, this is makes sense as a method of Bootstrap:</p> <pre><code>i_sampling_true = i[["Precipitation","Speed","State"]].sample(frac=1,r...
python-3.x|pandas|aggregate|pandas-groupby
1
349,860
34,000,074
pandas - return column of exponential values
<p>Starting from a sample dataframe <code>df</code> like:</p> <pre><code>a,b 0,0.71 1,0.75 2,0.80 3,0.90 </code></pre> <p>I would add a new column with exponential values of column <code>b</code>. So far I tried:</p> <pre><code>df['exp'] = math.exp(df['b']) </code></pre> <p>but this method returns:</p> <pre><code>...
<p>Well <code>math.exp</code> doesn't understand <code>Series</code> datatype, use numpy <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html" rel="noreferrer"><code>np.exp</code></a> which does and is vectorised so operates on the entire column:</p> <pre><code>In [24]: df['exp'] = np.exp...
python|pandas
26
349,861
34,398,644
Can I use pandas read_csv converter conditionally?
<p>I was wondering whether it is possible to use a converter conditionally based on the type of a column. For example if your dataset consists of two columns where the first one can be either an integer or timestamp it would be nice to be able to use a converter conditionally if the file eventually has a timestamp colu...
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">read_csv docs</a> state that you can pass a custom date parsing function using the <code>date_parser</code> argument.</p> <p>So you could do something like:</p> <pre><code>from datetime import datetime import pa...
python|pandas
2
349,862
34,002,591
Tensorflow slicing based on variable
<p>I've found that indexing still is an open issue in tensorflow <a href="https://github.com/tensorflow/tensorflow/issues/206">(#206)</a>, so I'm wondering what I could use as a workaround at the moment. I want to index/slice a row/column of a matrix based on a variable that changes for every training example.</p> <p>...
<p>Slicing based on a placeholder should work just fine. It looks like you are running into a type error, due to some subtle issues of shapes and types. Where you have the following:</p> <pre><code>x = tf.placeholder("float") i = tf.placeholder("int32") y = tf.slice(x,[i],[1]) </code></pre> <p>...you should instead h...
python|tensorflow
16
349,863
34,220,374
Apply 1 channel mask to 3 channel Tensor in tensorflow
<p>I'm trying to apply a mask (binary, only one channel) to an RGB image (3 channels, normalized to [0, 1]). My current solution is, that I split the RGB image into it's channels, multiply it with the mask and concatenate these channels again:</p> <pre class="lang-py prettyprint-override"><code>with tf.variable_scope(...
<p>The <a href="https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#mul" rel="nofollow noreferrer"><code>tf.mul()</code></a> operator supports <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow noreferrer">numpy-style broadcasting</a>, which would allow you...
mask|tensorflow
7
349,864
34,411,448
TensorFlow - optimization with normalization constraints
<p>Is there any implementation using TensorFlow to optimize a vector under a constraint such as |w|^2==1 ?</p>
<p>You can add a soft constraint to your loss: <code>some_constant * (norm(w)- 1)^2</code> but, as far as I know, there are no functionalities specifically for constrained optimization.</p>
tensorflow
3
349,865
34,357,326
How to extract vector from 3d numpy array?
<p>I have a set of numpy.arrays of NXM (two dimensions: Range and Azimuth). I need to form a stack of three dimensions and extract a single dimension vector to compute a covariance matrix (the red vectors in the picture).</p> <p><a href="https://i.stack.imgur.com/gxnnw.png" rel="nofollow noreferrer"><img src="https:/...
<p>You can make a 3D numpy array pretty easily and then just use the indexing to pull out the bits that you're interested in:</p> <pre><code>stackOfImages = np.array((image1, image2)) #iterate over these if many more redData = stackOfImages[:, N-1, M-1] </code></pre>
python|python-2.7|numpy|scipy|covariance
3
349,866
34,124,283
Pandas read_excel returns unicode values (instead of floats) sometimes at the end of matrix rows
<p>I work with Python 2.7 on a Mac. I have <a href="https://www.dropbox.com/s/cbbjbj38sn9htn9/SO%20data.xlsx?dl=0" rel="nofollow">this data in Excel</a> which I want to import in Python, possibly with Pandas. However, even if the importing goes smooth I have that some cells in the last column are actually imported as u...
<p>The data you posted does indeed have 5 unicode characters in the last column. Once these are removed, <code>dtypes</code> are all <code>float</code>:</p> <pre><code>df = pd.read_excel('SO Data.xlsx'), header=None, sheetname='P') print(df.info()) &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 72 entries, 0...
python|excel|pandas|unicode
2
349,867
34,093,984
Updating a NumPy array by adding columns
<p>I am working with a large dataset and I would like to make a new array by adding columns, updating the array by opening a new file, taking a piece from it and adding this to my new array. </p> <p>I have already tried the following code:</p> <pre><code>import numpy as np Powers = np.array([]) with open('paths power...
<p>Have you tried <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html" rel="nofollow"><code>numpy.column_stack</code></a>?</p> <pre><code>Powers = np.column_stack([Powers,Pname]) </code></pre> <p>However, the array is empty first, so make sure that the array isn't empty before concate...
python|arrays|python-3.x|numpy|multidimensional-array
1
349,868
34,069,151
Increase numpy array elements using array as index
<p>I am trying to efficiently update some elements of a numpy array A, using another array b to indicate the indexes of the elements of A to be updated. However b can contain duplicates which are ignored whereas I would like to be taken into account. I would like to avoid for looping b. To illustrate it:</p> <pre><cod...
<p>To correctly handle the duplicate indices, you'll need to use <code>np.add.at</code> instead of <code>+=</code>. Therefore to update the first row of <code>A</code>, the simplest way would probably be to do the following:</p> <pre><code>&gt;&gt;&gt; np.add.at(A[0], [1,1,1,2], 1) &gt;&gt;&gt; A array([[0, 4, 3, 3, 4...
python|arrays|numpy
11
349,869
34,007,632
How to remove a column in a numpy array?
<p>Imagine we have a 5x4 matrix. We need to remove only the first dimension. How can we do it with <strong>numpy</strong>? </p> <pre><code>array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.], [ 16., 17., 18., 19.]], dtype=float3...
<p>If you want to remove a column from a 2D Numpy array you can specify the columns like this </p> <p>to keep all rows and to get rid of column 0 (or start at column 1 through the end)</p> <pre><code>a[:,1:] </code></pre> <p>another way you can specify the columns you want to keep ( and change the order if you wish...
python|arrays|numpy
49
349,870
34,391,116
Subset data from pandas
<p>I have a pandas dataframe with columns <code>Cust_email,visit_date_time, transaction_date_time</code>. <code>Cust_email</code> contains the email id of the customer, <code>visit_date_time</code> contains the timestamp when the customer visited the product and <code>transaction_date_time</code> contains the transacti...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="nofollow"><code>isin</code></a> to test for membership of your customer ids, we filter the df first of those transactions that didn't complete, get the customer id's from those rows and pass to...
python|pandas|dataframe|subset
0
349,871
34,089,108
Python pandas - value_counts not working properly
<p>Based on <a href="https://stackoverflow.com/questions/33373030/how-to-append-columns-based-on-other-column-values-to-pandas-dataframe">this</a> post on stack i tried the value counts function like this </p> <p><code>df2 = df1.join(df1.genres.str.split(",").apply(pd.value_counts).fillna(0))</code></p> <p>and it wor...
<p>You have to remove first and last <code>[]</code> from column <code>genres</code> by function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> and then replace spaces by empty string by function <a href="http://pandas.pydata.org/pa...
python|pandas
1
349,872
37,071,526
Not calculating sum for all columns in pandas dataframe
<p>I'm pulling data from Impala using <code>impyla</code>, and converting them to dataframe using <code>as_pandas</code>. And I'm using <code>Pandas 0.18.0</code>, <code>Python 2.7.9</code></p> <p>I'm trying to calculate the sum of all columns in a dataframe and trying to select the columns which are greater than the ...
<p>Please review the simple code below and you may understand the reason of the error.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.random([3,3])) df.iloc[0,0] = np.nan print df print df.sum(axis=0) &gt; 1.5 print df.loc[:, df.sum(axis=0) &gt; 1.5] df.iloc[0,0] = 'string' prin...
python-2.7|pandas|impyla
0
349,873
36,761,353
Python Pandas: Bar plot X axis issue
<p>I got this dataframe df,</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt table = {'Count_Product': pd.Series([1,2,3]), 'Count_Transaction': pd.Series([1,1,2])} df = pd.DataFrame(table) df Count_Product Count_Transaction 0 1 1 1 2 1 2 3 2 </code></pre> <p>And I ...
<p>I think you need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> from column <code>Count_Product</code> and then change <code>df['Count_Product'].plot</code> to <code>df['Count_Transaction'].plot</code>:</p> <...
python|pandas|matplotlib
3
349,874
36,814,212
Plotting functions from a list using matplotlib
<p>I have been trying to print several equations I have using numpy and matplotlib. </p> <p>The functions are stored on a text file, one equation per line. These equations look like this: <code>np.exp(6.6506+(-171.637)/(x*32))</code></p> <p>My idea was to iterate to each line, generate the plot and save it somewhere....
<p>Use <code>eval</code>, with the usual reservations regarding security:</p> <pre><code>y = eval(line) </code></pre> <p>you may have to remove the new line <code>\n</code> from the lines you read from file with <code>line.strip('\n')</code></p> <p><br><br> <strong>drawing attention to <code>eval</code> security ris...
python|numpy|matplotlib
2
349,875
36,719,997
threshold in 2D numpy array
<p>I have an array of shape 512x512 which contains numbers between 0 and 100 at ith and jth position. Now I want to select array[i,j] &lt; 25 and zero at other places. I have tried with <code>array = array[where(array&lt;25)]</code>, which gives me a 1D array, but I want 2D. Please help me to solve this.</p>
<p>One solution:</p> <pre><code>result = (array &lt; 25) * array </code></pre> <p>The first part <code>array &lt; 25</code> gives you an array of the same shape that is 1 (True) where values are less than 25 and 0 (False) otherwise. Element-wise multiplication with the original array retains the values that are small...
python|numpy
51
349,876
37,083,872
Math Eval String in DataFrame Python
<pre><code>&gt;&gt;&gt; df['X'].head() 0 25+4 1 25+5 2 15+3 3 20+2 4 20+3 Name: X, dtype: object </code></pre> <p>How do I evaluate this so my dataframe is this:</p> <pre><code>&gt;&gt;&gt; df['X'].head() 0 29 1 30 2 18 3 22 4 23 Name: X, dtype: int64 </code></pre>
<p>Although there are security concerns, you can use <code>eval</code> to evaluate each element using a <code>lambda</code> expression.</p> <pre><code>df = pd.DataFrame({'X': ['25+4', '25+5', '15+3', '20+2', '20+3']}) &gt;&gt;&gt; df X 0 25+4 1 25+5 2 15+3 3 20+2 4 20+3 &gt;&gt;&gt; df.X.apply(lambda x: e...
python|numpy|pandas|dataframe|eval
1
349,877
37,030,058
Basic NumPy array replacement
<p>I have a rather basic question about the NumPy module in Python 2, particularly the version on trinket.io. I do not see how to replace values in a multidimensional array several layers in, regardless of the method. Here is an example:</p> <pre><code>a = numpy.array([1,2,3]) a[0] = 0 print a a = numpy.array([[1,...
<p>To change individual values you can simply do something like:</p> <pre><code>a[1,2] = 'b' </code></pre> <p>If you want to change all the array, you can do:</p> <pre><code>a[:,:] = 'c' </code></pre> <p>Use commas (<code>array[a,b]</code>) instead of (<code>array[a][b]</code>)</p>
python|arrays|numpy
1
349,878
37,107,597
what does the eporch means in tf,string_input_producer function
<p>There is api function in tensorflow,string_input_producer function, tf.train.string_input_producer(string_tensor, num_epochs=None, shuffle=True, seed=None, capacity=32, name=None) what does eporchs means here?Is it the same meaning as tranning in eporch?</p>
<p>epochs means the number of iteration over train data to learn it better.</p> <p>and considering to your error it's not related to this input. it's about your file. maybe it cant find the proper file to read.</p> <p>edit after seeing your code:</p> <p>you never initialized your variables. initialize them with sess...
tensorflow
0
349,879
36,697,373
Add elements of lists where dates match (Python)
<p>I have 2 lists:</p> <pre><code>vals = [1,2,3,4] dates = [t1, t2, t3, t4] </code></pre> <p>where dates are in Python's datetime format.</p> <p>Then, given another set of lists:</p> <pre><code>vals_2 = [1, 1, 2, 2] dates_2 = [t5,t6,t7,t8] </code></pre> <p>It could be that <code>t6</code> = <code>t1</code>, etc.</...
<p>Along the lines of what you suggested:</p> <pre><code>import datetime as dt vals = [1, 2, 3, 4] dates = [dt.date(2016,1,n) for n in range(1, 5)] vals_2 = [1, 1, 2, 2] dates_2 = [dt.date(2016,1,n) for n in range(3, 7)] df1 = pd.DataFrame({'date': dates, 'vals': vals}) df2 = pd.DataFrame({'date': dates_2, 'vals': v...
python|datetime|pandas
2
349,880
55,047,065
Unexpected key(s) in state_dict: "model", "opt"
<p>I'm currently using fast.ai to train an image classifier model.</p> <pre><code>data = ImageDataBunch.single_from_classes(path, classes, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats) learner = cnn_learner(data, models.resnet34) learner.model.load_state_dict( torch.load('stage-2.pth', map_locatio...
<p>My strong guess is that <code>stage-2.pth</code> contains two top-level items: the model itself (its weights) and the final state of the optimizer which was used to train it. To load just the model, you need only the former. Assuming things were done in the idiomatic PyTorch way, I would try</p> <pre><code>learner....
python|deep-learning|pytorch|fast-ai
7
349,881
55,067,348
Split pandas dataframe on boolian using boolian function
<p>I have a function</p> <pre><code>def return_true_false(a,b,c): ''' returns true if stuff, else returns false ''' </code></pre> <p>I then apply this function to a Dataframe twice to split the dataframe on the result</p> <pre><code>df_True = df[df.apply(lambda x: return_true_false(x[a],x[b],x[c]),axis=...
<p>IIUC, run it once assigning the result (to <code>mask</code> for example), then using boolean indexing:</p> <pre><code>mask = df.apply(lambda x: return_true_false(x[a],x[b],x[c]),axis=1) df_True = df[mask] df_false = df[~mask] </code></pre>
python|pandas
1
349,882
54,776,799
Plotting d orbital diagrams using matplotlib (or seaborn)
<p>guys, I'm a chemist and I've finished an experiment that gave me the energies of a metal d orbitals.</p> <p>It is relatively easy to get the correct proportion of energies in Excel <a href="https://i.stack.imgur.com/3aY2G.png" rel="nofollow noreferrer">1</a> and use a drawing program like Inkscape to draw the diagr...
<p>You can draw anything you like deriving from basic shapes and functions in matplotlib. Energy levels could be simple <code>marker</code>s, the texts can be produced by <code>annotate</code>.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt Energies = [-0.40008, -0.39583, -0.38466, -0.23478, -0.21...
python-3.x|pandas|matplotlib|seaborn
2
349,883
54,921,575
How can I read a text file in which items are quotations using pandas
<p>I have a file containing long texts, each in double quotation marks, like the following:</p> <pre><code>"blah1 balah1 ..... " "blah2 blah2 ......." "blah3 blah3 ......." "...." </code></pre> <p>I would like to make a <code>dataFrame</code> with one column ('text') out of these items. I tried:</p> <pre><code>data ...
<p>Use parameter <code>names</code> for specify column, then <code>header=None</code> is not necessary:</p> <pre><code>import pandas as pd temp=u'''"blah1 balah1" "blah2 blah2" "blah3 blah3"''' #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv' df = pd.read_csv(pd.compat.StringIO(temp), names=['text1...
python|pandas|dataframe
1
349,884
54,836,522
keras understanding Word Embedding Layer
<p>From the <a href="https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/" rel="nofollow noreferrer">page</a> I got the below code:</p> <pre><code>from numpy import array from keras.preprocessing.text import one_hot from keras.preprocessing.sequence import pad_sequences from keras.models i...
<p>1 - Yes, word unicity is not guaranteed, see the <a href="https://keras.io/preprocessing/text" rel="noreferrer">docs</a>:</p> <ul> <li>From <code>one_hot</code>: This is a wrapper to the <code>hashing_trick</code> function...</li> <li>From <code>hashing_trick</code>: "Two or more words may be assigned to the same i...
python|tensorflow|keras|word-embedding
11
349,885
54,920,921
Tensorflow lite model request a buffer bigger than the neccesary
<p>I created a custom model using keras in tensorflow. The version that I used was tensorflow nightly 1.13.1. I used the official tool to build the tensorflow lite model (the method tf.lite.TFLiteConverter.from_keras_model_file ).</p> <p>After I created the model I reviewed the input shape and nothing seems is bad.</p...
<p>You are correct, the input shape contains 1 * 240 * 240 * 3 <em>elements</em>.</p> <p>However, each element is of type int32, which occupies 4 bytes each.</p> <p>Therefore, the total size of the <em>ByteBuffer</em> should be 1 * 240 * 240 * 3 * 4 = 691200.</p>
tensorflow|tensorflow-lite
4
349,886
54,784,674
Python slicing, moving old slicing places?
<p>i previously got:</p> <pre><code>self.memory = np.zeros((MEMORY_CAPACITY, s_dim * 2 + a_dim + 1), dtype=np.float32) </code></pre> <p>but i needed to add a variable "done" to this memory, so i did:</p> <pre><code>self.memory = np.zeros((MEMORY_CAPACITY, s_dim * 2 + a_dim + 2), dtype=np.float32) </code></pre> ...
<p>Not quite sure what you mean about the part <em>furthermore some old ...</em></p> <p>But the numpy slicing syntax works. See this example:</p> <pre><code>&gt;&gt;&gt; x = np.random.randn(5, 6) &gt;&gt;&gt; x.shape (5, 6) &gt;&gt;&gt; x array([[-0.66028509, -0.03515113, 0.54097151, 1.64021491, 1.55407344, ...
python|numpy|numpy-slicing
0
349,887
54,726,703
Generating keypoint heatmaps in Tensorflow
<p>I am trying to train a model for facial keypoints detection. This is a Stacked HourGlass model. It outputs 256x256x68 dimensional tensor. Each of the 68 outputs will have a hot region around a keypoint. I have defined the model and graph constructs fine. My problem is in generating the dataset.</p> <p>I need t...
<p>Here's a way using SciPy, which you can work into your TF pipeline with a <code>tf.py_func</code>:</p> <pre><code>from scipy.stats import multivariate_normal pos = np.dstack(np.mgrid[0:68:1, 0:68:1]) # hotspot at pixel (22, 43) with roughly 4-pixel radial spread rv = multivariate_normal(mean=[22, 43], cov=4) plt.im...
python|tensorflow|dataset|pose-estimation
1
349,888
54,963,817
Numpy filtering based on all row values
<p>I'm trying to filter a 2D numpy array with another 2D numpy arrays values. Something like this: </p> <pre><code>array1 = np.array([[ 0, 0], [86, 4], [75, 74], [78, 55], [53, 94], [49, 83], [99, 75], ...
<p>Here's an inefficient but very explicit way to do this with np.all():</p> <pre><code># for each row in array2, check full match with each row in array1 bools = [np.all(array1==row,axis=1) for row in array2] # combine 3 boolean arrays with 'or' logic mask = [any(tup) for tup in zip(*bools)] # flip the mask mask = ...
python|numpy
1
349,889
55,036,940
pandas:how to get each customer probability with predict_proba
<p>I am using xgboost with objective='binary:logistic' to calculate each customer probability if he/she will make the spend. Using predic_proba in sklearn will print two probability for both 0 and 1,like:</p> <pre><code>[[0.56651809 0.43348191] [0.15598162 0.84401838] [0.86852502 0.13147498]] </code></pre> <p>...
<p>You can use pandas DataFrame() in order to make your form.</p> <pre><code> list_data = [[0.56651809, 0.43348191],[0.15598162, 0.84401838],[0.86852502, 0.13147498]] columns = ['prob_0', 'prob_1'] index = [1, 2, 3] pd.DataFrame(data = list_data, columns = columns, index= index) </code></pre>
pandas
1
349,890
55,087,617
How to remove a NaN column?
<p>I have a text file has 3 columns like:</p> <pre><code>1 2 3 2 4 6 3 6 9 </code></pre> <p>I want to arrange it like:</p> <pre><code>wave shape freq 1 2 3 2 4 6 3 6 9 </code></pre> <p>I used the following script:</p> <pre><code>import glob import pandas as pd import_fil...
<p>Do not take the suggestions of dropping the <code>NaN</code>s. That would be a solution to an <a href="https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem"><code>XY Problem</code></a> rather than a solution to the <em>cause</em>.</p> <p>Use instead</p> <pre><code>intial_data = pd.read_csv('data.t...
python|python-3.x|pandas|dataframe
2
349,891
55,033,762
How to check between which threshold level does a value lie in?
<p>I have a dataframe having columns looking like this (having 1400 unique <code>contextID</code>s and 28 different <code>IndicatorID</code>s):</p> <pre><code>ContextID IndicatorID threshold_values AlarmLevel actual_values 7289972 204511 -6.10904 -1 0 7289972 204511 -12....
<p>Sure there is a way to do this. Probably better ways than the one below, but this will work.</p> <p>Initialize Data:</p> <pre><code>import pandas as pd import numpy as np thresh = [-6.10904, -12.1848, -18.2606, 18.19404, 24.2698, 30.34557, 89.94568, 104.2932, 118.6407, 32.55574, 18.20825, 3.860765] df = pd.DataF...
python-3.x|pandas|logic
2
349,892
55,072,623
Importing an irregular shaped array into Python
<p>I have some data generated in Mathematica that I need imported into Python. The way the data is generated relies on symbolic calculations so simply generating it in Python is out of the question. The data is an array of dimensions (126,2) but, where the first position in each element is an integer, the second positi...
<p>You may use <a href="http://reference.wolfram.com/language/ref/Export.html" rel="nofollow noreferrer"><code>Export</code></a> with either <a href="http://reference.wolfram.com/language/ref/format/JSON.html" rel="nofollow noreferrer"><code>"JSON"</code></a> or <a href="http://reference.wolfram.com/language/ref/format...
python|arrays|numpy|wolfram-mathematica
1
349,893
54,844,453
Pandas Data Frame Convert Data in Long format to Wide format for specific Date Range
<p>I am trying to convert a time series data from long to wide format. The data is given below as follows.</p> <pre><code>+======+==========+======+======+ | Name | Date | Val1 | Val2 | +======+==========+======+======+ | A | 1/1/2018 | 1 | 2 | +------+----------+------+------+ | B | 1/1/2018 | 2 | ...
<p>First reindex the Dataframe to add missing dates. Then pivot and combine columns.</p> <pre><code>idx = pd.MultiIndex.from_product([df.Name.unique(), pd.date_range(df.Date.min(), df.Date.max())]) df = df.set_index(['Name','Date']).reindex(idx).reset_index().rename(columns = {'level_0':'Name', 'level_1':'Date'}) df...
python|pandas|dataframe
1
349,894
54,701,797
Getting different accuracy in deep learning model with same code
<p>I am following an example from a deep learning book (deeplearning with keras ch1) and this was the example i am following</p> <pre><code>from __future__ import print_function import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activat...
<p>I just read your notebook, and found you execute normalization cell twice, causing the bad results.</p> <pre><code># normalize X_train /= 255 X_test /= 255 print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') </code></pre>
tensorflow|machine-learning|keras|deep-learning|google-colaboratory
1
349,895
55,116,078
Sample weighting for CNN in TensorFlow
<p>I have a CNN implemented in Tensorflow adapted from the tutorial: <a href="https://www.tensorflow.org/tutorials/estimators/cnn#load_training_and_test_data" rel="nofollow noreferrer">CNN with Estimators</a>.</p> <p>Excerpt from data_input_fn:</p> <pre><code>dataset = dataset.batch(batch_size) iterator = dataset.m...
<p>It's possible to use sample weighting in tensorflow. Almost every loss function takes a "weights" argument which if you pass a tensor of the right shape will be used to weight the samples.</p>
python|tensorflow|machine-learning
0
349,896
54,750,105
How can I display multiple images in one tensorboard tab like it's done in tf-object-detection-api
<p>I would like to create tensorboard image summaries using using <code>tf.Summary.Image</code> not using <code>tf.summary.image</code> and tensors. So it should be done without <code>tf.Session</code>. Currently I use this</p> <pre><code> with BytesIO() as byte_io: img_crop_pil = Image.fromarray(image) ...
<p>Turns out the problem was in the <code>tf.Summary.Value</code> <code>tag</code> parameter. If you want several images in one tab you need this images to have tags in the following form. The most important part is the <code>/</code> in the tag name. It is parsed by tensorboard to split images inside tab</p> <pre><co...
python|tensorflow|tensorboard
2
349,897
54,792,245
Pandas dataframe: convert columns into rows of a single column
<p>I have a dataframe that looks like</p> <pre><code>userId feature1 feature2 feature3 ... 123456 0 0.45 0 ... 234567 0 0 0 ... 345678 0.6 0 0.2 ... . . </code></pre> <p>The features are mostly zeros but occasionally some of those would have non-...
<p>Magic from <code>melt</code> </p> <pre><code>df.melt('userId').query('value!=0') Out[459]: userId variable value 2 345678 feature1 0.60 3 123456 feature2 0.45 8 345678 feature3 0.20 </code></pre> <p>Notice using <code>stack</code> you need mask 0 to <code>NaN</code> </p> <pre><code>df.mask(df.eq...
python|pandas|dataframe|pivot-table
4
349,898
54,894,971
Extract multiple polygon coordinates of csv file
<p>I want to extract the (multiple) polygon coordinates of a .xlsx file into Panda Dataframe in Python. </p> <p>The .xlsx file is available on <a href="https://docs.google.com/spreadsheets/d/1Oel5q0zJafWCbMtkh9Tp8YhbEdID36LbpzBS8XuLfZM/edit#gid=0" rel="nofollow noreferrer">google docs</a>.</p> <p>Now I do this:</p> ...
<p>This would give you each pair of values on its own line:</p> <pre><code>import pandas as pd gemeenten2019 = pd.read_excel('Gemeenten 2019.xlsx', index=False, skiprows=0) gemeenten2019['KML'] = gemeenten2019['KML'].str.strip('&lt;&gt;/abcdefghijklmnopqrstuvwxyzGMP').str.replace(' ', '\n') </code></pre> <p>For ex...
python|pandas|csv|dataframe|polygon
0
349,899
54,757,293
Tensorflow freeze_graph unable to initialize local_variables
<p>When freezing a graph with a local variable, freeze_graph has an error stating "Attempting to use uninitialized value...". The local variable in question was initialized via:</p> <pre><code> with tf.variable_scope(tf.get_variable_scope(),reuse=tf.AUTO_REUSE): b_init = tf.constant(10.0, shape=[2, 1], dtyp...
<p>I wasn't able to include local_variables in my frozen graph, but I did come up with a work around.</p> <p>The initial problem was that my checkpoint was created from a graph that contained local_variables. Unfortunately, freezing the graph produced the error:</p> <pre><code>Attempting to use uninitialized value.....
tensorflow|tensorflow-serving
0