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 |
|---|---|---|---|---|---|---|
364,400 | 62,474,390 | Extracting US dollar amount | <p>This question has been asked before but I am still not able to make this work entirely. I have the following examples of strings:</p>
<pre><code>"Transfer to Retirement Rsvs-MA FX .11"
"Opening Balance FX 342,536,002.63"
"VA 85.85" ... | <p>You might use:</p>
<pre><code>(?<!\S)\$?(?:\d{1,3}(?:\,\d{3})*)?\.\d{2}-?(?!\S)
</code></pre>
<ul>
<li><code>(?<!\S)</code> Whitespace boundary on the left</li>
<li><code>\$?</code> Optional dollar sign</li>
<li><code>(?:\d{1,3}(?:\,\d{3})*)?</code> Optional part matching 1-3 digits optionally repeated by co... | python|regex|pandas|dataframe|match | 1 |
364,401 | 62,540,742 | How to change a dataframe element based on condition on another column in pandas | <p>I have looked around (e.g. <a href="https://stackoverflow.com/questions/56501996/how-to-set-a-pandas-dataframes-column-value-based-on-a-condition-applied-to-anot">here</a>), but I can't understand why my code is not working as expected.
I have a pandas dataframe and I'd like to add a column that marks the last zero ... | <p>For dataframes with mixed types (like here), it seems pandas creates copies when using <code>iloc</code> and similar functions. Instead of chain indexing, you can do this:</p>
<pre><code>df.iloc[i, df.columns.get_loc('C')]=True
</code></pre>
<p>or</p>
<pre><code>df.at[i, 'C'] = True
</code></pre>
<p>However, I'd sug... | python|pandas|dataframe | 1 |
364,402 | 62,835,641 | Python array is only 1D and I cannot use reshape to convert it to 2D | <p>I've created two programs to run a stochastic simulation on a system of chemical reactions. In the program I've got a function that's meant to update the elements of an array with the <code>derivative</code> of the changing molecule numbers <code>popul_num</code> and the stochastic rate constant of each reaction <co... | <p>One value is missing. This list contains only 7 values:</p>
<pre><code> [x2_derivative, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
</code></pre> | python|arrays|reshape|numpy-ndarray | 1 |
364,403 | 62,760,301 | how to do dot multiplication of vector and sparse matrix in python | <p>how to do <code>dot</code> multiplication between vector and matrix (sparse)?</p>
<p>It works with vector (ndarray type) and normal matrix (ndarray type).</p>
<pre><code>import numpy as np
import pandas as pd
from scipy import sparse
x1 = np.arange(8).reshape((2, 4)) * 10
x2 = np.arange(4).reshape((2, 2))
x1
# arr... | <p><code>x2[1]*x1</code> might work or <code>x2[1]@x1</code>. Either way gives the sparse matrix control over the multiplication. <code>x2.dot(...)</code> uses <code>x2.dot(np.array(x1))</code> which is wrong. <code>x2.dot(x1.A)</code> should also work.
If you want short answer you can read this</p> | python|scipy|sparse-matrix|numpy-ndarray | 0 |
364,404 | 62,568,236 | Installation of keras fails with Error: could not find a Python environment for /usr/bin/python3 | <p>Software Information:</p>
<p><strong>SUSE Linux Enterprise Server 12 (x86_64)
VERSION = 12
PATCHLEVEL = 5</strong></p>
<p>Symbolic link</p>
<p><strong>/usr/bin/python3 --version</strong> returns the below;
<strong>Python 3.4.10</strong></p>
<p><strong>R version 3.6.3 (2020-02-29) -- "Holding the Windsock"<... | <p>I am using an Arch Linux system with R (version 4.1.1). Assuming you have installed <a href="https://docs.anaconda.com/anaconda/install/linux-aarch64/" rel="nofollow noreferrer">Anaconda</a> in your system and is recognized in your path, after you have already installed the <code>reticulate</code> package:</p>
<ol>
... | python|r|tensorflow|keras | 0 |
364,405 | 62,560,750 | Count consecutive days by product pandas | <p>I need know the number off days each product had sold by row. Exemple "In the day 1 de product AX1 had sold 3, and the product AX2 had sold 2 on the day 1"</p>
<p>I have this:</p>
<pre><code>Product | Date | Sales
AX1 |2019-01-01 | 3
AX1 |2019-01-02 | 2
AX2 |2019-01-01 | 2
AX2 |2... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
# if not done already:
df["Date"]=pd.to_datetime(df["Date"])
df=df.sort_values(["Product", "Date"])
df["Days"]=df.groupby("Product")["Date"].diff()
mask=df["Days&q... | python|pandas | 3 |
364,406 | 62,819,908 | Filter rows in pandas dataframe by dynamically generated values (latest date) | <p>I have a data set with newsletter type, newsletter name, newsletter launch date, and email. Every launch goes over many rows because each email address that received the newsletter launch has its own row.</p>
<p>All the newsletters have at least one launch, but some newsletters have many launches. I want to clean my... | <p>I would sort by 'launch date' and group by 'newsletter name' (if that is the unique type one want to save one of each fore). This would return only the lates of each unique 'news letter'.</p>
<pre><code>df = df.sort_values(by=['launch date']).groupby('newsletter name').first()
</code></pre> | python|pandas|date|duplicates|filtering | 1 |
364,407 | 62,769,569 | Python create index from returns | <p>I have a dataframe of portfolio returns:</p>
<pre><code>date Portfolio %
30/11/2001 4.8
31/12/2001 -0.7
31/01/2002 1.3
28/02/2002 -1.4
29/03/2002 3.3
</code></pre>
<p>I need to create an index of returns, but to do this i need to have a starting figure of 1.0 and the formula references the... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.div.html" rel="nofollow noreferrer"><code>Series.div</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.add.html" rel="nofollow noreferrer"><code>Series.add</code></a> along with <a href=... | python|pandas|dataframe | 3 |
364,408 | 62,648,849 | Calculate linear regression slope matrix (Same to correlation matrix) - Python/Pandas | <p><a href="https://i.stack.imgur.com/u7iAd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u7iAd.jpg" alt="enter image description here" /></a>How do I calculate slope of each columns below? The .corr method scans all columns and find the correlation coeffficient with each column. I want to do the s... | <p>why not</p>
<pre><code>slope = np.dot(np.dot(np.diagflat(df2_norm.std().values) , allowableCorr.values), np.diagflat(1/df2_norm.std().values))
</code></pre> | python|pandas|numpy|dataframe|statistics | 0 |
364,409 | 62,590,953 | Numpy Matplotlib array of complex numbers to plot 3d graph | <p>I am trying to plot <code>y=x^2+1</code> in python using <code>matplotlib</code> and <code>numpy</code> in 3D with <code>Re(x)</code>, <code>Im(x)</code> and <code>Re(f(x))</code> on the 3 axes. However, I'm getting an error and I don't know how to continue further.
Error:
<code>ValueError: operands could not be bro... | <p>You have three issues:</p>
<ul>
<li>The way you create <code>carray</code> misses up with the expected shape</li>
<li>Using <code>ax.plot</code> demands that all <code>a</code>, <code>b</code> and <code>carray</code> to have the same size as shown in this <a href="https://matplotlib.org/mpl_examples/mplot3d/lines3d_... | python|numpy|matplotlib|complex-numbers | 1 |
364,410 | 62,768,974 | Python Regex Capture Between Specific Characters | <p>I'm struggling with some regex for a few parts of these strings below. This for use in a str.extract() and I need to capture:</p>
<ul>
<li>jump or crawl, this will follow two spaces</li>
<li>valueA or valueB, this will follow the $</li>
<li>amount between @ and \n, sometimes, but not always, this includes up to two ... | <p>You can use the pattern <code>(jump|crawl)\s+\$(value[AB])\s@\s(\d*\.?\d*)</code>:</p>
<pre><code>df = pd.DataFrame({"value":["⬆️ jump $valueA @ 5084\n\n#blah",
"⬆️ jump $valueB @ 628.15\n\n#blah",
"⬇️ crawl $valueB @ 626.8... | python|regex|pandas | 1 |
364,411 | 62,766,854 | Extract year contents from html code and save them as dataframe | <p>Given a section of html source code named <code>li</code> as follows:</p>
<pre><code>[<li>Project construction cycle</li>,
<li>
Start date: 2019...
Completion date: 2021... <a class="login-btn" href="javascript:"&... | <p>You may try:</p>
<pre><code>(Start date: \d{4}|Completion date: \d{4})
</code></pre>
<p><strong>Explanation of the above regex:</strong></p>
<ul>
<li><strong><code>(Start date: \d{4})</code></strong> - Represents first capturing group matching <code>Start date: </code> literally along with digits appearing exactly 4... | python-3.x|regex|pandas|dataframe | 1 |
364,412 | 62,618,893 | Conditional Moving Average | <p>I have a dataframe as below:</p>
<pre><code>data = pd.DataFrame({'Date':['2020-06-17','2020-06-18','2020-06-19','2020-06-20','2020-06-21','2020-06-22','2020-06-23','2020-06-24','2020-06-25','2020-06-26','2020-06-27','2020-06-17','2020-06-18','2020-06-19','2020-06-20','2020-06-21','2020-06-22','2020-06-23','2020-06-2... | <pre><code>w_size = 10
</code></pre>
<hr />
<pre><code>sub_df = df.query(f'qty != {0}')
sub_df.ewm(com = w_size).mean() # weighted average
sub_df.rolling(window=w_size).mean() # average (over window size)
</code></pre>
<hr />
<p>For just <strong>excluding</strong> some values from calculations, if <code>value = 0<... | python|pandas|moving-average | 1 |
364,413 | 62,641,525 | pandas row wise sum when when consecutive column value is less than a certain number | <p>I have a data frame like this,</p>
<pre><code>df
col1 col2 col3
A 34 1
B 86 2
A 53 21
C 24 33
B 21 2
C 11 1
</code></pre>
<p>Now I want to add col1 and col2 values row wise where consecutive col3 values are less than 3, so the fina... | <p>You can use <code>cumsum</code> to get consecutive blocks of value <code><=3</code>:</p>
<pre><code>s = df.col3.ge(3)
# print `s.cumsum()` and `s` to see details
df.groupby([s.cumsum(),s], as_index=False).agg({'col1':'first','col2':'sum'})
</code></pre>
<p>Output:</p>
<pre><code> col1 col2
0 A 120
1 A ... | python|pandas|dataframe | 1 |
364,414 | 62,686,296 | Remove duplicate values in a pandas column, but ignore one value | <p>I'm sure there is an elegant solution for this, but I cannot find one. In a pandas dataframe, how do I remove all duplicate values in a column while ignoring one value?</p>
<pre><code>repost_of_post_id title
0 7139471603 Man with an RV needs a place to park for ... | <p>You could try dropping the None values, then detecting duplicates, then filtering them out of the original list.</p>
<pre><code>In [1]: import pandas as pd
...: from string import ascii_lowercase
...:
...: ids = [1,2,3,None,None, None, 2,3, None, None,4,5]
...: df = pd.DataFrame({'id': ids, 'title':... | python|python-3.x|pandas|numpy|dataframe | 0 |
364,415 | 62,714,701 | In numpy, how to sort an array with the same order with another one? | <p>There are two numpy array a and w,
both of which have the same shape (d1,d2,..,dk,N).
We can think there are N sample with shape (d1,d2,...,dk).</p>
<p>Now, I want to sort a and w along a's last axis.</p>
<p>For example, a and w have shape (2,4):</p>
<pre><code>a = [[3,2,4,1],
[2,3,1,4]]
w = [[10,20,30,40],
... | <p>There's a function for that, <code>np.take_along_axis</code>:</p>
<pre><code>>>> a = np.array([[3,2,4,1], [2,3,1,4]])
>>> w = np.array([[10,20,30,40], [80,70,60,50]])
>>> sorted_index = a.argsort()
>>> sorted_index
array([[3, 1, 0, 2],
[2, 0, 1, 3]])
>>> np.take_al... | python|numpy|sorting | 2 |
364,416 | 62,581,522 | How to scale a dataframe with datetime field in it (as a index)? | <p>I want to scale a dataframe, which raises the error as in the title (or below).</p>
<p>My data:</p>
<pre><code>df.head()
timestamp open high low close volume
0 2020-06-25 303.4700 305.26 301.2800 304.16 46340400
1 2020-06-24 309.8400 310.51 302.1000 304.09 123867696
2 2020-06-23 3... | <p>Simply iterate through the columns and scale each individually like this:</p>
<pre class="lang-py prettyprint-override"><code>for col in X.columns:
X[col] = StandardScaler().fit_transform(X[col].to_numpy().reshape(-1,1)
</code></pre>
<p>you can create your own scaler if you want to do something within an SKlearn... | python|pandas|numpy | 0 |
364,417 | 62,600,863 | TensorFlow Lite Android Crashes on GPU Compute only when Input Size is >1 | <p>I've been working on an AndroidStudio app which uses TensorFlow Lite's GPU delegate to speed up inference speed. It uses a model which takes an input array of size [n]x[384] and outputs an array of size [n]x[1], with n being the number of 384-sized inputs I wish to feed in at a given time. Output n is only depende... | <p>After a recommendation to try out the TensorFlow Nightly implementation:</p>
<pre><code> implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly'
implementation 'org.tensorflow:tensorflow-lite-gpu:0.0.0-nightly'
</code></pre>
<p>I switched my implementation in build.gradle to use 0.0.0-nightly and my pro... | android-studio|tensorflow|tensorflow-lite | 0 |
364,418 | 62,679,006 | Plotting datetime for several years but showing only twelve months on x-axis | <p>I am trying to plot data with datetime as x-axis. The data is collected over several years.
I can convert the Date to datetime format, extract the year portion of the datetime and plot using that as color.</p>
<pre><code>df['Date']=pd.to_datetime(df['Date'],errors='coerce')
df['year']=df['Date'].dt.year
df['mthday... | <p>Posting below as one way that I have found to do this:
I use the mthday column and convert it back to datetime type. This puts all the year values for all the rows to default value of 1900. I then use mthday as x-axis and hide the year by specifying the x-axis tickmarks.</p>
<pre><code>df['mthday']=df['Date'].dt.str... | python|pandas|jupyter-notebook|plotly|jupyter | 3 |
364,419 | 62,532,941 | Pandas groupby SyntaxError: keyword can't be an expression | <p>I was doing a simple groupby, but got a deprecation / future warning message.</p>
<p>Here's my original groupby, which works 100% OK:</p>
<pre><code>
print(df)
customer_ID amount
0 joe 321
1 joe 5
2 joe 1
3 joe 3135
4 mary 35
5 mary ... | <p>Since it's a <code>SyntaxError</code>, it can't be related with <code>pandas</code>. You can get the same error with this:</p>
<pre><code>>>> print("Hello", 'end'="")
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
</code></pre>
<p>So the problem is w... | python|pandas | 1 |
364,420 | 62,701,231 | ModuleNotFoundError: No module named 'xlsxwriter' in databricks | <p>I am trying to save the content of pandas dataframe to excel file in windows/azure databricks.
import pandas as pd</p>
<h1>Create a Pandas dataframe from the data.</h1>
<p>df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})</p>
<h1>Create a Pandas Excel writer using XlsxWriter as the engine.</h1>
<p>writer = p... | <p>Make sure you have XlsxWriter installed</p>
<pre><code> pip install XlsxWriter
</code></pre>
<p>you might need to restart the kernel<a href="https://i.stack.imgur.com/yumrw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yumrw.png" alt="enter image description here" /></a></p>
<p>also, remember to import</... | pandas|dataframe | 7 |
364,421 | 62,528,719 | How to load tensorflow-js weights from express using tf.loadLayersModel()? | <p>I get the error - <code>RangeError: attempting to construct out-of-bounds TypedArray on ArrayBuffer</code> when I try to load a tf-js model into Reactjs.</p>
<p>I'm using express.js to send the json+bin files to react so that I can run inference in the browser itself.</p>
<p>Here's the relevant Express.js code. The ... | <p>I re-created your problem in a sandbox. <a href="https://codesandbox.io/s/upbeat-lumiere-qyeho?file=/src/index.js" rel="nofollow noreferrer">Server</a> | <a href="https://codesandbox.io/s/brave-murdock-ck6of?file=/src/App.js" rel="nofollow noreferrer">Client</a></p>
<p>The shards are being sourced from the same endp... | node.js|reactjs|express|tensorflow|tensorflow.js | 1 |
364,422 | 62,490,121 | how to convert Lenet model h5 to .tflite | <p>How do I correctly convert Lenet Model (input 32x32, 5 layers, 10 classes) to Tensorflow Lite? I used this lines of codes but it gives me really bad confidences in android, <a href="https://i.stack.imgur.com/FCVHm.jpg" rel="nofollow noreferrer">like this image</a>. The confidences are all around 0.1, or 10%.</p>
<p>... | <p>If .tflite file is generated with no mistakes it doesn't matter if the model is called Lenet or anything else. Also quantization will have a small decrease in accuracy but no major difference like you are stating. I would see how u are making bytebuffer to insert it inside interpreter. If u are using gray scale imag... | python|tensorflow|keras|tensorflow-lite | 2 |
364,423 | 54,662,346 | Confused about torch.nn.Sequential | <p>Supposing we want to add a new layer, say a linear layer, to the end of the classifier of another model, such as VGG16, why exactly do these two implementations lead to different results? More specifically, I don't understand why the first implementation produces 2 classfiers:</p>
<pre><code>vgg = torchvision.model... | <p>It's because you have a syntax error in the spelling of <em>classifier</em>. You have written it as</p>
<pre><code>vgg.classifer=nn.Sequential(vgg.classifier, nn.Linear(4096,300))
</code></pre>
<p>Note the missing <code>i</code> after <code>f</code> in <code>classifier</code> on LHS. So, you're inadvertently creat... | python|pytorch | 1 |
364,424 | 54,341,463 | Should I trim outliers from input features | <p>Almost half of my input feature columns have offshoot "outliers" like when the mean is <strong>19.6</strong> the max is <strong>2908.0</strong>. Is it OK or should I trim those to <code>mean + std</code>? </p>
<pre><code> msg_cnt_in_x msg_cnt_in_other msg_cnt_in_y \
count 330096.0 ... | <p>There is no general answer to that. It depends very much on your probem and data set.</p>
<p>You should look into your data set and check whether these outlier data points are actually valid and important. If they are caused by some errors during data collection you should delete them. If they are valid, then you c... | tensorflow|keras | 2 |
364,425 | 54,377,647 | Access index of of filtered value(s) | <p>Here I access the value of a series depending on a predicate : </p>
<pre><code>import numpy as np
s = pd.Series(np.array([1,2,3]))
print(type(s))
print([i for i in s if i > 2])
</code></pre>
<p>returns : </p>
<pre><code><class 'pandas.core.series.Series'>
[3]
</code></pre>
<p>How to access the index ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>index</code>:</p>
<pre><code>print (s.index[s > 2])
#alternative
#print (s[s > 2].index)
Int64Index([2], dtype='int64')
</code></pre>
<p>Your solutio... | python|pandas | 1 |
364,426 | 54,685,160 | Sorting data based on column entries | <p>I have a text file containing two column lets say col1 and col2. </p>
<pre><code>col1 Col2
A20 A19
A120 A117
A120 A118
A120 B19
A120 B20
.
.
.
B40 A205
</code></pre>
<p>and so on.
I want to sort the above columns such that it gives me only those entries which have A and B side by si... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#indexing-with-str" rel="nofollow noreferrer">indexing by <code>str</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> ... | python-3.x|pandas|sorting|dataframe|text | 3 |
364,427 | 54,386,310 | pandas.read_sql with sqlite is extremly slow | <p>I'm using pandas.read_sql with an sqlite Database and it is extremly slow.
I have a table with 800 rows and 49 columns (dataype just TEXT and REAL) and it takes over 3 Minutes to fetch the data from database to the dataframe.
The DB-File and the python script are running on the same machine and the same filesystem... | <p>I found the solution myself:
The Problem was using the connection as instance attribut: self.dbconn
If i always initiate a new connection and close it at the end perfomance is absolutely no problem !</p>
<pre><code> conn = self.create_connection(self.db_file)
self.logger.info('{} - START from sql: {}'.forma... | python-3.x|pandas|sqlite | 0 |
364,428 | 54,609,998 | How to do multi logic value comparisons between dataframes? | <p>I have two dataframes like so:</p>
<p>df1:</p>
<pre><code>Email DateTimeCompleted
2@2.com 2019-02-09T01:34:44.591Z
</code></pre>
<p>df2:</p>
<pre><code>Email DateTimeCompleted
b@b.com 2019-01-29T01:34:44.591Z
2@2.com 2018-01-29T01:34:44.591Z
</code></pre>
<p>How do I look up <code>Em... | <p>You can do the following:<br>
1. <code>merge</code> the two dataframes on keycolumns <code>Email</code> so you know which rows consist in both dataframes.<br>
2. Filter the rows which are greater than <code>today - 90days</code><br>
3. Concat the dataframes to final with <code>pd.concat</code></p>
<p>Code:</p>
<pr... | python-3.x|pandas|dataframe | 1 |
364,429 | 54,427,435 | How can I create a violin plot of a list of data separated by a binary class? | <p>I'm looking to show a violin plot of peoples ages, each belonging to either class 0 or 1. I have created a list of ages, and a seperate list corresponding to class. I am able to plot a violin plot for a single list, but how can I plot the age distribution seperated by class 1 and 0? </p>
<pre><code>import numpy as ... | <p>I am guessing that what you are looking for is using the x or hue parameter of seaborn violin plot function</p>
<p>With your data, this would go as</p>
<pre><code> #
# Here we need to add code to plot age distribution seperated by class
sns.violinplot(x=class, y=ages)
</code></pre>
<p>You can find some examples ... | python|pandas|seaborn|violin-plot | 0 |
364,430 | 54,602,673 | Keras input shape, simple array of input lists | <p>where each array([x1, x2, x3, ... , x15]) represents a single input</p>
<pre><code>[array([0. , 0.08333333, 0.08333333, 0.08333333, 0.08333333,
0.08333333, 0.08333333, 0. , 0.08333333, 0.08333333,
0.08333333, 0.08333333, 0.08333333, 0.08333333, 0. ])
array([0.04166667, 0.10416667, 0.1041... | <p>It didn't want a numpy array inside, it should be lists internally but an array at the topmost level only</p>
<pre><code>X_train = np.array([x.tolist() for x in df['board_in'].values])
y_train = df['target']
y_train = np.array([y for y in df['target'].values])
</code></pre> | python|tensorflow|keras|reshape | 0 |
364,431 | 54,629,689 | How to fix LSTM keras api 2 warning? | <p>I am trying to train a LSTM model using keras. I am getting this warning message while executing the code. How to update my <code>LSTM</code> call to the Keras 2 API ?</p>
<p>This is the warning message that I am receving. </p>
<blockquote>
<p>lstm.py:32: UserWarning: Update your <code>LSTM</code> call to the K... | <p>The answer is written on the message.</p>
<pre><code>LSTM(lstm_out, dropout=0.25, recurrent_dropout=0.28)
</code></pre> | python|tensorflow|keras|deep-learning | 3 |
364,432 | 54,255,431 | InvalidArgumentError: cannot compute MatMul as input #0(zero-based) was expected to be a float tensor but is a double tensor [Op:MatMul] | <p>Can somebody explain, how does TensorFlow's eager mode work? I am trying to build a simple regression as follows:</p>
<pre><code>import tensorflow as tf
tfe = tf.contrib.eager
tf.enable_eager_execution()
import numpy as np
def make_model():
net = tf.keras.Sequential()
net.add(tf.keras.layers.Dense(4, ac... | <p><strong>Part 1:</strong> The problem is indeed the datatype of your input. By default your keras model expects float32 but you are passing a float64. You can either change the dtype of the model or change the input to float32.</p>
<p>To change your model:</p>
<pre><code>def make_model():
net = tf.keras.Sequent... | python|tensorflow|keras|eager-execution | 45 |
364,433 | 54,509,004 | How to take derivative of trilinear interpolated function? | <p>I am a new user of python. I have a 3D regular grid data as a h5 file format. I can able to interpolate (trilinear interpolation) my data by using RegularGridInterpolator. But, I don't know how to take the derivative from my interpolated function. </p>
<p>(My problem is similar to <a href="https://stackoverflow.com... | <p>Calling the interpolated function <strong>f(x,y,z)</strong>, if you want to find partial <strong>df/dx</strong> at <strong>(x,y,z)</strong>, it's just <strong>f(floor(x+1),y,z) - f(floor(x),y,z)</strong>. The derivative is not really defined for integral values of <strong>x</strong>, since it changes at those point... | python|numpy|scipy|interpolation|hdf5 | 0 |
364,434 | 54,413,160 | Training, Validation, Testing Batch Size Ratio | <p>I'm doing transfer learning using Inception on Tensorflow, this is the training code that I followed : <a href="https://raw.githubusercontent.com/tensorflow/hub/master/examples/image_retraining/retrain.py" rel="noreferrer">https://raw.githubusercontent.com/tensorflow/hub/master/examples/image_retraining/retrain.py</... | <p>You can follow the advice from the other answers for the dataset split ratio. However, the batch size has absolutely <em>nothing</em> to do with how you've split your datasets.</p>
<p>The batch size determines how many training examples are processed in parallel for training/inference. The batch size at training ti... | python|tensorflow|conv-neural-network|training-data | 12 |
364,435 | 54,281,777 | Simple tensorflow keras model with single matrix multiply not working | <p>I'm trying to setup a simple tf.keras model in which a vector is fed in as input and the output is the result of a single matrix multiply. </p>
<p>The lines of code to create the model suceed but calling it for a forward pass results in an error. </p>
<pre><code>n_input_nodes = 2
n_output_nodes = 1
x = tf.keras.I... | <p>They require a dense tensor and not a sparse tensor. Consider this shape</p>
<pre><code>W = tf.ones((n_input_nodes,), dtype=tf.float32)
</code></pre>
<p>It requires a tensor of shape ( 2, ) which is dense.</p> | python|tensorflow | 0 |
364,436 | 54,445,471 | AND-gate with Pytorch | <p>I'm new to PyTorch and deep learning generally.<br>
The code I wrote can be seen longer down.
I'm trying to learn the simple 'And' problem, which is linearby separable.<br>
The problem is, that I'm getting poor results. Only around 2/10 times it gets to the correct answer.<br>
Sometimes the loss.item() values is stu... | <h1>1. Using zero_grad with optimizer</h1>
<p>You are not using <code>optimizer.zero_grad()</code> to clear the gradient. Your learning loop should look like this:</p>
<pre><code>for epoch in range(epochs):
optimizer.zero_grad()
pred = model(data_x)
loss = criterion(pred, data_y)
loss.backward()
o... | python|deep-learning|pytorch | 1 |
364,437 | 54,377,686 | set value of pandas ffill | <p>I want exactly the same behaviour as pandas dataframe.fillna('ffill') method but instead of using the last non-NaN value, I want to pick the value myself, for example</p>
<p><code>[NaN, NaN, NaN, 1, 2, 3, 4, 5, NaN, NaN, NaN]</code> </p>
<p>should become</p>
<pre><code>[NaN, NaN, NaN, 1, 2, 3, 4, 5, 0, 0, 0]
</co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> for filtering non missing values after forward filling:</p>
<pre><code>s = pd.Series([np.NaN, np.NaN, np.NaN, 1, 2, np.NaN, 4, 5, np.NaN, np.NaN, np.NaN])
print (s)
0 ... | python|pandas | 3 |
364,438 | 54,352,791 | weighted moving average in pandas - having trouble implementing | <p>I have a one-dimensional time series (below), created using pandas. that I'm having trouble creating a weighted moving average for. I've seen others have come across this problem in pandas but there doesn't seem to be a consensus solution from what I've read. </p>
<pre><code>1899 0.780
1900 -3.278
1901 1.0... | <p>I think your weighted average function may be wrong (the code looks ok). Try:</p>
<pre><code># use the .dot method for shortness' sake
anom_winter_av_npi.rolling(window=7).apply(lambda x: wts.dot(x) / wts.sum())
</code></pre> | python|pandas|moving-average|weighted-average | 1 |
364,439 | 54,517,731 | Pandas Series - Count rows between column values | <p>Pandas series:</p>
<pre><code> 2004-01-01 0
2004-01-02 0
2004-01-03 0
2004-01-04 0
2004-01-05 1
2004-01-06 0
2004-01-07 0
2004-01-08 3
2004-01-09 0
2004-01-10 2
2004-01-11 0
</code></pre>
<p>I want to add,efficiently, a column which count ... | <p>Use:</p>
<pre><code>df['B'] = df.groupby(df.A.gt(0).cumsum()).cumcount(ascending=False)
print (df)
A B
2004-01-01 0 3
2004-01-02 0 2
2004-01-03 0 1
2004-01-04 0 0
2004-01-05 1 2
2004-01-06 0 1
2004-01-07 0 0
2004-01-08 3 1
2004-01-09 0 0
2004-01-10 2 1
2004-01-11 0 0
</code></pre>... | python|pandas | 1 |
364,440 | 54,544,986 | Need to change GPU option to CPU in a python pytorch based code | <p>The code basically trains the usual MNIST image dataset but it does the training on a GPU. I need to change this option so the code trains the model using my laptop computer. I need to substitute the <code>.cuda()</code> at the second line for the equivalent in CPU. </p>
<p>I know there are many examples online on ... | <p>It is better to move up to latest pytorch (1.0.x).</p>
<p>With latest pytorch, it is more easy to manage "device".</p>
<p>Below is a simple example.</p>
<pre><code>device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#Now send existing model to device.
model_ft = model_ft.to(device)
#Now send i... | deep-learning|gpu|pytorch | 5 |
364,441 | 54,462,105 | SageMaker Ground Truth with TensorFlow | <p>I've seen examples of labeling data using SageMaker Ground Truth and then using that data to train off-the-shelf SageMaker models. However, am I able to use this same annotation format with TensorFlow Script Mode? </p>
<p>More specifically, I have a tensorflow.keras model I'm training using TF Script Mode, and I'd ... | <p>I am from Amazon SageMaker Ground Truth team and happy to assist you in your experiment. Just to be clear our understanding, are you running TF model in SageMaker using TF estimator in your own container (<a href="https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/tensorflow/README.rst" rel="nofol... | python|tensorflow|amazon-sagemaker|labeling | 3 |
364,442 | 54,503,836 | Extracting multi-variable equation coeficcients with numpy.polyfit | <p>this is one of those questions that's probably going to be totally obvious once answered, but for now I'm stuck.</p>
<p>I'm trying to re-create an equation from a result dataset and the four parameters that produced it.</p>
<p>The data is in a matrix with the last column being the result.</p>
<p>I saw that <a hre... | <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow noreferrer">Polyfit docs</a> tell us that</p>
<blockquote>
<p>Several data sets of sample points sharing the same x-coordinates can
be fitted at once by passing in a 2D-array that contains one dataset
per column.</... | python|numpy | 1 |
364,443 | 54,342,503 | python how to use groupby for classify data and calculate other column's mean | <p>I have one dataframe as below. I want to use 'part1' column as the benchmark for classify the data to 3 parts(each part has same number dataset) and calculate the mean of each group's part2's mean. Such as row0 and row1 as groupB and the mean is (0.67+(-0.03))/2.</p>
<pre><code>import pandas as pd
df = pd.DataFrame... | <p>if you want to calculate the mean of per day,you can use <code>groupby</code> as follow:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"date":["20130101","20130101","20130103","20130103","20130105","20130105"],
"part1":[0.5,0.7,1.3,1.5,0.1,0.3],
"part2":[0.67,-0.03,1.95,-3.25,-0.3,0.6]
})
df.gr... | python|dataframe|pandas-groupby | 1 |
364,444 | 54,490,150 | Why validation accuracy remains at 75% while train accuracy is 100 %? | <p>I used my own data set to train a model using retrain.py file from Tensorflow site. However, with my first set of images, I am seeing test accuracy of 100% while validation accuracy is at 70%. I see that validation entropy is increasing which tells overfitting. I am new to this field and got to this stage by followi... | <p>Your model has over-fitted on the training data. If its a large model, you should consider using transfer learning where you train the model on a large dataset like ImageNet and then fine-tune on your data. You can also try adding some form of regularization to prevent overfitting specially <code>Dropout</code> and ... | python|tensorflow | 0 |
364,445 | 54,650,423 | pytorch torch.jit.trace returns function instead of torch.jit.ScriptModule | <p>I need to run in c++ a pre-trained pytorch nn model (trained in python) to make predictions.</p>
<p>To do so, I'm following the instructions on how to load a pytorch model in c++ given here: <a href="https://pytorch.org/tutorials/advanced/cpp_export.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/adva... | <p>Thanks for asking <a href="https://stackoverflow.com/users/4280242/jatentaki">Jatentaki</a>. I was using PyTorch 0.4 in Python and when I updated to 1.0 it worked.</p> | python|c++|pytorch|libtorch | 2 |
364,446 | 54,383,151 | BeautifulSoup4 cannot locate table no matter what I try | <p>I am trying to scrape 2 tables from a webpage simultaneously.
BeautifulSoup finds the first table no problem, but no matter what I try it cannot find the second table, here is the webpage: <a href="https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014" rel="nofollow noreferrer">Hockey Reference: Justin A... | <p>Because of javascript loading additional information</p>
<p>Today <a href="https://pypi.org/project/requests-html/" rel="nofollow noreferrer">requests_html</a> can load with html page also javascript content.</p>
<pre><code>pip install requests-html
from requests_html import HTMLSession
session = HTMLSession()
r ... | python|pandas|beautifulsoup | 2 |
364,447 | 54,654,915 | Merge columns containing categories with columns containing integers | <p>I would like to create a correlation data between columns <a href="https://seaborn.pydata.org/examples/many_pairwise_correlations.html" rel="nofollow noreferrer">like in this diagonal correlation matrix</a>.</p>
<p>My data is currently is this format:</p>
<p><a href="https://i.stack.imgur.com/FxXZK.png" rel="nofol... | <p>Assuming that your original dataframe is called df and your columns are T, G and Sample*, the following code prepare a new data frame with the desired format:</p>
<pre><code>list_T = list(df['T'].unique())
list_G = list(df['G'].unique())
list_Samples = list(df.drop(['T', 'G'], axis = 1).columns)
cols = []
data = [... | python|pandas|dataframe | 1 |
364,448 | 54,539,305 | How to Compare two Columns of Data to Ensure None of the Data Matches | <p>I am performing a comparison to ensure account numbers in df1 do not bleed over into other account numbers in df2</p>
<p>My intention is to identify and output the row coordinates and values in each df that contain any 'unwanted' matching account numbers</p>
<p>df1 & df2 have a single column that contains acco... | <p>You could merge on the column, then use the output to lookup problem rows in the original datasets</p>
<pre class="lang-py prettyprint-override"><code>target_col = 'Account Number'
matching_account_nos = pd.merge(df1[[target_col]], df2[[target_col]], on='Account Number'), how='inner').values
# now use this to look... | python|pandas|compare | 2 |
364,449 | 54,274,374 | Importing .csv file in Python 3 from folder | <p>There are 2 csv files in same location:
1- candidates.csv
2- Store.csv</p>
<p>When I'm importing candidates.csv filw while using this code, it is getting imported:</p>
<pre><code>data=pandas.read_csv("C:\\Users\\Nupur\\Desktop\\Ankit\\candidates.csv")
</code></pre>
<p>But when I'm using same code for importing St... | <p>Try using this,</p>
<pre><code>data=pandas.read_csv("C:\\Users\\Nupur\\Desktop\\Ankit\\Store.csv",encoding = "ISO-8859-1")
</code></pre> | python|pandas|dataframe|unicode | 1 |
364,450 | 54,412,544 | Cannot feed value of shape for Tensor Placeholder | <p>I am training a model using 3D point cloud data in TensorFlow. My batch size is 64, so TensorFlow expects to receive batch of 64 of 3D points like: (64,1024,3). When I run the training code:</p>
<pre><code>feed_dict = {ops['points_pl']: augmented_data,
ops['labels_pl']: current_label[start_idx:... | <p>You don't need to define the size of the batch dimension precisely. Instead you put None as the size of that dimension. You can define your placeholders e.g.:</p>
<pre><code>n1 = 1024
n2 = 3
ops['points_pl'] = tf.placeholder(tf.float32, [None, n1, n2])
ops['labels_pl'] = tf.placeholder(tf.float32, [None])
</code><... | python|tensorflow | 1 |
364,451 | 54,448,266 | Converting UNIX timestamps into pandas datetime taking timezone into account | <p>I would like to convert the following pandas series containing UNIX timestamps into a pandas datetime using either <code>to_datetime()</code> or <code>arrow</code> library in Python. I want to set the timezone to UTC and currently it is <code>Europe/Paris</code></p>
<p>For Pandas I am using the following function, ... | <p>Try using:</p>
<pre><code>pd.to_datetime(df['dates'], unit='s').astype('datetime64[ns, Europe/Paris]').dt.tz_convert('UTC')
</code></pre>
<p>Or if versions is lower than 0.24.0, you can use:</p>
<pre><code>s = pd.to_datetime(df['dates'], unit='s').dt.tz_localize('Europe/Paris')
s.dt.tz_convert('UTC')
</code></pre... | python|pandas|datetime | 3 |
364,452 | 54,597,864 | Count consecutive equal values in array | <p>Say I have the following <code>numpy</code> array:</p>
<pre><code>a = np.array([1,5,5,2,3,6,5,2,5,5,5])
</code></pre>
<p>I'm trying to come up with a <code>numpy</code> solution to count the amount of times a given value appears consecutively. So, for example for number <code>5</code> I'd like to get:</p>
<pre><c... | <p>Here is one option adapted from <a href="https://stackoverflow.com/questions/54446907/how-to-calculate-numbers-of-uninterrupted-repeats-in-an-array-in-python/54447096#54447096">this answer</a>:</p>
<pre><code>def count_consecutive(arr, n):
# pad a with False at both sides for edge cases when array starts or end... | python|arrays|numpy | 5 |
364,453 | 54,283,307 | Why am I not getting the size of the images | <p>I have <code>374</code> <code>32x32</code> images that I read and stored in a list as follows:</p>
<pre><code>for root, dirs, files in os.walk(image_directory):
for i in range(number_of_images):
img = cv2.imread(root + '/' + str(i) + '.jpg')
real_images.append(img)
</code></pre>
<p>when I wante... | <p>What @HaBom said in the comment might be the case. I tried the following and got a similar result as yours.</p>
<pre><code>import numpy as np
a = []
for i in range(10):
a.append(np.arange(10))
print(np.array(a).shape)
a.append(np.array([1]))
print(np.array(a).shape)
Output:
(10,10)
(11,)
</code></pre>
<p>Try... | python|list|numpy|opencv | 1 |
364,454 | 54,508,830 | How to compare pandas DataFrames using set difference | <p>I have <code>df1</code> and <code>df2</code>:</p>
<pre><code>df1 = pd.DataFrame([[1,1,1,1],[2,2,1,1],[0,0,1,1],[1,1,1,1],[2,2,1,1],[0,0,4,1]],
columns=['col1','col2','col3','col4'])
df2 = pd.DataFrame([[1,1,1,1],[3,3,1,1],[0,0,1,1],[1,1,5,1],[3,3,1,1],[0,0,1,1]],
columns=['co... | <p>You can make use of <code>merge</code> with <code>indicator=True</code>:</p>
<pre><code>u = df1.merge(df2, how='outer', indicator=True)
df3 = u.query('_merge == "left_only"').drop('_merge', 1)
df4 = u.query('_merge == "right_only"').drop('_merge', 1)
df3
col1 col2 col3 col4
1 2 2 1 1
3 0... | python|python-3.x|pandas|dataframe|set | 2 |
364,455 | 54,638,054 | what can I use instead of .loc when i also have NaN values in my table? | <p>I want to groupby some athletes by their name an get the smallst age from every person and then sort them by their age from the youngest to the oldest, but in my data there are also some Nan values and i get a FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, ... | <p>IIUC this can be achieved much more easily by using <code>.sort_values</code> + <code>groupby</code> + <code>head</code>. Output will be youngest age per name, sorted from youngest to oldest with all names with missing ages at the end.</p>
<h3>Sample Data:</h3>
<pre><code>import pandas as pd
import numpy as np
np... | python|pandas | 2 |
364,456 | 54,636,310 | Python currency styling issue in html | <p>I am trying to add the rupee styling attached with the values using babel <a href="https://i.stack.imgur.com/QAP5o.png" rel="nofollow noreferrer">Rupee sign with values</a>
am using babel to style the currency but after converting the dataframe to html
am not getting the rupee styled font but some garbage like <a h... | <p>I don't have access to your DataFrame code, so I can only provide an answer based on your current question. </p>
<p><strong>PLEASE NOTE:</strong> This is my first real attempt in using Pandas DataFrame. </p>
<pre><code>import pandas as pd
from babel.numbers import format_currency
indian_rupee = lambda x: format_... | python|html|pandas | 1 |
364,457 | 73,637,041 | Cannot read f1-score from csv file | <p>i am reading classification_report file after doing 10 fold cv</p>
<pre><code>for i in _all_files:
print(i)
df = pd.read_csv(i)
saved_column = df.f1-score
a = saved_column[5]
li.append(a)
</code></pre>
<p>I want to add f1-score and find mean. But I am getting below error:</p>
<pre><code>Attribu... | <p>Use:</p>
<pre><code>saved_column = df['f1-score']
</code></pre>
<p>Hyphens are not allowed as part of an attribute name. That is, using the dot notation.</p> | python|pandas | 2 |
364,458 | 73,767,979 | Interpolated values for specific missing indices of DataFrame or Series | <p>With a dataframe like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
{'key': 1, 'value': 0.4},
{'key': 4, 'value': 0.5},
{'key': 6, 'value': 0.7},
{'key': 10, 'value': 1.3},
{'key': 11, 'value': 1.4},
{'key': 13, 'value': 1.1},
])
df.set_index('key', inplace=True)
</code></p... | <p>You can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow noreferrer">scipy's <code>interp1d</code></a>:</p>
<pre><code>from scipy.interpolate import interp1d
interp = interp1d(df.index, df, axis=0)
interp([3,6,9])
</code></pre>
<p>Output (I duplicated... | python|pandas|dataframe|interpolation | 1 |
364,459 | 73,638,808 | Replace all NaN value using the the value of another table | <p>How can I change null value and replace them using the value in the same row?</p>
<pre><code> user days_unseen
0 1.0 2.0
1 4.0 5.0
2 1.0 NaN
</code></pre>
<p>I want to change NaN in index 2, replacing it with the value of user in index 2 and add 1 to it.</p>
<p>So that the NaN wil... | <p>Looks like you want <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a>:</p>
<pre><code>df['days_unseen'] = df['days_unseen'].fillna(df['user'].add(1))
</code></pre>
<p>Or, with <a href="https://pandas.pydata.org/docs/user_guide/indexing.... | python|pandas|fillna | 1 |
364,460 | 73,788,249 | filling null cells with specific values in a dataframe | <p>Assume we have the following dataframe</p>
<pre><code>date = '20/09/2022'
A B
n.a. 15/02/2022
0.74 15/02/2022
0.3 ''
1 ''
1 15/02/2022
n.a. ''
</code></pre>
<p>and we want to do the following:</p>
<ul>
<li>if the value in A column is equal to 1 then fill the B co... | <p>You can use boolean indexing:</p>
<pre><code>date = '20/09/2022'
m1 = pd.to_numeric(df['A'], errors='coerce').eq(1)
m2 = df['B'].replace('', pd.NA).isna() # or df['B'].eq('')
df.loc[m1, 'B'] = 'n.a.'
df.loc[m2&~m1, 'B'] = date
</code></pre>
<p>output:</p>
<pre><code> A B
0 n.a. 15/02/2022
1 0... | pandas|dataframe|filter | 0 |
364,461 | 73,638,899 | Splitting a non delimited column and create an additional column to count which number value | <p>I have a problem in which I want to take Table 1 and turn it into Table 2 using Python.</p>
<p>Does anybody have any ideas? I've tried to split the Value column from table 1 but run into issues in that each value is a different length, hence I can't always define how much to split it.</p>
<p>Equally I have not been ... | <p>Given:</p>
<pre><code> ID Value
0 1 000000S
1 2 000FY
</code></pre>
<p>Doing:</p>
<pre><code>df.Value = df.Value.apply(list)
df = df.explode('Value')
df['Position'] = df.groupby('ID').cumcount() + 1
</code></pre>
<p>Output:</p>
<pre><code> ID Value Position
0 1 0 1
0 1 0 2... | python|pandas|dataframe | 1 |
364,462 | 73,808,000 | What does the Linear regression layer, converted into an image tell me? | <p>I am following <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="nofollow noreferrer">this tutorial</a>.</p>
<p>However, I decided to take the linear layers, And then make them convertible into an image of 1 * 19 * 19. In doing so, I get a bunch of pixels at random places.
<a href="ht... | <p>I hate to break it to you, but this is an image (full of sound and fury) signifying nothing. When you flatten the output of your <code>Conv2d</code> layers and pass this output through 2 <code>Linear</code> layers, you lose any spatial meaning to the neurons. A "linear" or "dense" layer connects ... | python|machine-learning|pytorch|conv-neural-network | 0 |
364,463 | 73,525,516 | Pandas Fill in Missing Row in Group with multiple keys | <p>I'm looking to fill in a dataframe with a missing row based on a few criteria.</p>
<pre><code>Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 keyA 39686 non-null object
1 keyB 39686 non-null... | <p>Try as follows. First, we use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>df.pivot</code></a> to "group" all values (per each week) for each <code>key*</code>-sequence (as index). Next, we use <a href="https://pandas.pydata.org/docs/ref... | python|pandas | 3 |
364,464 | 73,625,230 | How to remove all cells with single char pandas | <p>I have this df:</p>
<pre><code>df1 = pd.DataFrame({'Number' : ['one', 'two', '-', '-', 'five'],
'Color' : ['-', 'red', 'blue','yellow', '-']})
---
Number Color
0 one-five -
1 two red
2 - blue-black
3 - yellow
4 five -
</code></pre... | <p>try this the <code>replace</code> function in pandas replace the exact <code>string</code> matching not like <code>str.replace</code></p>
<pre><code>df1.replace("-","",inplace=True)
</code></pre> | python|pandas|dataframe | 2 |
364,465 | 73,687,254 | Python Pandas dataframe to JSON file | <p>My dataframe is:</p>
<pre><code>import pandas as pd
from tabulate import tabulate
data0 = {'dir':[0,'','',90,'','','']}
data1 = {'dist':['0 to 1h','1h to 2h','2h to 3h','0 to 1h','1h to 2h','2h to 3h','> 3h']}
data2 = {'max':[-0.271, -0.17 , -0.034, -0.322, -0.208, -0.057, 0.018]}
data3 = {'min':[-0.441, -0.339,... | <p>Here is one way o do it:</p>
<pre class="lang-py prettyprint-override"><code># Put values in dicts
df["items"] = df.apply(
lambda x: {"max": {x["dist"]: x["max"]}, "min": {x["dist"]: x["min"]}}, axis=1
)
# Add missing values
df["dir"... | json|pandas|dataframe | 0 |
364,466 | 73,776,655 | Visualize overlapping categories in one-hot encoding Pandas DataFrame | <p>I have a pandas DataFrame that looks like this:</p>
<p><a href="https://i.stack.imgur.com/z3hjo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z3hjo.png" alt="enter image description here" /></a></p>
<p>One instance can have a value of 1 in more than one category. I was wondering how to visualize... | <p>Maybe could you compute the overlapping between categories pair-wise, then plot the resulting matrix with a heat map for visualization purpose, with <code>plt.matshow</code> ?</p>
<p>With <code>A</code> the numpy array of the one hot labels, of shape <code>(N, d)</code>, <code>N</code> the number of examples, <code>... | python|pandas|deep-learning|data-science | 1 |
364,467 | 73,798,838 | Create new column from existing one with more values in it | <p>I have column with following values:</p>
<pre><code>d = {'id': [1, 2, 3, 4, 5],
'value': [['Red', 'Blue', 'Yellow'],
['Blue', 'Yellow', 'Orange'],
['Green', 'Purple', 'Yellow', 'Red'],
['Violet', 'Blue', 'Green', 'Red', 'Brown'],
['Blue', 'Green']]}
d... | <p>Use list comprehension with window function and pass to <code>DataFrame</code> constructor:</p>
<pre><code>from itertools import islice
#https://stackoverflow.com/a/6822773/2901002
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...... | python|pandas|dataframe|tuples|apply | 3 |
364,468 | 73,653,193 | Generate Rows in Pandas dataframe based on 2 date columns | <p>Given a sample dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>01-01-2015</td>
<td>09-08-2022</td>
</tr>
<tr>
<td>2</td>
<td>01-01-2016</td>
<td>05-10-2020</td>
</tr>
</tbody>
</table>
</d... | <p>Given:</p>
<pre><code> ID Start_Date End_Date
0 1 01-01-2015 09-08-2022
1 2 01-01-2016 05-10-2020
</code></pre>
<p>Doing:</p>
<pre><code># Ensure your columns are proper datetimes:
for col in ('Start_Date', 'End_Date'):
df[col] = pd.to_datetime(df[col])
# For each row, create a daily DatetimeIndex... | python|pandas|date | 2 |
364,469 | 73,628,579 | How to calculate percentage probability using a pivot table in pandas | <p>I am working with a dataframe with two columns. One column is coded for either "control" or "treatment" while the other column is "true" or "false". I was wondering how I could use a pivot table and/or groupby to calculate the probability of true or false given either the cont... | <p>You can <code>groupby</code> and use <code>value_counts</code> with <code>normalize=True</code></p>
<pre><code>df = pd.DataFrame({
'Group':['C','C','C','T','T','T','T'],
'Result':[True,True,False,False,False,False,True],
})
p_df = (
df.groupby('Group')['Result']
.value_counts(normalize=True)
.re... | python|pandas|dataframe|group-by|pivot-table | 2 |
364,470 | 73,727,816 | How to freeze part of selected layer(eg nn.Linear()) of a model in Pytorch? | <p>question:
fc = nn.Linear(n,3);
I want to freeze the parameters of the third output of the fc when I train this layer.</p> | <p>With monolithic layer you can't. But you can split layer, making a separate <code>Linear</code> for each output channel:</p>
<pre><code>fc1 = nn.Linear(n,1)
fc2 = nn.Linear(n,1)
fc3 = nn.Linear(n,1)
</code></pre>
<p>Here you can freeze <code>fc3</code></p> | pytorch | 0 |
364,471 | 73,698,556 | Pandas. delete rows between two dates groupby person | <p>I have two dataframes; available_df and delete_df.</p>
<pre><code><available_df>
Person start_day end_day available
1 2012-07-13 2012-07-27 0
1 2012-07-20 2012-08-03 0
1 2012-07-27 2012-08-10 0
2 2012-05-06 2012-05-20 0
2 2012-05-13... | <p>I would use <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pandas.merge_asof</code></a> here:</p>
<pre><code>out= (pd
.merge_asof(available_df.sort_values('end_day'),
delete_df.sort_values('start_day'),
by='Person', left_... | python|pandas | 1 |
364,472 | 73,665,285 | Pytorch lightning: see input/ouptut size in model summary when using nn.ModuleList | <p>When I use nn.ModuleList() to define layers in my pytorch lightning model, their "In sizes" and "Out sizes" in ModelSummary are "?"
Is their a way to have input/output sizes of layer in model summary, eventually using something else than nn.ModuleList() to define layers from a list of a... | <p>In your case you are using the layers in the list in a sequential manner:</p>
<pre><code>for layer in self.moduleList:
out = layer(out)
</code></pre>
<p>However, nn.ModuleList does not force you to run your layers sequentially. You could be doing this:</p>
<pre><code>out = self.moduleList[3](out)
out = self.modu... | pytorch|pytorch-lightning | 1 |
364,473 | 73,625,726 | How can I fill a serie of dates with 0 value_counts()? | <p>I am counting how many times repeat a date in an excel sheet (filtering by month), but in the cases that the date doesnt exist, i want to fill it with a 0 in the value_counts() function. Then i need to plot it.</p>
<p>Imagine that is a bunch of trucks dispatching some product:2022-07-04 i have only 1 truck, and then... | <p>Assuming you want daily value counts, use <code>asfreq</code> and <code>fillna</code>:</p>
<pre><code>july_log_mel.index = pd.to_datetime(july_log_mel.index)
july_log_mel.asfreq('D').fillna(0)
</code></pre> | python|pandas|plot | 1 |
364,474 | 73,739,975 | pandas: calculate probability group by | <p>I'm unable to understand the output when calculating probability for a group by use-case.
I'm interested to calculate probability, for example, in the below data frame, grouped by <code>a1</code> probability of <code>a2</code></p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,1,0],[0,1,1],[0,1,1],[1,1,0],[1,... | <p>In your ouput is <code>0.75</code>, not <code>1.75</code> - solution should be simplify with <code>mean</code> by boolean <code>DataFrame</code>:</p>
<pre><code>df1 = df["a2"].gt(0).groupby(df['a1']).mean().reset_index(name='prob')
print (df1)
a1 prob
0 0 1.00
1 1 0.75
df2 = df[["a1",... | python|pandas|probability | 1 |
364,475 | 73,743,639 | Divide almost similar columns and get percentage | <p>I have a dataframe <code>df</code></p>
<pre><code>x y z x_o y_o z_o
1 5 3 10 20 15
3 2 7 10 15 20
</code></pre>
<p>How can I divide x,y,z with their respective _o part and get percentage?</p>
<p>desired output:</p>
<pre><code>x y z x% y% z%
1 5 3 10 25 20
3 2 7 30 13.33 35
</code></pre> | <p>You can select all columns by lists, divide DataFrames with multiple 100 and append to original <code>DataFrame</code>:</p>
<pre><code>df = (df.join(df[['x','y','z']].div(df[['x_o','y_o','z_o']].to_numpy())
.mul(100)
.round(2)
.add_suffix('%')))
print (df)
x y z x_o y_o ... | python|pandas | 1 |
364,476 | 73,806,991 | Read space separated text file in pandas | <p>I am trying to read a text file present in this url into a pandas dataframe. <a href="https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/recent/TU_Stundenwerte_Beschreibung_Stationen.txt" rel="nofollow noreferrer">https://opendata.dwd.de/climate_environment/CDC/observ... | <p>The <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer">read_fwf</a> function in pandas can read a file with a table of fixed-width formatted lines into a DataFrame.</p>
<p>The header line confuses the auto-width calculations so best to skip the header lines and expl... | python|pandas|dataframe|delimiter | 4 |
364,477 | 73,582,684 | Append dataframes to multiple Excel sheets | <p>I'm trying to append 3 dataframes to 3 existing sheets in an Excel file (one dataframe per sheet).</p>
<p>This is my code:</p>
<pre><code>with pd.ExcelWriter(output_path, mode="a", if_sheet_exists="overlay") as writer:
df_a.to_excel(writer, sheet_name="A", index=False)
df_b.to_e... | <p>You have to find last row and land new dataframe after it.
assuming you have some data in place and all headers, you can test like below:</p>
<pre><code>with pd.ExcelWriter(output_path, mode="a", if_sheet_exists="overlay") as writer:
# getting last row from Sheet "A" and adding 1 as... | python|excel|pandas | 0 |
364,478 | 73,544,662 | Numpy: Complex Equation Curve is Plotted Incorrectly | <p>I am trying to use the Python to do some graphical analysis.</p>
<p>I need to plot this equation:
Where fn is on the x axis (log scale 0 - 10) and Mg is on the y axis.
Ln and Qe are dummy variables that I will enter different values for, but for now I am working with just</p>
<pre><code>Ln = 5
Qe = 0.5
</code></pre>... | <p>You can write complex functions by using <code>j</code>.
For example <code>x = 3 + 5j</code>.
Besides the imaginary part you had placed a parenthesis incorrectly.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
Ln = 5
Qe = .5
fn = np.linspace(.1, 10, 1000)
Mg_... | python|python-3.x|numpy|matplotlib|graphing | 4 |
364,479 | 73,598,206 | Convert to_datetime when days don't contain leading zero | <p>I'm trying to get the index of my dataFrame to be of type datetime. My CSV file contains seperate columns of Dates and Times which i combine upon importing:</p>
<pre><code>df = pd.read_csv("example.csv", sep=";", decimal=",", parse_dates=[["Date", "Time"]])
</code></... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.zfill.html" rel="nofollow noreferrer"><code>Series.str.zfill</code></a> (as suggested by @FObersteiner in the comments) and apply <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>... | python|pandas|datetime|strftime | 1 |
364,480 | 73,691,631 | Pandas: Display One Row per Column Value based on Date | <p>Suppose I have a dataframe <code>df</code> which prints as follows:</p>
<pre><code> Order Report Name Last Updated
6 1 Fund Balance Sheet Sep 11 10:36:28 AM
15 1 Fund Balance Sheet Sep 08 11:07:22 AM
14 2 Fund Income Statement - Oper... | <p>There's no year on there, so I'm assuming the years are all the same?</p>
<p>Sort the dataframe by the <code>'Last Updated'</code>. Then <code>drop_duplicates</code> and keep the last.</p>
<pre><code>df = df.sort_values('Last Updated')
df = df.drop_duplicates(subset = 'Report Name', keep='last')
</code></pre>
<p>Ass... | python|pandas | 0 |
364,481 | 73,622,516 | Coalesce values only from columns where column matches with data dates | <p>I have a data frame similar to one below.</p>
<pre><code> Date 20180601T32 20180604T33 20180605T32 20180610T33
2018-06-04 0.1 0.5 4.5 nan
2018-06-05 1.5 0.2 nan 0
2018-06-07 1.1 1.6 nan nan
2018-06-10 0.4 1.1 ... | <p>Use <a href="https://pandas.pydata.org/docs/user_guide/indexing.html#indexing-lookup" rel="nofollow noreferrer">lookup</a> with convert <code>Date</code>column to same format like columns names:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'])
idx, cols = pd.factorize(df['Date'].dt.strftime('%Y%m%d'))
df['ob... | python|pandas|coalesce | 3 |
364,482 | 73,837,250 | How to iterate through DataFrame and use the values in requests? | <p>amazing pythoners,</p>
<p>I am hoping to get some help with my below scenario</p>
<p>I have a list of a few centers based on which I want to extract employee data for each center. Earlier I was using the below method and it was working beautifully.</p>
<p>row[0] in the CSV file had the whole URL which looked somethi... | <p>If I understand correctly, the Center ID is this: <code>CID = AA['id']</code><br />
Try iterating through the <code>id</code> column this way:</p>
<pre><code>for CID2 in AA['id']:
try:
url2 = f"https://api.test.com/v1/centers/{CID2}/employees?page=1&size=100"
print(url2)
except ... | python|pandas|dataframe|loops|iteration | 1 |
364,483 | 73,748,420 | Accessing all the rows with a same particular element from the pandas dataframe | <p>I have this particular dataset in a CSV file, I want to find out the names of all crops that grow in the summer season. How can I do that?</p>
<p><img src="https://i.stack.imgur.com/rsDWv.png" alt="enter image description here" /></p> | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame.loc</code></strong></a> to return the rows of every crop that grows in the summer.</p>
<pre><code>import pandas as pd
df = pd.read_csv('anvesh.csv')
mask = df['Season... | pandas|dataframe | 0 |
364,484 | 73,761,285 | Changing values in grouped dataframe based on first row value of the column in that group | <p>I am using the below code to arrange some data. It is grouped by <code>'ID'</code> and <code>'L'</code> and I have used a condition to print True in the <code>MT</code> column if it is <code>True</code>. What I want is that When the first row of the group is true, every other row in that group should print true irre... | <p>You can use <code>groupby</code>, index on the MT column, and then <code>transform</code> with a lambda that checks if the value is True.</p>
<pre><code>df3['MT'] = df3.groupby('ID')['MT'].transform(lambda x: x.values[0] if x.values[0] else x)
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/0gBrE.... | python|pandas|google-colaboratory | 0 |
364,485 | 73,796,804 | plotting time and temperature in xy plot | <p>I want to plot a xy plot where x axis contain temperature values(first column) and y axis contain time in hr:min:sec(second column) .</p>
<pre><code>8.8900 06:09:95.50
9.4500 06:09:00.56
10.5800 08.06:95.48
11.6500 09:07:73.58
56.3650 00:08:00.47
85.7823 07:01:03.23
</code></pre>
<p>I just want to plot a xy plot.<... | <p>The simplest approach would be to use <code>pandas</code>.</p>
<p>Load the file as whitespace delimited file into <code>pandas.DataFrame</code> object as:</p>
<pre><code>import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('inpdata.txt', names=['temp', 'time'], delim_whitespace=True)
</code></p... | python-3.x|pandas|dataframe|numpy|matplotlib | 1 |
364,486 | 73,707,869 | How to use pandas groupby on one column with agg - max one col, min another col - without producing multi-level columns | <p>I have the following pandas DataFrame:</p>
<p><a href="https://i.stack.imgur.com/Ax2gz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ax2gz.png" alt="enter image description here" /></a></p>
<pre><code>account_number = [1234, 5678, 9012, 1234.0, 5678, 9012, 1234.0, 5678, 9012, 1234.0, 5678, 9012]... | <p>leaving the order number out, per your comment above. If order # are same for an account, then add the order number to the columns list in merge</p>
<pre><code>result = df.groupby("account_number").agg({"customer_dob": "max", "purchase_date": "min"}).reset_index()
r... | python|pandas|group-by|max|aggregate | 0 |
364,487 | 73,811,324 | Assignment of the last variable is being persistent, how to solve it? | <p>I am trying to do assignments to different variables in my code, but for some reason, the last one is being persistent. I have tracked the problem until the example below. If someone is able to explain this behavior it will be great.</p>
<pre><code>import numpy as np
metric_a = metric_b = metric_c = metric_d= np.ze... | <p>You can do that with <strong><code>astype</code></strong> like that :-</p>
<pre><code>metric_a = metric_a.astype('float')
metric_a[metric_a == j] = temp_a
print(metric_a[j])
</code></pre>
<p>output:-</p>
<pre><code>1.0
</code></pre> | python|python-3.x|numpy|numpy-ndarray | 0 |
364,488 | 73,636,683 | pandas - mask works on whole dataframe but on selected columns? | <p>I was replacing values in columns and noticed that if use <code>mask</code> on all the dataframe, it will produce expected results, but if I used it against selected columns with <code>.loc</code>, it won't change any value.</p>
<p>Can you explain why and tell if it is expected result?</p>
<p>You can try with a data... | <p>i guess it's because the DataFrame.loc property is just giving access to a slice of your dataframe and you are masking a copy of the dataframe so it doesn't affect the data.</p>
<p>you can try this instead:</p>
<pre><code>dt[columns] = dt[columns].mask(dt[columns] == 0)
</code></pre> | python|python-3.x|pandas|in-place | 2 |
364,489 | 73,648,115 | Data ino pd.DataFrame | <pre><code>from datetime import timedelta, date
from nsepy import get_history
import pandas as pd
def importdata(stock):
stock_fut = get_history(symbol=stock,
start=date.today() - timedelta(days = 3), end=date.today(),
futures=True,
expiry_date=date(2022,9,29))
... | <p>Change the line to:</p>
<pre><code>df = pd.DataFrame([a[i]])
</code></pre> | python|pandas|dataframe | 0 |
364,490 | 73,812,047 | Pandas, adding multiple columns of list | <p>I have a dataframe like this one</p>
<pre><code>df = pd.DataFrame({'A' : [['a', 'b', 'c'], ['e', 'f', 'g','g']], 'B' : [['1', '4', 'a'], ['5', 'a']]})
</code></pre>
<p>I would like to create another column C that will be a column of list like the others but this one will be the "union" of the others
Someth... | <p>As you have lists, you cannot vectorize the operation.</p>
<p>A list comprehension might be the fastest:</p>
<pre><code>from itertools import chain
df['out'] = [list(chain.from_iterable(x[1:])) for x in df.itertuples()]
</code></pre>
<p>Example:</p>
<pre><code> A B C ... | python|pandas|dataframe | 1 |
364,491 | 73,827,410 | How I can delete a seperator without using str.replace in pandas? | <p>I have this DF:</p>
<pre><code>Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5 Unnamed: 6 Unnamed: 7 Unnamed: 8 Unnamed: 9 ... Unnamed: 23 Unnamed: 24 Unnamed: 25 Unnamed: 26 Unnamed: 27 Unnamed: 28 Unnamed: 29 Unnamed: 30 Unnamed: 31 Unnamed: 32
0 NaN NaN NaN NaN NaN NaN CMO & KPI ... | <p>When just using <code>.replace('-', '')</code> the output is:</p>
<pre><code>'FMS PSO Zywiec 1'
</code></pre>
<p>As there are two spaces in between <code>FMS</code> and <code>PSO</code>, the output for using <code>.split(' ')</code> contains an empty string. You can just use <code>.split()</code> to solve this prob... | python|pandas|dataframe | 2 |
364,492 | 73,543,637 | Python numpy - string representation of a matrix to 2D numpy array while keeping formatting and feed it to NetworkX | <p>I need some help with my code. I have txt files in the following format (2 samples):</p>
<pre><code>wwwwwwwwwwwwwwwwwwwwwwwwww
w...o.xx.o......o..xoxx..w
w...oooooo........o..o...w
w....xxx.........o.oxoo.ow
wx...............oxo...oow
wwwwwwwwww........o...wxxw
wb ...co..............wxxw
w ........Ao....o....wxxw
w... | <p>You can create a grid graph, and then remove all nodes where you have a zero. In this way you will have a graph in which there is a node for each '1' in your matrix, and adjacent 1s are connected.</p>
<pre><code>from itertools import product
import networkx as nx
import numpy as np
coor = np.array(list(product(*ma... | python|arrays|numpy|matrix|networkx | 2 |
364,493 | 71,274,502 | my output is right alignment in default using pandas read_csv option | <p>I have using the below python pandas code to read a csv file but the output is not proper and its default right alignment</p>
<p>Input:</p>
<pre><code>Name,Age,Income
Rob, 24,4521
Siva,34,54821
</code></pre>
<p>Code:</p>
<pre><code>import pandas as pd
df = pd.read_csv("C:/Users/vpitcs9/income.csv")
df
</co... | <p>Looks like the input delimiter is not <code>,</code> and <code>;</code> instead.</p>
<p>Try using</p>
<pre class="lang-py prettyprint-override"><code>df = pd.read_csv("C:/Users/vpitcs9/income.csv", sep=';')
</code></pre> | python|pandas | 0 |
364,494 | 71,154,385 | Values from two columns appear as a single column in another dataframe | <p>One dataframe looks like this:</p>
<pre><code>Thing Number1 Number2
43 STK
64 BOX
32 STK BOX
46 THG
34 BOX THG
...
</code></pre>
<p>And another one like this:</p>
<pre><code>Thing Pa... | <p>I think your solution is efficient.</p>
<pre><code>df = (df2.merge(df1, on='Thing')
.query("Package == Number1 | Package == Number2")
.drop(['Number1','Number2'], axis=1))
print (df)
Thing Package Value1 Value2
0 43 STK 1 1
1 64 BOX 2 1
3 32 ... | python|pandas|dataframe | 0 |
364,495 | 71,116,462 | How to aggregate Python dataframe calculating a rate | <p>Initially I have a dataframe like this:</p>
<pre><code>GERENCY RESI1
2 -1
4 -1
4 1
5 1
6 -1
4 -1
2 1
6 -1
6 1
6 -1
...
</code></pre>
<p>I need to aggregate the values to obtain something like this:</p>
<pre><code>GERENCY RATE
2 28/362
3 ... | <p>Let us check <code>groupby</code> with <code>mean</code></p>
<pre><code>out = df['RESI1'].eq(1).groupby(df['GERENCY']).mean().to_frame('RATE').reset_index()
Out[66]:
GERENCY RATE
0 2 0.500000
1 4 0.333333
2 5 1.000000
3 6 0.250000
</code></pre> | python|pandas|group-by | 3 |
364,496 | 71,191,000 | Cannot find the table data within the soup, but I know its there | <p>I am trying create a function that scrapes college baseball team roster pages for a project. And I have created a function that crawls the roster page, gets a list of the links I want to scrape. But when I try to scrape the individual links for each player, it works but cannot find the data that is on their page.</p... | <p>A number of things:</p>
<ol>
<li>I would pass the headers as a global</li>
<li>You are slicing 1 character too late the link I think for <code>player_</code></li>
<li>You need to re-work the logic of <code>find_data()</code>, as data is present in a mixture of element types and not in table/tr/td elements e.g. found... | python|pandas|function|beautifulsoup|web-crawler | 1 |
364,497 | 71,142,244 | Why does running numpy (array substraction) in diferent process is so slow (compare to single process) even if multithreading is deactivated | <p>Given the following script:</p>
<pre class="lang-py prettyprint-override"><code>#!python
import os
import time
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM... | <p>The probleme was that my CPU (intel) enabled the Turbo mode when i'was using only one process.</p> | python|numpy|performance|process | 0 |
364,498 | 71,142,940 | Data Frame modification based on existing columns in Python Pandas? | <p>I have Data Frame in Python Pandas like below:</p>
<pre><code>col1 | col2 | col3
--------------------------------
2021-04-23 | 30.22 | 2021-04-01
2022-11-15 | 15.50 | 2022-05-22
2022-10-01 | 48.96 | 2022-11-14
</code></pre>
<p>And based on 3 columns above I need as a result something like below:</p>
<ul>
<li>... | <p>You can try, suppose df your dataframe:</p>
<pre><code>df['col1_X'] = pd.to_datetime(df['col1']).dt.to_period('M')
df['col2_X'] = df['col2'].round(0).astype(int)
df['col3_X'] = pd.to_datetime(df['col3']).dt.strftime('%d-%b-%Y')
# Here to rearrange the index
df = df[['col1','col1_X','col2','col2_X','col3','col3_X']]
... | python|pandas|dataframe|numpy|aggregation | 0 |
364,499 | 71,182,235 | Conditionally filter rows based on mean of a category in pandas | <p>I have a dataframe and I want to filter out values of the table based on a grouped column mean.</p>
<p>Eg.</p>
<pre><code>df = pd.DataFrame({'Year':[2020, 2021, 2020, 2021],
'Cars': ['Bentley', 'Toyota',
'Aston Martin', 'Nissan'],
'Max Speed': [380,... | <p>You can use <code>transform</code> to directly create the condition that aligns with the original data frame:</p>
<pre><code>df[df['Max Speed'].groupby(df.Year).transform(lambda x: x > x.mean())]
Year Cars Max Speed
0 2020 Bentley 380
1 2021 Toyota 370
</code></pre> | python-3.x|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.