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 |
|---|---|---|---|---|---|---|
351,100 | 68,389,770 | How to automatically resize an HDF5 dataset with h5py? | <p>Is there a way for an <a href="https://www.hdfgroup.org/solutions/hdf5/" rel="nofollow noreferrer">HDF5</a> dataset to start small in size and automatically be resized to fit more and more items as they are appended into it?</p>
<p>I know that using <a href="https://www.h5py.org/" rel="nofollow noreferrer">h5py</a> ... | <p>Short answer: No.<br />
I'm not an expert on the underlying HDF5 libraries, but I don't think they have this capability (and h5py is simply a wrapper). The (sort of) good news: h5py will throw an exception if you try to write beyond the allocated size.
Code below expands on your example to demonstrate.</p>
<pre><cod... | python|numpy|hdf5|h5py | 1 |
351,101 | 68,307,438 | Is there a way to add a column to a list that does a datetime operation with another column's data, without using a loop? | <p>I'm trying to plot a time series using pyplot. I have a 2-D numpy array with the time data that looks like this (truncated array):</p>
<pre><code>sndTemps_time = array([[ 0. , 0. ],
[ 0.041667, 1. ],
[ 0.083333, 2. ],
[ 0.125 , 3. ]]).
</code></pre>
<p>... | <p>I simplify your problem:</p>
<pre><code>a = pd.DataFrame([100, 200, 300, 400], columns = ['example'])
print('this is before adding a column')
print(a)
a['new_col'] = a['example'][0]
print('this is after adding a column')
print(a)
</code></pre>
<p>Output:</p>
<pre><code>this is before adding a column
example
0 ... | python|pandas|dataframe|numpy|matplotlib | 0 |
351,102 | 68,210,937 | How to connect the output of one network to the input of another network in Keras? | <p>I have two networks with given architectures:</p>
<pre><code>hidden_state = 256
embedding_size = 128
# Encoder
enc_input = Input(shape=(max_fr_len,), name='enc_input')
x = Embedding(en_vocab, embedding_size)(enc_input)
x = GRU(hidden_state, return_sequences=True)(x)
x = GRU(hidden_state, return_sequences=True)(x)
e... | <p>Ah yes, delightful help as always, thank you. Anyways for anyone wondering I found a solution. It is not my idea, however I decided to post it.</p>
<p>Instead of connecting it on fly you need to only instantiate layers and create two separate functions to connect it later on. Full code below.</p>
<pre><code># Encode... | tensorflow|keras | 0 |
351,103 | 68,180,612 | How to append in a loop for Excel file within pandas | <p>I have two DataFrames.
The first one comes from an API, and the second one comes from an Excel file.</p>
<p><strong>df1</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>name</th>
<th>description</th>
<th>author</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td></td>... | <p>You can use <code>df.merge</code> to join two dataframes.</p>
<pre><code>df1.merge(df2, on='name')
</code></pre> | python|pandas|data-science|jupyter | 0 |
351,104 | 68,295,971 | Assign values from one column of pandas dataframe to the list of parameters in another column | <p>I am reading in a csv file that contains a column of parameter names, and then several columns of values under different scenarios. I want to assign the parameter values from a specific column to the parameters. How can I do this? The order of the rows will change.</p>
<p>In this simple example, I effectively wan... | <p>Create Series and then select by <code>params</code> values:</p>
<pre><code>s = df.set_index('params')['value']
print (s)
a 1
b 2
c 3
Name: value, dtype: int64
print (s['a'])
1
print (s['b'])
2
print (s['c'])
3
</code></pre> | python|pandas | 0 |
351,105 | 68,442,363 | Assign values of label into corresponding column in data frame | <p>I have a pandas data series with act like a reference of certain values for specific labels. I would like to popualte the values for the corresponding "label/index" into another data frame. As an example</p>
<pre><code>import pandas as pd
A = pd.DataFrame(index=[0, 1, 2], data=[[1, 2, "goat"], [4... | <p>Let's try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> on <code>data</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>rename</code></a>... | python|pandas | 0 |
351,106 | 68,158,702 | Replace repetitive values in column | <p>I want to add a column which has values not equal to column <code>N</code> after <code>N=31</code> has reached and then plot it like
<code>plt.plot(X[N==1],FT[N==1]), plt.plot(X[new_col==63],FT[new_col==63])</code>
The data is following</p>
<pre><code>
+-------+-----+----+-------+-------+
| X | N | CN | Vdiff ... | <p>Is this the ouput you need? We cannot simply <code>groupby</code> by <code>N</code> as it has repetitive, non-adjacent values, as we need to preserve the order. We count here the condition where <code>N</code> is changed compared to its own previous value.</p>
<pre><code>import pandas as pd
from io import StringIO
... | python|pandas|dataframe | 0 |
351,107 | 68,383,549 | Python - Keep all rows of a group if a name is contained in any row | <p>I have a report that contains Invoice IDs and approvers. Invoices can have multiple approvers, which results in the IDs being duplicated (this is fine). What I want to do, is check each group of Invoice IDs to see if either of 2 approvers are in the list of approvers associated with that ID. If they are, then I want... | <p>This should work:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'invoice_ID': ['149877RV' ,'149877RV' ,'149877RV','149877RV','149877RV','149877RV','149877RV'],
'Approver': ['Jane Doe','Joe Manchin','Michael Frank','Kevin Holder','Michael Frank','Michael Frank','James Doe']})
mask=df['Ap... | python|pandas|group-by | 1 |
351,108 | 68,243,131 | Applying markers to certain plotly.express plots | <p>I am working with pandas and plotly to map out f1 data. I currently have been able to retrieve the following data:</p>
<pre><code> driverId position time lap
0 bottas 3 0 days 00:01:46.833000 1
0 bottas 3 0 days 00:01:40.188000 2
0 hamilton ... | <ul>
<li>refer back to this <a href="https://stackoverflow.com/questions/68146256/convert-times-to-designated-time-format-and-apply-to-y-axis-of-plotly-graph/68152217#68152217">question</a> for definition of data frame</li>
<li>have defined <code>colour_drivers</code></li>
<li>for markers use <code>px.scatter</code> an... | python|pandas|plotly | 1 |
351,109 | 68,435,187 | Python Dataframe convert each cell-string to a list type and explode | <p>I have a dataframe consists lists as cells. I run into the issues when I <code>explode</code> it. I understood that the list is stored inside the cell as <code>str</code> type not <code>object</code> type.
My code:</p>
<pre><code>xdf = pd.DataFrame({'A':[str([1,2])],'B':[str([10,20])]})
xdf
A B
0 [... | <pre><code>xdf.applymap(eval).apply(lambda x: x.explode())
</code></pre> | python|pandas|list|dataframe | 1 |
351,110 | 68,110,595 | Inflate polygon to allow for errors using "contains" in sjoin | <p>The problem I am facing is following:</p>
<p>I have a <code>geodandas</code> dataframe, <code>df_geometries</code>, containing polygons and an <code>id</code>.</p>
<pre><code>id geometry_zone
A1 POLYGON ((119.82334 28.350468, 119.79008 28.350468, 122.85067 28.084328, 122.85067 44.851055, 119.92314 44.717983, 119.8... | <ol>
<li><p>Decide what distance you can tolerate with error. And buffer the polygons accordingly. Then sjoin.</p>
<ul>
<li>This is determined by how your original data was created. Although the eye appears to be on the line, the actual coordinate values may not be.</li>
</ul>
</li>
<li><p>You can check how far each po... | python|pandas|geopandas | 0 |
351,111 | 68,058,887 | Identical Pandas and SQLite queries not giving same results | <p>I have made a query with the file "Sample - Superstore.csv" from <a href="https://github.com/mikemooreviz/superstore" rel="nofollow noreferrer">https://github.com/mikemooreviz/superstore</a> that will give me the count for each case that contains some type of criteria for strings, as well as a count withou... | <p>The pandas line <code>df['strings_conditions'] = ....</code> will assign exactly one condition to each dataframe row, the same condition when the name is encountered again. The view has the same issue: one "strings_condition" per name. (The numbers are different because the tests are in a different order t... | pandas|string|sqlite|group-by|count | 1 |
351,112 | 68,191,368 | Generating a 3D object (e.g. via Mayavi) and exporting it as 3D image stack (e.g. tiff) | <p>My current task is to generate a 3D image space where there are 3D objects (of iso-surfaces) that I designed and export it as an image stack (numpy or tiff).</p>
<p>I came down to using Mayavi to generate 3D iso-surfaces. I know Mayavi is originally designed to provide 3D visualizations on its own, but I would like ... | <p>You might go for the vtk class <code>vtkImplicitModeller</code>.
E.g.:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from vedo import Points, Volume
n_mer, n_long = 6, 11
dphi = np.pi/1000.0
phi = np.arange(0.0, 2*np.pi + 0.5*dphi, dphi, 'd')
mu = phi*n_mer
x = np.cos(mu)*(1+np.cos(n_long*m... | python|numpy|3d|vtk|mayavi | 2 |
351,113 | 68,155,620 | Numpy busday_count not considering holidays | <p>I have a dataset and I need to calculate working days from a given date to today, excluding the given list of holidays. I will be including weekends.</p>
<p>Date Sample:</p>
<p><a href="https://i.stack.imgur.com/yWKjt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yWKjt.png" alt="enter image desc... | <p>Make sure <code>today</code> and <code>R_REL_DATE</code> are in pandas datetime format with <code>pd.to_datetime()</code>:</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame({'R_REL_DATE': {0: '7/23/2020', 1: '8/26/2020'},
'DAYS IN QUEUE': {0: 338, 1: 304}})
df["today"... | python|pandas|numpy|date|python-holidays | 0 |
351,114 | 68,208,345 | Populate Pandas dataframe with group_by calculations made in Pandas series | <p>I have created a dataframe from a dictionary as follows:</p>
<p><code>my_dict = {'VehicleType':['Truck','Car','Truck','Car','Car'],'Colour':['Green','Green','Black','Yellow','Green'],'Year':[2002,2014,1975,1987,1987],'Frequency': [0,0,0,0,0]}</code></p>
<p><code>df = pd.DataFrame(my_dict)</code></p>
<p>So my datafra... | <p>You are on a good path. You can continue like this:</p>
<pre><code>grp_by_series=grp_by_series.reset_index()
res=df[['VehicleType', 'Colour']].merge(grp_by_series, how='left')
df['Frequency'] = res[0]
print(df)
</code></pre>
<p>Output:</p>
<pre><code> VehicleType Colour Year Frequency
0 Truck Green ... | python|pandas|dataframe|pandas-groupby|series | 2 |
351,115 | 68,251,969 | Filtering third-party Python warnings with newlines | <p>I am trying to suppress a warning from a third-party module (in this case, PyTables via Pandas) using an environment variable. The warning starts with a newline.</p>
<p>Example of warning:</p>
<pre><code>python -c 'import pandas as pd; pd.DataFrame([None]).to_hdf("test.h5", "/data")'
/usr/lib/py... | <p>Your problem occurs because <code>PerformanceWarning</code> isn't a built-in warning category (<a href="https://docs.python.org/3/library/warnings.html" rel="nofollow noreferrer">list here</a>).</p>
<p>Based on your use case you can use an approach below, but be careful as some heavy-handed approaches may also suppr... | python|python-3.x|pandas|warnings | 1 |
351,116 | 68,122,785 | Why is Normalization causing my network to have exploding gradients in training? | <p>I've built a network (In Pytorch) that performs well for image restoration purposes. I'm using an autoencoder with a Resnet50 encoder backbone, however, I am only using a batch size of 1. I'm experimenting with some frequency domain stuff that only allows me to process one image at a time.</p>
<p>I have found that m... | <p>To answer my own question, my network was unstable in training because a batch size of 1 makes the data too different from batch to batch. Or as the papers like to put it, too high an internal covariate shift.</p>
<p>Not only were my images drawn from a very large varied dataset, but they were also rotated and flipp... | python|tensorflow|image-processing|pytorch|autoencoder | 0 |
351,117 | 68,284,416 | python How to sum over diagonals of data frame | <p>Say that I have this data frame:</p>
<pre><code> 1 2 3 4
100 8 12 5 14
99 1 6 4 3
98 2 5 4 11
97 5 3 7 2
</code></pre>
<p>In this above data frame, the values indicate counts of how many observations take on (100, 1), (99, 1), etc.</p>
<p>In my context, the diag... | <p>If there are same indices in both <code>DataFrame</code>s and columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> with aggregate <code>sum</code>:</p>
<pre><code>df = df1.stack().groupby(df2.stack()).su... | python|pandas|dataframe | 2 |
351,118 | 68,307,152 | Determining Camera Texture | <p>Been stuck a while trying to figure an issue out for android devices. The sample code from the <a href="https://js.tensorflow.org/api_react_native/0.3.0/#cameraWithTensors" rel="nofollow noreferrer">tensorFlow.js library</a> says that the resolution of the camera has to be determined empirically. With iphone it's be... | <p>The <code>textureDims</code> also varies depending on whether the user is in potrait or landscape so the current hard-coded value for iOS devices wouldn't work as well if the user were to change the orientation of the device.</p>
<p>What you could use instead is <a href="https://reactnative.dev/docs/usewindowdimensi... | react-native|tensorflow|tensorflow.js | 0 |
351,119 | 68,036,430 | change the color of superpixels in python | <p>I am trying to change the color of superpixels from an image in black/white and save the new white/black image.
I use slic for superpixel algorithm:</p>
<pre><code>segments = slic(img, n_segments = 100, sigma = 5)
</code></pre>
<p>I tried to loop over each unique superpixel from segments and set the value 255 for wh... | <p>You can actually directly index the <code>y</code> array with your superpixels:</p>
<pre class="lang-py prettyprint-override"><code>mask = y[segments]
</code></pre>
<p>Or, if you want to make sure you get 0/255 uint8:</p>
<pre class="lang-py prettyprint-override"><code>yu8 = np.where(y == 1, 255, 0).astype(np.uint8)... | python|numpy|image-processing|scikit-image | 1 |
351,120 | 68,289,481 | Pandas python error '<' not supported between instances of 'str' and 'int' while filtering column only with integers | <p>I would like to filter only values below 10.000.000 in a column "Size" in a dataframe.</p>
<p>The dataframe example is below (original file is much larger):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-co... | <p>The column "Size" is of type <code>str</code>. Try to convert it to integer first:</p>
<pre class="lang-py prettyprint-override"><code>df["Size"] = df["Size"].str.replace(",", "").astype(int)
print(df[df.iloc[:, 3] < 10000000])
</code></pre>
<p>Prints:</p>
<pre cl... | python|pandas|dataframe|filter | 3 |
351,121 | 68,195,273 | Interpretation of Tensorboard Images for Object detection | <p>I am training different models with Tensorflow Object Detection using this github <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">library</a>.
When I monitor the Tensorboard while training, I see the "<strong>Images</strong>" tab along with &qu... | <p>As you know, TensorBoard is a visualization toolkit, which allows you to visualize almost anything you need to help you interpret your model behavior.</p>
<p>Alongside showing diagrams in scalars or time series, it can give you other things, such as a look at the graphics in your datasets. Often, you might write cod... | tensorflow|computer-vision|object-detection|tensorboard | 0 |
351,122 | 68,345,259 | RFECV with a pipeline containing ColumnTransformer | <p>My question refers to a problem which has been raised in the following similar unanswered question: <a href="https://stackoverflow.com/questions/62861453/using-a-pipeline-containing-columntransformer-in-scikits-rfecv">Using a Pipeline containing ColumnTransformer in SciKit's RFECV</a></p>
<p>I am trying to selec... | <p>I have been trying to solve this problem in a similar constellation for some time until I got fed up by the complicated internal conversions of scikit-learn and decided to write my own rfecv working with pipelined transformers.</p>
<p>Basically I implemented the algorithm from Guyon, Isabelle, et al. "Gene sele... | python|pandas|numpy|scikit-learn|feature-selection | 1 |
351,123 | 68,113,075 | Problem with batch_encode_plus method of tokenizer | <p>I am encountering a strange issue in the <code>batch_encode_plus</code> method of the tokenizers. I have recently switched from transformer version 3.3.0 to 4.5.1. (I am creating my databunch for NER).</p>
<p>I have 2 sentences whom I need to encode, and I have a case where the sentences are already tokenized, but s... | <p>You need a non-fast tokenizer to use list of integer tokens.</p>
<p><code>tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name, add_prefix_space=True, use_fast=False)</code></p>
<p><code>use_fast</code> flag has been enabled by default in later versions.</p>
<p>From the HuggingFace documentation,</p>
<blo... | python|pytorch|huggingface-transformers|huggingface-tokenizers|huggingface-datasets | 3 |
351,124 | 68,101,693 | Can I process large number of text files faster than doing it sequentially? | <p>I'm working with a dataset with thousands of text files, around ~700kb each. The filenames contain the input parameters which produced the data (column separated time, frequency, amplitude). I've created a dictionary with the filenames as keys, and the parameters as the values in a tuple (to be able to associate the... | <p>You should try parallelization of your code eg. with <a href="https://joblib.readthedocs.io/en/latest/parallel.html" rel="nofollow noreferrer"><code>joblib.Parallel</code></a>, something like this:</p>
<pre class="lang-py prettyprint-override"><code>from joblib import Parallel, delayed
def task(filename):
df = ... | python|pandas|dataframe|csv | 0 |
351,125 | 68,154,073 | How to change the shape of a numpy matrix as a function of matrix values | <p>I have a 4×6 numpy array</p>
<pre><code>x = array([[ 0, 0, 50, 55, 500, 550],
[ 0, 1, 60, 65, 600, 650],
[ 1, 0, 70, 75, 700, 750],
[ 1, 1, 80, 85, 800, 850]])
</code></pre>
<p>I want to transform it to this 2×2×4 array</p>
<pre><code>y = array([[[ 50, 55, 500, 5... | <p>You could do the following:</p>
<pre><code>import numpy as np
x = np.array([[ 0, 0, 50, 55, 500, 550],
[ 0, 1, 60, 65, 600, 650],
[ 1, 0, 70, 75, 700, 750],
[ 1, 1, 80, 85, 800, 850]])
y = np.zeros((2, x.shape[0]-2, x.shape[1]-2)
y[x[:,0],x[:,1]] = x[:, 2... | python|numpy|multidimensional-array|indexing|tensor | 0 |
351,126 | 68,325,227 | Change one element of column heading in CSV using Pandas | <p>I have created a CSV file which looks like this:</p>
<blockquote>
<p>RigName,Date,DrillingMiles,TrippingMiles,CasingMiles,LinerMiles,JarringMiles,TotalMiles,Comments<br />
0,08 July 2021,19.21,63.05,43.16,45.41,8.52,0,"Tested all totals. Edge cases for multiple clicks.
"<br />
1,09 July 2021,19.21,63.05,43... | <p>After 3 hours of trial and error (and a lot of searching in vain), I solved it by doing this:</p>
<pre><code>df= pd.read_csv('ton_miles_record.csv')
user_input = 'SD555'
df.rename(columns={ df.columns[1]: user_input}, inplace=True)
df.to_csv('new_csv.csv', index=False)
</code></pre>
<p>I hope this helps someone e... | python-3.x|pandas|dataframe|csv | 0 |
351,127 | 68,157,711 | I'm working with a dictionary of colors but muy function can use more than I have. Pandas | <p>For context I'm working with a function that use <code>i</code> centroids, The centroids reagroups different points because I'm using a k-means clustering. I defined a dictionary of colors:</p>
<pre><code> colmap = {1: 'r', 2: 'g', 3: 'b', 4: "y", 5: "k", 6: "m", 7: "orange"... | <p>Don't use a dictionary at all. Use the HSV color model to calculate the colors. Divide H (hue) into <em>n</em> pieces. If that's still not sufficient in amount, you can change S (saturation) and V (value) as well to get brighter or darker colors of the same hue.</p>
<p>This should easily give you more than 50 colors... | python|pandas|numpy|colors | 3 |
351,128 | 68,367,265 | Pytorch: torch.int32 to torch.long | <p>I'm new in stackoverflow, hope this post respects all the requirements.</p>
<p>As in the tile, I was wondering how to change the type of a data from torch.int32 to torch.long, as I obtain this error in my code:</p>
<p>ValueError: Argument <code>edge_index</code> needs to be of type <code>torch.long</code> but found ... | <p>There are two easy ways to convert tensor data to torch.long and they do the same thing. Check the below snippet.</p>
<pre><code># Example tensor
a = torch.tensor([1, 2, 3], dtype = torch.int32)
# One Way
a = a.to(torch.long)
# Second Way
a = a.type(torch.long)
# Test it out (Should print long version of dtype)
p... | python|types|pytorch | 0 |
351,129 | 68,200,591 | How to sort Pandas fields based on another value with out loosing date grouping | <p>I currently have a Data Frame that resembles this sample table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Model</th>
<th>Horse Power</th>
</tr>
</thead>
<tbody>
<tr>
<td>2019-02-05</td>
<td>Spx</td>
<td>100</td>
</tr>
<tr>
<td></td>
<td>P2</td>
<td>210</td>
</tr>
<tr>... | <p>You can use <code>sort_values</code> and <code>sort_index</code> to get your output:</p>
<p>If <code>Date</code> is already the index of your dataframe:</p>
<pre><code>>>> df.sort_values('Horse Power', ascending=False) \
.sort_index(kind='mergesort')
Model Horse Power
Date
2019-02-05 P... | python|pandas|dataframe|sorting|datetime | 0 |
351,130 | 68,280,377 | Random Forest Classifier Error with Python - Index out of bounds | <p>everyone! As a quick heads up, I'm following this link in order to try to do a random forest classifier:
<a href="https://towardsdatascience.com/random-forest-in-python-24d0893d51c0" rel="nofollow noreferrer">https://towardsdatascience.com/random-forest-in-python-24d0893d51c0</a></p>
<p>This assignment is about hote... | <p>the method <code>index()</code> of a <code>list</code> object returns the index of the queried element in a list, i.e. an <em>integer</em> (<code>int</code>) value. As a side node: a <code>pandas.DataFrame</code> object would expect a column name, i.e. a <em>string</em> (<code>str</code>). Since you have a matrix (<... | python|pandas|numpy | 0 |
351,131 | 68,181,938 | Chunk a large dataset by using a string in the column name using pandas | <p>I have a dataset containing 3000 columns
every column looks like 'abc_dummy0', 'dfg_dummy0, asd_dummy0' and it's of length 130 before it moves onto 'dfg_dummy1'.... and so on until 'lkj_dummy39'</p>
<p>I can use</p>
<pre><code>cols = [col for col in df.columns if 'dummy1' in col]
</code></pre>
<p>And it lists all th... | <p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> on axis=1 and create a <code>dict</code> entry for each group:</p>
<pre><code>dfs = {group_name: frame
for group_name, frame in
df.groupby(df.co... | python|pandas|csv | 0 |
351,132 | 68,274,836 | pytorch, AttributeError: module 'torch' has no attribute '_utils_internal' | <p>I need to test some fastai models in an environment without GPU, specifically in a windows server. I trained some fastai models in Google colab, and now need to test them in real time, connected to an industrial process. Nevertheless I'm limited with hardware.</p>
<p>In Google colab, I worked with this configuration... | <p>I experienced the same problem (Pytorch 1.11.0, Torchvision 0.12.0, CUDA 11.3, Python 3.10) and came around with a somewhat "hacky" solution.</p>
<p>First I checked the file _ops.py in the given location, it contained indeed the statements and function:</p>
<pre><code>import torch._utils_internal
...
path ... | python-3.x|deep-learning|pytorch|anaconda|fast-ai | 0 |
351,133 | 68,314,840 | Checking continuity of a excel datafile | <p>I have a excel data file with the date time delimited. I want to check whether the data is continuous or not.
i have tried to check it by counting the total number of columns and then matching with the supposed number of datapoints(number of rows).
but this method has limitation when there is actually gaps. I'd need... | <p>Use <code>pandas</code> library to do a <code>groupby</code> and then <code>count</code> the number of records minute column</p>
<pre><code>import pandas as pd
csv_path = '/home/sci_lab/Desktop/shankar_test/RCM_data/l1-492.csv'
df = pd.read_csv(csv_path)
gdf = df.groupby(['year', 'month', 'date', 'hour'])['min'].c... | python|pandas|continuity | 0 |
351,134 | 68,348,141 | Wrong order of values on X axes when build charts with groups using plotly.py | <p>Rows in my data consist of three columns: version, configuration, and value. I want to have two lines which represent configurations on my chart to show dependency of value (y axis) on version (x axis). Everything works perfect as long as every configuration (group) have the same set of values on x axis:</p>
<pre><c... | <p>My solution is to use <code>category_orders</code> argument:</p>
<pre><code>fig = px.line(df,
x='version',
y='value',
color='config',
line_group='config',
category_orders={'version': df["version"]}
)
</code></pre>
<blockquote>
<p>categ... | python|python-3.x|pandas|plotly|plotly-python | 1 |
351,135 | 68,148,468 | Retrieving the average of averages in Python DataFrame | <p>I have a mass <code>pandas</code> DataFrame <code>df</code>:</p>
<pre><code>year count
1983 5
1983 4
1983 7
...
2009 8
2009 11
2009 30
</code></pre>
<p>and I aim to sample 10 data points per <code>year</code> 100 times and get the mean and standard devia... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>def fn(x):
_100_means = [x.sample(10).mean() for i in range(100)]
return {
"mean_of_100_means": np.mean(_100_means),
"total_sd": np.std(_100_means),
}
print(df.groupby("year")["count"].apply... | python|pandas|dataframe|mean|standard-deviation | 3 |
351,136 | 68,278,197 | Python Pandas: Iteratively extract column values from dataframe using condition | <p>I have two dataframes each containing 3 columns df1(A, B, C) and df2(X, Y, Z). My aim here is extract all the rows from df1 in which the difference between A and X (A in each single row, X in all rows) is greater than a defined threshold value <strong>and</strong> the same for B against Y values, <strong>and</stron... | <p>With <code>np.repeat</code> and <code>np.tile</code> create your comparison tables</p>
<pre><code>abc = np.repeat(df1.values, df2.shape[0], axis=0).reshape(df1.shape[0], -1)
xyz = np.tile(np.hstack(df2.values), df1.shape[0]).reshape(df1.shape[0], -1)
df3 = df1[np.all(np.abs(abc - xyz) > thres, axis=1)]
</code></... | python|pandas|dataframe|truthtable | 0 |
351,137 | 68,258,830 | How can I pass a matrix by a function? | <p>I need to pass a matrix (5000x121) by a function (an sum of exponential distribution) and save the results in another matrix. It is returning a key error and I can´t solve it.</p>
<p>Any idea to help me resolve this problem?</p>
<p>I appreciate any help.</p>
<p>First rows and columns of the matrix. This is also a ma... | <p>You get a pandas error (Keyerror) when it tries to search for key 121 and doesn't find it. Since we don't know the content of "matrix.xlsx" it is hard to locate the problem, it'd depend on the index and name of the columns of the object A, buy you can use <a href="https://pandas.pydata.org/pandas-docs/stab... | python|pandas|numpy | 0 |
351,138 | 68,122,570 | NumPy template matching SQDIFF with `sliding window_view` | <p>The SQDIFF is defined as <a href="https://docs.opencv.org/4.5.2/df/dfb/group__imgproc__object.html#gga3a7850640f1fe1f58fe91a2d7583695dab65c042ed62c9e9e095a1e7e41fe2773" rel="nofollow noreferrer">openCV definition</a>. (I believe they omit channels)</p>
<p><a href="https://i.stack.imgur.com/FlJRQ.gif" rel="nofollow n... | <p>As a last resort, you may perform the computation in tiles, instead of computing "all at once".</p>
<p><code>np.lib.stride_tricks.sliding_window_view</code> returns a <strong>view</strong> of the data, so it doesn't consume a lot of RAM.</p>
<p>The expression <code>B - locations</code> can't use a view, an... | python|numpy|opencv|stride | 2 |
351,139 | 68,111,801 | Convert dictionary with list into pandas dataframe | <p>I have a Python dictionary</p>
<pre><code>result_dict = { 'kontonummer': None,
'industryPredictions': {'Supermarket': 0.006795256825841207,
'Cars': 0.01113155396585519},
'paymentmethods': ['Klarna SofortUeberweisung',
... | <p>Just use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>pd.json_normalize</code></a>, and pass the dictionary you have</p>
<pre class="lang-py prettyprint-override"><code>>>> pd.json_normalize(result_dict)
kontonummer ... | python|pandas|list|dictionary|flatten | 2 |
351,140 | 68,208,793 | python Pandas optimization for ubyte data (0..255) | <p>How is it possible to optimize Pandas df to ubyte data type (0..255)? (by default is int64 for integer)</p>
<p>If I will convert data to Categorical type, will df use less memory?</p>
<p>Or the only way to optimize it - use NumPy instead of Pandas?</p> | <p>For unsigned integer data in range 0..255, you can reduce the memory storage from default <code>int64</code> (8 bytes) to use <code>uint8</code> (1 byte). You can refer to <a href="https://www.educative.io/edpresso/reduce-the-memory-usage-when-loading-a-file-in-pandas" rel="nofollow noreferrer">this article</a> for... | python|pandas|dataframe|numpy|uint64 | 0 |
351,141 | 68,062,571 | RuntimeError: The size of tensor a (4144) must match the size of tensor b (256) at non-singleton dimension 3 site:stackoverflow.com | <p>I am training a generator network with an image size <code>(3, 256, 256)</code>. The network is as shown in the below</p>
<pre><code># Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 3
# Size of feature maps in generator
ngf... | <p>I think the problem is <code>the net_input</code> before going through the model is not <code>size=(1,3,256,256)</code> instead <code>(1,3,4144,4144)</code>. Try resize <code>net_input</code>.</p> | python|deep-learning|pytorch|tensor | 0 |
351,142 | 68,295,795 | Pythonic way to regroup a pandas dataframe using max of a column | <p>I have the following data frame that has been obtained by applying <code>df.groupby(['category', 'unit_quantity']).count()</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>category</th>
<th>unit_quantity</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>banana</td>
<td>1EA</td>
<... | <p>Starting from your DataFrame :</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> df = pd.DataFrame({'category': ['banana', 'eggs', 'eggs', 'full cream milk', 'full cream milk', 'full cream milk'],
... 'unit_quantity': ['1EA', '100G', '100ML', '100G... | python|pandas|dataframe | 1 |
351,143 | 68,171,456 | Unable to install Pandas Library using pip3 | <p>I try to install Pandas library uisg <code>pip3</code> and get the following errors:</p>
<pre><code>ERROR: Command errored out with exit status 1:
command: /Users/chaklader/PycharmProjects/OptimizingPublicTransport/producers/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'&q... | <p>My guess is you're using a too high python version, see similar issues <a href="https://github.com/pandas-dev/pandas/issues/32045" rel="nofollow noreferrer">1</a> <a href="https://stackoverflow.com/questions/64370149/problems-installing-pandas-and-yfinance-with-python-3-9-on-my-mac">2</a>.</p>
<p>You can try python ... | python|pandas|pip | 1 |
351,144 | 68,062,143 | Is there a way to run a function before the optimizer updates the weights? | <p>I'm going through PyTorch tutorial and just learned about <code>optimizer.step</code> and how it makes an update to the network's parameters (<a href="https://pytorch.org/tutorials/beginner/examples_nn/two_layer_net_optim.html" rel="nofollow noreferrer">here</a>).</p>
<p>Is there a way to create a function that when... | <p>I got this bit of code from <a href="https://discuss.pytorch.org/t/how-to-modify-the-gradient-manually/7483/2" rel="nofollow noreferrer">https://discuss.pytorch.org/t/how-to-modify-the-gradient-manually/7483/2</a> and edited it slightly:</p>
<pre><code>loss.backward()
for p in model.parameters():
weights = p.dat... | python|machine-learning|pytorch | 2 |
351,145 | 68,047,715 | compare the row values to get the value from other column | <p>I have a pandas dataframe</p>
<pre><code> qtr value
0 2008Q2 485000000.000
1 2008Q2 485000000.000
2 2008Q2 485000000.000
3 2008Q2 485000000.000
4 2008Q2 12399000000.000
5 2008Q4 181000000.000
6 2009Q2 179000000.000
7 2009Q3 359200000.000
8 2009Q3 3221289753.000
0 2008Q2 48500... | <p>IIUC:</p>
<p>try:</p>
<pre><code>c1=df[df['qtr'].eq(pd.Period('2009Q3'))]
c2=df[df['qtr'].eq(pd.Period('2009Q2'))]
res=c2['value'].mask(c1['value'].values>c2['value'].values,c1['value'].values)
df['newval']=df['value']
df.loc[res.index,'newval']=res.values
</code></pre>
<p>output of <code>df</code>:</p>
<pre><cod... | python|python-3.x|pandas | 0 |
351,146 | 68,185,710 | Python Pandas partial slicing and sorting on dataframe columns | <p>I have an input file of the wavelengths and absorbance from a spectrometer. In this file the data is recorded and just added as the last two columns of the dataframe. The columns are needed to specify the wavelength at which a specific absorbance (=data) was measured.</p>
<div class="s-table-container">
<table class... | <ul>
<li>this is classic <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">wide to long</a></li>
<li>your sample data has two readings for wavelength 796 in second set of data. This effectively means duplicates, dealt with this by putting a <strong>... | python|pandas|dataframe|slice|data-manipulation | 0 |
351,147 | 68,118,799 | Interpolating multivariate data generated from different regular grids | <p>I'm trying to interpolate a dataset of dimensions <code>(m,n,k,l)</code>. The data was generated for <code>m</code> different values of an input parameter, where for each index of <code>m</code> it was evaluated a regular grid. Essentially using a nested for loop over the parameters indexed by <code>n, k, l</code>. ... | <p>As mentioned in the comment, the alternative approach, while very inneficient, as it doesn't exploit the gridded nature of your data, consists in simply building 1-D input data arrays (one for each coordinate) from the grid coordinates (that's what the <code>unroll_arrays</code> function does, for your specific case... | python|numpy|multidimensional-array|scipy|interpolation | 1 |
351,148 | 68,188,742 | Transfer Pandas Dataframe to SFTP using Paramiko | <p>Here I have a function that is to upload a Dataframe to ftp server..</p>
<pre><code>import pandas as pd
import paramiko
df42 = pd.to_csv('file.csv')
def uploadToSftp():
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='host',usern... | <p>Something like the following would work</p>
<pre><code>import pandas as pd
import paramiko
with ftp_client.open('/path/on/ftp/server/file.csv', 'w', bufsize=32768) as f:
f.write(df42.to_csv(index=False))
</code></pre> | python|pandas|paramiko | 0 |
351,149 | 68,275,134 | How to check for Range of Values (domain) in a Dataframe? | <p>So want to determine what values are in a Pandas Dataframe:</p>
<pre><code>import pandas as pd
d = {'col1': [1,2,3,4,5,6,7], 'col2': [3, 4, 3, 5, 7,22,3]}
df = pd.DataFrame(data=d)
</code></pre>
<p>col2 hast the unique values 3,4,5,6,22 (domain). Each value that exists shall be determined. But only once.</p>
<p>Is ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html" rel="nofollow noreferrer"><code>df.max()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.min.html" rel="nofollow noreferrer"><code>df.min()</code></a> to find the ran... | pandas|dataframe|dns | 0 |
351,150 | 68,050,736 | RuntimeWarning: invalid value encountered in sqrt return np.sqrt((EA**2)-(m**2))/(EA) | <p>as the title suggests, I keep getting an error with a square root. I suppose it is probably due to the fact that there may be a negative number under the square root, but I can't seem to find it.</p>
<p>The issue comes from this line of code:</p>
<pre><code>lf_rf_momentum_diff_neutrino_pi = find4mtm_C_lf(140, 105, 5... | <p>When I run this for me the first values encountered by beta_calc is m = 140 and EA = 30.6... so your assumption that E >> m is false. that's why you get a warning. the sqrt return a nan (not a number).</p>
<p>If you actually need complex number you can swap <code>np.sqrt((EA**2)-(m**2))/(EA))</code> to <code>n... | python|function|numpy|error-handling|sqrt | 0 |
351,151 | 68,294,163 | Why does converting from np.float16 to np.float32 modify the value? | <p>When converting a number from half to single floating representation I see a change in the numeric value.</p>
<p>Here I have <code>65500</code> stored as a half precision float, but upgrading to single precision changes the underlying value to <code>65504</code>, which is many floating point increments away from the... | <p>The error is <em>not</em> "many floating point increments away" [corrected to match OP's improved wording]. Read the standard IEEE 754-2008. It specifies 10 bits for the mantissa, or 1024 distinct values. Your value is on the close order of 2^16, so you have an increment of 2^6, or 64.</p>
<p>The format... | python|numpy|floating-point|precision|half-precision-float | 4 |
351,152 | 758,980 | Matplotlib suddenly crashes after reinstalling Xcode? | <p>I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting </p>
<pre><code>...
/sw/lib/python2.5/site-packages/matplotlib-0.91.1-py2... | <p>You're using Python from Fink, so Xcode doesn't have anything to do with it. <code>from numpy.core.ma import *</code> works fine with Apple's bundled Python and NumPy too.</p> | python|xcode|numpy|matplotlib | 3 |
351,153 | 59,435,147 | Long Run Time in pandas | <p>I was writing a program for manual confusion matrix. I had to loop over 10K iterations.</p>
<pre><code>df_a=df_a.sort_values('proba')
tpr_lst=[]
fpr_lst=[]
for i in tqdm(df_a['proba']): #df_a['proba'] contains 10K points, each point will be taken a new threshold to determine y_pred is 0 or 1, all this is too plot a... | <p>Sagemaker ml.p2.xlarge or use p2.xlarge.</p>
<p>Stop the instance after using to avoid over paying.</p>
<p><a href="https://course.fast.ai/start_sagemaker.html" rel="nofollow noreferrer">https://course.fast.ai/start_sagemaker.html</a></p> | python-3.x|pandas|amazon-web-services | 0 |
351,154 | 59,305,886 | Rearrange pandas data frame from (id, name:a, value:b) to (id, a: b) | <p>I import data in a pandas dataframe from as SQL database. Every row includes a id, a parameter name, and the corresponding parameter value. Just like in this stripped down example:</p>
<pre><code>import pandas as pd
data = [
['aaa', 'A', 0],
['bbb', 'A', 1],
['aaa', 'B... | <p>Yes there is an easy solution with <code>pivot_table</code>:</p>
<pre><code>output = df.pivot_table(index='id', columns='name')
print(output)
value
name A B C
id
aaa 0 2 4
bbb 1 3 5
</code></pre> | python|pandas|dataframe | 1 |
351,155 | 59,149,281 | How to create rows for unique values in columns in pandas? | <p>I have a pandas dataframe with thousands of rows like so:</p>
<pre><code>IntentID IntentName Query Response
1 Intent Name 1 Query 1 Response1
2 Intent Name 1 Query 1 Response2
3 Intent Name 2 Query 2 Response3
4 ... | <p>Try this:</p>
<pre><code>df['IntentID'] = df.groupby('IntentName') \
['IntentID'].transform('first') \
.rank(method='dense') \
.astype('int')
</code></pre>
<p>How it works:</p>
<ul>
<li>Group the rows by <code>IntentName</code></li>
<li>For each group, k... | python|pandas|dataframe | 2 |
351,156 | 59,104,676 | How to apply function on the basis of column condition in a dataframe | <p>I am trying to apply a function over a column in a dataframe if one of the column i.e. df['mask'] contain False it should skip that row. mask column is bool type</p>
<p>this is mine function </p>
<pre><code> def dates(inp):
temp = inp
parser = CommonRegex()
inp = inp.apply(parser.dates... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.pipe.html" rel="nofollow noreferrer"><code>Series.pipe</code></a> for pass columns to function and also filter rows with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow n... | python|pandas | 1 |
351,157 | 59,372,834 | Set column value foreach row with a specific condition with pandas | <p>this question is very similar to another question I asked a few times ago: <a href="https://stackoverflow.com/questions/55421118/pandas-set-value-if-most-columns-are-equal-in-a-dataframe">Pandas set value if most columns are equal in a dataframe</a></p>
<p>I have this DataFrame: </p>
<pre><code> NET_0 NET_1 ... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> with compare all values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a>,... | python|pandas | 4 |
351,158 | 59,045,488 | what is the default weight initialization used in Pytorch embedding layer? | <p>When we create an embedding layer using the class <code>torch.nn.Embedding</code>, how are the weights initialized ? Is uniform, normal or initialization techniques like <em>He</em> or <em>Xavier</em> used by default?</p> | <p>In <code>Embedding</code>, by default, the weights are initialization from the Normal distribution. You can check it from the <a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/sparse.html#Embedding" rel="nofollow noreferrer"><code>reset_parameters()</code></a> method:</p>
<pre><code>def reset_param... | deep-learning|pytorch | 3 |
351,159 | 59,080,184 | Linear interpolation between unique values - Python | <p>I have a df that contains multiple values at duplicate time points. I want to interpolate values for two specific columns but only between unique time points. Using the df below, I want to interpolate <code>X</code> and <code>Y</code> only but between unique time points.</p>
<pre><code>import pandas as pd
import nu... | <p>First we <code>drop_duplicates</code> based on <code>Time</code> to get unique rows, then we interpolate, and update our original dataframe with these values.</p>
<p>Finally we use <code>ffill</code> to forwardfill our values:</p>
<pre><code>interpolation = df.drop_duplicates('Time')[['X', 'Y']].interpolate()
df.l... | python|pandas|interpolation | 1 |
351,160 | 59,191,047 | `TypeError` when using `cupy.nanstd` and `cupy.nanvar` | <p><code>cupy</code> raises <code>TypeError</code> while I'm running the following code on Windows 10.</p>
<pre class="lang-py prettyprint-override"><code>import cupy as cp
print(cp.nanstd(cp.asarray([1, 2, 3, 4, 5], dtype='float64')))
</code></pre>
<p>the error is shown as below:</p>
<pre class="lang-py prettyprint... | <p><strong>Edit</strong></p>
<pre><code>import cupy as cp
import numpy as np
cp.nanstd(cp.asarray(np.asarray([1, 2, 3, 4, 5], dtype='float64')))
</code></pre>
<p>alternatively</p>
<pre><code>cp.nanstd(cp.array([1, 2, 3, 4, 5], dtype='float64'))
</code></pre> | python|numpy|cupy | 0 |
351,161 | 59,278,948 | This is my training and validation accuracy is there something wrong with code ? or data? | <p>This is my classification code with pytorch. <br/>
it classify the image like cifar10.<br/> </p>
<p>The problem is I trained the classification model <br/>
but when I submit the result it always has very low accuracy<br/>
so I'm thinking is there something wrong with my code or data <br/></p>
<p>does my training a... | <p>You should have a seperate dataset for this line. Instead of train_dataset you should give val_dataset. You Val.Acc is high because you are validating on the training dataset itself.</p>
<pre><code> valloader = DataLoader(train_dataset, batch_size=batch_size, sampler=SubsetRandomSampler(valid_idx))
</code></pre> | machine-learning|deep-learning|pytorch | 0 |
351,162 | 59,072,423 | Pandas - Duplicate rows on function application | <p>I have a dataframe, and I'm trying to apply a single function to that dataframe, with multiple arguments. I want the results of the function application to be stored in a new column, with each row duplicated to match each column, but I can't figure out how to do this.</p>
<p>Simple example:</p>
<pre><code>df= pd.D... | <p>Using the <code>explode</code> method (pandas >= 0.25.0):</p>
<pre class="lang-py prettyprint-override"><code>df1 = df.assign(c=df.apply(lambda row: [row.a+10, row.a+11], axis=1))
df1 = df1.explode('c')
print(df1)
</code></pre>
<pre><code> a b c
1 4 7 14
1 4 7 15
2 5 8 15
2 5 8 16
</code></pre> | python|pandas | 0 |
351,163 | 59,289,721 | Bounding box of numpy array with periodic boundary conditions (wrapping) | <p>I would like to do something similar to <a href="https://stackoverflow.com/questions/4808221/is-there-a-bounding-box-function-slice-with-non-zero-values-for-a-ndarray-in">this</a> question, or <a href="https://stackoverflow.com/questions/31400769/bounding-box-of-numpy-array?noredirect=1&lq=1">this</a> other one,... | <p>We can adapt <a href="https://stackoverflow.com/a/59057567">this</a> answer like so:</p>
<pre><code>import numpy as np
def wrapped_bbox(a):
dims = [*range(1,a.ndim)]
bb = np.empty((a.ndim,2),int)
i = 0
while True:
n = a.shape[i]
r = np.arange(1,2*n+1)
ai = np.any(a,axis=tupl... | python|arrays|numpy|bounding-box | 0 |
351,164 | 59,074,630 | How do I set CRON job limits to match a user? | <p>I have a bash shell script that runs about 70 instances of a python application. Each python instance run TensorFlow 2.0 which wakes up once per hour and does some work.
The bash shell script runs fine in the user shell but core dumps after the 36th instance of the job when running in cron.</p>
<p>I have the shell... | <p>It turns out I need to set the pid limit for eth cron job as well.
This can be done as follows:</p>
<pre><code>/bin/echo 48000 | /usr/bin/sudo tee /sys/fs/cgroup/pids/system.slice/cron.service/pids.max
</code></pre>
<p>This sets the control group for the cron service to have a 48000 limit so that the threads limit... | python|tensorflow|cron|multicore|cron-task | 0 |
351,165 | 59,401,345 | How to delete tensorflow-datasets data | <p>I downloaded The Oxford-IIIT Pet Dataset using <a href="https://www.tensorflow.org/datasets" rel="nofollow noreferrer">tensorflow-datasets</a> and it contains corrupt data:</p>
<pre><code>Corrupt JPEG data: 240 extraneous bytes before marker 0xd9
Corrupt JPEG data: premature end of data segment
</code></pre>
<p>I ... | <p>Usually the datasets are stored in a .keras folder under your home folder. Simply deleting the old dataset will cause it to redownload upon execution.</p> | tensorflow|dataset|delete-file|tensorflow-datasets | 1 |
351,166 | 59,442,858 | What is the difference between the code below? | <p>What is the difference between these two lines of code?</p>
<pre class="lang-py prettyprint-override"><code>print(df.drop(df.where(df['Quantity']==0).index).rename(columns={'Weight':'Weight(oz)'}))
</code></pre>
<p>and</p>
<pre class="lang-py prettyprint-override"><code>print(df.drop(df[df['Quantity'] == 0].ind... | <p>It is difference because it uses <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>DataFrame.where</code></a>:</p>
<pre><code>df.where(df['Quantity']==0).index
</code></pre>
<p>it only replace non matched rows to <code>NaN</code>s, so th... | python|pandas | 3 |
351,167 | 59,067,277 | somehow my accuracy is very low on cifar10? | <pre><code>with torch.no_grad():
for data in test_loader:
images,labels = data
images, labels = images.to(device), labels.to(device)
outputs, features = net(images)
_ , predicted = torch.max(outputs,1)
total += labels.size(0)
correct += (predicted==labels).sum().item(... | <p>The trick training that exact dataset (cifar10) and getting better accuracy is to use data augmentation.</p>
<p>Originally cifar10 has 50.000 images for training and 10.000 for validation.</p>
<p>If you don't augment images while training you will overfit. Training accuracy will be much bigger than validation accu... | gpu|pytorch | 1 |
351,168 | 59,354,651 | Plotting multiple columns groupedby on a single graph | <p><a href="https://i.stack.imgur.com/da8Wy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/da8Wy.png" alt="enter image description here"></a></p>
<p>For the above Pandas DataFrame <code>pd</code> I want to plot according to the following conditions:</p>
<ul>
<li>A single line plot</li>
<li>For eac... | <p>Create your dataframe, make sure to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> to sort by algorithm and num_ingress.</p>
<pre><code>import pandas as pd
algorithm = ['A', 'A', 'A', 'A', 'A', 'B', '... | pandas|matplotlib|plot|group-by|seaborn | 2 |
351,169 | 59,347,143 | Connected components from an adjacency matrix using Numpy or Scipy | <p>I've the following adjacency matrix: </p>
<pre><code>array([[0, 1, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0]])
</code></pre>
<p>Which can be drawn like that:</p>
... | <p>While you could indeed use DFS to find the connected components, SciPy makes it even easier with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.connected_components.html#scipy.sparse.csgraph.connected_components" rel="noreferrer"><code>scipy.sparse.csgraph.connected_components</co... | python|numpy|graph|scipy | 11 |
351,170 | 59,236,488 | TensorBoard: adding output image to callback | <p>I built a network that attempts to predict raster images of surface temperatures.
The output of the network is a <code>(1000, 1000)</code> size array, representing a raster image. For training and testing these are compared to the real raster of their respective samples.
I understand how to <a href="https://www.ten... | <p>Depending on the <code>tensorflow</code> version you are using, I would have 2 different codes to suggest. I will assume you use > <code>2.0</code> and post the code I use for that version for image-to-image models. I basically initialize a callback with a noisy image (I am doing denoising but you can easily adap... | python|tensorflow|keras|raster|tensorboard | 2 |
351,171 | 59,068,185 | Pandas sum of variable number of columns | <p>I have a pandas dataframe like this -</p>
<pre><code>Time 1 A 2 A 3 A 4 A 5 A 6 A 100 A
5 10 4 6 6 4 6 4
3 7 19 2 7 7 9 18
6 3 6 3 3 8 10 56
2 5 9 1 1 ... | <p>Use numpy - idea is compare array created by <code>np.arange</code> with length of columns with <code>Time</code> columns converted to index with broadcasting to 2d mask, get matched values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where<... | python|pandas | 3 |
351,172 | 59,195,322 | Cannot Split Malaria Dataset using Tensorflow Datasets | <p>I am following the the <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb" rel="nofollow noreferrer">Transfer Learning Tutorial</a>. The notebook successfully runs using the Cats and Dogs Dataset but when I change it to malaria dataset it th... | <p>I tried the tutorial with the following code and it worked:</p>
<pre><code>(raw_train, raw_validation, raw_test), metadata = tfds.load(
'malaria',
split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
with_info=True,
as_supervised=True,)
</code></pre>
<p>Maybe if you could post the code you used we can compare.<... | python-3.x|tensorflow|tensorflow-datasets | 3 |
351,173 | 59,165,369 | TypeError: strptime() argument 1 must be str, not Period | <p>i have this data frame.</p>
<pre><code>import pandas as pd
from datetime import datetime
df = pd.DataFrame({'id': [11,22,33,44,55],
'name': ['A','B','C','D','E'],
'timestamp': [1407617838,965150022,1158531592,1500701864,965149631]})
</code></pre>
<pre><code>df
id name tim... | <p>If you take the year through the <code>dt</code> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/series.html#accessors" rel="nofollow noreferrer">acessor of timeseries</a>, you get integers (instead of "Period" objects):</p>
<pre><code>df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df['... | python|pandas | 1 |
351,174 | 59,162,223 | What is the use of drop_first in pandas? | <p>What exactly is the use of <code>drop_first=True</code> in the code below?</p>
<pre>
ins = pd.get_dummies(ins, columns=['gender', 'region'], <b>drop_first=True</b>)
</pre> | <p>The main reason for including the <code>drop_first</code> when using this function is to avoid creating a multicollinearity issue between the variables, this means that after using the <code>get_dummies()</code> function a regression model might find a linear relationship between them, hence not fulfilling the Guass... | python|pandas | 2 |
351,175 | 59,048,841 | Import json and convert all columns to strings | <p>I am trying to import a (very) large json file (3.3m rows, 1k columns), that has nested multiple nested jsons within it. Some of these nested jsons are double nested. I have found two ways to import the json file into a dataframe, however, I can't get the imported json to be flattened, and converted to strings at he... | <p>I found a solution that worked, and was able to both import and flatten the jsons, as well as convert all text to strings.</p>
<pre class="lang-py prettyprint-override"><code># Function to import data from ARIC json file to dataframe
def Data_IMP(path):
with open(path) as Data:
d = json.load(Data)
... | python|json|python-3.x|pandas | 0 |
351,176 | 59,255,537 | expected dense_4 to have 2 dimensions, but got array with shape (1449, 480, 640, 1) | <p>I'm trying to design a Convolutional Network to estimate the Depth of images using Keras.</p>
<p>I have RGB Input images with the shape of(1449,480,640,3) and have the Grayscale Output Depth Maps with the shape of (1449,480,640,1)
but at the end when I want to design the final layers, I get stuck. using a Dense lay... | <p>I guess your architecture has some problems. If I understood well, what you want in the output should be of size (1449,480,640,1). </p>
<p>First of all, your last layer activation is a softmax, and your loss is set to be the 'binary_crossentropy' which really does not make sense. and additionally, you have another ... | python|tensorflow|keras|depth|estimation | 1 |
351,177 | 59,297,336 | How to preserve rows with empty (nan) cells when doing groupby on a dataframe in python pandas | <p>I have a dataframe which contains four columns: ["Artist", "Album", "Title", "Point"] where the first three columns identify a song, and the fourth is a score. Each song may appear in a list multiple times, and some songs has no album information, which is a nan value in the corresponding cell.
I use the following c... | <p>.fillna('N/A') that will fix the searches. but with more data, there's probably a better solution</p>
<pre><code>A['Album'].fillna('N/A', inplace=True)
</code></pre>
<p>you sums should work then</p> | python|pandas|dataframe | 2 |
351,178 | 59,399,450 | Reshaping data frame and counting values based on criteria | <p>I have the data set below. I am trying to determine the type of customer by providing a tag. My excel crashes due to too much data when I attempt, so trying to complete with Python.</p>
<pre><code>item customer qty
------------------
ProdA CustA 1
ProdA CustB 1
ProdA CustC 1
ProdA CustD 1
ProdB CustA ... | <h3>Method 1:</h3>
<p>We can achieve this using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pd.crosstab</code></a>, and then using the sum of <code>ProdA</code> and <code>ProdB</code> to <a href="https://pandas.pydata.org/pandas-docs/stable/... | python|pandas | 2 |
351,179 | 59,454,756 | Python pandas dataframe from csv | <p>I have some data in a csv in the following format: </p>
<pre><code>5494;2006;4
3579;1143;3
1251;2567;2
5687;652;4
3018;3440;4
...
</code></pre>
<p>When I do </p>
<pre><code>df = pd.read_csv('ratings.csv')
</code></pre>
<p>, I only get 1 column 5494;2006;4 and the values below it are 3579;1143;3 ..... | <p>You just need to define the seperater, <code>df = pd.read_csv('ratings.csv', sep=';')</code></p> | python|pandas|csv | 1 |
351,180 | 59,256,077 | filter result in new column | <p>I have a panda file structure as below (python 3)</p>
<pre>
Particulars AMT
AA(AED)
QP 7
WP 8
ST 9
AB(USD)
RR 6
RA 8
DA(INR)
DRS 5
DRW 3
UTS 6
</pre>
<p>I want the output to be as below (python 3)</p>
<pre>
Particula... | <p>Try this:</p>
<pre><code>df['LOG'] = None
df['LOG'] = df[df['Particulars'].str.contains(r'\w+\(\w+\)')].reindex(range(0,len(df))).fillna('')
</code></pre>
<p>output:</p>
<pre><code> Particulars AMT LOG
0 AA(AED) AA(AED)
1 QP 7
2 WP 8
3 ST 9 ... | pandas|filter | 1 |
351,181 | 59,343,199 | KNN with tips dataset | <p>I'm trying to apply the <code>KNN</code> to the <code>tips dataset</code> and I mapped the objects as follows:</p>
<pre><code>f.Male=df.Gender.map({'Female':0,'Male':1})
df.Smokes = df.Smoker.map({'No': 0, 'Yes': 1})
df.Dinner = df.Time.map({'Lunch': 0, 'Dinner': 1})
df.Day_w = df.Day.map({'Sun': 0, 'Mon': 1, 'Tue'... | <p>The value error says, that the input values contain the string "female" (check your dataframe, if the values are really all numeric). </p>
<p>I woud expect that your column mapping for column "Gender" didn't work. In the code you assigned to mapping of the "Gender" column to the "Male" column (not "Gender" column),... | python|pandas|knn|valueerror | 1 |
351,182 | 59,447,941 | How to Read file and store content into a 2D matrix? | <p>I have a ton of data file in the same format as described below and I'm trying to make a colormesh plot from this:</p>
<pre><code>0 0 1 2
-3 1 7 7
-2 1 2 3
-1 1 7 3
</code></pre>
<p><code>[0 1 2]</code> of the first row are values for the y axis of the plot, and <code>[-3 -2 -1]</code> of the first column are ... | <p>You are getting the error because <code>Matrix</code> is a list and you are trying to index it using a <code>tuple</code>, <code>i,j</code>. And that is not a valid operation. You can index a list oly with <code>integers</code> or <code>slices</code></p>
<p>Secondly your <code>data</code> variable is already a <cod... | python|numpy|matplotlib|matrix | 1 |
351,183 | 59,253,239 | Python how to insert data from dataframe to MySQL | <p>I get row of datafram and insert to mysql with this code, res is data I want to insert to mysql.</p>
<pre><code>res = df.loc[df.ID == l_id]
mycursor = mydb.cursor()
sql = "INSERT INTO log (id, user, number, state, j_id) VALUES (%s, %s, %s, %s, %s )"
val = [(None, res['User'], res['Pages'] , res['State'], l_id )]
... | <p>Try this:</p>
<pre><code>val = [(None, res['User'].item(), res['Pages'].item() , res['State'].item(), l_id )]
</code></pre>
<p>The res['User'] by itself returns a pandas object which you can't pass as mysql arguments. You need to extract the value of the pandas object.</p> | python|mysql|pandas|dataframe | 1 |
351,184 | 59,082,207 | How to deal with itertools.product when using numpy array? | <p>I want to get tensor products of two numpy arrays. For example, given</p>
<pre><code>a = np.random.uniform(-1,1,size=[10,2])
b = np.random.uniform(2,3,size=[20,3])
</code></pre>
<p>and I want to take </p>
<pre><code>products = np.array(list(prod for prod in itertools.product(a,b)))
</code></pre>
<p>However, when... | <pre><code>In [129]: products = np.array(list(prod for prod in itertools.product(a,b)))
</code></pre>
<p>The result is a 2d array - but with object dtype:</p>
<pre><code>In [130]: products.shape
Out[130]: (200, 2)
</code></pre>
<p>The first row of this arra... | python|arrays|numpy|itertools | 2 |
351,185 | 59,141,953 | Add a new dataframe column which counts the values in certain column less than the date prior to the time | <p> EDITED <br><br>
I want to add a new column called prev_message_left which counts the no. of messages_left per ID less than the date prior the given time. Basically I want to have a column which says how many times we had left message on call to that customer prior to the current time and date. This is how my data ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> to get the cumulative sum in the correct order by groups. You can create groups using <a href="https://pandas.pydata.org/pandas-docs/stable/refer... | pandas|dataframe|group-by | 1 |
351,186 | 59,455,086 | split multiple values into two columns based on single seprator | <p>I am new to pandas.I have a situation I want to split length column into two columns a and b.Values in length column are in pair.I want to compare first pair smaller value should be in a nad larger in b.then compare next pair on same row and smaller in a,larger in b.</p>
<p>I have hundred rows.I think I can not use... | <p>The problem comes from the fact that your length column is made of set not lists. </p>
<p>Here is a way to do what you want by casting your length column as list:</p>
<pre><code>df['length'] = [list(x) for x in df.length] # We cast the sets as lists
df['a'] = [x[0::2] for x in df.length]
df['b'] = [x[1::2] for x i... | python-3.x|pandas|postgresql | 0 |
351,187 | 59,417,495 | Conditional splitting the data into training and testing (Pandas) | <p>I have a code using Python to do a prediction task. The task is to predict the sales for a company across different years from 2015 to 2019.</p>
<p>I want to split the data into training set and testing set.</p>
<p>But the question is, I want to train the model using the data from 2015 to 2018, and test the model ... | <p>Since you've got a condition at the very beginning, you lose the benefits of using shuffling methods used in machine learning preprocessing. Therefore I would recommend not performing train-test split with such condition (I assume biased results). Nevertheless if you need to do it then try:</p>
<pre><code>train = y... | python|pandas|machine-learning | 0 |
351,188 | 59,473,988 | Fast way of relabeling array elements or making elements contiguous in python | <p>I have a massive size 3d array to deal with. I want to relabel elements in following way</p>
<pre><code>import numpy as np
given_array = np.array([1, 1, 1, 3, 3, 5, 5, 5, 8, 8, 8, 8, 8, 23, 23, 23])
required_array = np.array([0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4])
</code></pre>
<p>I know there is <code>... | <p>If the given array is unsorted, this will be quicker than sorting it:</p>
<pre><code>from numba import njit
import numpy as np
@njit()
def relabel_fast(array, count):
i = 0
while i < len(array):
data = array[i]
count[data] += 1
i += 1
a = 1 # Position in count
b = 0 # Pos... | arrays|numpy|image-processing|scipy|numba | 2 |
351,189 | 59,394,530 | What is the fastest Mask R-CNN implementation available | <p>I'm running a Mask R-CNN model on an edge device (with an NVIDIA GTX 1080). I am currently using the Detectron2 Mask R-CNN implementation and I archieve an inference speed of around 5 FPS.</p>
<p>To speed this up I looked at other inference engines and model implementations. For example ONNX, but I'm not able to ga... | <p>It's almost impossible to get higher inference speed for Mask R-CNN on GTX 1080. You may check <a href="https://github.com/facebookresearch/detectron2" rel="nofollow noreferrer"><code>detectron2</code></a> by Facebook AI Research.</p>
<p>Otherwise, I'd suggest to use <a href="https://github.com/dbolya/yolact" rel="n... | tensorflow|deep-learning|computer-vision|pytorch|onnx | 3 |
351,190 | 59,214,763 | Pandas.read_csv() FileNotFoundError even though file exists | <p>I try to run this piece of Python 3 code in my Anaconda Jupyter Notebook (same cell, nothing else in):</p>
<pre><code>train = pd.read_csv('tutorial\labeledTrainData.tsv', header=0, delimiter="\t", quoting=3) #OK!
test = pd.read_csv('tutorial\testData.tsv', header=0, delimiter="\t", quoting=3) #FileNotFou... | <p>Python is interpreting <code>\t</code> as a tab in the string <code>'tutorial\testData.tsv'</code>.</p>
<p>You can change this, as you've found out, by using <code>r"..."</code> to indicate it as a <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow noreferrer... | python|pandas|file|csv|file-io | 3 |
351,191 | 59,204,740 | Mapping between ids and indices using numpy arrays | <p>I'm working on a graphical application that uses shapes such as quads, trias, lines etc. to represent geometry.</p>
<p>The input data is based on ID's.
A list of points is provided, each with an ID and coordinates (x, y, z)
A list of shapes is provided, each defined using the ids from he list of points</p>
<p>S... | <p>As I understand, essentially you're looking for a fast way to find the index of a number in a list, e. g., you have a list like:</p>
<pre><code>nodes = [932, 578, 41, ...]
</code></pre>
<p>and need a structure that would give </p>
<pre><code>id_to_index[932] == 0
id_to_index[578] == 1
id_to_index[41] == 2
# etc.... | python|arrays|numpy | 0 |
351,192 | 59,163,724 | How to append a numpy array with a few record array fields? | <p>I have an array with a few record fields.</p>
<pre><code>arr=np.array([[(0,1,3)]],dtype=[('A','i4'),('B','i4'),('C','u4')])
print(arr)
[[(0, 1, 3)]]
</code></pre>
<p>I'd like to add a new column and to get an array like this one: </p>
<pre><code>arr2=np.array([[(0,1,3,0)]],dtype=[('A','i4'),('B','i4'),('C','u4'),... | <pre><code>import numpy as np
n = 4
m = 5
arr=np.array([[(3*(j*n + i),3*(j*n + i)+1,3*(j*n + i)+2) for i in range(n)] for j in range(m)],dtype=[('A','i4'),('B','i4'),('C','u4')])
c = np.array([[(i*j,) for i in range(1,n+1)] for j in range(1,m+1)],dtype=[('D','i4')])
arr2 = np.zeros(arr.shape,dtype=[('A','i4'),('B','... | python|arrays|numpy | 1 |
351,193 | 59,450,102 | Calculating the orientation of a figure to straighten it out (in python) | <p>I have a code that calculates the orientation of a figure and a function that straightens the figure out based on the calculated orientation. When I run the code, the orientation seems to be fine, but when the function tries to straighten the figure out it looks like the figure has gotten another shape. Could there ... | <p>Here is one way to do deskewing using the rotated bounding rectangle in Python/OpenCV</p>
<p>Input:</p>
<p><a href="https://i.stack.imgur.com/MufC6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MufC6.png" alt="enter image description here"></a></p>
<pre><code>import cv2
import numpy as np
# ... | python|numpy|opencv|image-manipulation | 1 |
351,194 | 59,314,269 | Pandas merge: Insert columns at specific positions | <p>I have 2 dataframes:</p>
<pre><code>df_a ["user", "name", "zip", "city"]
df_b ["user", "gender", "country"]
</code></pre>
<p>I'm joining these 2 dataframes on <code>user</code> column-</p>
<pre><code>final_df = pd.merge(df_a, df_b, on='user', how='left')
# column order --> ["user", "name", "zip", "city", "gend... | <p>You could do:</p>
<pre class="lang-py prettyprint-override"><code>column_list = list(final_df.columns)
#Now rearrange the list the way you want the columns to be
#Then do
final_df = final_df[column_list]
</code></pre> | python|python-3.x|pandas|dataframe | 0 |
351,195 | 59,309,294 | How to remove rows in pandas dataframe column that contain the hyphen character? | <p>I have a DataFrame given as follows:</p>
<pre><code>new_dict = {'Area_sqfeet': '[1002, 322, 420-500,300,1.25acres,100-250,3.45 acres]'}
df = pd.DataFrame([new_dict])
df.head()
</code></pre>
<p>I want to remove hyphen values and change acres to sqfeet in this dataframe.
How may I do it efficiently?</p> | <h2><strong>Use list comprehension:</strong></h2>
<pre><code>mylist = ["1002", "322", "420-500","300","1.25acres","100-250","3.45 acres"]
# ['1002', '322', '420-500', '300', '1.25acres', '100-250', '3.45 acres']
</code></pre>
<p><strong>Step 1: Remove hyphens</strong></p>
<pre><code>filtered_list = [i for i in myli... | python-3.x|pandas|dataframe | 1 |
351,196 | 59,374,220 | How to manipulate your Data Set based on the values of your index? | <p>I have this Dataset, <a href="https://i.stack.imgur.com/uaDO5.png" rel="nofollow noreferrer">wind_modified</a>. In this Dataset, columns are the locations and Index is the Date. And the Values in the columns are the wind speeds.
Let's say I want to find the average wind speed in January for each location, how do I u... | <p>Sure, if want all Januaries for all years first filter them by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and add <code>mean</code>:</p>
<pre><code>#if necessary convert index to DatetimeIndex
#df.index ... | python|pandas|dataframe|dataset | 1 |
351,197 | 59,203,688 | dynamic name for a file in Python | <p>I have a subject_id which is a dynamic number.For instance, it could be equal to 60. I am manually defining some file names as follows:
x_file = "50.txt"
x_csv_file = "50.csv"
The number (50) could have been 1 or any-number else. Is there any way that I can define <code>subject_id=50</code> JUST one time and then us... | <p>You might want to define a simple function for this</p>
<pre><code>def file_name(subject_id):
x_file = '{}.txt'.format(subject_id)
x_csv_file = '{}.csv'.format(subject_id)
return x_file, x_csv_file
</code></pre> | python|pandas|numpy|dynamic|filenames | 1 |
351,198 | 59,130,088 | How to sort a pandas dataframe by the length of its rows | <p>I have a pandas dataframe i want to sort by the length of its rows. The dataframe looks like this: <a href="https://i.stack.imgur.com/0dF91.png" rel="nofollow noreferrer">a dataset loaded into a dataframe</a>. The dataframe consists of ca. 7000 transactions. I want to sort so that the transactions that include the m... | <p>You can try:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[pd.isna(df).sum(axis=1).sort_values(axis=0).index]
</code></pre>
<p>In short what it does:
<code>pd.isna()</code> will return <code>true/false</code> dataframe of the same shape as your original one with <code>True</code> if respective cell is... | python|pandas|sorting|dataframe|data-science | 2 |
351,199 | 59,383,082 | Merge df in two keys, just working for one key | <p>so I've two df, They need to be merged in two keys <code>Channel and Week</code>. When attempting the merging it returns NaN values for all rows in Column Contacts_F..</p>
<p>Data:</p>
<pre><code>df = pd.DataFrame({ 'week' : ['01', '02', '45'] ,
'Channel' : ['AA', 'BB', 'CC'],
... | <p>See below for working example of how to perform merge. Various syntax errors in prompt are corrected. </p>
<pre class="lang-py prettyprint-override"><code> import pandas as pd
df = pd.DataFrame({'week': [1, 2, 45],
'Channel': ['AA', 'BB', 'CC'],
'level': ['1degr... | python|pandas|merge | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.