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 |
|---|---|---|---|---|---|---|
354,100 | 63,182,594 | compare two columns and set up conditions | <p>I have two data frames</p>
<pre><code>df1
name gender
John 1
Mina 1
Cici 0
Dean 1
Lily 0
df2
n g
King 1
Cici 1
Cici 1
Dean 0
Juli 0
</code></pre>
<p>For the two dataframe, I want to return all the rows where</p>
<pre><code>df1['name'] == df2['n'] and df1['gender... | <p>Yes we do <code>merge</code></p>
<pre><code>out=df1.merge(df2,left_on='name',right_on='n').query('gender!=g')
</code></pre> | python|pandas | 1 |
354,101 | 62,964,492 | Why front end of the python web application throws an exception? | <p>I am building a python web application to show a gold price movement in a time-series graph. But my callbacks are not working and it throws the following exception in the front end of the application.</p>
<pre><code>ID not found in layout
6:42:46 AM
Attempting to connect a callback Input item to component:
"n... | <p>Checkout your callback function. The <code>@app.callback</code>'s <code>Input</code> tells, the app which element (button) should <em>run</em> this callback. Dash tries to find an HTML element with <code>id="none"</code> in your case.</p>
<pre class="lang-py prettyprint-override"><code>@app.callback(
[... | python|pandas|callback|dashboard|plotly-dash | 0 |
354,102 | 63,267,305 | how to ffill and and letter in pandas? | <p>New to the pandas.</p>
<p>Struggling find a way to ffill and concat a string.
I imported excel sheet then like to fill the blank (NaN) with proceeding value plus some distinguisher(like-1).</p>
<p>-from-</p>
<pre><code>1 a
2 nan
3 b
4 nan
</code></pre>
<p>-to-</p>
<pre><code>1 a
2 a-1
3 b
4 b-1
</code></pre>
... | <p>After you do <code>ffill</code>, you can compute the order of each rows with <code>groupby().cumcount()</code>:</p>
<pre><code>df['col'] = df['col'].ffill()
orders = df.groupby('col').cumcount()
# concatenate the order except for the first rows
df['col'] = np.where(orders==0, df['col'], df['col'] + '-' + orders.ast... | pandas | 0 |
354,103 | 62,923,051 | Pandas comparing dataframes and changing column value based on number of similar rows in another dataframe | <p>Suppose I have two dataframes:</p>
<p>df1:</p>
<pre><code> Person Number Type
0 Kyle 12 Male
1 Jacob 15 Male
2 Jacob 15 Male
</code></pre>
<p>df2:
A much larger dataset with similar format except there is a count column that needs to increment based on df1</p>
<pre><code> Person Number Ty... | <pre><code>df1 = df1.groupby(df.columns.tolist(), as_index=False).size().to_frame('Count').reset_index()
df1 = df1.set_index(['Person','Number','Type'])
df2 = df2.set_index(['Person','Number','Type'])
df1.add(df2, fill_value=0).reset_index()
</code></pre>
<p>Or</p>
<pre><code>df1 = df1.groupby(df.columns.tolist(), as... | python|pandas|numpy | 0 |
354,104 | 63,025,037 | Pull out the ID if last value on last 3 dates are less than 70 | <p>I am trying to write an algorithm in python using pandas where I want to print the IDs if the Value of that id for last 3 consecutive days are less than 70.</p>
<p>In the given table as we see Value of A in last three dates (18/2/2019, 15/2/2020 and 16/2/2020)
are 76 , 89 and 77 respectively so It should not be prin... | <p>You can do <code>rolling</code></p>
<pre><code>s=df.Value.lt(70).groupby(df['id']).rolling(3).sum().groupby(level=0).last()
s.index[s==3]
Index(['B'], dtype='object', name='id')
</code></pre> | python|pandas|data-science | 0 |
354,105 | 63,000,767 | How to get specific global package (module) of python in venv? | <p>I had installed TensorFlow of 586 MB in my ubuntu now if I create any venv environment I have to redownload it in the venv. is there any way by that I can get the TensorFlow from global to my venv without downloading or having extra modules.</p> | <p>Normally <em>pip</em> wouldn't need to download <em>tensorflow</em> again, as it keeps copies of downloaded artifacts in a local <em>cache</em> on the file system. But it would need to install it in each <em>virtual environment</em>, unless...</p>
<p>Maybe <em>venv</em>'s <code>--system-site-packages</code> option i... | python|tensorflow|python-venv | 1 |
354,106 | 63,231,396 | Count values in column and assign to row | <p>I have a dataframe like this:</p>
<pre><code> dT_sampleTime steps
0 0.002 0.001
1 0.004 0.002
2 0.004 0.003
3 0.004 0.004
4 0.003 0.005
5 0.007 0.006
6 0.001 0.007
</code></pre>
<p>and I want to count how often the ... | <p><code>map</code> the 'steps' column with the <code>value_counts</code> of the 'dt_sampleTime' column. Then fill the missing values with 0.</p>
<pre><code>df['absolute frequency'] = (df['steps'].map(df['dT_sampleTime'].value_counts())
.fillna(0, downcast='infer'))
# dT_sampl... | python|pandas|list|histogram | 1 |
354,107 | 63,083,112 | Keep rows of dataframe if multiple conditions met | <p>Given the following dataframe:</p>
<pre><code>df = pd.DataFrame({'A': ["EQ", "CB", "CB", "FF", "EQ", "EQ", "CB", "CB"],
'B': ["ANT", "ANT", "DQ", "DQ", "BQ", "VGQ&... | <p>Let us try <code>filter</code></p>
<pre><code>s=df.groupby('B').filter(lambda x : pd.Series(['EQ','CB']).isin(x['A']).all())
Out[7]:
A B
0 EQ ANT
1 CB ANT
5 EQ VGQ
7 CB VGQ
</code></pre>
<p>Then</p>
<pre><code>s=s[s.A.isin(['EQ','CB'])]
</code></pre> | pandas|dataframe|conditional-statements|sample | 3 |
354,108 | 63,146,075 | how to obtain a 3d mask tensor from two given 2d mask tensors? | <p>Given two 2d masks m1, m2 (both shape [m,m]), obtain 3d mask m3 (shape [m,m,m]):</p>
<blockquote>
<p>if m1[i][j] == True and m2[i][k] == True and i != j and i != k and j != k, then m3[i][j][k] = True</p>
</blockquote>
<p>Note that m1 and m2 is diagonal, m1[i][j] = m1[j][i], m2[i][k]=m2[k][i]. but m3[i][k][j] is not ... | <pre><code>def _get_triplet_mask(mask1, mask2):
indices_equal = tf.cast(tf.eye(tf.shape(mask1)[0]), tf.bool)
indices_not_equal = ~indices_equal
i_not_equal_j = tf.expand_dims(indices_not_equal, 2)
i_not_equal_k = tf.expand_dims(indices_not_equal, 1)
j_not_equal_k = tf.expand_dims(indices_not_equal, ... | tensorflow | 0 |
354,109 | 63,072,135 | How to do I give some space between Y axis and my starting and ending vertical bars in Matplotlib | <pre><code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
plt.style.use('ggplot')
overs = np.arange(1, 51)
india_score = np.random.randint(low = 1, high = 18, size = 50, dtype = 'int16')
plt.bar(overs, india_score, width = 0.80, align = 'center', color = 'orange', ... | <p>Here is how you could do this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
plt.style.use('ggplot')
overs = np.arange(1, 51)
india_score = np.random.randint(low = 1, high = 18, size = 50, dtype = 'int16')
plt.bar(overs, india_score, width = 0.80... | python|numpy|matplotlib | 0 |
354,110 | 62,963,977 | Pandas: find nearest higher high (OHLC) | <p>I'm trying to find the fastest solution to iterate over each row of Open High Low Close data and count out how many rows exist between the current row's high and the next high that’s greater than or equal to the original. Here is a shortened code example which I think explains it well (I'd be trying to find the fin... | <p>using <code>list comprehension</code> and get <code>index to list</code></p>
<pre><code>In [166]: d = {'high': [1.2, 1.1, 1.1, 1.4, 1.3, 1.2, 1.3]}
In [167]: df = pd.DataFrame(data=d)
In [168]: df['rows_to_higher_high']=[(df['high'].values[i+1:]>=val).tolist().index(True) if True in (df['high'].values[i+1:]>... | python|pandas|ohlc | 1 |
354,111 | 63,311,269 | Installing yfinance errors window 7 Anaconda | <p>I tried installing yfinance using <code>pip install yfinance</code> and I got:</p>
<pre><code>Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'd:\\users\\myself\\anaconda3\\lib\\site-packages\\numpy\\core\\multiarray.cp36-win_amd64.pyd'
Consider using the '--user' option or chec... | <p><strong>Case 1: <code>pip</code></strong></p>
<p>Source: <a href="https://stackoverflow.com/questions/50087098/permission-denied-error-by-installing-matplotlib">Permission denied error by installing matplotlib
</a></p>
<h1>Linux / macOS</h1>
<p>From your terminal, you can <strong>install the package for your user on... | python|numpy|pip|yfinance | 2 |
354,112 | 63,121,983 | Bidirectional RNN Implementation pytorch | <p>Hi I am trying to understand bidirectional RNN.</p>
<pre><code>> class RNN(nn.Module):
>
>
> def __init__(self,n_vocab,n_embed,hidden_size,output_size):
>
> super().__init__()
>
> self.hidden_size = hidden_size
>
> self.embedding = nn.Embedding(n_vocab+1,n_embed) ## ... | <p><code>torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)</code> will concatenate the last hidden states of the 2 GRUs (backward and forward).</p>
<p>While <code>x[:,-1,:]</code> is a concatenation of the last hidden state of the forward GRU with the first hidden state of the second GRU. In other words, it only foc... | nlp|pytorch|recurrent-neural-network | 0 |
354,113 | 62,904,739 | Collapse duplicate rows in an array into a single unique row | <p>Given a 2D array (A) with multiple columns and rows, and a 1D array (B) of the same length. (A) contains duplicate rows and I want to collapse these duplicate rows into one unique entry but add the corresponding values in (B). Currently I am using a dictionary to solve this issue, but I think it is not ideal and too... | <p>You could use <code>np.unique</code>:</p>
<pre><code>unq,idx,inv = np.unique(example_keys,axis=0,return_inverse=1,return_index=1)
# change idx order to order of appearance
aux = np.bincount(idx)
nz = aux.nonzero()
aux[idx] = np.arange(idx.size)
idx = aux[nz]
new_keys = unq[idx]
new_vals = np.bincount(inv,np.ravel(... | python|arrays|algorithm|numpy | 1 |
354,114 | 62,954,156 | New column to get the previous date for a certain category (Python) | <p>I'm trying to create a certain prediction model. I decided to do the entire data manipulation with
python this time instead of with DAX (pbi) to learn python.</p>
<p>I have 2 columns that are relevant for this question : Customer and Date.
Each row is an invoice created for that customer at that certain date.</p>
<p... | <p>Firstly, looks like your <code>Date</code> column is of type string rather than datetime. Let's convert it to datetime. Then, sort the dataframe by <code>Date</code>.</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date')
# Output:
Customer Date
0 A 17/07/2020
1 B 15/07/2020
2... | python|pandas|data-science|data-manipulation | 0 |
354,115 | 62,972,000 | why is the accuracy constant but loss does change? | <p>As you can see below i have two functions , <code>get_data()</code> outputs a data frame for the selected asset history and passes it to <code>train_model()</code> every thing works fine but as the model trains the accuracy does not seem to change the loss does go down but the accuracy stays the same after the seco... | <p>From your loss function, it looks like you have a regression network. Your loss is Mean Squared Error and the metric accuracy does not have any meaning for regression networks. Accuracy metric is only meaningful when used for classification models. So you can remove the metrics=['accuracy'] from your compile code an... | python|tensorflow|keras | 1 |
354,116 | 62,960,403 | Batch Normalization while Transfer Learning | <p>I am currently transfer learning using the MobilenetV2 architecture. I have added several Dense layers on the top before my classification. Should I add <code>BatchNormalization</code> between these layers?</p>
<pre><code>base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(200,200,3))
x = ba... | <p>Batch Normalization will help with covariance shift and as you are training on new data batch-wise, it would be a good thing for the network. There is nothing as too much BatchNormalization, just put after every layer that is having activations in it.</p> | python|tensorflow|keras|transfer-learning|batch-normalization | 1 |
354,117 | 62,922,119 | How to turn a numpy array to a numpy object? | <p>I have a NumPy array as follows:</p>
<pre><code>[[[ 0 0]]
[[ 0 479]]
[[639 479]]
[[639 0]]]
</code></pre>
<p>and I would like to convert it into something like so:</p>
<pre><code>[( 0 0)
( 0 479)
(639 479)
(639 0), dtype=dtype([('x', '<i2'), ('y', '<i2')])]
</code></pre>
<p>I have tried... | <pre><code>In [117]: arr = np.array([[[0,0]],[[0,479]],[[639,479]],[[639,0]]])
In [118]: arr
Out[118]:
array([[[ 0, 0]],
[[ 0, 479]],
[[639, 479]],
[[639, 0]]])
In [11... | python|numpy | 1 |
354,118 | 63,175,828 | Convert numpy array into a bytestring readable by the src of an html img tag | <p>I have a numpy array that I want to display through the <code>src</code> attribute of an <code>img html</code> component, kinda like this exemple :</p>
<pre><code>def get_placeholder_thumbnail_html_value():
encoded_image = base64.b64encode(open("../assets/placeholder_thumbnail.png", 'rb').read())
r... | <p>I had basically the same problem, with the added condition that the image format needed to be png. Here's my solution using cv2 and base64:</p>
<pre class="lang-py prettyprint-override"><code>import cv2
import base64
def ndarray_to_b64(ndarray):
"""
converts a np ndarray to a b64 string reada... | python|html|image|numpy|html-parsing | 2 |
354,119 | 63,124,350 | Why do I get unstable values in an encoded dataframe for each time I run an autoencoder? | <p>I'm trying to find an optimal number of clusters on my data with elbow method and silhouette score while using KMeans. Although, I'm testing these methods using dimensionality reduction.</p>
<p>If I try PCA several times, I will get the same graphs for elbow method and silhouette every time. But if I try an encoder ... | <p>try to set the seed using this lines at the top of your code:</p>
<pre><code>tf.random.set_seed(33)
os.environ['PYTHONHASHSEED'] = str(33)
np.random.seed(33)
random.seed(33)
session_conf = tf.compat.v1.ConfigProto(
intra_op_parallelism_threads=1,
inter_op_parallelism_threads=1
)
sess = tf.compat.v1.Session... | tensorflow|cluster-analysis|autoencoder|encoder|dimensionality-reduction | 1 |
354,120 | 63,117,874 | Python convert string to date in dataframe | <p>I kindly ask you to help me with the following</p>
<p>I have a dataframe of string that I would like to convert to dates. Unfortunately, system generates an error</p>
<pre><code>Dataframe
ID col_1
0 1 \/Date(1529424891295)\/
1 2 \/Date(1529424891295)\/
2 3 \/Date(1529424891295)\/
def con... | <p>It seems like you forgot to add the row(<code>x</code>) that it's being modified:</p>
<pre><code>def convert_dates(timestamp_str):
timestamp2 = datetime.datetime.fromtimestamp(int(timestamp_str[7:20])/1000)
timestamp3 = timestamp2.strftime("%Y-%m-%dT%H:%M:%SZ")
return timestamp3
df['col_3'] = ... | python-3.x|pandas|dataframe | 2 |
354,121 | 63,229,237 | Finding the most frequent combination in DataFrame | <p>I have a DataFrame with two columns <code>From</code> and <code>To</code>, and I need to know the most frequent combination of locations <code>From</code> and <code>To</code>.</p>
<p>Example:</p>
<pre><code>From To
------------------
Home Office
Home Office
Home Office
Airport Home
Re... | <p>if the order does matter:</p>
<pre><code>df['FROM_TO'] = df['FROM'] + df['TO']
df['COUNT'] = 1
df.groupby(['FROM_TO'])['COUNT'].sum()
</code></pre>
<p>gives you all the occurrences in one go. Simply take the max to find the largest occurrence.</p>
<p>If the order does matter first sort the values before:</p>
<p>df... | python|pandas | 2 |
354,122 | 63,204,145 | Reading decimal representation floats from a CSV with pandas | <p>I am trying to read in the contents of a CSV file containing what I believe are IEEE 754 single precision floats, in decimal format.</p>
<p>By default, they are read in as int64. If I specify the data type with something like <code>dtype = {'col1' : np.float32}</code>, the dtype shows up correctly as float32, but t... | <p>CSV is a text format, IEEE 754 single precision floats are binary numeric format. If you have a CSV, you have text, it is not that format at all. If I understand you correctly, I think you mean you have text which represent integers (in decimal format) that correspond to a 32bit integer interpretation of your 32bit ... | python|pandas|numpy|csv|ieee-754 | 2 |
354,123 | 63,135,395 | How to plot a horizontal stacked bar with annotations | <ul>
<li><p>I used the example for Discrete distribution as horizontal bar chart example on matplotlib <a href="https://matplotlib.org/gallery/lines_bars_and_markers/horizontal_barchart_distribution.html#sphx-glr-gallery-lines-bars-and-markers-horizontal-barchart-distribution-py" rel="nofollow noreferrer">Discrete dist... | <ul>
<li>Both options us DataFrame <code>df</code> from the OP.</li>
<li>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><code>pandas.DataFrame.plot</code></a> with the parameter <code>stacked=True</code></li>
</ul>
<h2>Option 1: <code>'Party'</code> as th... | python|pandas|matplotlib|data-transform | 1 |
354,124 | 63,004,400 | Getting a UserWarning when calculating centroid of a GeoSeries | <p>Running the command <code>dataframe['geometry'].centroid</code> a warning is shown:</p>
<p><img src="https://i.stack.imgur.com/wDz1a.png" alt="" /></p>
<p>The column 'geometry' is made up of Multipolygon objects. How can I solve this issue to accurately calculate the centroid of my multipolygon's shapes?</p> | <p>This error could be solved by a projection to flat the surfaces down. The dataset I was using was a GeoDataFrame with a crs value of epsg=4326, as shown in the following screenshot</p>
<p><a href="https://i.stack.imgur.com/oFtUd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oFtUd.png" alt="https://i.stac... | python|geopandas | 10 |
354,125 | 63,014,556 | Cannot convert a list of "strings" to a tf.Dataset.from_tensor_slicer() - ValueError: Can't convert non-rectangular Python sequence to Tensor | <p>I have the following data:</p>
<pre class="lang-py prettyprint-override"><code>partial_x_train_features = [
[b'south pago pago victor mclaglen jon hall frances farmer olympe bradna gene lockhart douglass dumbrille francis ford ben welden abner biberman pedro cordoba rudy robles bobby stone nellie duran james fla... | <p>You will need to turn these strings into vectors, and pad them to equal length. I'll show you an example with just <code>partial_x_train_actors_array</code>:</p>
<pre><code>import tensorflow as tf
partial_x_train_actors_array = [b'victor mclaglen', b'jon hall', b'frances farmer',
b'... | python|tensorflow|keras|tensorflow-datasets | 3 |
354,126 | 63,010,065 | Tensorboard visualization don't appear in google collab | <p>I am implementing a simple linear regression code in google collab and trying to visualize the results with tensorboard with the following command
<code>%tensorboard --logdir=/tmp/lr-train</code>.</p>
<p>However, when I run this command, the tensorboard just simply does not show up. Instead I just see the following ... | <p>I tried your code in Colab and was able to reproduce what you mentioned and found a solution that worked as described below.</p>
<p>Use a ”space” between <code>—logdir</code> and <code>/tmp/lr-train</code> instead of a <code>=</code>.</p>
<p><strong>What did not work as mentioned in the question:</strong></p>
<pre><... | tensorflow|google-colaboratory|tensorboard | 1 |
354,127 | 63,316,921 | How can I loop over all Pandas Data Frames in the workspace? | <p>I would like to be able to iterate over all data frames (not the names!) that are currently in the workspace.</p>
<p>To get a list of all data frames I found the following solution <a href="https://stackoverflow.com/questions/41113663/pandas-get-a-list-of-all-data-frames-loaded-into-memory">here</a>:</p>
<pre><code>... | <p>This will yield the output you want as <code>dict</code>:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'Col1' : list(range(100))})
df2 = pd.DataFrame({'Col1' : list(range(100))})
alldfs = {key: value for key, value in locals().items() if isinstance(value, pd.core.frame.DataFrame)}
#or using your method
... | python|pandas|dataframe | 2 |
354,128 | 63,160,524 | What should be the size of input image for training a YOLOv3 Model Architecture CNN.? | <p>I've implemented a YOLOv3 from scratch and I plan to fine-tune using MS-COCO weights for some different data.
The dataset I've chosen has images of 720*1280 size.</p>
<p>When I go through the YOLOv3 paper, 1st CONV2d layer is there with filter_size =3 and stride = 1, and output size is 256*256....</p>
<p>Can someone... | <p>From <a href="https://pjreddie.com/media/files/papers/YOLOv3.pdf" rel="nofollow noreferrer">Yolov3</a> paper:</p>
<ul>
<li>If best possible accuracy/mAP is what you want then use <code>608 x 608</code> as input layer size in the <a href="https://github.com/AlexeyAB/darknet/blob/master/cfg/yolov3.cfg" rel="nofollow n... | pytorch|object-detection|yolo|conv-neural-network | 1 |
354,129 | 62,942,833 | Modeling five ordinary differenty equations, and plotting them | <p>I am new to python and coding in general, I have made this following code run with one set of parameters and now I have set four different functions that have each their own parameters to run. I would like these to all plot together so that we see a step function. thank you in advance. it gives following error</p>
<... | <p>You might want to replace</p>
<pre class="lang-py prettyprint-override"><code>for t in range(0,91):
plt.plot(t,xx[:,0],'b-',label = '$x_h$')
...
</code></pre>
<p>with</p>
<pre><code>plt.plot(t[0:91],xx[0:91,0],'b-',label = '$x_h$')
...
</code></pre>
<p>You might then perhaps also want to use the vector <code... | python|numpy|ode|odeint | 1 |
354,130 | 63,087,405 | How to write a function that changes the order of DataFrame columns? (Python) | <p>The function should move the 'profit' column to the beginning</p>
<pre><code><pre><code>
df1 = pd.DataFrame(np.array([[1, 2, 10], [4, 5, 20], [7, 8, 30]]), columns=['a', 'b', 'profit'])
df2 = pd.DataFrame(np.array([[1, 2, 20], [4, 5, 30], [7, 8, 40]]), columns=['a', 'b', 'profit'])
df3 = pd.DataFrame(np.... | <p>You need to change the line you call the function to:</p>
<pre><code>df1 = move_col(df1)
</code></pre>
<p>and you need to add a return.</p>
<p>so your code should be:</p>
<pre><code>df1 = pd.DataFrame(np.array([[1, 2, 10], [4, 5, 20], [7, 8, 30]]), columns=['a', 'b', 'profit'])
df2 = pd.DataFrame(np.array([[1, 2, 20... | python|pandas|dataframe | 0 |
354,131 | 63,308,344 | How do I exclude all rows with certain characters from my dataframe? | <p>I'm pulling data from a website through an API and sorting it into pandas dataframes. One of my dataframes has a column containing a value that has non-standard characters, which won't pass through to MySQL using .to_sql. I'd like to drop any rows that contain non-standard characters or find a way to eliminate the t... | <p>If you are using 3.7+, there is a function called <code>isascii()</code> - <a href="https://docs.python.org/3/library/stdtypes.html#str.isascii" rel="nofollow noreferrer">https://docs.python.org/3/library/stdtypes.html#str.isascii</a></p>
<pre><code>n [26]: import pandas as pd
In [27]: df['Colc'].tolist()
Out[27]:
... | python|mysql|pandas|dataframe | 1 |
354,132 | 63,026,079 | string matching - best distance algorithm to use | <p>I have two dataframes, <code>df1</code> and <code>df2</code>, that have information about polling stations. The dataframes are of different lengths. Both dataframes have a column called <code>ps_name</code>, which is the name of the polling stations, and a column called <code>district</code> that indicates which dis... | <p>One option is to use <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshtein distance</a> which is implemented in the package <a href="https://github.com/seatgeek/fuzzywuzzy" rel="nofollow noreferrer">fuzzywuzzy</a> (or <a href="https://chairnerd.seatgeek.com/fuzzywuzzy-fuz... | python|pandas|dataframe|string-matching|jaro-winkler | 0 |
354,133 | 63,039,828 | FileNotFoundError: [Errno 2] No such file or directory: 'Audio-Classification/wavefiles/b1' | <p>I am working over Audio Classification using deep learning and I am following a video series and stuck over one phase.
The below code is the written code in spyder:</p>
<pre><code>import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
... | <p>I think it’s just that your file directory is not set right.</p>
<p>It seems like your <code>wdir = 'C:/Users/atalp/Desktop/Audio-Classification'</code>.</p>
<p>So the read file line should be like <code>wavfile.read('wavefiles/' + f)</code> instead of <code>wavfile.read('Audio-Classification/wavefiles/' + f)</code>... | python|pandas|deep-learning | 0 |
354,134 | 63,186,185 | Given a list of strings, search a specific column for matching strings and return index value | <p>The goal: I have a excel sheet with three columns. "BigList" containing about ~1000 genes. "Expression" with numeric gene expression values. "SmallList" containing small list of ~10 genes I am interested in.</p>
<p>For each gene in "SmallList", I want to search for its index i... | <p>Here is a solution (if I understand the goal correctly). First, create test data:</p>
<pre><code>import pandas as pd
big = pd.DataFrame({
'gene': ['GeneA', 'GeneB', 'GeneC', 'GeneD', 'GeneE', ],
'expression': ['exp-A', 'exp-B', 'exp-C', 'exp-D', 'exp-E', ]})
small = pd.DataFrame({
'gene': ['GeneA', 'G... | python|excel|pandas | 0 |
354,135 | 63,141,782 | Webscraping different URLs - limit | <p>I have coded a web scraper for auto trader but for some reason when iterating through urls I can only ever get a maximum length of 1300 for my dataframe. There are 13 results per page so is there some sort of significance about a limit of 100 or am I just doing something wrong? Any help would be greatly appreciated ... | <p>Maybe just use a url shortener if the length of the url is too long</p> | python|pandas|web|web-scraping|beautifulsoup | 0 |
354,136 | 63,197,721 | I'm getting a ValueError: No gradients provided for any variable | <p>I'm having a bit of trouble trying to get my code to work</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import train_test_split
batch_size = 1
csv = "EmergeSync.csv"
val_csv = "EmergeSync.csv"
... | <p>So basically the error is correct there were no gradients found by the optimizer and can no longer update your network.</p>
<p>Now you need to ask yourself how are the gradients calculated. There are calculated by taking the partial derivative of your loss function w.r.t to all the parameters.</p>
<p>Your loss funct... | python|tensorflow | 0 |
354,137 | 62,991,870 | Jupiter Notebook Pandas read_csv Parse Error | <p>I try to Write a Dashboard using Python in Anaconda Jupiter Notebook. As first I want to read in CSV files from a online source and this is where the Problem begins :D</p>
<h2>Everything is written correctly but i have a Parse Error:</h2>
<pre><code> ParserError Traceback (most recent ... | <p>Please try by fetching contect as raw data from git repository:</p>
<pre><code>#In the latest version of pandas (0.19.2) you can directly pass the url
confirmed_df = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_con... | python|pandas|parse-error | 1 |
354,138 | 63,199,649 | Python - dataframe, for loop that interprets values of one column, plots range of rows | <p>I have a dataframe, with 3 columns: (timestamp, arduino read value #1, arduino read value #2) saved and imported via CSV. I basically need to plot several graphs based on this data, but am unsure how to structure what I seek.</p>
<p>Based on the individual values in column 3 (arduino read value #2), I need to plot c... | <p>You could try a version of the following:</p>
<pre><code>col1 = []
col2 = []
for i in range(len(df)+1):
if df['Column3'][i] > 0:
col1.extend(df['Column1'][i-5:i])
col1.extend(df['Column1'][i:i+6])
col2.extend(df['Column2'][i-5:i])
col2.extend(df['Column2'][i:i+6])
import matplotlib.pyplot as pl... | python|pandas|dataframe|matplotlib | 0 |
354,139 | 63,015,259 | In pandas, what is the difference between [list] and [[list]]? | <p>I'm sorry if this question is already answered, but I truly don't know the different names of either of those (object or list or array?), so I am still confused.</p>
<p>I'm just curious as a follow up from this question.</p>
<p><a href="https://stackoverflow.com/questions/59879577/pandas-getting-typeerror-only-integ... | <p>The relevant code you talk about in the linked question is:</p>
<pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'a': [1, 2]})
df2 = pd.DataFrame({'b': [3, 1]})
df1.columns = [['b']] # WRONG
df1.columns = ['b'] # CORRECT
df1.merge(df2, on='b')
</code></pre>
<p><code>df.columns</code> must be a... | python|pandas | 2 |
354,140 | 63,224,415 | pandas error in df.apply() only for a specific dataframe | <p>Noticed something very strange in pandas. My dataframe(with 3 rows and 3 columns) looks like this:</p>
<p><a href="https://i.stack.imgur.com/ZsxwL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZsxwL.png" alt="enter image description here" /></a></p>
<p>When I try to extract ID and Name(separated... | <p>From the doc of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">pandas.DataFrame.apply</a> :</p>
<p>'broadcast' : results will be <strong>broadcast to the original shape</strong> of the DataFrame, the original index and columns will be retain... | python|pandas|data-science|data-cleaning | 2 |
354,141 | 62,909,144 | Fill NaN values based on specific condition in pandas | <p>I have a dataframe as shown below</p>
<pre><code>Date t_factor t1 t2 t3 t_function
2020-02-01 5 4 NaN NaN 4
2020-02-03 23 6 NaN NaN 6
2020-02-06 14 9 NaN NaN ... | <p>We can define a function for that</p>
<pre><code>def imporove(iterable):
for i in range(len(iterable)):
if iterable[i].isnull() == True:
iterable[i] = iterable[i-1]
</code></pre>
<p>I hope you got a basic idea.
now you can pass
<code>df['t1'].apply(improve)</code></p> | python-3.x|pandas | 1 |
354,142 | 62,981,621 | Pytorch how to increase batch size | <p>I currently have a tensor of torch.Size([1, 3, 256, 224]) but I need it to be input shape [32, 3, 256, 224]. I am capturing data in real-time so dataloader doesn't seem to be a good option. Is there any easy way to take 32 of size torch.Size([1, 3, 256, 224]) and combine them to create 1 tensor of size [32, 3, 256... | <p>You are probable using jit model, and the batch size must be exact like the one the model was trained on.</p>
<pre><code>t = torch.rand(1, 3, 256, 224)
t.size() # torch.Size([1, 3, 256, 224])
t2= t.expand(32, -1,-1,-1)
t2.size() # torch.Size([32, 3, 256, 224])
</code></pre>
<p>Expanding a tensor does not allocate ne... | python|numpy|opencv|pytorch|onnx | 1 |
354,143 | 62,976,926 | How to change mlmultiarray to string | <p>I am using a CoreML converted from a TensorFlow model for iOS. When I converted, the output is mlmultiarray, instead of the expected dictionary and string types.
Thus, the output would not be readable at all.
How would you fix this?
Thanks!</p> | <p>When you convert the model from TF to Core ML, you need to tell the converter this is a classifier. The easiest way to do this is to provide a text file (or array) containing the class labels when you run the converter.</p> | ios|swift|tensorflow|coreml|coremltools | 0 |
354,144 | 63,248,562 | How to handle a .csv input for use in Tensorflow Serving batch transform? | <p><strong>Information:</strong>
I am loading an existing trained model.tar.gz from an S3 bucket, and want to perform a batch transform with a .csv containing the input data. The data.csv is structured in such a way that reading it into a pandas DataFrame gives me rows of complete prediction inputs.</p>
Notes:
<ul>
<li... | <p><strong>Solution:</strong> The problem was solved by saving the dataframe as .csv using the arguments header=False, index=False. This makes the saved csv not include the dataframe indexing labels. TFS accepted a clean .csv with only float values (without labels). I assume the error message <em>Invalid argument: JSON... | csv|amazon-s3|tensorflow-serving|amazon-sagemaker | 2 |
354,145 | 62,976,805 | Pandas rows do columns | <p>Hello I have this <a href="https://i.stack.imgur.com/EWKUx.jpg" rel="nofollow noreferrer">hull line rows</a> that I want to convert to this <a href="https://i.stack.imgur.com/vNc5u.jpg" rel="nofollow noreferrer">keeping x and y coordinates as columns</a>. I try many things, but I could not took results</p> | <p>if u want each row to list do something like this</p>
<pre><code>Row_list =[]
for index, rows in df.iterrows():
new_list =[rows.column1, rows.column2, rows.column3]
Row_list.append(new_list)
</code></pre>
<p>df is the dataframe</p> | python|pandas | 0 |
354,146 | 63,258,554 | Pandas: Index Not Preserved when performing Groupby Rolling on Datetime | <p>I have a dataframe where some dates are the same. As an illustration of the problem, I have created a sample df with dates all the same.</p>
<pre><code>df = pd.DataFrame({"column1": range(6),
"column2": range(6),
'group': 3*['A','B'],
'd... | <p>You can use <code>.reset_index()</code> and then include that <code>index</code> column as a resull of the rest with <code>.groupby</code> and <code>.agg</code>. I imagine this will be much faster than lambda x.</p>
<pre><code>df = pd.DataFrame({"column1": range(6),
"column2": ran... | python|pandas | 0 |
354,147 | 63,213,881 | PyTorch tensors have same value after being added to a list | <p>While learning gradients and optimizing the process by Pytorch, I wanted to figure out the change of loss function values vs weights values with the graph. While I tried to graph, I used both <code>numpy</code> and <code>torch</code>, because I wanted to compare. During to store list of grad. and loss function value... | <p><code>w.grad</code> is a tensor; it (the <strong>same</strong> tensor) is appended to the list at each iteration, so the list contains copies of the same tensor, not copies of its <strong>value</strong> at each point in time as you'd probably intend.</p>
<p>The standard way of handling this is to use:</p>
<pre><code... | python|numpy|pytorch|gradient | 1 |
354,148 | 63,017,751 | Why is only one dataframe formatted correctly? | <p>I'm working on a personal project and came across something that I didn't understand the outcome of. My aim was to split my list-type column into individual columns (each column having one element of the list) and I was able to do that successfully. However, one way of implementing it doesn't give the result I want,... | <p>What I was trying to explore in my comments was how the 'lists' were loaded from the <code>csv</code>.</p>
<p>If I make a dataframe with list elements:</p>
<pre><code>In [314]: df = pd.DataFrame([None,None], columns=['data'])
In [315]: df['data']=[[1,2,3], [4,5]] ... | python|pandas|numpy | 1 |
354,149 | 62,937,585 | Python Pandas: Shape of passed values is (126, 5), indices imply (84, 5) | <p>I have 2 dataframes with 84 rows, clearly the same lengths, but when i want to concat them to 1 df (concat by column - to have the name, Edge and Offset to the right of Latitude and Longitude), i get this error,.</p>
<p>what is going on?</p>
<pre><code> Latitude Longitude
0 45.403538 -75.735729
1 45.403506 ... | <p>I got it:</p>
<pre><code> name Edge Offset
0 TUN-W 1 3000
1 TUN-E 2 3000
2 BAY-W 5 102510
3 BAY-E 6 102579
4 PIM-W 5 186035
.. ... ... ...
37 PTSTTW 33 52710
38 PTSTTE 34 18997
39 PAG11 40 24362
40 PAG14 50 9927
41 PHND15 177 11662
</code></... | python|pandas | 1 |
354,150 | 63,003,382 | Randomly select rows from DataFrame Pandas | <p>Okay this is somewhat tricky. I have a DataFrame of people and I want to randomly select 27% of them. I want to create a new Boolean column in that DataFrame that shows if that person was randomly selected.</p>
<p>Anyone have any idea how to do this?</p> | <p>The in-built <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="nofollow noreferrer"><code>sample</code></a> function provides a <code>frac</code> argument to give the fraction contained in the sample.</p>
<p>If your <code>DataFrame</code> of people is <code>people... | python|pandas | 1 |
354,151 | 63,305,154 | SQLAlchemy cannot autoload an mssql temporary table | <p>I'm not able to connect to temporary tables created on an SQL server using SQLAlchemy.</p>
<p>I connect to the server:</p>
<pre><code>engine = create_engine(URL, poolclass=StaticPool)
</code></pre>
<p>I fill a temporary table with data from a pandas dataframe:</p>
<pre><code>df_tmp.to_sql('#table_test', con=engine)
... | <p>(re: comments to the question)</p>
<p>Actually, it is a limitation of the current mechanism by which SQLAlchemy's <code>mssql</code> dialect checks for the existence of a table. It queries <code>INFORMATION_SCHEMA.TABLES</code> for the current catalog (database), and <code>#temp</code> tables do not appear in that v... | python|sql-server|pandas|sqlalchemy|pyodbc | 5 |
354,152 | 62,918,158 | Dynamically capture the values in loop while creating a pandas dataframe | <p>While creating the dataframe, I would like the year and month value to get captured in the variable. For example, for first pass, dataframe name should be df_2019_1 and so on. Any suggestions would be appreciated !!!</p>
<pre><code>year = [2019]
month = [1,2,3]
for year in year:
for month in month:
df_year_... | <p>You cannot access names like this in python, but you can store them in a dictionary, also <code>year in year</code> is overriding.</p>
<pre><code>years = [2019]
months = [1,2,3]
df_dict = {}
for year in years:
for month in months:
df_dict[(year, month)] = pd.DataFrame()
print(df_dict[(2019, 1)])
</code></pr... | python|pandas | 1 |
354,153 | 63,034,982 | Can't access Pandas | <p>Hi I am having major trouble with shell.
I am not able to change the path for pip and python.
Python 3.7 is downloaded elsewhere.
Pip has an unknown path. I tried upgrading pip but it stored a blob of code and I don't know what to do with it.
Pandas not available on terminal (shell) which uses python 2.7.</p>
<p>Err... | <p>Have you tried pip3 install yet?</p>
<p>pip could default to the installation of pip for python2 as well.</p>
<p>Finally, if it is doable in your system, you may uninstall python 2 completely as it is out of support anyway, this would save you a lot of headache in the future!</p> | python|pandas|pip | 0 |
354,154 | 63,185,991 | loadtxt to structured array and adding one column with value from filename | <p>i`m new to python and nupmy.</p>
<p>I have to import some Data from txt-File and insert it to a postgresql database.</p>
<p>I read the data this way:</p>
<pre><code>type_definitions = ([('StationID', 'S4'), ('East', np.float), ('North', np.float), ('Height', np.float)])
filename = os.path.join(directory, file)
day =... | <p>Ok,i did it.
Not really elegant,but it works.</p>
<pre><code>weekday = int(day)
for i in range(0, len(DataSet[day]['StationID'])-1):
StationID = DataSet[day]['StationID'][i].decode('UTF-8')
East = DataSet[day]['East'][i]
North = DataSet[day]['North'][i]
Height = DataSet[day]['Height'][i]
sql_quer... | python|numpy|structured-array | 0 |
354,155 | 62,916,215 | Pytorch dataloader Transforms tensor error | <p>[<img src="https://i.stack.imgur.com/jrBni.png" alt="The dataset class][1]" /><a href="https://i.stack.imgur.com/iYlqo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iYlqo.png" alt="The transforms applied to the image" /></a>Unable to access the pytorch dataloader values for use
TypeError: defaul... | <p>Why don't you try <code>img = img.resize((1024, 1024))</code> before the transformation inside the <strong>getitem</strong>() method?</p>
<pre><code>def __getitem__(self, idx):
row = self.df.loc[idx]
img_id, img_label = row['Image Index'], row['disease_vec']
img_fname = row['path']
img = Image.open(i... | python|pytorch|image-preprocessing|dataloader | 0 |
354,156 | 62,987,369 | Python function appended values as list values into my dataframe. How to normalize? | <p>I applied a function to append a list of values to my dataframe using this code:</p>
<pre><code>lat=[]
for i in addresses['whole_address']:
try:
lat.append([locator.geocode(f'{i}').latitude])
except: lat.append('na')
addresses["latitude"]=lat
</code></pre>
<p>My output in data fram... | <p>I recommend using the apply function.</p>
<pre><code>def df_geocode(row):
try:
lat = [locator.geocode(f'{row['whole_address']}').latitude]
except:
lat = 'na'
return lat
address["Latitude"] = addresses.apply(df_geocode, axis=1)
</code></pre> | python|pandas | 0 |
354,157 | 62,985,888 | Tensorflow 2.2 does not find GPU on my Microsoft Windows Surface book 3-- no CUDA-capable device is detected | <p><a href="https://i.stack.imgur.com/ZetLe.png" rel="nofollow noreferrer">deviceQuery confirms Computer has Cuda capable device</a>
I get this error after seemingly to load cuda files:</p>
<pre><code>2020-07-19 17:18:41.922056: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic... | <p>I got this solved by adding:
<code>os.environ['CUDA_VISIBLE_DEVICES'] = "0"</code></p> | python|tensorflow|deep-learning|gpu | 0 |
354,158 | 63,046,990 | geopandas plotting - Identify locations that fall outside of the map | <p>I have a <code>shapefile</code> that shows the map of Pakistan at district level. I also have a <code>geodataframe</code> that has information about polling stations in Pakistan.</p>
<p>I have mapped the <code>geodataframe</code> on to the <code>shapefile</code>, but noticed that some lat/lon values from the <code>g... | <p>I suspect that the geometries of Pakistan you use are the problem. They are too complex and detailed to use. In your use-case, simple geometry provided by <code>naturalearth_lowres</code> should give better performance. Here I provide a runnable code that demonstrates the use of simple Pakistan geometry to perform <... | plot|gis|shapes|shapefile|geopandas | 1 |
354,159 | 62,941,939 | Drop almost duplicates rows based on timestamp | <p>I'm trying to remove some data almost duplicates. I'm looking for a way to detect the closest (<code>edited_at</code>) trip made by the user without losing informations.</p>
<p>So I want to solve this problem by calculating the difference between succesive timestamps and I remove minimum difference (zero in this exa... | <p>Because your DataFrame is duplicated with respect to <code>['user_id', 'prompt_uuid']</code> taking a simple <code>diff</code> does not give the time difference between successive groups. First <code>drop_duplicates</code> then calculate the time difference within each <code>'user_id'</code>. You can then filter thi... | pandas|pandas-groupby|drop-duplicates | 0 |
354,160 | 62,898,732 | Histograms with a lot of dimensions in Python | <p>I'm doing a simulation of a stochastic many-body system, and currently I need to obtain a multidimensional probability distribution from generated data. For this purpose, I was trying to use <code>np.histogramdd</code> as in:</p>
<pre><code>bins = np.linspace(start = -x_max, stop = x_max, num = n_bins)
hists = np.hi... | <p>In the third case, dims=10, you are getting an error due to overflow. A relevant thread is adding here:
<a href="https://stackoverflow.com/questions/39089618/why-is-numpy-prod-incorrectly-returning-negative-results-or-0-for-my-long-li">Why is numpy.prod() incorrectly returning negative results, or 0, for my long lis... | python|numpy|bigdata|histogram | 0 |
354,161 | 67,970,400 | How to access array from vectors by time index | <p>Let's say I have four different vectors from a measurement, where each index corresponds to a certain time. Meaning that the values "1, 4, 7, 10" or also "2, 5, 8, 11" of the following example belong together. I now want to create a matrix, which allows to be accessed by time index. With time ind... | <p>Since mat is a 3-dim array (and not a matrix), you should use:</p>
<pre><code>print(mat[:,:,0])
</code></pre> | python|numpy | 1 |
354,162 | 67,788,097 | Calling specific dictionary values from a dictionary with multiple values per key, Python | <p>I have a df that contains columns for vendor_name, street_address, city, state, country, zip_code. I've converted this to a dictionary:</p>
<p>vend_dict = vendor.to_dict</p>
<p>I have another df that has a column for vendor_name, but is missing all address info. I would like to map the dictionary against the new dat... | <p>Looks like you need to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a> the data frames instead of your current method.</p>
<p>For example, if you had data like:</p>
<pre><code>df1:
vendor_name | street_address | city | state | coun... | python|pandas|dictionary|mapping | 0 |
354,163 | 67,954,722 | Changing some values in df column based on another | <p>I have a df with multiple columns and values. Say:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>Jo</td>
<td>$10</td>
</tr>
<tr>
<td>345</td>
<td>Bella</td>
<td>$20</td>
</tr>
<tr>
<td>567</td>
<td>IgnoreM... | <p>Try:</p>
<pre><code>names_to_ignore = ['ignoreme','IgnoreMe']
</code></pre>
<p>Finally:</p>
<pre><code>c=df['Name'].isin(names_to_ignore) #checking if this condition satisfies or not
df.loc[c,'Cost']=float('NaN')
</code></pre>
<p><strong>OR</strong></p>
<p>via <code>np.where()</code>:</p>
<pre><code>#import numpy a... | python|python-3.x|pandas | 1 |
354,164 | 67,918,429 | How to create columns based on string | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Item</th>
<th style="text-align: right;">Date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">Bread,Muffin</td>
<td style="text-align: right;">1/3</td>
</tr>
<tr>
<td style="text-align: left;">Jam,Cake</td>... | <p>If need <code>1</code> if value exist in column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>Series.str.get_dummies</code></a>:</p>
<pre><code>df = df.join(df.pop('Item').str.get_dummies(',').replace(0, ''))
print (df)
Da... | python|pandas | 4 |
354,165 | 67,701,915 | tf.nn.conv2d_transpose() double width and height for dynamic shapes of input tensor | <p>When I tried to use <strong>tf.nn.conv2d_transpose()</strong> to get layer result which has doubled width, height and halved depth, it worked while using specified <strong>[batch, width, height, channel(input and output)].</strong></p>
<p>By setting <strong>batch_size="None",</strong> training works well f... | <p>Self answer...</p>
<p>I cannot come up with suitable 'standard' solution to set w, h as None property for transpose convolution.</p>
<p>However I solved problem by giving transpose convolution's shape as maximum shape of my training/validation images. For example, if the maximum width and height of my images = [656 ... | python|tensorflow|machine-learning|deep-learning | 0 |
354,166 | 67,949,696 | How to build pd series with user input iteratively one cell at a time? | <p>I am trying to categorize the remaining default cats in a pd series with my own input data:</p>
<pre><code>ex_df = df[df['Cat_Self_Pred'] == 'Uncatted'][['Content','Amount','Cat_Self_Pred']] # shallow copy, so that the orig df is changed
for x in range(len(ex_df)): # how ever many this would be
print(ex_df[['Co... | <p><code>ex_df</code> is a the result of 2 “indexing” operations on the dataframe, so assigning to it will always generate a warning. Basically it could be a <code>view</code> (what you call a shallow copy) or a <code>copy</code>.</p>
<p>See <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html... | python|pandas|dataframe|input|series | 1 |
354,167 | 67,891,853 | Deleting times in a dataframe based on the current time | <p>I have the following data frame denoted by dfm.</p>
<p>My aim is to eliminate the rows with the time within 2.5hrs of the current time.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>time</th>
<th>A</th>
<th>year</th>
<th>time2</th>
<th>new_column</th>
<th>dateTime</th>
</tr>
... | <p>First thing, change ct into pd.datetime. I am not certain about the compatibility between python datetime and pandas datetime. You can basically filter after that.</p>
<p>For instance, code I use for changing now into pd.datetime is:</p>
<pre><code>from datetime import date, timedelta
now = datetime.datetime.now()
d... | python|pandas|dataframe|datetime | 1 |
354,168 | 67,610,083 | Python/MatPlot Save Graph Objects to One File | <p>I have a program that reads data in from SQL server, passes it to an object class via a loop, creates 6 graphs as objects, and saves each to a file. I'm trying to save all to the same file (file type does not matter PDF, jpg, etc.)</p>
<pre><code>#main
...
data = pd.dataframe(pd.read_sql("Select * from FOO"... | <p>FYI,</p>
<p>While awaiting answers, I decided to try a different approach by reading the created .png files into a pdf versus creating one document plotting or displaying the objects themselves. This is what worked for me if anyone is researching this in the future and wanting different options:</p>
<pre><code>from ... | python|numpy|matplotlib | 0 |
354,169 | 67,967,493 | Instead of appending values, pandas appends a column of NaNs. Why? | <p>Why do I get NaN value when adding values in the b column and not for a?
This is the code:</p>
<pre><code>df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
#extract all rows where a is present in the grps column
#for each... | <p>Try the following:</p>
<pre><code>df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
#extract all rows where a is present in the grps column
#for each a in a row, create an entry in a column (index 'a') in newdf from corresponding... | python|pandas|dataframe | 1 |
354,170 | 67,907,994 | Multiple based on different data frame | <p>I have two dataframes:
df1:</p>
<pre><code> Name Segment Axis 1 2 3 4 5
Amazon 1 slope NaN 2.5 2.5 2.5 2.5
Amazon 1 x 0.0 1.0 2.0 3.0 4.0
Amazon 1 y 0.0 0.4 0.8 1.2 1.6
Amazon 2 slope NaN 2.0 2.0 2.0 2.0
Amazon 2 x 0.0 ... | <p>Try this:</p>
<pre><code>#merge df2 to align to df1
u = df1.merge(df2,on=['Name','Segment'],how='left')
#find columns to multiply the cost
cols = df1.columns ^ ['Name','Segment','Axis']
#multiply and assign back
df1[cols] = u[cols].mul(u['Cost'],axis=0).where(df1['Axis'].eq('slope'),df1[cols])
</code></pre>
<hr />
<... | python|pandas|numpy | 3 |
354,171 | 67,896,539 | what if the size of training set is not the integer multiple of batch size | <p>I am running the following code against the dataset of <a href="https://www.kaggle.com/fvcoppen/solarpanelspower" rel="nofollow noreferrer">PV_Elec_Gas3.csv</a>, the network architecture is designed as follows</p>
<pre><code>class CNN_ForecastNet(nn.Module):
def __init__(self):
super(CNN_ForecastNet,sel... | <h1>NO!!!!</h1>
<p><a href="https://i.stack.imgur.com/jDq4n.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jDq4n.gif" alt="enter image description here" /></a></p>
<p>In your <code>forward</code> method you <code>x.view(-1)</code> before passing it to a <code>nn.Linear</code> layer. This "flatt... | pytorch | 2 |
354,172 | 67,726,112 | Filter data with some conditions | <p>I have a dataframe</p>
<pre><code>username score
1 0.0008
1 0.1
1 0.000009
2 0.2
2 0.0098
2 0.7
3 0.99
3 0.019
3 0.0001
</code></pre>
<p>I need to filter using that condition</p>
<pre><code>d = {1: 0.05, 2: 0.01, 3: 0.02}
</code></pre... | <p>You can <code>map</code> the <code>username</code> with your dictionary <code>d</code> and then with boolean indexing, only select those that have <code>score</code> <code>l</code>ess <code>t</code>han the mapping result:</p>
<pre><code>df[df.score.lt(df.username.map(d))]
</code></pre>
<p>to get</p>
<pre><code> us... | python|pandas | 5 |
354,173 | 67,787,062 | Pandas: how to aggregate data weekly? | <p>I have a pandas dataframe the looks like the following:</p>
<pre><code>df
date lat lon val
0 2010-09-01 38.5437 -9.50659 6
1 2010-09-02 38.5437 -9.50659 3
2 2010-08-10 38.5437 -9.50659 1
3 2010-08-11 38.5437 -9.50659 5
4 2010-08-12 38.5437 -9.50659 6
</code></pre>
... | <p>Convert <code>val</code> to numeric first and then remove <code>[]</code> around <code>'lat', 'lon'</code>:</p>
<pre><code>df['val'] = pd.to_numeric(df['val'])
df['date'] = pd.to_datetime(df['date'])
df = (df.groupby(['lat', 'lon', pd.Grouper(key='date', freq='W-MON')])['val']
.mean()
.reset_index(... | python|pandas | 4 |
354,174 | 67,875,106 | Mean between two datetimes; if NaN, get last non-NaN value | <p>Yesterday I asked <a href="https://stackoverflow.com/questions/67857428/pd-dataframe-get-average-value-per-id-between-two-datetimes-if-nan-get-last-n">this</a> question (with some good answers) which is very similar, but slightly different from the problem I'm presented with now. Say I have the following <code>pd.Da... | <p>Create a temp column <code>between_time</code>. Then Groupby <code>id</code> column and then, in <code>apply</code> add the condition - > If for a particular <code>id</code> is there any value that lies within the range? If yes, take the mean else take the value present at <code>last_valid_index</code>.</p>
<pre>... | python|pandas|dataframe | 2 |
354,175 | 68,025,540 | I am trying to manipulate the pixel values without clipping them | <p>I have an image which has a max pixel value - <code>287.4976094062538</code> and min pixel value - <code>-41.082841881780645</code> I am trying to bring them in range between <code>0-255</code></p>
<p>what I did:-</p>
<ul>
<li>I have divided all the pixel values with max pixel value and then multiplied with 255</li>... | <p>Scikit-image has function for this:</p>
<p><a href="https://scikit-image.org/docs/dev/api/skimage.exposure.html#skimage.exposure.rescale_intensity" rel="nofollow noreferrer">https://scikit-image.org/docs/dev/api/skimage.exposure.html#skimage.exposure.rescale_intensity</a></p>
<p>It maybe better to rescale it to rang... | python|image|numpy|image-processing|computer-vision | 2 |
354,176 | 67,613,244 | Python - Getting keyError(key) when using groupBy.agg() | <pre><code>import pandas as pd
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict2 = {
"brand": "Ford",
"model": "F150",
"year": 1999
}
dict3 = {
"brand": "Chevy",
&... | <p>Use <code>.iloc</code>:</p>
<pre><code>grouped = df.groupby('col0')
first = lambda a : a.iloc[0]
df = grouped.agg({'col1':first, 'col2': first, 'col3': first})
</code></pre> | python|pandas | 1 |
354,177 | 67,899,436 | Error when selecting rows in pandas dataframe based on column value | <p>I have a dataframe <code>df</code> which looks like this:</p>
<pre><code>col1 col2 col3
A 45 4
A 3 5
B 2 5
</code></pre>
<p>I want to make a separate dataframe, <code>df2</code>, which only has the rows where <code>col</code> in <code>df</code> equals <code>A</code>. Hence it should look l... | <p>What you tried works for me, you can try this:</p>
<pre><code>df2 = df[df.col1 == 'A']
</code></pre>
<p><strong>Output</strong></p>
<pre><code> col1 col2 col3
0 A 45 4
1 A 3 5
</code></pre>
<p><strong>Edit</strong>
Tested on pandas version</p>
<pre><code>pd.__version__
'1.2.4'
</code></pre> | python|pandas|dataframe | 2 |
354,178 | 67,811,345 | Boolean filter geopandas dataframe following shapely within | <p>I have a geopandas dataframe I perform a convexhull operation on a multipoint dataset using shapely.</p>
<pre><code>top_sample_col.within(cvh_base)
</code></pre>
<p>This returns a boolean, how do I assign to a new gdf only those that are assigned true? (option A)</p>
<p>I can use <code>.set_index()</code> but then h... | <p>You can pass the boolean array as a mask directly.</p>
<pre class="lang-py prettyprint-override"><code>df = df.loc[top_sample_col.within(cvh_base)]
</code></pre> | pandas|geopandas|shapely | 1 |
354,179 | 67,806,700 | Merge rows in Pandas dataframe based on common columns, while appending some fields | <p>Please excuse me if this is a very basic question I am a relative beginner with both Python and Pandas.</p>
<p>I have a csv file of observations and classifications. Each observation appears multiple times in the results as the classification is repeated using different training data, indicated by the "split_on... | <p>use <code>pivot</code>:</p>
<pre><code>from statistics import mode
k = df.pivot(index=['datetime', 'bID', 'data1', 'data2', 'data3'], columns=[
'split_on'], values=['probability', 'prediction'])
k.columns = k.columns.map(lambda x: '_'.join(x[::-1]))
df = k.reset_index()
df['prediction_avg'] = df.filt... | python|pandas|dataframe | 1 |
354,180 | 67,695,336 | AttributeError: module 'tensorflow_core.compat.v2' has no attribute '__internal__' (Worked a week ago?) | <p><a href="https://i.stack.imgur.com/g1W5k.png" rel="nofollow noreferrer">Image: Error Message and Script</a></p>
<p>I am working on Google Colab and do not have much experience with Python. The image above has code that is from <a href="https://github.com/smousavi05/EQTransformer" rel="nofollow noreferrer">https://gi... | <p>! pip install tensorflow==1.15.0
! pip uninstall keras-nightly
! pip install keras==2.0.8
like this</p> | python|tensorflow | 0 |
354,181 | 67,845,362 | Sort pandas df subset of rows (within a group) by specific column | <p>I have the following dataframe let’s say:</p>
<p>df</p>
<pre><code>
A B C D E
z k s 7 d
z k s 6 l
x t r 2 e
x t r 1 x
u c r 8 f
u c r 9 h
y t s 5 l
y t s 2 o
</code></pre>
<p>And I would like to sort it based on col D for each sub row (that has for example same cols A,B and C in this case)</p>
<p>The expected output... | <p>I think it should be as simple as this:</p>
<pre class="lang-py prettyprint-override"><code>df = df.sort_values(["A", "B", "C", "D"])
</code></pre> | python|pandas|dataframe|numpy | 5 |
354,182 | 67,978,919 | Pandas: Cannot subtract date-time objects (timedelta, datetime) | <p>Here is the setup:</p>
<pre><code>Python 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:00:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help.
import pandas as pd
import numpy as np
from datetime import datetime, timede... | <p>I have not touched <code>NaT values</code>, please feel free to fill them with 0 or other values, if required.</p>
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer">pd.timedelta</a> along with <code>dt</code> accessor and then apply ... | python|pandas|datetime|timestamp|timedelta | 0 |
354,183 | 67,986,537 | How do I check for conflict between columns in a pandas dataframe? | <p>I'm working on a Dataframe which contains multiple possible values from three different sources for a single item, which is in the index, such as:</p>
<pre><code>import pandas as pd
import numpy as np
inp = [
{"Item": "Item1", "Local A": np.nan, "Local B": 6, "Local ... | <p>IIUC, try:</p>
<pre><code>df['Conflict'] = np.where((df.iloc[:, 1:].nunique(axis=1) != 1),'Yes',np.nan)
</code></pre>
<p>Output:</p>
<pre><code> Item Local A Local B Local C Conflict
0 Item1 NaN 6.0 5 Yes
1 Item2 6.0 7.0 5 Yes
2 Item3 NaN NaN 5 ... | python|python-3.x|pandas|dataframe | 1 |
354,184 | 67,835,626 | Generate html from pandas dataframe | <p>Pardon me I am new to handle html through pandas and having trouble generating required format</p>
<p>I have dataframe like below</p>
<pre><code>Category Date Avg Price - growth (%) Profit Overall profit
A 4/18/2021 34.30% 706.10% 669.60%
B 4/18/2021 97.4... | <p>To structure your data you can try this</p>
<pre><code>>>> df.groupby(['Date','Category']).sum().unstack('Category').swaplevel(0,1,axis=1).sort_index(axis=1)
Category A B C
AVG_Price Overall_profit Profit AVG_Price Overal... | python-3.x|pandas|dataframe|pandas-styles | 1 |
354,185 | 67,986,807 | Create Pandas DataFrame from a list and list of lists | <p>I have two python lists</p>
<pre><code>messages = ['message1', 'message2', 'message3']
labels = [[1,0,1,3,1], [1,1,2,0,3], [0,0,2,1,0]]
</code></pre>
<p>I am creating dataFrame which will take <strong>messages</strong> as first column and <strong>labels</strong> as <strong>cat_1, cat_2, cat_3, cat_4, cat_5</strong>... | <p>If no problem with starting by <code>0</code> for new columns names use <code>DataFrame</code> constructors with <code>join</code>:</p>
<pre><code>df = pd.DataFrame({'message': messages}).join(pd.DataFrame(labels).add_prefix('cat_'))
print (df)
message cat_0 cat_1 cat_2 cat_3 cat_4
0 message1 1 0... | python|python-3.x|pandas|list|dataframe | 4 |
354,186 | 67,772,345 | Get rows with same value combination in seperate columns using pandas | <p>I am trying to perform entity matching for the first time and want to "get rid" of the obvious matches first, so I can focus working with the fuzzy cases. I have a dataset of almost 600.000 entries containing information about clothes.</p>
<p>What I need is all different prices of the suppliers that have t... | <p>My idea is two concatenate two dataframes - one dataframe without duplicates and dataframes where we have prices for each type. I believe it could be done by using fewer lines, but I will give you my solution as there are no other:</p>
<pre><code>pd.concat([
(
df.drop_duplicates(subset=['product_id', 'co... | python|pandas|group-by|pandas-groupby | 1 |
354,187 | 67,742,402 | ImportError: Could not find the DLL(s) 'msvcp140.dll or msvcp140_1.dll' | <p>I am following this tutorial <a href="https://youtu.be/iPwepy-SVCQ?t=404" rel="nofollow noreferrer">YOLOv4 Object Detection with TensorFlow</a></p>
<p>while running this script</p>
<pre><code># Convert darknet weights to tensorflow
## yolov4
python save_model.py --weights ./data/yolov4.weights --output ./checkpoints... | <p>I have dealt with the exact problem , Search the file name in google you will get the correct file ,Download it the site you are downloading from will show you the path to paste that folder too ; If your not able to get that file i can provide you the corresponding <code>dll</code> files download links too...</p> | python|python-3.x|tensorflow|dll|yolo | 0 |
354,188 | 68,022,719 | Python getting shared memory: size is not consistent | <p>Process 1:</p>
<pre><code>shm=multiprocessing.shared_memory.SharedMemory(name="shm", create=True, size=10000)
print(shm.size)
</code></pre>
<p>Prints 10000</p>
<p>Process 2:</p>
<pre><code>shm=multiprocessing.shared_memory.SharedMemory(name="shm")
print(shm.size)
</code></pre>
<p>Prints 12288</p>... | <p>shared memory is rounded to the next page size, which is in your case 3 * 4096. You have to slice the buffer to the correct size</p>
<pre><code>shm = multiprocessing.shared_memory.SharedMemory(name="shm")
buffer = shm.buf[:10000]
</code></pre> | python|numpy|shared-memory | 2 |
354,189 | 67,891,563 | Python How to plot "grouped by" scatter on (mean of column vs percentile) | <p>I have the following dataframe <code>df_male</code>:</p>
<p><a href="https://i.stack.imgur.com/h4KT0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h4KT0.png" alt="enter image description here" /></a></p>
<p>And I used groupby() to see mean value of <code>gagne_sum_t</code> column on each <code>r... | <p>I don't think you need to do <code>group_by</code> again. You can start plotting from the grouped dataframe. You already have this:</p>
<pre><code>plot_df = df_male.groupby(["risk_percentile","race"]).aggregate(np.mean)
</code></pre>
<p>If you have pyplot (typically imported as <code>plt</code>) ... | python|pandas-groupby|scatter-plot | 0 |
354,190 | 67,969,224 | Recursively group rows and columns of python DataFrame | <p>I have a DataFrame representing the similarity of row items with column items with an index from 0 to 1.
I want to group the more similar items and create a new dataframe by dropping the grouped items rows and columns and then adding a single row and column both indexed with a tuple containing the 2 merged items, an... | <p>I case you're still looking for a solution ...</p>
<p>I think the problem with <code>.append</code> stems from an index misinterpreation. The tuple is most likely leading to a <code>MultiIndex</code> which then collides with the labels of the dataframe (I've looked a bit into the respective Pandas implementation but... | python|pandas|recursion|tuples|multi-index | 1 |
354,191 | 67,706,732 | How to color dataframe based on each group? | <p>I have a dataframe as below</p>
<pre><code>import pandas as pd
import seaborn as sns
import numpy as np
df = sns.load_dataset("diamonds")
df.head()
</code></pre>
<pre><code> carat cut color clarity depth table price x y z
0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.... | <p>You can try the below function which takes matplotlib colours and maps it back based on the Variable column:</p>
<pre><code>from matplotlib import colors
def colr(x):
y = x.assign(k=x['Variable'].ne("").cumsum())
d = dict(enumerate(colors.cnames))
y[:] = np.broadcast_to(y['k'].map(d).radd('back... | python|pandas|dataframe|pandas-styles | 3 |
354,192 | 67,766,010 | When mapping tensor values with dictionary i get TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key | <p>I try to create a new tensor based on a dictionary that maps 1 to 1 the values from a tensor to some other value (the example below is trivial on purpose), and i get the error "TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key." - even though I do not use Tensors as keys in the dictiona... | <p>you are getting the error because when you type-casted using int(x) it was still a tensor. it was type <code> tensorflow.python.framework.ops.EagerTensor</code> . pls use numpy()(i.e tensor to numpy.int32).</p>
<p>so code change would be</p>
<pre><code>tf.map_fn(lambda x: m[x.numpy()], elems=tensor1, fn_output_sign... | python|tensorflow|tensorflow2.0 | 0 |
354,193 | 67,797,103 | Standardizing a set of columns in a pandas dataframe with sklearn | <p>I have a table with four columns: CustomerID, Recency, Frequency and Revenue.
<a href="https://i.stack.imgur.com/iA0BN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iA0BN.png" alt="My table" /></a></p>
<p>I need to standardize (scale) the columns Recency, Frequency and Revenue and save the colum... | <p><code>fit_transform</code> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler.fit_transform" rel="nofollow noreferrer">returns an ndarray</a> with no indices, so you are losing the index you set on <code>df.set_index('CustomerID',... | python|pandas|scikit-learn|standardized | 3 |
354,194 | 67,621,704 | How to read specific lines that contain a specific string with Pandas read_csv()? | <p>I would like to sort out only the columns and rows I want to use when downloading a CSV.</p>
<p>with</p>
<pre><code>df = pd.read_csv("https://data.org/data.csv",usecols = ['Lion','Tree'])
</code></pre>
<p>I can read only the columns I want, but how can I read only the rows whose column "Lion" con... | <ul>
<li><p>If what you're asking for is to filter rows <strong>while</strong> reading the csv file, the answer is that there is no built-in way to do that.</p>
</li>
<li><p>But you can do what you want when the csv file has been loaded in a DataFrame like that:</p>
</li>
</ul>
<p><code>df = df.loc[df['Lion'] == 'anima... | python|pandas|dataframe | 1 |
354,195 | 67,613,483 | Saved Model file size is the same after pruning with Tensorflow Model Optimization | <p>I have a model that is around 1.1gb when I save it with the <code>model.save()</code> API. That's a bit too big for my liking so I tried pruning it following the official Tensorflow tutorial (<a href="https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras" rel="nofollow noreferrer">https://ww... | <p>The reason you are seeing no change in model size with pruning alone is that the weights are still stored as a floating point value, they are just set as 0. If you subsequently zip the model you will see that a pruned model is smaller in size than the original model. This can be useful for moving the model around, f... | python-3.x|tensorflow2.0 | 0 |
354,196 | 67,819,784 | Negate isin - pandas | <p>I have the following line in my code where I group df based on a column <code>Package</code>, and calculate the size of each group based on a criteria on another column <code>Id</code>.</p>
<pre><code>df.groupby("Package")["Id"].apply(lambda x: x.isin(someList).sum())
Package
P1 1
P2 ... | <p>In your solution add <code>~</code> with parentheses to lambda function:</p>
<pre><code>df.groupby("Package")["Id"].apply(lambda x: (~x.isin(someList)).sum())
</code></pre>
<p>Or use syntactic sugar - create <code>Series</code> of not membership and aggregate by Series <code>df["Package"... | python|pandas|dataframe | 1 |
354,197 | 67,735,425 | pandas.Series.drop didn't work out for me | <pre><code>s = pd.Series(data=np.arange(3), index=['A', 'B', 'C'])
s.drop(labels=['B', 'C'])
print(s)
</code></pre>
<p>I use the example from the pandas official documentation page. I tried to run it on Jupyter notebook and PyCharm, but both of them showed this:</p>
<pre><code>A 0
B 1
C 2
dtype: int32
</code><... | <p>Either do</p>
<pre><code>s.drop(labels=['B', 'C'], inplace=True)
</code></pre>
<p>or</p>
<pre><code>s = s.drop(labels=['B', 'C'])
</code></pre> | python|pandas|numpy | 1 |
354,198 | 67,790,749 | 'Other' category for values appearing less than 5 times | <p>job_title has too many different values for it to be useful so I am trying to create an 'other' category for all values in job_title that have occurred less than 5 times.</p>
<p>I have managed to display those that occur less than 5 times through the code below:</p>
<pre><code>df[df.groupby('job_title')['job_title']... | <p>Let's use <code>loc</code> to assign values, based on this boolean series.</p>
<pre><code>df.loc[df.groupby('job_title')['job_title'].transform('size')<5, 'job_title'] = 'Other'
</code></pre> | python|pandas|jupyter-notebook | 1 |
354,199 | 67,925,579 | Combine dataframe in python but avoid duplicates | <p>I have two dataframes, df1, and df2. I am joining on two different column names. For some reason when I perform this join, the result creates exponential duplicated rows. How would I avoid this. I am using outer join.</p>
<p><strong>Data</strong></p>
<p>df1</p>
<pre><code>ID Date
a 1/1/2022
a 1/1/2022
b 2/1/2... | <p>Indeed, a left join should do it. Simply try changing "outer" to "left" in the how argument.</p>
<pre><code>join = pd.merge( df1, df2, left_on='Date', right_on='Quarter', how='left')
</code></pre> | python|pandas|numpy | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.