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 |
|---|---|---|---|---|---|---|
372,800 | 65,267,138 | Python Pandas - How to match data from one dataframe to another | <p>I have two dataframes related to stocks and their prices that I'm trying to cross-match data from each dataframe.</p>
<p><code>df1</code> = database of users who have each chosen a number of stocks:</p>
<pre><code> Username Stock 1 Stock 2
0 JB3004 TSLA MSFT
1 JM3009 SHOP SPOT
2 DB0208 TWTR ... | <p>Just saw this and I thought I'd give it a whirl.</p>
<p>Use pandas.DataFrame.stack() on df2 to align everything with df1. Rename some fields, if you want.</p>
<pre><code>df2t = df2.stack().reset_index().rename(
columns={
"level_0":"date",
"level_1&quo... | python|pandas|dataframe | 0 |
372,801 | 65,182,820 | How to store matrices within a matrix in Python like on MATLAB? | <p>I'm aware that MATLAB has a function to store 2D matrices in array cells, but how can I do this on Python? I need to store 4X4 matrices in each column of a 1X5 array. Is this possible? Thanks</p> | <p>I think it's possible you can build array for each 4x4 matrix and create another matrix where you can reference 5 different 4x4 matrix.</p>
<pre><code>a = np.array([[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]])
</code></pre>
<p>create 5 different array like this as per your r... | python|matlab|numpy|matrix | 0 |
372,802 | 65,243,986 | I want to plot multiple variables from a dataframe using matplotlib but the final plot looks so weird | <p>I have a dataframe containing stocks of multiple companies and a date column. I want to plot these stocks values on the y axis and date on the x axis in the same plot.</p>
<p>Each stock starts from a different value (for example amazon starts from $3103 whereas apple starts from $112)</p>
<p>When I do that my plot l... | <p>You can manipulate your data by creating a multi-index with <code>pd.MultiIndex.from_tuples()</code>:</p>
<p>This makes the <code>plot</code> automatically give you the output you are looking for:</p>
<p>Pandas Setup:</p>
<pre><code>plot_stocks['Date'] = pd.to_datetime(plot_stocks['Date'])
plot_stocks = plot_stocks.... | python|pandas|matplotlib | 2 |
372,803 | 65,237,788 | apply filters on images when there is no data pixels | <p>I have image that contains many no data pixels. The image is 2d numpy array and the no-data values are "None". Whenever I try to apply on it filters, seems like the none values are taken into account into the kernel and makes my pixels dissapear.</p>
<p>For example, I have this image:<br />
<a href="https:... | <p>If you want to apply a linear smoothing filter, then you can use the Normalized Convolution.</p>
<p>The basic recipe is:</p>
<ol>
<li>Create a mask image that is 1 for the pixels with data, and 0 for the pixels without data.</li>
<li>Set the pixels without data to any number, for example 0. NaN is not valid because ... | python|numpy|image-processing|scipy|imagefilter | 2 |
372,804 | 65,070,558 | Cast a Python class to Numpy Array | <p>Can I cast a python class to a numpy <code>array</code>?</p>
<pre><code>from dataclasses import dataclass
import numpy as np
@dataclass
class X:
x: float = 0
y: float = 0
x = X()
x_array = np.array(x) # would like to get an numpy array np.array([X.x,X.y])
</code></pre>
<p>In the last step, I would like the t... | <p>From <a href="https://numpy.org/doc/stable/reference/generated/numpy.array.html" rel="nofollow noreferrer">docstring of <code>numpy.array</code></a> we can see requirements for the first parameter</p>
<blockquote>
<p><code>object</code>: <code>array_like</code></p>
<p>An array, any object exposing the array interfac... | python|python-3.x|numpy|python-dataclasses | 5 |
372,805 | 65,168,843 | Python 3 numpy uses integer division on matrices and regular division on vectors? | <p>When running the following code:</p>
<pre class="lang-py prettyprint-override"><code>from platform import python_version
print(python_version())
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x[1,:] = x[1,:] / 5
print(x)
y = np.array([1,2,3])
y = y / 5
print(y)
</code></pre>
<p>I get the following o... | <blockquote>
<p>Why does numpy / python use integer division when dividing a row in a matrix by a scalar</p>
</blockquote>
<p>It doesn't - the <em>symptom</em> you are seeing is due to the assignment.</p>
<pre><code>>>> x = np.array([[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>Dividing by an integer produces an... | python|python-3.x|numpy|division|integer-division | 1 |
372,806 | 65,205,738 | Filling a 3D Array and Plotting the Values | <p>I would like to write a code in Python that evaluates the time evolution of a density distribution, p(x,y). The initial conditions is p(t=0,x,y)=exp[-((x-500)^2)/500] and the formula for the solution is in the code below: t-time index, i-space index (x-direction), j-space index (y-direction), and v=0.8</p>
<p>My goa... | <p>Looks like you only fill the values <code>for t in range(0,T-1)</code> which stops at T=8, and you are trying to get <code>x = P[9,i]</code>. They never get filled so obviously they are all 0.</p>
<p>Try to use <code>range(0, T)</code>, it will loop over <code>0,1,2,...,T-1</code>. Also change <code>range(0,Nx), ran... | python|arrays|numpy|plot|colormap | 0 |
372,807 | 65,454,168 | Why is performance of in-place modification to a numpy array related to the order of dimension being modified? | <pre class="lang-py prettyprint-override"><code>import numpy as np
a = np.random.random((500, 500, 500))
b = np.random.random((500, 500))
%timeit a[250, :, :] = b
%timeit a[:, 250, :] = b
%timeit a[:, :, 250] = b
107 µs ± 2.76 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
52 µs ± 88.1 ns per loop (mean ±... | <p>As several comments have indicated, it's all about <a href="https://en.wikipedia.org/wiki/Locality_of_reference" rel="nofollow noreferrer">locality of reference</a>. Think about what numpy has to do at the low-level, and how far away from each other in memory the consecutive lvalues are in the 3rd case.</p>
<p>Note ... | python|numpy|numpy-ndarray|numpy-slicing | 1 |
372,808 | 65,341,548 | apply color to the cells based on the value in cell in dataframe | <p><a href="https://i.stack.imgur.com/0FUB3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0FUB3.png" alt="enter image description here" /></a></p>
<p><strong>working code</strong></p>
<pre><code> import pandas as pd
import seaborn as sns
import matplotlib as mpl
import numpy as np
from matplotlib i... | <p>This <a href="https://stackoverflow.com/a/42563850/6660373">answer</a> will help and also this <a href="https://stackoverflow.com/a/20528097/6660373">answer</a>.</p>
<p>To create sample df:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df =... | python|pandas|matplotlib|seaborn | 2 |
372,809 | 65,092,614 | Put same keys from a column in a list | <pre><code> Name Adress Voor Hoofd Na Dish
0 Aisha_BStraat15 BStraat15 BStraat13 BStraat15 AStraat22 Hoofd
1 Aline_AStraat29 AStraat29 AStraat48 AStraat29 AStraat81 Hoofd
2 Alma_BStraat21 BStraat21 AStraat53 BStraat51 BStraat21 Na
9 Bel_BStraat2... | <p>If I understood well what do you need it will be in the following way:</p>
<pre><code>voor_values = list(df[df.Voor.duplicated(keep=False)].Name.values)
hoofd_values = list(df[df.Hoofd.duplicated(keep=False)].Name.values)
na_values = list(df[df.Na.duplicated(keep=False)].Name.values)
repeated_values = voor_values +... | python|pandas|list|dataframe|key | 0 |
372,810 | 65,230,805 | How to install Python 3.8 along with Python 3.9 in Arch Linux? | <p>I'm working with tensorflow. Recently Arch replaced Python 3.8 with 3.9 and at the moment there is no tensorflow build for Python 3.9. Downgrading Python version for the whole system for that single reason do not looks like good idea for me. My goal is to create virtual environment with python 3.8.
Is there a way to... | <p>Go for package <code>python38</code> in AUR, if you have an AUR helper like yay just use <code>yay -S python38</code>. Otherwise, just download the <a href="https://aur.archlinux.org/packages/python38/" rel="noreferrer">PKGBUILD</a> and install manually with <code>makepkg</code>.</p>
<p>You can also update python wi... | python|linux|tensorflow|virtualenv|archlinux | 16 |
372,811 | 65,297,488 | Pandas calculate rolling count of consecutive values within tolerance | <p>Say I have a list of requests counts to a website for consecutive days. I want to calculate the number of days the current day's request count is within some tolerance (% of the current day's count).</p>
<p>Synthetic example:</p>
<pre><code>>>> pd.DataFrame({'req': {0: 15, 1: 16, 2: 14, 3: 15, 4: 16, 5: 16,... | <p><strong>Updated:</strong></p>
<p>Here's a way to get it done (taking the last previous rows):</p>
<pre class="lang-py prettyprint-override"><code>def last_within_range(df, target_col='req', tolerance=10):
df = df.copy()
s = pd.Series(dtype=int, index=df.index)
# Get low and high tolerance
d... | python|pandas | 1 |
372,812 | 50,104,637 | Extract Numbers out of a Column in Pandas DataFrame using pd.series.str.extractall vs. re.findall | <p>I have the following column in a pandas df: </p>
<pre><code>| Primary_key |
|-------------|
| LIT1-1.10_t |
| LIT1-1.20_t |
| LIT1-1.30_t |
| LIT4-1.99_t |
| LIT4-1.88_t |
| LIT4-1.77_t |
</code></pre>
<p>I want do extract the version number out of the 'Primary_key' (String); split it into a version_number and... | <p>Yes, <code>str.extract</code> with named capturing groups should do it.</p>
<pre><code>v = df.Primary_key.str.extract(r'(?P<version_nr>\d+).(?P<ID>\d+)_', expand=True)
</code></pre>
<p>To update <code>df</code>, </p>
<pre><code>df = pd.concat([df, v], axis=1)
</code></pre>
<p></p>
<pre><code>df
P... | python|pandas|dataframe | 1 |
372,813 | 49,995,407 | Tensorflow CNN plot learning rate vs accuracy | <p>I want to implement the Cyclic LR approach (for finding the optimal learning rate boundaries), which requires me to plot the learning rate vs accuracy. But right now, I can't seem to get that working. When training the model, part of the code below, it either plots an empty graph, or gives me empty lists, and I'm no... | <p>There is nothing TF specific here. <code>lr_list.append(sess.run([lr1]))</code> will indeed append the current value of <code>lr1</code> tensor to <code>lr_list</code>. It is pure Python at this point. If the list is empty at the end, debug it like you would any regular python code... e.g. make sure this line is act... | python|tensorflow|tensorboard | 0 |
372,814 | 49,842,260 | TypingError in Numba 0.37 | <p>I'm trying to optimize a Python code for the calculation of the following formula :
<a href="https://i.stack.imgur.com/7BrcC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7BrcC.png" alt="erez_photo"></a></p>
<p>where phi is a 2D array, and phi_i is a 1D array.
I've build a code for it, and tri... | <p>Append arrays to lists isn't supported and if supported in the future not recommendable if it can be avoided.
Also writing out all loops is recommendable for best performance using Numba.</p>
<p><strong>Example</strong></p>
<pre><code>@nb.njit(fastmath=True,parallel=True)
def calcAlpha(phi,fix_phis):
phi_sq = ... | python|python-2.7|numpy|jit|numba | 1 |
372,815 | 49,977,099 | How to get batched reduce_sum for different range of a big matrix? | <pre><code>import tensorflow as tf
tf.enable_eager_execution()
emb = tf.ones([100,16])
start_pos = tf.constant([1,2])
end_pos = tf.constant([11,31])
</code></pre>
<p>By providing a big matrix emb, and start position start_pos and end position end_pos. How to get the reduce_sim of different range of emb (e.g. the res... | <p><em>EDIT:</em></p>
<p>Actually it is not so hard to do it better in a vectorized way. It takes more memory, but it should be much faster:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
tf.enable_eager_execution()
emb = tf.ones([100,16])
start_pos = tf.constant([1,2])
end_pos = tf.con... | matrix|tensorflow|deep-learning | 2 |
372,816 | 50,197,214 | Pandas Data Re-arrangement | <p>I am working on sport.
The purpose is to record current eventdatetime and PreviousEventTime in a game. I have a sample dataset in the below link.</p>
<p><a href="https://drive.google.com/open?id=1DUNrWPFwrkZHpq_KeA4rZCJ94sbpUEDI" rel="nofollow noreferrer">https://drive.google.com/open?id=1DUNrWPFwrkZHpq_KeA4rZCJ94sb... | <p>First you have to load your dataset into pandas dataframe after we can use shift method.</p>
<pre><code>last_val=df["Time"].iloc[-1]
df['second_eventime']=df['Time'].shift(-1) #This will leave last column value as blank
df.iloc[-1, df.columns.get_loc('second_eventime')] = last_val #To Maintain the value at last r... | python|pandas|dataframe | 0 |
372,817 | 49,940,511 | Why does pd.concat change the resulting datatype from int to float? | <p>I have three dataframes: timestamp (with timestamps), dataSun (with timestamps of sunrise and sunset), dataData (with different climate data). Dataframe <code>timestamp</code> has datatype <code>"int64"</code>.</p>
<p><code>timestamp.head()
timestamp
0 1521681600000
1 1521681900000
2 1521682200000
3 1521... | <p>Because of this - </p>
<pre><code>timestamp 7188 non-null int64
sunrise 7176 non-null float64
...
</code></pre>
<p><code>timestamp</code> has 7188 non-null values, while <code>sunrise</code> and onwards have 7176. It goes without saying that there are 12 values that are <em>not</em> non-null... meaning... | python|pandas|dataframe|concat | 17 |
372,818 | 49,937,629 | Keras model input syntax, use of plus (+) | <p>my main question is about the use of "+" when declaring a keras model inputs /outputs,
how is this different from the normal <code>[input1, input2],[output1,output2]</code> method?
for example <a href="https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html" rel="nofollow noref... | <p>ok, so basically the "+" is applying the keras ADD merge layer to the inputs. this is apparently the only way to add new inputs to an existing graph, this <a href="https://stackoverflow.com/questions/42804966/convert-sequential-to-functional-in-keras#42808714">question</a> gave me the hint.
The second problem was t... | tensorflow|machine-learning|input|keras|add | 0 |
372,819 | 50,163,386 | multivariate KNN prediction | <p>So, I have code that works for knn.predict() if I have data that has 1 feature to predict the next outcome. To put this into context, I have stock data (Open, High, Low, Close) where I use "Open" as "X" data and "Close" as "Y" data and knn.predict will predict the next value of Y.</p>
<p>When I try to use "Open, H... | <p>For training, you're using </p>
<pre><code>X = np.array(df.ix[:, 2:6])
</code></pre>
<p>i.e., a matrix with 6 - 2 = 4 columns, meaning that the neighbors are 4-tuples.</p>
<p>For predicting, you're using </p>
<pre><code>u = df['Close'].iloc[-1]
</code></pre>
<p>which is a scalar. </p>
<p>The nearest neighbor i... | python|pandas|machine-learning|scikit-learn|knn | 1 |
372,820 | 50,078,749 | Tensorflow-hub Text-Module Preprocessing | <p>I'm playing around with the new Modules which are available on the tensorflow-hub (which I really like - thanks for that).</p>
<p>Whats unclear to me, is the preprocessing which should take place when feeding a sentence. The module <a href="https://www.tensorflow.org/hub/modules/google/nnlm-en-dim128/1" rel="nofoll... | <p>Yes, the output represents a fixed-dimensional representation of the entire sentence.</p>
<p>You can also embed single words to get their vectors. In your case:</p>
<pre><code>embeddings = embed({"default": ["Cat", "sat", "on", "mat"]})
</code></pre>
<p>Should give you a result with shape (4, 128).</p> | tensorflow|tensorflow-hub | 2 |
372,821 | 49,996,486 | Python 3.6 - Cannot get current stock prices from quandl, pandas and datetime | <p>I try to write a small "program" that gets the stock prices from Quandl.
The user should be able to enter a startring date (yyyymmdd) and the the program should then get the data from that date and forward to current date.</p>
<pre><code>import datetime as dt
import pandas_datareader as web
ticke... | <p>The WIKI database is indeed no longer updated or supported starting from March 27, 2018. The closest alternative on Quandl is EOD, which is a value-priced end-of-day US stock price data feed.</p> | python|datetime|stock|quandl|pandas-datareader | 0 |
372,822 | 49,982,927 | Pandas count all occurrences on different columns in a dataframe | <p>I have a data frame similar to this one
<code>
GRP HOST1 HOST2 HOST3 FILESIZE
0 0 srv39 srv45 srv47 203498176
1 1 srv102 srv36 srv38 452763956
2 1 srv101 srv36 srv45 453277268
3 1 srv101 srv34 srv45 448174741
4 1 srv36 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a> for reshape anf then aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</cod... | python|pandas|dataframe|multi-index | 3 |
372,823 | 49,920,843 | Reading batches of images and training in Tensorflow | <p>I am trying to read images in batches here. And train them. When I execute this
it seems to get stuck. There is no progress.
Can anyone spot the problem ? There are no logs being written.</p>
<pre><code>def train():
filenames = tf.train.string_input_producer(
tf.train.match_filenames_once("D:/*.png"))
reader = ... | <p>I am considering this as an answer until I receive other answers.
The problem I found was related to </p>
<pre><code> filenames = tf.train.string_input_producer(
tf.train.match_filenames_once("D:/Development_Avecto/TensorFlow/resizedimages/*.png"))
</code></pre>
<p>The problematic code has a pattern like th... | tensorflow | 0 |
372,824 | 50,063,089 | pandas expanding (cummulative) value_counts | <p>Is there a way to get the value counts up to each row in a dataframe?</p>
<pre><code>|f1|f2|
-------
v1 | a value_counts -> {a:1}
v2 | a value_counts -> {a:2}
v3 | b value_counts -> {a:2,b:1}
v4 | c value_counts -> {c:1,a:2,b:1}
</code></pre> | <p>You could call <code>cumsum</code> on the output of <code>get_dummies</code> on the column of interest:</p>
<pre><code>>>> pd.get_dummies(df["f2"])
a b c
0 1 0 0
1 1 0 0
2 0 1 0
3 0 0 1
>>> pd.get_dummies(df["f2"]).cumsum()
a b c
0 1 0 0
1 2 0 0
2 2 1 0
3 2 1 1
</... | python|pandas | 1 |
372,825 | 50,084,989 | Concatenating header list to Dataframe in pandas | <p>I am having trouble to concatenate 2 simple <code>DataFrames</code>. I upload first one <code>.txt</code> file containing the data set, and then another one containing the <code>header</code> of the previous dataset.</p>
<p>First I upload the 2 DataFrames:</p>
<pre><code>df = pd.read_csv(file_dir + file_name, sep ... | <p>Your <code>list_names</code> is a <em>list of lists</em>. The requirement is to have a flat list.</p>
<p>You need to amend this line:</p>
<pre><code>list_names = df_column_names.T.values.tolist()
</code></pre>
<p>To this:</p>
<pre><code>df_column_names = df_column_names.transpose() # transpose dataframe if neces... | python|pandas|dataframe|append|concatenation | 1 |
372,826 | 49,913,241 | Pandas : Copy recent date's data for missing days | <p>I have some data in the following format in a pandas Dataframe where the index is data. This is financial data for which certain date's data can be missing. I need to fill in the missing day's data with the most recent date's (prior to date of interest) data. Also, I need to fill in only for week days. How do I acco... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.ffill.html" rel="nofollow noreferrer"><code>ffill</code></a> for al... | python|pandas | 2 |
372,827 | 49,951,472 | how to add proportion label on the stacked bar chart in python bar chart | <p>I have plotted stacked bar chart and want to add text indicating its proportion on the bar but do not know how I can add those labels on.</p>
<p>My codes are,</p>
<pre><code>tps = df3[df3['Action Type_new']!='NA'].pivot_table(values=['Column'],
index='year',
columns='Action Typ... | <h3>Update using matplotlib 3.4.2</h3>
<p>Thanks <a href="https://www.linkedin.com/posts/trentonmckinney_python-anaconda-pandas-activity-6799871827448598528-3rUd" rel="nofollow noreferrer">@TentonMcKinney</a></p>
<pre><code>df1 = df['Column']
ax = df1.plot(kind='bar',stacked=True)
for c in ax.containers[::2]:
ax.ba... | python|pandas|matplotlib|pivot|bar-chart | 2 |
372,828 | 49,806,457 | Google cloud Platform and google machine learning | <p>I have to use several services of the google cloud platform but I'm pretty confused between the several services (Google Machine learning engine, google Data prep, Data lab).</p>
<p>How do they interact together ?
And I have a more specific question : I ran a python script (to use SVM classifier) in the cloud shell... | <p>When you create a project on the Google Cloud Platform (GCP), you can configure the project to access different services. Many of these services, such as Cloud Storage, Datastore, BigTable, and Dataprep, involve storing and transforming data at high speed.</p>
<p>Another service, the Google Compute Engine (GCE), ma... | google-app-engine|tensorflow|machine-learning | 1 |
372,829 | 50,033,178 | Using multiple_gpu_model on keras - causing resource exhaustion | <p>I built my network the following way: </p>
<pre><code># Build U-Net model
inputs = Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))
s = Lambda(lambda x: x / 255) (inputs)
width = 64
c1 = Conv2D(width, (3, 3), activation='relu', padding='same') (s)
c1 = Conv2D(width, (3, 3), activation='relu', padding='same') (c1)
p1 = ... | <p>The first dim of the tensor is the batch_size, so everthing is fine in your case. You have specified your batch_size as 256 and you use 8 gpus. So your resulting batch_size is 32 as stated in the error.
Also the error suggest that your model still is too big with a batch_size of 32 for your gpus to handle.</p> | python|tensorflow|keras|gpu | 2 |
372,830 | 49,992,220 | how would I find the min value of an index AFTER a certain value | <p>I have the following list as such:</p>
<pre><code>y = np.array([ 9.7, 10.1, 10.5, 10.2, 10.1, 9.9, 9.8])
</code></pre>
<p>I want to find the index of a minimum value that fulfils the criteria of having passed both a threshold and the max of said threshold.</p>
<p>In this, instance the threshold is 1... | <p>You could create a new array starting from the given index and then do <code>np.max(newArray)</code></p> | arrays|python-3.x|numpy | 0 |
372,831 | 49,914,043 | I want to change DataFrame's value from str into int | <p>I want to change DataFrame's value from str into int.
I wrote codes,</p>
<pre><code>import scipy as sp
import scipy.stats
import pandas as pd
import numpy as np
x = sp.stats.chi2_contingency(df)
print(x)
</code></pre>
<p>df variable has DataFrame table like</p>
<pre><code>A B C D
0 23 45 18 49
</code></pre>
<p>W... | <p>It seems values are strings, so convert them to numeric:</p>
<pre><code>df = pd.DataFrame({'A': {0: '23'}, 'B': {0: '45'}, 'C': {0: '18'}, 'D': {0: '49'}})
print (df)
A B C D
0 23 45 18 49
x = sp.stats.chi2_contingency(df.astype(int))
print(x)
(0.0, 1.0, 0, array([[ 23., 45., 18., 49.]]))
</code><... | python|pandas | 1 |
372,832 | 50,068,443 | Collapse rows in Pandas dataframe with different logic per column | <p>I want to collapse dataframe rows that match values for a given column but the rest of the columns have to be collapsed with different logic. Example:</p>
<pre><code>City ColumnA ColumnB
Seattle 20 30
Seattle 30 20
Portland 25 25
Portland 10 40
</cod... | <p>use <code>groubpy</code> and <code>.agg</code>:</p>
<pre><code>df.groupby('City', as_index=False).agg({'ColumnA':'min', 'ColumnB':'mean'})
City ColumnA ColumnB
0 Portland 10 32.5
1 Seattle 20 25.0
</code></pre> | python|pandas|dataframe|pandas-groupby | 1 |
372,833 | 50,142,569 | Pandas read data without header or index | <p>Here is the <strong>.csv</strong> file :</p>
<pre><code>0 0 1 1 1 0 1 1 0 1 1 1 1
0 1 1 0 1 0 1 1 0 1 0 0 1
0 0 1 1 0 0 1 1 1 0 1 1 1
0 1 1 1 1 1 1 1 1 1 1 1 2
0 1 1 1 0 1 1 1 1 1 1 1 1
0 0 0 ... | <p>You might want <code>index_col=False</code></p>
<pre><code>df = pd.read_csv(file,delimiter='\t',
header=None,
index_col=False)
</code></pre>
<p>From the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer">Docs</a>,</p>
<b... | python|pandas|csv|numpy | 13 |
372,834 | 49,951,575 | How can I convert a Pandas column to be all of the same timezone? | <p>I have two columns in a pandas dataframe that have datetimes loaded from a Postgresql database. In each column there are datetimes with varying timezones. How can I convert these to datetimes to be of the same timezone?</p> | <p>Assuming the columns are timezone aware, you can use</p>
<pre><code>for column in df.columns:
df[column] = pd.DatetimeIndex(df[column]).tz_convert(tz)
</code></pre>
<p>where <code>tz</code> is the time zone you want.</p> | pandas | 0 |
372,835 | 49,848,597 | Explode column of strings and count character frequencies | <p>I have a dataset with 2 columns that look like:</p>
<pre><code>|group| |sequence|
A BX
A X
B SFS
B BCX
B BSS*B1S
A BBX
</code></pre>
<p>I'd like some way to be able to group and find the frequency of each character, to get something like this:</p>
<pre><code> |group| |cha... | <p>You could use an efficient <code>repeat</code>-based solution followed by <code>groupby</code>:</p>
<pre><code>from itertools import chain
# Step 1 - flatten your dataframe
df = pd.DataFrame({
'group' : df['group'].repeat(df.sequence.str.len()),
'char' : list(chain.from_iterable(df.sequence.tolist()))
})
... | python|string|pandas|dataframe | 4 |
372,836 | 50,225,770 | Performing mathematical operations on a pandas dataframe | <p>The column looks like</p>
<pre><code> Mod_month Mod_year Reg_Year Reg_Month
10 2016 2016 10
1 2018 2016 12
2 2017 2017 2
</code></pre>
<p>I want to perform some mathmatical operations on coloumns of a dataframe to calculate differ... | <p>I think need remove <code>df[]</code>, because it is syntax of <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> or selecting by <code>subset</code> of columns:</p>
<pre><code>df['difference'] = df['mod_month'] - df['last... | python|pandas|dataframe | 2 |
372,837 | 49,945,797 | Python convert multidimensional numpy array into multiple 1d numpy arrays | <p>I stacked 56 lots of 2D numpy arrays of size (100,13) using <code>numpy.dstack</code> so that my shape of X is:</p>
<pre><code>X.shape
(56, 100, 13)
</code></pre>
<p>Now I want to divide this along its depth into 56*100 lots of 1D arrays of length 13.</p>
<p>I tried this <code>L = numpy.split(X[0],(100,13), axis ... | <p>Here's an example of using reshape to solve it, with some examples showing the order of the new 1D data after reshaping:</p>
<pre><code>In [96]: X = np.random.rand(56, 100, 13)
In [97]: Y = X.reshape(56*100, 13)
In [98]: (X[0, 1, :] == Y[1, :]).all()
Out[98]: True
In [99]: (X[0, 99, :] == Y[99, :]).all()
Out[99]... | python|arrays|numpy | 1 |
372,838 | 49,946,423 | using min() function in a pandas datagram with an exception value | <p>I'm using a min() function in a pandas dataframe with the intent to get the minimum values.</p>
<p>However, in the DataFrame, all "bad data" values have been replaced with -9999999. </p>
<p>How do I ignore that value in a min() function? that value carries no data value. </p>
<p>here's some code:</p>
<pre><cod... | <p>A solution is to get the values over that number:</p>
<pre><code>df.values[df.values > -9999999].min()
</code></pre>
<p>In general, <em>Numpy's Not a number</em> <code>np.nan</code> is the best representation of a bad data instead of an actual numerical value, and in Pandas v>0.15, it writes NULL to SQL.</p> | python|pandas | 2 |
372,839 | 49,906,809 | json does not have column names after resample pandas | <p>How to get column names when you are using to_json on resample data? </p>
<pre><code>amount = df['amount'].resample('M').last()
amount = amount.to_json()
</code></pre>
<p>output that I'm getting:</p>
<pre><code>{"1501459200000":1.79,"1504137600000":88.80}
</code></pre>
<p>output I want:</p>
<pre><code>[{"time":... | <p>You can use parameter <code>orient='records'</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow noreferrer"><code>to_json</code></a>, but if need only <code>dates</code> add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series... | python|pandas | 2 |
372,840 | 49,984,571 | Feasibility of converting all python pandas/numpy code to base python | <p><strong>General python question-</strong>
I have built a script using numpy and pandas libraries. I have now been told that I cannot use any libraries- only base python to code. This is because apparently open source libraries are not approved. </p>
<ol>
<li><p>Does this restriction make sense? Isn't base python a... | <p>I'm only going to address the 2nd point. Reimplementing all of numpy/pandas is certainly a <em>very</em> large and useless task. But you're not reimplementing all of it, you only need some parts, and if it's only a few functions, than it's certainly possible.</p>
<p>I'd start from a working script, replace arrays b... | python|pandas|numpy | 0 |
372,841 | 50,110,099 | Turn Numpy Array of Points into Numpy Array of Distances | <p>If we are given <code>"starting_point"</code> and <code>"list_of_points"</code>, how do we create a new numpy array "distances" that contains the distance between the "starting_point" and each point in "list_of_points"? </p>
<p>I tried to do this by looping through <code>"list_of_points"</code> with the following ... | <p>You are on the right track with using Numpy for this. I personally found Numpy very unintuitive when I first used it, but it gets (a little) easier with practice. </p>
<p>The basic idea is that you want to avoid loops and use vectorized operations. This allows <em>much</em> faster operations on large data structure... | python|numpy | 0 |
372,842 | 49,943,958 | Using a variable for pandas read_csv() | <p>I use the below code to find a .csv file with a certain pattern. I would then like to pass it into the read_csv() function, but it seems that it only accepts a string. What can I do to pass my variable "csv_file" into the function?</p>
<p>Code:</p>
<pre><code>csv_file = glob.glob('******* Output.csv')
</code></pre... | <p><code>glob.glob</code> return list of files matched with your regex, but read_csv need a file name, so you could iterate all the files</p>
<pre><code>csv_files = glob.glob('******* Output.csv')
#it will get list of dataframes
d = [pd.read_csv(csv_file) for csv_file in csv_files]
</code></pre> | python|pandas|glob | 0 |
372,843 | 49,942,622 | Install part of pandas module | <p>Pandas is a pretty bulky module, hence I do not wish to install it in its entirity. Only the ones I'll be using in my codes. </p>
<pre><code>from pandas import DataFrame
from pandas import ExcelWriter
from pandas import pivot_table
from pandas import read_csv
</code></pre>
<p>How can I pip install only these pack... | <p>This is not officially supported by <code>pandas</code>. The pandas documentation (<a href="https://pandas.pydata.org/pandas-docs/stable/install.html" rel="nofollow noreferrer">link</a>) make no mention of how to install some parts of the module but not others. This is probably because of how tightly coupled the f... | python|python-2.7|pandas|pip | 1 |
372,844 | 63,841,108 | Getting empty data frame while merging two dataframe in python | <p>I am trying to merge two dataframes based on some columns but getting empty dataframe. Can you please help me to get proper solution?</p>
<p>Explain:</p>
<p>df1:</p>
<pre><code> kol_id thrc_nm jnj_id
0 101152 VIR 7124166
</code></pre>
<p>df1.info()</p>
<pre><code><class 'pandas.core.frame.DataFrame'>... | <p>Problem is column <code>jnj_id</code> in <code>df2</code> is filled by <code>objects</code> (<code>strings</code>), but there are trailing <code>0</code>, so not match. I guess reason is <code>df1['jnj_id']</code> was filled by <code>integers</code> and <code>df2['jnj_id']</code> was filled ny <code>floats</code>, c... | python|pandas|dataframe|join | 0 |
372,845 | 64,071,280 | Splitting column with text data without delimiters into individual columns | <p>My dataset is in dataframe (df1):</p>
<p><a href="https://i.stack.imgur.com/1FKER.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1FKER.png" alt="enter image description here" /></a></p>
<p>want to split the event_type field in above df1 into individual columns for each of the letters that are up ... | <p>Use the spark column split function.</p>
<pre><code>df = df.withColumn('len', length('event_type'))
df2 = df.withColumn('temp', rpad('event_type', 20, ' ')) \
.select(*df.columns, *map(lambda i: split('temp', '|')[i].alias('step_' + str(i+1)), range(0, 20))) \
.drop('temp')
df2.show(10, False)
+---+----------... | python|pandas|pyspark | 2 |
372,846 | 64,026,103 | Get sum per month from daily data into new column while keeping daily data | <p>I have a df with daily data and some levels per day:</p>
<pre><code>date | value1 | value2 | level
2020-01-01 | 1 | 2 | "a"
2020-01-01 | 3 | 10 | "b"
2020-01-01 | 2 | 3 | "c"
2020-01-02 | 1 | 2 | "a"
2020-01-02 | 3 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></... | pandas|date|sum | 1 |
372,847 | 63,810,558 | I want to create an Anova Table with Dataset having one dependent column and otheras independent column | <p>I have a data set having columns col1, col2,col3,col4,col5. I want col1 as dependent variable and other as independent variable. How would i create the formula?
I am creating like this.
I confused what should be the <strong>?</strong></p>
<pre><code>import statsmodels.api as sm
from statsmodels.formula.api import ol... | <p>This Works for me</p>
<pre><code>formula = 'col1 ~ ' + ' + '.join(['%s' % variable for variable in y])
model = ols(formula=formula, data=anovaData).fit()
</code></pre> | python|pandas|dataframe|anova | 1 |
372,848 | 64,162,212 | Counting the number of consecutive occurences of numbers in dataframe with multi index | <p>I have a dataframe that has a multi index (stock and datetime) with a dummy column that contains 1s and 0s and I would like to count for each stock and for each day, in each row how many times the 1s or 0s have occurred in the 'Dummy" column, starting at 1 every time, and counting up for 1s and counting down fo... | <p>Just slightly modify your previous solution</p>
<pre><code>m = df.Dummy.diff().ne(0).cumsum()
counters = df.groupby([df.index.get_level_values(0),
df.index.get_level_values(1).date,
m]).cumcount()+1
df['Counter'] = np.where(df['Dummy']==0, -1, 1) * counters
Out[95]:
... | pandas|dataframe|pandas-groupby | 1 |
372,849 | 63,886,561 | Is there a way in pandas to groupby and then count unique where another column has a specified value? | <p>I have a pandas dataframe with numerous columns. For simplicity, let's say the columns are, 'country', 'time_bucket', 'category' and 'id'. The 'category' can be either 'staff' or 'student'.</p>
<pre><code>import pandas as pd
data = {'country': ['A', 'A', 'A', 'B', 'B',],
'time_bucket': ['8', '8', '8... | <p>We can use the <code>groupby</code> operation with <code>apply</code>. The <code>apply</code> takes a function as an argument which will receive a sub dataframe for each grouping. Using the data you gave and grouping by [country, time_bucket] it would receive 3 rows for [A,8], 1 for [B,8] and 1 for [B,9]</p>
<p>To g... | python|pandas|dataframe|pandas-groupby|unique | 1 |
372,850 | 63,991,551 | pandas join on time with tolerance and allow for multiple matches | <p>How can I perform a time based JOIN in pandas including tolerance when I need to match multiple results from the right side?</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id_group_key':[1,1,1,2], 'time':['2020-01-01 00:01:00', '2020-01-01','2020-01-02', '2020-01-01'], 'left_value':[1,2,4,3]})
df['time'] = ... | <p>Simply inverting the order could solve the issue:</p>
<pre><code>result = pd.merge_asof(df_right, df, on='id_group_key', tolerance=pd.Timedelta('36 days'), left_index=True, right_index=True)
</code></pre>
<p>However, this would not allow for an <code>OUTER JOIN</code>.</p> | python|pandas|join|time-series | 0 |
372,851 | 63,972,958 | pandas: filter data using column in unix timestamp | <p>One column of my <code>dataframe</code> contains unix timestamp. I am looking for a way to filter records by date similar to this <code>SQL</code> statement:</p>
<pre><code>SELECT * FROM mytable WHERE to_timestamp(log_time) < '2007-04-13';
</code></pre>
<p>to filter records in my <code>dataframe</code>. Sample re... | <ul>
<li>In order to use datetime <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">Boolean selection</a>, the <code>log_time</code> column needs to be converted to a datetime column, or create a separate datetime column from <code>log_time</code>... | python|pandas|dataframe | 0 |
372,852 | 64,123,868 | Print all elements of 1d array in formated string | <p>I am working on 1D-arrays of variable length in python and trying to print them in a formated string in a comfortable way.</p>
<p>Example array:</p>
<p><code>numbers = [1.0, 2.0, 3.0]</code></p>
<p>Desired output:</p>
<p><code>"The numbers are 1.0, 2.0, 3.0"</code></p>
<p>I can't get any further than this ... | <p>This should do the job:</p>
<pre class="lang-py prettyprint-override"><code>"The numbers are " + ", ".join([f"{n:.1f}" for n in numbers])
</code></pre>
<p>(f-strings are python 3.6+, modify the syntax in the list comprehension if you need to support an older version)</p> | python|numpy | 2 |
372,853 | 64,163,283 | pandas apply only returning first value when using logical indexing | <p>I create two dataframes:</p>
<pre><code>data = [['John'], ['Mary']]
df1 = pd.DataFrame(data, columns = ['Name'])
df1['Height'] = 0
data = [['John', 5], ['Mary', 6]]
df2 = pd.DataFrame(data, columns = ['Name', 'Height'])
df1
Output:
Name Height
0 John 0
1 Mary 0
df2
Output:
Name Heig... | <p>Why not just do a <code>.merge</code> which will be more efficient anyway? You can specify just the <code>Name</code> column in df1 with <code>df1[['Name']]</code> when doing the merge, so you don't create two duplicate <code>Height</code> columns.</p>
<pre><code>df1 = pd.merge(df1[['Name']], df2,how='left', on='Nam... | pandas | 1 |
372,854 | 63,801,504 | Convert columns in dataframe with comas into numeric data to plotting | <p>I'm new in the world of plotting in Python I started learning today doing a mini project by my own, I tried to scrape data and represent here's my code:</p>
<pre><code>import requests
import pandas as pd
from pandas import DataFrame
import numpy as np
import bs4
from bs4 import BeautifulSoup
import matplotlib.pyplot... | <p>After running the script, as you say the column "Casos Totales" is being interpreted as string due to the commas in the values. You can change this using <code>.str.replace(',','')</code> and then <code>.astype(float)</code>, right after renaming the column names in your dataframe:</p>
<pre><code>df['Casos... | python|python-3.x|pandas|matplotlib|beautifulsoup | 1 |
372,855 | 64,026,275 | python pandas loops to melt or pivot multiple df | <p>I have several df with the same structure. I'd like to create a loop to melt them or create a pivot table.</p>
<p>I tried the following but are not working</p>
<pre class="lang-py prettyprint-override"><code>
my_df = [df1, df2, df3]
for df in my_df:
df = pd.melt(df, id_vars=['A','B','C'], value_name = 'my_value'... | <p>You need assign output to new list of <code>DataFrame</code>s:</p>
<pre><code>out = []
for df in my_df:
df = pd.melt(df, id_vars=['A','B','C'], value_name = 'my_value')
out.append(df)
</code></pre>
<p>Same idea in list comprehension:</p>
<pre><code>out = [pd.melt(df, id_vars=['A','B','C'], value_name = 'my_val... | python|pandas|loops|pivot|melt | 2 |
372,856 | 63,950,755 | Trying to unstack dataframe with multiple empty columns (NaN) | <p>I currently have a code which turns this:</p>
<pre><code> A B C D E F G H I J
0 1.1.1 amba 50 1 131 4 40 3 150 5
1 2.2.2 erto 50 7 40 8 150 8 131 2
2 3.3.3 gema 131 2 150 5 40 1 50 3
</code></pre>
<p>Into this:</p>
<pre><code> ID User 40 50 131 ... | <p>Idea is convert first 2 columns to <code>MultiIndex</code>, then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> by selected pair and unpair columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/panda... | python|pandas | 2 |
372,857 | 64,145,692 | Python: curve fit looks scrambled | <p>I am trying to fit a curve to some data but the resulting curve looks like a scrambled mess. I don't know whether or not the coefficients are accurate. With this sample data set it prints something like a triangle and with my original data set it looks even worse. It's mostly tutorial. I tried removing the sympy cod... | <p>This is because Matplotlib will only draw lines between the few points in your original data (in the x and y arrays) and in the order they are defined. There are only 3 unique x values (plus some noise) which is why you see what looks like a triangle.</p>
<p>The fix is to create a new array with evenly spread, and o... | python|numpy|curve-fitting | 3 |
372,858 | 64,035,708 | How can I reset the index in a .groupby output? | <p>I have the following dataframe. I want to group the name and brand columns by their respective unique values.</p>
<p><a href="https://i.stack.imgur.com/2BTSS.png" rel="nofollow noreferrer">dataframe</a></p>
<p>I wrote the following python code to group them:</p>
<pre><code>high_products = products.reset_index().grou... | <p>Change the first line of your code to (count aggregation on name, brand):</p>
<pre><code>high_products = products.groupby(['name', 'brand']).agg(['count']).reset_index()
</code></pre> | python-3.x|pandas-groupby | 0 |
372,859 | 63,881,363 | Tensorflow fit method with generator error. AttributeError: 'tuple' object has no attribute 'shape' | <p>I'm trying to get a basic segmentation model going before making major tweaks and no matter how simple I make it I receive this error. I'm working on Collaboratory</p>
<pre><code>Found 500 images belonging to 1 classes.
Found 500 images belonging to 1 classes.
Found 50 images belonging to 1 classes.
Found 50 images ... | <p>I am guessing now, but <code>.fit()</code> expects data, a <code>tf.data.Dataset</code> structure or a data_generator (which I am not great familiar with). However, you are passing a tuple as you return <code>zip(train_image_generator, train_mask_generator)</code>, which is no format <code>.fit()</code> can use for ... | python|tensorflow|keras | 1 |
372,860 | 63,911,955 | Fine tune GPT-2 on large text for generate a domain text | <p>Tryin to train GPT-2 on a very large text, in order to generate text from <strong>specific domain</strong>.<br />
Working with tensorflow2 .</p>
<p>For example, let's say I have all of Harry Potter books :)<br />
And I want to train the GPT-2 on them, so I could later generate text from the Harry Potter domain.</p>
... | <p>Your problem is not related to training on different domains. Rather, you're simply providing a text length (apparently 149887 tokens) that's longer than the maximum length that the model can support (1024). You have three options:</p>
<ol>
<li><p>Manually truncate your input strings to the max length of tokens.</p>... | tensorflow|keras|deep-learning|nlp|huggingface-transformers | 2 |
372,861 | 63,809,453 | How does Tensorflow Federated update model from server | <p>New to Tensorflow so not sure if this is a specific question for Tensorflow Federated.</p>
<p>I'm studying adversarial attack on federated learning in this <a href="https://github.com/tensorflow/federated/blob/master/tensorflow_federated/python/research/targeted_attack/attacked_fedavg.py" rel="nofollow noreferrer">c... | <p>In the code you point to, <code>initial_weights</code> is only a collection of values (<code>tf.Tensor</code> objects), and <code>model_weights</code> is a reference to the <code>model</code>'s variables (<code>tf.Variable</code> objects). We use <code>initial_weights</code> to assign the initial value to the model'... | tensorflow|tensorflow-federated | 2 |
372,862 | 64,147,508 | Tensorflow: List of available **kwargs | <p>In Tensorflow API documents, I have difficulty to find all available keyword arguments.</p>
<p>For example, <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/GlobalMaxPool1D" rel="nofollow noreferrer">"GlobalMaxPooling1D"</a> layer in Tensorflow API:</p>
<pre class="lang-py prettyprint-ov... | <p>In the case of <code>tf.keras.layers.Layer</code> subclasses, like <code>GlobalMaxPooling1D</code>, <a href="https://github.com/tensorflow/tensorflow/blob/fcc4b966f1265f466e82617020af93670141b009/tensorflow/python/keras/engine/base_layer.py#L308-L316" rel="nofollow noreferrer">valid keyword arguments</a> are</p>
<pr... | tensorflow|keras | 2 |
372,863 | 64,073,899 | CNN ValueError: Unknown layer: Functional when testing my model | <pre><code>import os
import numpy as np
import pandas as pd
import cv2
from glob import glob
from tqdm import tqdm
import tensorflow as tf
from sklearn.model_selection import train_test_split
def read_image(path, size):
image = cv2.imread(path, cv2.IMREAD_COLOR)
image = cv2.resize(image, (size, size))
imag... | <p>Never mind, all I need to do was pip Install Tensorflow 2.3.1 and fixed it and Test my images perfectly.</p>
<p>Despite it being a CPU render not a GpU render. For having the
2020-09-26 11:12:19.333012: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cublas64_10.dll'; ... | python|tensorflow|keras|neural-network|conv-neural-network | 0 |
372,864 | 63,851,063 | Trying to access subset of mnist dataset in pytorch [equal samples from each class] | <p>Trying to access subset of mnist dataset in pytorch [equal samples from each class] but getting this error</p>
<pre><code>prng = RandomState(42)
random_permute = prng.permutation(np.arange(0, 6000))[0:3000]
indx = np.concatenate([np.where(np.array(mnist_data.targets) == classe)[0][random_permute] for classe in range... | <p>MNIST dataset does not have a uniform distribution of targets. You are getting this error because class 0 in MNIST contains 5923 samples.</p>
<pre><code>nums = [0]*10
for i in range(60000):
nums[(int(mnist_data.targets[i]))] += 1
print(nums)
</code></pre>
<p>This will print <code>[5923, 6742, 5958, 6131, 5842, 542... | python|arrays|numpy|pytorch|mnist | 1 |
372,865 | 64,070,710 | Pandas groupby sum difference shift cumulative sum | <p>I have a table similiar to this</p>
<pre><code>import pandas as pd
data = [['2019-02-01',0 ,5],
['2019-02-01',1, 12],
['2019-02-01',2,18],
['2019-02-01' ,3, 23],
['2019-02-01' ,4 ,20],
['2019-03-01',0 ,12],
['2019-03-01', 1,7],
['2019-03-01' ,2, 6],
['2019-03-01' ,3, 5],
['2019-03-01' ,4, 8]]
df = pd.Data... | <p>Try with reversed the order and <code>cumsum</code></p>
<pre><code>df['New'] = df.iloc[::-1].groupby('Start_Month').Complete.cumsum()
df
Start_Month Bucket Complete New
0 2019-02-01 0 5 78
1 2019-02-01 1 12 73
2 2019-02-01 2 18 61
3 2019-02-01 3 23 ... | python|pandas | 2 |
372,866 | 63,871,093 | LSTM multi task learning functional api keras | <p>I have 2 train values X_data, B_data. I want 2 shared lstm layers to predict 2 outputs for X_data and B_data</p>
<pre><code>l1 = layers.LSTM(40)(X_data)
flat_layer = Flatten()(l1)
l2 = layers.LSTM(20)(B_data)
flat_layer2 = Flatten()(l2)
output1 = Dense(1, activation='sigmoid')(flat_layer)
output2 = Dense(1, activa... | <p>The mistake is that <code>keras.Model(inputs)</code> does not take in the input <em>data</em> but the input <em>layer</em> (just as you did correctly with <code>outputs</code>). The data is passed via <code>model.fit()</code>. So first of all, you'll need two <code>Input</code> layers:</p>
<pre><code>X_data = np.ran... | python|tensorflow|keras|lstm | 1 |
372,867 | 63,770,987 | How to group by a specific given values by Pandas? | <p>I have this dataframe:</p>
<pre><code>a b c
1 2 5
1 3 5
1 4 4
2 5 3
</code></pre>
<p>I know the value of every column could only range from 1 to 5 so I try this</p>
<p><code>df.groupby([1,2,3,4,5]).count()</code></p>
<p>I got this</p>
<pre><code> a b c
1 1 ... | <p>I will do <code>stack</code> + <code>unstack</code></p>
<pre><code>s = df.stack().groupby(level=1).value_counts().unstack(0,fill_value=0)
Out[183]:
a b c
1 3 0 0
2 1 1 0
3 0 1 1
4 0 1 1
5 0 1 2
</code></pre> | python-3.x|pandas | 3 |
372,868 | 63,907,127 | How to remove loose letters from a text field on the dataframe | <p>I have the following datadrame:</p>
<pre><code> import pandas as pd
df_Msg = pd.DataFrame({'Id': [1, 2, 3],
'Sentence': ['I like fictions', 'Thank s you', 'I need to by a new book']})
print(df_Msg)
</code></pre>
<p>output:</p>
<pre><code>Id Sentence
1 I like fictions
2 Thank s you
3 ... | <p>IIUC use a word boundary:</p>
<pre><code>print(df_Msg["Sentence"].str.replace(r"\b[A-Za-z]\b\s?", ""))
0 like fictions
1 Thank you
2 need to by new book
Name: Sentence, dtype: object
</code></pre> | python|pandas|dataframe | 3 |
372,869 | 63,892,971 | How to delete the min value of array an print the size in a for loop | <p>Following code gets a value as the first input(a) e.g 7 and then get 7 separate values as 2nd input(b). I want to delete the min value of second input each time and the print the size of renaming input(b). For example if b = np.array([2, 2, 3, 4, 4, 5, 6, 6, 6]) the output should be 7 6 4 3. The code raised with err... | <p><code>b > min(b)</code> creates a boolean array. <code>b</code> is a list and cannot be indexed by boolean array. A <code>np.array</code>, though, can be indexed by boolean array.</p>
<p>Just need to insert <code>b = np.array(b)</code> right after constructing <code>b</code></p>
<pre class="lang-py prettyprint-ov... | python|arrays|numpy | 0 |
372,870 | 63,922,156 | Applying a convnet classifier trained on tiles to a large image | <p>My task is to find a certain letter on a picture of a document. Using classical computer vision I have segmented the image into characters. Then I used a neural network trained on 25×25 pixel images of characters to classify them into the one that I want and all others. Using this I can reconstruct the locations of ... | <p>As one solution, I suggest you to use <a href="https://www.tensorflow.org/api_docs/python/tf/image/extract_patches" rel="nofollow noreferrer"><code>tf.image.extract_patches</code></a> function to extract the patches from the image and apply your trained classifier on each patch. This has a few benefits:</p>
<ul>
<li... | python|tensorflow|keras|deep-learning|computer-vision | 0 |
372,871 | 63,788,349 | Filling NaN values in pandas using Train Data Statistics | <p>I will explain my problem statement:</p>
<p>Suppose I have train data and test data.
I have NaN values in same columns for both train and test. Now my strategy for the nan imputation is this:
Groupby some column and fill the nans with mean of that group. Example:</p>
<pre><code>x_train = pd.DataFrame({
'Occupation':... | <p>Create <code>mean</code> to <code>Series</code>:</p>
<pre><code>mean = x_train.groupby('Occupation')['expenditure'].mean()
print (mean)
Occupation
driver 30.0
mechanic 25.0
teacher 100.0
unemployed 0.0
Name: expenditure, dtype: float64
</code></pre>
<p>And then replace missing values by <a h... | pandas|dataframe|group-by | 4 |
372,872 | 63,762,565 | Converting CSV into Flare JSON | <p>I am trying to convert csv data into Json with parent and child relationship for my python application.
The csv file contain Genesymbol and disease name. Based on the Gene symbol am converting it into Child. The sample csv file</p>
<pre><code>gene,disease
A1BG,Adenocarcinoma
A1BG,apnea
A1BG,Athritis
A2M,Asthma
A2M,A... | <p>Maybe try something like this:</p>
<pre class="lang-py prettyprint-override"><code>import json
import pandas as pd
result = (
df
.groupby("gene", as_index=False).agg(list)
.rename(columns={"gene": "name", "disease": "children"})
.to_dict("recor... | python|json|pandas|csv | 1 |
372,873 | 63,999,677 | Select IDs which satisfy a condition in each repetition | <p>I want to select from column ID those unique elements which are completed. Each ID represent a task and can appear multiple times. A task is completed only when the status column has a value of 100 for every row.
Example of dataset:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data= {'ID': ['A', 'A', 'B', 'B... | <p>Considering the variable is a status I'm assuming it exists exclusively [0,100]? If so the minimum status must be 100 for that ID.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data= {'ID': ['A', 'A', 'B', 'B', 'C', 'D'], 'Status': [100, 100, 100, 25, 100, 34]})
df_completed=df.groupby(['ID']).min()==100 #giv... | python|pandas | 1 |
372,874 | 64,051,603 | Using both vCPU's with google cloud computing. Python code. PyTorch | <p>I am new to cloud computing. I made a virtual machine in google cloud computing, machine type:</p>
<p><code>e2-highcpu-2 (2 vCPU's, 2 GB geheugen)</code></p>
<p>I run a script with running the command</p>
<p><code>python3 simulation1.py </code></p>
<p>When I look at the output control screen, I note that only 50% of... | <p>Looks like your question can be resumed to "is Python capable of running on multiple cores?"</p>
<p>And you can find the answer to that question perfectly explained in this <a href="https://stackoverflow.com/questions/7542957/is-python-capable-of-running-on-multiple-cores">post</a>.</p>
<p>Basically:</p>
<... | python|google-cloud-platform|pytorch | 1 |
372,875 | 63,993,211 | Change column values using iloc doesn't works | <p>I want to create a 'istrain' column in dataframe.
Some rows belonged to train data, some to test data.</p>
<p>So I tried as below.</p>
<pre class="lang-py prettyprint-override"><code>df['istrain'] = 0
df.iloc[:train_len,:]['istrain'] = 1
</code></pre>
<p>But it didn't work.</p>
<p>I solved my problem by changing the... | <p><code>iloc</code> is integer-location based indexing.</p>
<p><code>df.iloc[:train_len,:]['istrain']</code> returns a view and due to performance reasons the result is inherently unpredictable. It is documented <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy" r... | python|pandas | 0 |
372,876 | 64,170,341 | how to alter column of a dataframe with different values and by various condition in python? | <p>I have a data frame where I want to alter the column "conf" with different values according to the condition satisfied.</p>
<pre><code>df=pd.DataFrame({"conf":[100,100,100,100],
"i":[-2,3,-3,10],
"o":[12,13,14,16],
"n":[6,4,6,1],
... | <p>For else is possible invert mask by <code>~</code>, chain mask by <code>&</code> and multiple with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p>
<pre><code>m0 = (df["id"]>1.5) & (df[&quo... | python-3.x|pandas | 2 |
372,877 | 63,886,762 | Tensorflow: None of the MLIR optimization passes are enabled (registered 1) | <p>I am using a very small model for testing purposes using tensorflow 2.3 and keras.
Looking at my terminal, I get the following warning:</p>
<pre><code>I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:118] None of the MLIR optimization passes are enabled (registered 1)
</code></pre>
<p>However, the code wor... | <p>MLIR is being used as another solution to implementing and optimizing Tensorflow logic. This informative message is <em>benign</em> and is saying MLIR was not being used. This is expected as in TF 2.3, the MLIR based implementation is still being developed and proven, so end users are generally not expected to use t... | python|tensorflow|keras|deep-learning | 76 |
372,878 | 63,845,871 | Create new panda dataframe with fixed distance using interpolate | <p>I have a dataframe of the following form.</p>
<pre><code>df = {'X': [0, 3, 6, 7, 8, 11],
'Y1': [8, 5, 4, 3, 2, 1.5],
'Y2': [1, 2, 4, 5, 5, 5]}
</code></pre>
<p>I would like to create a new dataframe where I use interpolate where 'X' is stepping in fixed steps [0, 2, 4, 6, 8, 10].
To find the ne... | <p>The solution I found was the following:</p>
<pre><code>step_size = 0.25
no_steps = int(np.floor(max(b['X'])/step_size))
for i in range(0,no_steps+1):
b = b.append({'X' : 0.25*i, 'StepNo' : 10, 'PointNo' : 23+i}, ignore_index=True)
b = b.sort_values(['X'])
b = b.set_index(['X'])
c = b.interpolate('index')
c = c.r... | pandas|interpolation | 0 |
372,879 | 64,091,345 | Merge multiple Series as a single column into a DataFrame | <p>I have the following data frames:</p>
<p>A.</p>
<pre><code> k m n
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
5 x x x
6 x x x
7 x x x
8 x x x
9 x x x
</code></pre>
<p>B1.</p>
<pre><code> l i j
1 x 46 x
2 x 64 x
3 x 83 x
9 x 70 x
</code></pre>
<p>B2.</p>
<pre><code> l ... | <p>you can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> the Bx dataframes, and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.duplicated.html" rel="nofollow noreferrer"><code>duplicated</co... | python|pandas | 1 |
372,880 | 64,018,774 | Pandas Custom Cumcount | <p>I am trying to cumulative count the column <code>Value</code> grouped by the column <code>User</code>, but only increasing the count if there have been a different value in between.</p>
<p>The best I was able to achieve was a normal cumcount using:</p>
<pre><code>df['Cumcount'] = df.groupby(['User', 'Value'].cumcoun... | <p>You could set two conditions to create a series that returns <code>True</code> and <code>False</code> and set it to <code>s</code>.</p>
<ol>
<li>The first condition with <code>.duplicated()</code> indicates whether or not any of the rows are duplicates.</li>
<li>The second condition does a <code>.groupby('User')</co... | python|pandas|dataframe|group-by|running-count | 1 |
372,881 | 64,054,851 | Problem with 'skiprows' when reading csv with pandas | <p>I have a big dataframe (~5 millions rows) that has some wrong data in it.
I have identified the indexes of the rows with wrong data and now I am trying to remove the 'wrong' rows from the dataframe.</p>
<p>Due to the size of the dataframe, I am using the <code>chunksize</code> feature while reading the csv.
To skip ... | <p>the easiest way to remove bad rows is to do it explicitely</p>
<pre><code>df = df.loc[~df.index.isin(list_of_bad_rows]),]
</code></pre> | pandas | 0 |
372,882 | 64,078,421 | pandas.merge result is larger than the two separate dataframes | <p>I have to dataframes <code>a, b</code> with datetimeindices and want to merge them, so that all indices are included and where holes occur, nan-values will be.</p>
<p>this worked in the past:</p>
<pre><code>df = pd.merge(train_t1s.iloc[:lols], sym_train_t1.iloc[:lols], how='outer', sort=True, left_index=T... | <ul>
<li>This answer is a commination of the following:
<ul>
<li><a href="https://stackoverflow.com/questions/22720739/">Pandas Left Outer Join results in table larger than left table</a></li>
<li><a href="https://stackoverflow.com/questions/13035764">Remove rows with duplicate indices (Pandas DataFrame and TimeSeries)... | python|pandas|merge | 2 |
372,883 | 64,074,698 | How to add 5% Gaussian noise to the signal data | <p>I want to add 5% Gaussian noise to the multivaraite data.
Here is the approach</p>
<pre><code>import numpy as np
mu, sigma = 0, np.std(data)*0.05
noise = np.random.normal(mu, sigma, data.shape)
noise.shape
</code></pre>
<p>Here is the signal. Is this a correct approach to add 5% Gaussian noise
<a href="https://i.s... | <p>I think you are on the right track, noise is additive in nature and if you look at the (SNR) Signal to Noise Ratio calculation</p>
<p><strong>SNR = 20 * log(p_s)/(p_n)</strong></p>
<p>which is nothing but</p>
<p><strong>SNR = 20 (log(p_s) - log(p_n))</strong></p>
<p>so we are basically <strong>subtracting</strong> t... | python|numpy|signal-processing|gaussian | 2 |
372,884 | 63,771,787 | Is there a way to convert a numpy array to a dataframe then back to numpy array and still maintain the original shape? | <p>I loaded 2 numpy arrays from an npz file with the <code>dtype</code>; <code>float64</code> & <code>int64</code>, and one with the shape <code>(10, 16, 12)</code>. Within this code, I try to convert from a numpy array to a dataframe (for some necessary operations) but when I convert it back to a numpy array the s... | <p>Experiment with a simpler 3d array:</p>
<pre><code>In [95]: arr = np.arange(24).reshape(3,2,4)
In [96]: df = pd.DataFrame(data=[np.arange(3), arr]).T
In [97]: df
Out[97]:
0 1
0 0 [[0, 1, 2, 3], [4, 5, 6, 7]]
1 1 [[8, 9, 10, 11], [12, 13, 14, 15]]
2 2 [[16, 17, ... | python|arrays|pandas|numpy|tensorflow | 0 |
372,885 | 64,099,029 | Python: How to find most frequent combination of elements? | <p>A machine provides fault codes which are provided in a pandas dataframe. <code>id</code> identifies the machine, <code>code</code> is the fault code:</p>
<pre><code>df = pd.DataFrame({
"id": [1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,4],
"code": [1,2,5,8,9,2,3,5,6,1,2,3,4,5,6,7],
})
</code></pre>
<p>... | <p>Use custom function <code>all_subsets</code>, then flatten values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> and last use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.v... | python|pandas|combinations | 5 |
372,886 | 64,155,043 | Bring index info to the groupby selection in PYthon Pandas Dataframe | <p>I have the following dataframe called 'grouped':</p>
<p><a href="https://i.stack.imgur.com/4SuHo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4SuHo.png" alt="enter image description here" /></a></p>
<p>I am using the following code to bring the max/min for each column:</p>
<pre><code>mm = group... | <p>Add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmax.html" rel="nofollow noreferrer"><code>DataFrame.idxmax</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html" rel="nofollow noreferrer"><code>DataFrame.idxmin</code></a... | python|pandas | 1 |
372,887 | 63,780,184 | Simple computation in numpy | <p>I have numpy array like this <code>a = [-- -- -- 1.90 2.91 1.91 2.92]</code></p>
<p>I need to find % of values more than 2, so here it is 50%.
How to get the same in easy way? also, why len(a) gives 7 (instead of 4)?</p> | <p>Try this:</p>
<pre><code>import numpy as np
import numpy.ma as ma
a = ma.array([0, 1, 2, 1.90, 2.91, 1.91, 2.92])
for i in range(3):
a[i] = ma.masked
print(a)
print(np.sum(a>2)/((len(a) - ma.count_masked(a))))
</code></pre>
<p>The last line prints 0.5 which is your 50%. It subtracted from the total length of... | numpy | 1 |
372,888 | 64,157,192 | PyTorch Factorial Function | <p>There does not seem to be a PyTorch function for computing a factorial. Is there a method to do this in PyTorch? I am looking to manually compute a Poisson distribution in Torch (I am aware this exists: <a href="https://pytorch.org/docs/stable/generated/torch.poisson.html" rel="noreferrer">https://pytorch.org/docs/s... | <p>I think you can find it as <code>torch.jit._builtins.math.factorial</code> <strong>BUT</strong> <code>pytorch</code> as well as <code>numpy</code> and <code>scipy</code> (<a href="https://stackoverflow.com/a/21753913/10749432">Factorial in numpy and scipy</a>) uses <code>python</code>'s builtin <code>math.factorial<... | python|math|deep-learning|pytorch|torch | 6 |
372,889 | 64,155,918 | Issue with separated point and errorbar in Seaborn pointplot | <p>I am trying a quite simple exercise: plotting some data with y-errorbars using python/seaborn. The data is stored in a pandas.DataFrame looking like this (note: lateron I will use "xname" for "limitcount":</p>
<p><a href="https://i.stack.imgur.com/a5smv.png" rel="nofollow noreferrer"><img src="ht... | <p>For <code>plt</code>, you need to pass the actual data to <code>x</code> and <code>y</code>, do instead of</p>
<pre><code>plt.errorbar(x='xname', y='mean', yerr='variance', data=pands_dataframe)
</code></pre>
<p>You want to do:</p>
<pre><code>plt.errorbar(x=pands_dataframe['xname'],
y=pands_dataframe['... | python|pandas|matplotlib|seaborn | 0 |
372,890 | 64,159,143 | XML to dictionary to DataFrame in Python | <p>I want to print data from an XML file. To do that, I created a dictionary to parse the file. Finally, I used a for loop to print the data in a new DataFrame.</p>
<pre><code><BREVIER>
<BRV>
<MONO>stuff</MONO>
<TITD>stuff</TITD>
<TITF>Blabla</TITF>
<... | <p>There are several ways to approach it, but basically, since you are dealing with an xml file, might as well use xml tools like xpath.</p>
<p>Let's say your xml looks like this:</p>
<pre><code>meds = """<BREVIER>
<BRV>
<MONO>stuff</MONO>
<TITF>Blabla</TITF>... | python|xml|pandas|dataframe | 2 |
372,891 | 63,766,408 | Apply method for pandas | <p>i am having a problem while working with apply method. so, i am trying to make the first and last letter of a series uppercase. First i have made a simple series i.e</p>
<pre><code>s1 = pd.Series(['pandas','python','javascript','c#'])
s1
</code></pre>
<p>The output:</p>
<pre><code>0 pandas
1 python
2 ... | <p>Your function prints the result instead of returning it using <code>return</code>. Furthermore, the <code>for</code> loop is extra in your function as the <code>.apply</code> method applies the function to one item at a time.</p>
<p>You can change your function to:</p>
<pre><code>def upp(x):
return f'{x[0].upper... | python|pandas|function|apply | 3 |
372,892 | 64,173,996 | Pandas conditional slicing, using both "and" and "or" | <p>This is just a quick question with a yes or no answer. I couldn't find an answer for on google or here (difficult to google).</p>
<p>I just want to know if I am doing this the correct way.</p>
<p>I am trying to select data matching certain conditions. Here is a snipped from my code.</p>
<pre><code>c1 = (data['recenc... | <p>Yes, this is a perfectly reasonable thing to do.</p>
<p>According to the Pandas manual, you can combine multiple selectors using boolean operators such as <code>&</code>, <code>|</code>, and <code>~</code>.</p>
<blockquote>
<p>Another common operation is the use of boolean vectors to filter the data. The operato... | python|pandas | 0 |
372,893 | 64,050,966 | Fill categorical NaN values based upon proportion within groupby | <p>I am working with a dataset that consists of entirely categorical features.</p>
<p>One column only has missing values: 2480 NaN out of 8124.</p>
<p>I can successfully fill the NaN values based upon the percentage of existing categorical values:</p>
<pre><code>print(df['stalk-root'].value_counts(normalize=True), '\n'... | <p>Here's a solution with <code>groupby</code></p>
<pre><code>was_null = df['stalk-root'].isna()
for _, gdf in df.groupby('class')['stalk-root']:
vc = gdf.value_counts(normalize=True)
df.loc[gdf.loc[gdf.isna()].index, 'stalk-root'] = (
np.random.choice(vc.index, gdf.isna().sum(), p=vc)
)
</code></p... | python-3.x|pandas|pandas-groupby | 1 |
372,894 | 47,021,810 | Residual learning in tensorflow | <p><img src="https://i.stack.imgur.com/IEJhv.png" alt="inception layer"></p>
<p>I am attempting to replicate this image from a research paper. In the image, the orange arrow indicates a shortcut using residual learning and the layer outlined in red indicates a dilated convolution.</p>
<p>In the code below, r5 is the ... | <p>The image is quite straight forward - it says you should <strong>add</strong> them, so:</p>
<pre><code>#relu layer
r5 = tf.nn.relu(layer5)
...
#dilation layer
h_conv4 = conv3d_dilation(concat1, 1154)
#combined
combined = r5 + h_conv4
</code></pre> | python|tensorflow|deep-learning|conv-neural-network|deep-residual-networks | 3 |
372,895 | 46,722,887 | Populating a multiIndexed pandas Series | <p>I have a pandas dataframe full of data</p>
<pre><code>import pandas as pd
import numpy as np
varNames = ["point1","point2","point3","point4","point5"]
df = pd.DataFrame(np.random.randn(5,2),index=varNames,columns=["data1","data2"])
</code></pre>
<p>and I would like to create a series with a multiIndex created fro... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> with parameter <code>level</code> with <code>max</code>:</p>
<pre><code>df3 = df.reindex(index, level=0).div(df.reindex(index, level=1)).max(level=0)
</code></... | python|pandas | 0 |
372,896 | 46,802,239 | Converting a long series into a dataframe based on occurrence of specific keys in Pandas | <p>First, apologies if the question subjectseems vague. I will try to make it clear.
I have a Panda series like:</p>
<pre><code>A
a1
b1
c1
B
a2
b2
c2
</code></pre>
<p>What we need is to form a dataframe where {A,B} are the values of column one, and the values following each are the values of column two. For our examp... | <p>Use <code>pd.Series.str.extract</code></p>
<pre><code>d1 = s.str.extract('([A-Z])*(.+)*', expand=True)
d1[0].ffill(inplace=True)
d1.dropna()
0 1
1 A a1
2 A b1
3 A c1
5 B a2
6 B b2
7 B c2
</code></pre> | python|pandas|dataframe | 2 |
372,897 | 46,652,914 | Data Wrangling in python exclude entries with '0' values | <p>I have a pandas data frame that contains 2 columns W(number of Wins) and L(number of Losses).
I would like to eliminate all rows of data that have a value of 0 for both W and L.</p>
<pre><code>pitching_df.groupby('playerID')['W', 'L'].sum()
playerID W L
aardsda01 2 5
aasedo01 3 8
abbotpa01 0 0
ab... | <p>You can try</p>
<pre><code>df[df[['W', 'L']].ne(0).all(1)]
playerID W L
0 aardsda01 2 5
1 aasedo01 3 8
3 abernte02 8 19
</code></pre> | python|pandas|data-cleaning | 0 |
372,898 | 47,034,429 | Multiply Python Pandas dataframes together to get product of values in column | <p>I need help creating a Python function to achieve the following:</p>
<p>1) Take 3 Pandas dataframes as input (containing an index column, and an associated integer or float value in the second column). These are defined as follows:</p>
<pre><code>import pandas as pd
df1=pd.DataFrame([['placementA',2],['placementB... | <p>Use <code>product</code> of all indexes and columns and create <code>DataFrame</code> by constructor, for multiple all columns use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.prod.html" rel="nofollow noreferrer"><code>prod</code></a>:</p>
<pre><code>from itertools import product... | python|pandas|recursion|dataframe|iteration | 2 |
372,899 | 46,728,584 | Repeat previous index | <p>I have an array of indicators <code>a</code>, which contains a <code>1</code> if the index of the last <code>0</code> should be replicated. Otherwise, current running index goes through:</p>
<p>That is, </p>
<pre><code>a = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1])
i = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])... | <p>Here's one vectorized way making use of <code>masking</code> and <code>maximum-accumulation</code> with <code>np.maximum.accumulate</code> -</p>
<pre><code>i[np.maximum.accumulate(np.where(a==0, np.arange(len(a)), 0))]
</code></pre>
<p>Another way to put it would be -</p>
<pre><code>i[np.maximum.accumulate(np.ara... | python|performance|numpy | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.