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 |
|---|---|---|---|---|---|---|
358,600 | 66,858,937 | Pandas drop duplicates but keep maximum value | <p>I'm sure variations of this question have been asked, but I have a very specific scenario that I need to execute efficiently.</p>
<p>Imagine a dataframe outlined like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Value</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>... | <p>I'd suggest sorting by descending <code>value</code>, and using <code>drop_duplicates</code>, dropping the values that have duplicate <code>Date</code> and <code>id</code> values. The first value (e.g. the highest), will be kept by default</p>
<pre><code>df.sort_values("Value", ascending = False).drop_dupl... | python|pandas | 3 |
358,601 | 66,980,857 | Conditional filtering on dataframe with multiple columns | <p>I have a dataframe with 80 columns. Out of those, there are some 45 columns that I need to check for "all-zero" value filter. If for a row, all those 45 columns have zero as their value, then that row is marked as True. Otherwise as False.</p>
<p>Here's a sample dataframe for this problem:</p>
<pre><code>d... | <p>You can use <code>loc</code> indexing and then check if <code>all</code> entries of rows (<code>axis=1</code>) equals to 0 (<code>eq(0)</code>):</p>
<pre class="lang-py prettyprint-override"><code>df["mark"] = df.loc[:, "col5": "col19"].eq(0).all(axis=1)
</code></pre>
<p>to get</p>
<pre... | python-3.x|pandas|dataframe|filter | 1 |
358,602 | 67,063,917 | How to stack only some of pandas DataFrame series on bar chart | <p>I have a following DataFrame:</p>
<pre><code>from matplotlib import pyplot as plt
import pandas as pd
plotdata = pd.DataFrame({
"pies_2018":[40, 12, 10, 26, 36],
"pies_2019":[19, 8, 30, 21, 38],
"pies_2020":[10, 10, 42, 17, 37],
"pies_produced": [100, 80, 75, ... | <p>Try to plot twice with option <code>stacked</code> and <code>position</code>:</p>
<pre><code>fig, ax = plt.subplots(figsize=(10,6))
# plot first 3 columns, stacked and shifted left
plotdata.iloc[:,:-1].plot.bar(stacked=True, position=1, width=.4, ax=ax)
# plot last column, shifted right
plotdata.iloc[:,-1:].plot.b... | python|pandas|matplotlib | 2 |
358,603 | 67,047,348 | Adjust seaborn countplot by hue groups | <p>I have a dataset that looks something like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">status</th>
<th style="text-align: center;">age_group</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">failure</td>
<td style="text-align: center;">18-2... | <p>The easiest way to show the proportions, is via <code>sns.histogram(..., multiple='fill')</code>. To force an order for the age groups and the status, creating ordered categories can help.</p>
<p>Here is some example code, tested with seaborn 0.11.1:</p>
<pre class="lang-py prettyprint-override"><code>import matplot... | python|pandas|matplotlib|statistics|seaborn | 1 |
358,604 | 66,866,776 | PyTorch Installation Error - Could not find a version that satisfies the requirement | <p>Hello there! I’ve been trying to install PyTorch, but so far all I got is error messages. I tried the command line</p>
<pre><code>pip install torch==1.8.1+cpu torchvision==0.9.1+cpu torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html
</code></pre>
<p>that was given on the tutorial, and I get the... | <p>I had the same issue but it was because of my internet connection. Can you confirm that you have access to this <a href="https://download.pytorch.org/whl/torch_stable.html" rel="nofollow noreferrer">URL</a>?</p>
<p>If it is okay, it may be because of your Python version. Which version are you on? PyTorch 1.8.1 works... | pytorch | 0 |
358,605 | 67,181,797 | Filter array by value in last column | <p>I have matrix like this:</p>
<pre><code>m1 =
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 2, 3, 1, 1, 0]
[1, 3, 7, 3, 1, 1]
</code></pre>
<p>I need to filter it tp get value 1 in the last column. So result should be like this:</p>
<pre><code>filter_array =
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 3, 7, 3, 1, 1]
</co... | <p>Simply do this:</p>
<pre><code>filtered = m1[m1[:, -1] == 1]
</code></pre>
<p><strong>Note</strong>: Your original code did not work because you were assigning the return value of <code>append()</code> method to the <code>filter_array</code>. Since the return value when append to a list is successful is <code>None</... | python|arrays|numpy|array-filter | 2 |
358,606 | 67,072,769 | How can I set positive values to one color and negative values to another in matplotlib? | <p>I have a bar plot of random positive and negative values. I would like to set all negative values to the color blue and all positive values to red in the bar chart.
How do you make negative values to blue and positive values to red?</p>
<p>This is what I have so far and tried but I get an error:</p>
<pre><code>rand ... | <p>The numpy expression <code>rand < 0</code> gives an array of True and False values. This can't be used for an <code>if</code>-test. In an <code>if</code>-test the whole expression needs to be either True or False.</p>
<p>However, the expression <code>rand < 0</code> can be used as an index into an array, makin... | python|numpy|matplotlib|jupyter | 2 |
358,607 | 67,022,524 | I don't find a way to use my wav file as dataset in PyTorch | <p>hello I am new to PyTorch and I want to make a simple speech recognition but I don't want to use pytorch.datasets I have some voices for dataset but I don't find anywhere to help me.</p>
<p>I want to use .wav files. I saw a tutorial but he used pytorch dataset.</p>
<pre class="lang-p prettyprint-override"><code>impo... | <p>Since you are talking about the speech recognition and pytorch, I would recommend you to use a well-developed set of tools instead of doing speech-related training tasks from scratch.</p>
<p>A good repo on github is <a href="https://github.com/espnet/espnet" rel="nofollow noreferrer">Espnet</a>. It contains some qui... | python|pytorch|dataset|custom-dataset | 1 |
358,608 | 67,097,912 | How can I merge summed data to non-summed data? | <p>I am trying to merge two data frames together, based on PSID and 'location'. One data frame comes to me summed and one comes to me non-summed.</p>
<p>Here is the summed DF.</p>
<p><a href="https://i.stack.imgur.com/jA9Jk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jA9Jk.png" alt="enter image d... | <p>Lets try, transform sum before we merge; Happy to review if this is not what you want.</p>
<p>calc spending sum</p>
<pre><code>g=df_second.assign(spending_sum=df_second.groupby('location')['spending'].transform('sum'))
</code></pre>
<p>merge</p>
<pre><code>df_combined = pd.merge(df_first, g, left_on='PSID', right_on... | python|python-3.x|pandas|dataframe | 1 |
358,609 | 66,988,968 | Reloading a PyQt5 App without Restarting it first | <p>I have created an app and on one of the Windows (<code>CreateProjectWindow(QDialog)</code>) I complete a form which I then submit using <code>self.buttonBox.accepted.connect(self.getInfo)</code>.</p>
<p>On submission, I want the <code>self.tableComboBox</code> in <code>UpdateProjecWindow(QDialog)</code> automaticall... | <p>There is normally no need to restart a Qt application, and certainly this is not required for your case: restarting the QApplication is almost like closing the program and opening it again, doing that just to update some data doesn't make any sense at all.</p>
<p>A possible solution is to create a custom signal for ... | python-3.x|pandas|pyqt5 | 0 |
358,610 | 66,986,195 | keras stuck at 0 loss value | <p>i'm doing <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia" rel="nofollow noreferrer">this kaggle contest</a> where i have to classify this x-ray in 3 category bacteria,virus or normal. Problem is that my accuracy is really low like 25% and loss is stuck at 0. I use a pretrained nn using weight... | <p>There are 3 categories to predict, so the last layer in your model should contain 3 neurons(1 for each class), not 1 neuron</p>
<p>Try to change</p>
<pre><code>mio_classificatore = Dense(1, activation='softmax')(base_model.layers[-2].output)
</code></pre>
<p>to</p>
<pre><code>mio_classificatore = Dense(3, activation... | python|tensorflow|keras | 0 |
358,611 | 66,871,951 | How to find RGB value of a segmentation in Python | <p><a href="https://i.stack.imgur.com/xTcXE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xTcXE.jpg" alt="enter image description here" /></a></p>
<p>I try to find de mean RGB value of the segmentation in the picture enclosed.</p>
<p>Probably I have to transform it to a numpy array and save this nu... | <p>Use <a href="https://scikit-image.org/" rel="nofollow noreferrer">scikit-image</a> library</p>
<pre><code>pip install scikit-image
</code></pre>
<p>Read and find mean</p>
<pre><code>from skimage import io
image = io.imread('https://i.stack.imgur.com/xTcXE.jpg')
</code></pre>
<p>Mean RGB values for all pixels in the ... | python|numpy|rgb | -1 |
358,612 | 67,021,748 | ImportError: Spatial indexes require either `rtree` or `pygeos` in geopanda but rtree is installed | <p>I am trying to clip spatial data in python but when I run my code...</p>
<pre><code>europe = gpd.clip(worldmap, europe_bound_gdf)
</code></pre>
<p>... I get the error:</p>
<p>(<code>ImportError: Spatial indexes require either </code>rtree<code>or</code>pygeos`.)</p>
<p>When I try to install rtree using:</p>
<pre><co... | <p>I had the same issue and this solved it for me:</p>
<pre><code>pip uninstall rtree
sudo apt install libspatialindex-dev
pip install rtree
</code></pre>
<p>Found the answer <a href="https://gis.stackexchange.com/questions/379648/error-while-using-sjoin-in-geopandas">here</a>.</p> | python|gis|geopandas | 11 |
358,613 | 66,909,065 | How to set a limited defined random values in numpy matrix | <p>How to set a limited random values by amount and range in nupmy matrix ?</p>
<p>Means instead :</p>
<pre><code>random_matrix = np.random.rand(5, 5)
</code></pre>
<pre><code>[[0.38555213 0.96454126 0.91586422 0.92638243 0.85516641]
[0.64717218 0.2716665 0.70945594 0.74754943 0.48870502]
[0.23381316 0.01992578 0.8674... | <p>If i understand the question correctly, you want to create a matrix that is zero in all places except for 3 random indices that will have a random value between the range 1-5.</p>
<p>For this i would suggest doing:</p>
<pre><code>null_matrix = np.zeros((5,5), dtype=np.int32)
rng = np.random.default_rng()
x = rng.ch... | python|numpy | 0 |
358,614 | 66,948,562 | How to flag an outlier(s) /anomaly in selected columns in python? | <p>In the dataset <code>df</code> below. I want to flag the anomalies in all columns except <code>A</code>, <code>B</code>,<code>C</code> and <code>L</code>.</p>
<p>Any value less than 1500 or greater than 400000 is regarded as an anomaly.</p>
<pre><code>import pandas as pd
# intialise data of lists
data = {
... | <p>If you set the subset as the argument of the apply function, you will get what you want.</p>
<pre><code>exclude_cols = ['A','B','C','L']
def flag_outliers(s, exclude_cols):
if s.name in exclude_cols:
print(s.name)
return '' # or None, or whatever df.style() needs
else:
s = pd.to_nume... | python|pandas | 1 |
358,615 | 66,774,430 | ValueError: setting an array element with a sequence when creating new columns in pandas | <p>I am trying to create a new column Trend by writing this code</p>
<pre><code>df_cal['Trend'] = np.where((df_cal['75% Quantile'] > df_cal['Shift 75% Quantile']) & (df_cal['25% Quantile'] > df_cal['Shift 25% Quantile']), "Up",
np.where(df_cal['75% Quantile'] < df_cal['Shift 7... | <h3>Explanation</h3>
<p>I use pandas.mask() to achieve the conversion you need</p>
<h3>Source Code</h3>
<pre><code>up_cond = (df_cal['75% Quantile'] > df_cal['Shift 75% Quantile'])
& (df_cal['25% Quantile'] > df_cal['Shift 25% Quantile'])
down_cond = (df_cal['75% Quantile'] < df_cal['Shift 75% Quantile']... | python-3.x|pandas|numpy | 0 |
358,616 | 66,894,031 | CNN using tensorflow from_tensor_slices | <p>I'm trying to make a classification CNN using image data. I have 10,000 images, which I've divided up into 8,000 for training and 2,000 for validation. They start out as simple numpy arrays with shape (8000, 192, 192) and (2000, 192, 192) respectively. I'm trying to load them into TF following <a href="https://www.t... | <p><a href="https://www.tensorflow.org/tutorials/load_data/numpy" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/load_data/numpy</a><br />
you must set the BATCH_SIZE like this, if you don't need BATCH_SIZE, just set number to the size of whole data</p>
<p>BATCH_SIZE = 64<br />
train_dataset = train_dat... | python|tensorflow|keras|dataset|conv-neural-network | 0 |
358,617 | 66,794,360 | Calculating covariance matrix amongst different features using Pandas dataframe | <p>I have a dataset into a pandas dataframe with 9 set of features and 249 rows, I would like to get a covariance matrix amongst the 9 features (resulting in a 9 X 9 matrix), however, when I use the df.cov() function, I only get a 3 X 3 matrix. What am I doing wrong here?</p>
<p>Thanks!</p>
<p>Below is my code snippet<... | <p>The excluded columns are probably non-numeric (even though they look like so!). Try</p>
<pre><code>cov_processed_df = processed_df.astype(float).cov()
</code></pre>
<p>To see the data types of the original df, you may run:</p>
<pre><code>print(processed_df.dtypes)
</code></pre>
<p>If you see <code>"object"... | python|pandas|dataframe|covariance | 1 |
358,618 | 67,171,253 | Insert or append empty rows to a numpy array | <p>There are references to using <code>np.append</code> to add to an initially empty array, such as <a href="https://stackoverflow.com/questions/22392497">How to add a new row to an empty numpy array</a>.</p>
<p>Instead, my question is how to allocate extra empty space at the end of an array so that it can later be ass... | <p>I find that the fastest solution is to create an <strong>empty</strong> larger array and then copy the input array into its initial rows:</p>
<pre><code>shape = (1000, 1000)
array = np.ones(shape)
new_shape = (2000, 1000)
def version1(): # Uses np.concatenate().
new_rows = np.square(array)
return np.concatenat... | numpy | 0 |
358,619 | 66,833,232 | Pandas groupby without any aggregating operations | <p>I have a dataframe as shown below, and I am trying to "group" by Col1 (see desired output). This should be obvious, but I must not be searching for the right key words. Everything I try with groupby either returns a series or seems to need some kind of aggregation.</p>
<pre><code>df = pd.DataFrame({'Col1':... | <p>In my understanding, this should achieve your goal: Multiindexing</p>
<pre><code> df = pd.DataFrame({'Col1': ['A','B','A','B','B','B','A','A','B',],
'Col2': ['q','e','r','y','c','a','j','g','v',],
'Col3': [1,13,5,22,13,2,5,9,12],
})
print(df.set_index(["C... | python|pandas-groupby | 0 |
358,620 | 66,885,736 | 'TensorDataset' object has no attribute 'size' | <p>I tried to load csv file into tensor dataset for vertical federated learning.
The reference website is <a href="https://github.com/OpenMined/PyVertical/blob/master/examples/PyVertical%20Example.ipynb" rel="nofollow noreferrer">https://github.com/OpenMined/PyVertical/blob/master/examples/PyVertical%20Example.ipynb</a... | <p>Okay, it is clearer now ! So <code>add_idx</code> creates a new class which inherits from the one you give as arguments. Therefore when you call</p>
<pre><code>temp = add_ids(data_utils.dataset.TensorDataset)
</code></pre>
<p><code>temp</code> is actually a child class from <code>TensorDataset</code>. The way its <c... | pytorch|dataset|tensor | 0 |
358,621 | 67,079,040 | How to vectorize Numpy Array Modification like in Matlab | <p>Using Matlab you can modify an array from indices using vectorization :</p>
<pre><code>A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>Output :</p>
<pre><code>A =
1 2 3 4 5 6 7 8 9
</code></pre>
<p>Modifying :</p>
<pre><code>A([2,4,6:9]) = -1
</code></pre>
<p>Output :</p>
<pre><cod... | <p>You can't combine a fancy integer index and a slice like that in numpy, so you have two options:</p>
<ol>
<li><p>Convert the slice to numerical indices:</p>
<pre><code>A = np.array([1,2,3,4,5,6,7,8,9])
A[[1, 3, 5, 6, 7, 8]] = -1
</code></pre>
<p>Notice the double square brackets: the index is a list of integers.</p>... | python|matlab|numpy | 2 |
358,622 | 66,775,301 | Trying to group repeated x values, and find the mean of the y values associated with these repeats | <p>I am using pandas. I wrote this script that does what I want but is definitely not optimized at all. Basically, I find all x repeats in namearray, take the average of the associated y values, replace the y value of the first row with the average and remove all repeated x value's rows except for the first row. Effect... | <pre><code>data.groupby(['x']).mean()['y']
</code></pre>
<p>In this way you group the data based on <code>x</code> find the mean of all columns associated to that group by calling <code>.mean</code> and the slice the column <code>y</code> that you need.</p> | python|pandas | 0 |
358,623 | 67,169,115 | Series of numpy operations seem to depend on numpy arrays initialization | <p>I'm in the process of vectorizing a series of operations with numpy arrays. And in doing that, I'm getting different results in different executions of my code. I'm using <code>numpy.random.randn</code> to get numpy arrays of the shapes that I need and testing if my operations do what I want them to do. I sometimes ... | <p>Don't reshape after <code>broadcast_to</code>. Transpose if you must, or use <code>big_C[:,:,None,:]</code> to make a (2,3,1,6,8)</p> | python|numpy|array-broadcasting | 1 |
358,624 | 66,993,629 | How to explode pandas and add new rows and columns based on condition | <p>I have a dataframe like this:</p>
<pre><code>start stop speaker_label y
309.16 309.58 2 5
312.01 312.59 2 5
313.4 313.59 1 4
314.35 314.92 2 4
316.96 317.27 1 5
319.36 319.89 1 5
322.01 323.10 2 7
</code>... | <p>As I understand the bullet requirements, you can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><strong><code>explode</code></strong></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"... | python|pandas | 1 |
358,625 | 67,060,643 | How to decode bit code to emoji python pandas | <p>How to decode bit code to emoji from each text of a row in pandas, study case sentiment analysis</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Text</th>
<th>Sentimen</th>
</tr>
</thead>
<tbody>
<tr>
<td>\xf0\x9f\x8e\xb6 la la la...hm hmm \xf0\x9f\x8e\xa7 "Semua diam ,semua bisu&qu... | <p>Apply the <code>encoding</code> parameter while converting source to a data frame.</p>
<p><strong>Example</strong> with hard-coded text:</p>
<pre><code>import io
import pandas as pd
data_string='''
Text Sentimen
\xf0\x9f\x8e\xb6 la la la...hm hmm \xf0\x9f\x8e\xa7 "Semua diam ,semua bisu" "Kita cob... | python|pandas|decode|emoji | 0 |
358,626 | 67,047,188 | need a "bag of words" type of transformer | <p>I have a NLP project where a collection of words are encoded currently by <code>w2v</code>, to compare to other collections of words. I'd like to try <code>transformers</code> which could give a better encoding than <code>w2v</code>. However, due to the nature of the data, I won't need positional encoding at all (du... | <p>You can access the repective embedding layer with <a href="https://huggingface.co/transformers/main_classes/model.html#transformers.PreTrainedModel.get_input_embeddings" rel="nofollow noreferrer">get_input_embeddings()</a>. Please have a look at this example for roberta:</p>
<pre class="lang-py prettyprint-override"... | nlp|word2vec|huggingface-transformers|transformer-model | 1 |
358,627 | 67,038,338 | Plotting Legend On Pandas Plot | <p>I have the current dataframe:</p>
<p><a href="https://i.stack.imgur.com/CJvnO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CJvnO.png" alt="enter image description here" /></a></p>
<p>I have used the pandas inbuilt plot to kind of plot the different regions on 1 graph against each other and got ... | <p>Take <code>region_name</code> A, B, C, D as example</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import matplotlib.pyplot as plt
iterables = [[2000, 2019], ['A', 'B', 'C', 'D']]
index = pd.MultiIndex.from_product(iterables, names=['year', 'region_name'])
df = pd.DataFrame({'all_motor_ve... | python|pandas|plot | 1 |
358,628 | 66,901,976 | PyCharm unsolved reference 'linspace' in '__init__.pyi | __init__.pyi' | <p>PyCharm gives me an unsolved reference warning when I use np.linspace.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
ls = np.linspace(0, 100, 5)
</code></pre>
<pre class="lang-py prettyprint-override"><code>Cannot find reference 'linspace' in '__init__.pyi | __init__.pyi'
</code></pre>
<p>Th... | <p>As commented by user2235698, I was running an older version of PyCharm 2020.3 which contains a bug (should be fixed in version 2020.3.3), see <a href="https://youtrack.jetbrains.com/issue/PY-46169" rel="nofollow noreferrer">https://youtrack.jetbrains.com/issue/PY-46169</a>.</p>
<p>To fix it manually I changed the fo... | python|numpy|pycharm|warnings | 0 |
358,629 | 67,094,410 | How to sort values in Pandas based on values in other column? | <p>I have dataframe like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>int_time</th>
<th>leng</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>4123</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>243</td>
<td>2</td>
</tr>
<tr>
<td>7</td>
<td>1232</td>
<td>3</td>
</tr>
<tr>
<td>... | <p>you can use merge -</p>
<pre><code>n = df['int_time'].max()
new_df = pd.DataFrame({'id': range(1, int(n) + 1)})
new_df = new_df.merge(df, left_on='id', right_on='int_time', how= 'left').fillna(0).drop('id_y', axis=1).rename(columns={'id_x': 'Id'})
print(new_df)
</code></pre>
<p><strong>output-</strong></p>
<div clas... | python|pandas|dataframe | 1 |
358,630 | 66,823,677 | How to draw a family tree from a Pandas DataFrame? | <p>I have a table where I store information about my ancestors. As an example, I created a similar table inspired by The Godfather.</p>
<pre><code> |--------+---+-------------+-----------+------+------+--------+--------+----------------+----------------|
| ID | S | First name | Last name | DoB | DoD | FID ... | <p>I improved the drawing but it still not reach my expectations. So here is the code with some comments on modifications.</p>
<ul>
<li>Blank cells blank instead of <code>NaN</code>:
<ul>
<li><code>keep_default_na=False</code></li>
</ul>
</li>
<li>Replacing each blank in <code>ParentID</code> by a specific string:
<ul>... | python-3.x|pandas|data-visualization|graphviz|directed-acyclic-graphs | 2 |
358,631 | 67,149,912 | RuntimeError: CUDA runtime implicit initialization on GPU:0 failed. Status: all CUDA-capable devices are busy or unavailable | <p>Problem:
when I run the following command</p>
<pre><code>python -c "import tensorflow as tf; tf.test.is_gpu_available(); print('version :' + tf.__version__)"
</code></pre>
<p>Error:</p>
<pre><code>RuntimeError: CUDA runtime implicit initialization on GPU:0 failed. Status: all CUDA-capable devices are busy ... | <p>I can confirm the case mentioned in a comment.</p>
<p>I had the problem while working with an Ubuntu VM, executed on VMware ESXi host, and using a <strong>vGPU</strong> partition for a v100 Nvidia GPU.</p>
<p>I got the same error, and I have already tried changing cuda versions and downloading (pip) softwares compil... | python|tensorflow|gpu|nvidia | 1 |
358,632 | 66,890,521 | Optimize and batch byte file data into keras models | <p>I'm trying to feed my model.fit with chunked data since my entire dataset doesn't fit my memory.
TF version is 2.4.</p>
<p>I've optimized dataset stored in file saving it in byte, each col is 1 byte (0-255) but now I need to read it in chunk and start learning process of my network.</p>
<p>Before this I was using .c... | <p>Let <code>file</code> be the file, in which you store the data. To create a dataset, one first needs to create a <code>generator</code> for reading the data. Schematically, it should have the following structure:</p>
<pre><code> def generator(file):
with open(file,'r') as f:
for linne in f:
... | python|tensorflow|keras|dataset | 1 |
358,633 | 67,138,600 | Optimize computation time in nested for loops? | <p>I have this code:</p>
<pre><code>import numpy as np
from skimage.util import img_as_ubyte
from skimage.feature import canny
import math
image = img_as_ubyte(sf_img)
edges = np.flipud(canny(image, sigma=3, low_threshold=10, high_threshold=25))
non_zeros = np.nonzero(edges)
true_rows = non_zeros[0]
true_col = non_zer... | <p>You can use <strong>Numba JIT</strong> to speed up the computation (since the default CPython <em>interpreter</em> is very bad for such computation). Moreover, you can rework the loops so that the code can run in <strong>parallel</strong>.</p>
<p>Here is the resulting code:</p>
<pre class="lang-py prettyprint-overri... | python|performance|numpy | 2 |
358,634 | 47,443,992 | Mask a 2D array with different masks for each dimension | <p>I have three different arrays.</p>
<p>One is a latitude array (-90 to 90) another is a longitude array (0 to 360) and the last is a 2D temperature array with the shape (len(lats), len(lons) where len(lats) != len(lons). </p>
<p>I have obtained a longitude mask via other means and have created a latitude mask via:<... | <p>My guess is your solution is almost right, just flip dimensions:</p>
<pre><code>twodmask = latmask[:, None] & lonmask[None, :]
</code></pre>
<p>and perhaps use or instead of and? (Not sure about that.)</p>
<pre><code>twodmask = latmask[:, None] | lonmask[None, :]
</code></pre> | python|numpy|geo | 1 |
358,635 | 47,203,117 | aggregate rows into tensorflow variable | <p>I have a tf.Variable tensor that should work as a result aggregator.</p>
<p>The idea is that I will execute an operation on the graph with batches of data and the results should be appended as new rows to my result Variable.</p>
<p>Because at the beginning the variable should be empty, I initialize it like this:</... | <p>You're creating <code>result_tensor</code> by feeding a 0. Which means your <code>result_tensor</code> is a scalar value and not a row as you expect. The <code>expected_shape</code> property doesn't fix that.</p>
<p>Instead, you should declare <code>result_tensor</code> to be <code>tf.zeros([1, 25088])</code> as 25... | neural-network|conv-neural-network|tensorflow|tensorflow-slim | 0 |
358,636 | 47,357,646 | Create a new column in python dataframe based on the presence of NaN in a specific column | <p>I have a dataframe with NaNs</p>
<pre><code>df = pd.DataFrame({"A": [10,20,30, np.nan], "B": [20, np.nan, 10,np.nan]})
A B
0 10.0 20.0
1 20.0 NaN
2 30.0 10.0
3 NaN NaN
</code></pre>
<p>I would like to create a new column 'C'.
In any row if either column 'A' or 'B' has a NaN, column 'C' will ... | <p>Use <code>notnull</code> + <code>all</code>:</p>
<pre><code>df['C'] = df.notnull().all(1).astype(int)
df
A B C
0 10.0 20.0 1
1 20.0 NaN 0
2 30.0 10.0 1
3 NaN NaN 0
</code></pre> | python|pandas|dataframe|na | 2 |
358,637 | 47,373,969 | Pandas: how to use a function dictionary to assign a column value based on calculations between other columns | <p>With the following Pandas DataFrame, how would I make a new column, "spend" for example, based on a function name in another column?</p>
<p>Example Dataset</p>
<pre><code> cost method metric rate total planned
0 CPMV 2000 100 1000
1 CPMV 4000 100 1000
2 Flat ... | <p>This can be achieved by first setting up a function dictionary. Keys will be the names and values the calculation. Then, using a lambda inside an apply function, you can determine which key's function you would like to use by selecting the cost method for reference.</p>
<ol>
<li>Make a function that accepts your da... | python|pandas|dictionary | 1 |
358,638 | 47,251,280 | Capacity of queue in tf.data.Dataset | <p>I have problem with Tensorflow's new input pipeline mechanism. When I create a data pipeline with tf.data.Dataset, which decodes jpeg images and then loads them into a queue, it tries to load as much image as it can into the queue. If throughput of loading images is greater than throughput of images processed by my ... | <p>This will buffer n_samples, which looks to be your entire dataset. You might want to cut down on the buffering here.</p>
<pre><code>dset = dset.shuffle(n_samples, None)
</code></pre>
<p>You might as well just repeat forever, repeat won't buffer (<a href="https://stackoverflow.com/questions/47117498/does-tf-data-da... | tensorflow | 2 |
358,639 | 47,144,487 | input text file (a double quoted string w/ %e %i sqrt z1 z2 log) into sympy or numpy or scipy for a Laurent series | <p>Lengthy title, but I thought it might be best to be very informative...</p>
<p>I have very long expressions using symbols such as %i, %e, log, z1 and z2, that is sandwiched in between double quotes, e.g. something like,</p>
<pre><code>"(4*z1*z2*%e^(z2^2+z1^2)*((%e^z1^2-%e^z2^2)^2*(96*%e^(13*(((-(202907687053026635... | <p><code>numpy.loadtxt()</code> is generally used to read tabular data from text files into Numpy arrays. It may be better to use Python to read your file into a string variable and then convert it to an Sympy expression using <code>sympy.sympify()</code>.
Suppose I have a file <code>cal.txt</code> that contains a one-... | string|file|numpy|sympy|series | 1 |
358,640 | 47,297,263 | Queue shapes must have the same length as dtypes | <p>Im trying to initialize a FIFOQueue similar to the shape of my numpy array
but get the below error.</p>
<p>My - numpy array shape - (1, 17428, 3)</p>
<pre><code>dtypes=[tf.float32,tf.float32,tf.float32]
print len(dtypes)
shapes=[1, 17428, 3]
print len(shapes)
q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shap... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/FIFOQueue" rel="nofollow noreferrer">documentation</a> specifies that the parameters for <code>FIFOQueue</code>'s constructor are (emphasis mine):</p>
<blockquote>
<ul>
<li><code>dtypes</code>: A list of <code>DType</code> objects. The length of <code>d... | python|numpy|tensorflow | 3 |
358,641 | 47,393,115 | Get indices of N highest values in numpy array | <p>My code:</p>
<pre><code>import numpy as np
N = 2
a = np.array([[0.5, 0.3, 0.2],
[0.2, 0.6, 0.2],
[0.3, 0.2, 0.7],
[np.nan, 0.2, 0.8],
[np.nan, np.nan, 0.8]
])
ind = np.argsort(np.where(np.isnan(a), -1... | <p><a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer"><code>Advanced-index</code></a> and check for <code>NaNs</code> to give us a mask, which could be then used with <code>np.where</code> to do the choosing, like so -</p>
<pre><code>In [244]: a... | python|arrays|numpy | 1 |
358,642 | 47,159,215 | Tensorflow in DSX: Consuming prediction results fails due to list() | <p>I have successfully built a model using Tensorflow in Python in IBM Data Science Experience. It works to evaluate test data using this model. However, when I invoke it to do a prediction on records, I cannot consume the result that evaluate returns. I follow the description from <a href="https://www.tensorflow.org/g... | <p>Looks like you have a variable called <code>list</code>, which shadows the standard python type <code>list</code>.</p> | python|tensorflow|data-science-experience | 2 |
358,643 | 47,518,628 | Pandas dataframe long to wide transformation with different number of rows per index | <p>I have a pandas data frame with session ID's, URL and TimeStamp in the following format:</p>
<pre><code>SessionId TimeStamp URL
aa420858 20:24 url1
aa420858 20:26 url2
aa420858 20:27 url3
bb779bc3 18:18 other_url1
bb779bc3 18:21 other_url2
bb779bc3 18:24 oth... | <p><code>pivot_table</code>+ <code>concat</code></p>
<pre><code>df1=df.pivot_table(index='SessionId',columns=df.groupby('SessionId').cumcount(),values='TimeStamp',aggfunc='sum').\
add_prefix('TimeStamp_')
df2=df.pivot_table(index='SessionId',columns=df.groupby('SessionId').cumcount(),values='URL',aggfunc='sum')... | python|pandas|pivot | 5 |
358,644 | 47,134,173 | Can't access part of Pandas dataframe by multiindex | <p>I'm new with Pandas so this is basic question. I created a Dataframe by concatenating two previous Dataframes. I used</p>
<pre><code>todo_pd = pd.concat([rabia_pd, capitan_pd], keys=['Rabia','Capitan'])
</code></pre>
<p>thinking that in the future I could separate them easily and saving each one to a different loc... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>DataFrame.xs</code></a>:</p>
<pre><code>df1 = todo_pd.xs('Rabia')
df2 = todo_pd.xs('Capitan')
</code></pre> | python|pandas | 0 |
358,645 | 47,257,408 | InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float | <p>So for the following code:</p>
<pre><code>with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(2000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
print('step... | <pre><code>print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
</code></pre>
<p>Just delete the blank spaces before "print" in your last line :)</p> | python|tensorflow | 0 |
358,646 | 47,290,053 | How to use if statement PyTorch using torch.FloatTensor | <p>I am trying to use the <strong>if statement</strong> in my PyTorch code using <code>torch.FloatTensor</code> as data type, to speed it up into the <strong>GPU</strong>.</p>
<p>This is my code:</p>
<pre><code>import torch
import time
def fitness(x):
return torch.pow(x, 2)
def velocity(v, gxbest, pxbest, pybes... | <p>When you compare pyTorch tensors, the output is usually a <code>ByteTensor</code>. This data type is not suitable for if statements.</p>
<p>Change the condition inside the <code>if</code>:</p>
<pre><code>if (minynext[0] < miny[0])
</code></pre> | python|gpu|pytorch | 0 |
358,647 | 47,227,727 | ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,) | <p>I am getting error which is specify "<strong>ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)</strong>"
I just want to get prediction results bu I can not run fit method.(<code>estimator.fit(input_fn=get_input_fn_train(), steps=10000</code>) I get the error while trying to run this code. I ... | <p>I don't know if there are other problems but one problem you have is that <code>example_id_column</code> argument to <code>SVM</code> needs to be a string. It is a name of the feature column representing example ids. In your code it is an integer Tensor. See <a href="https://www.tensorflow.org/api_docs/python/tf/con... | python|machine-learning|tensorflow|svm | 0 |
358,648 | 47,351,542 | Change batch size in each training in Tensorflow | <p>I am trying to implement a simple LSTM model in tensorflow. I have lines of sentences as array of char as input. </p>
<p>Sample input:</p>
<pre><code>['Y', 'â', 'r', 'â', 'b', ' ', 'n', 'e', ' ', 'i', 'n', 't', 'i', 'z', 'â', 'r', 'd', 'ı', 'r', ' ', 'b', 'u']
</code></pre>
<p>Each training step I am trying to fe... | <p>When I post this question, I just started the <code>RNN</code>. Actually the answer is very simple and I am answering it if there are people who face the same problem as me.</p>
<p>The solution is using <strong>Dynamic RNN</strong>. It allows you to give input with different sequences and its very important on most... | python|tensorflow|lstm|rnn | 0 |
358,649 | 47,211,664 | extract rows of data from a bunch of csv files that match specific dates mentioned in one column | <p>I have 61 csv file that are related to 61 days of the year but in each file there is not just the data of that date, there are also data corresponding to other of 61 days. The form of data is</p>
<pre><code>4d7cc82e33d042fdf13b9149bcdacee1;2015-03-01 05:21.:52;45.631616;9.2073;20;0
4d7cc82e33d042fdf13b9149bcdacee1;... | <p>How about something like this:</p>
<pre><code>from datetime import datetime
import pandas as pd
import glob
data_path = '/my/data/'
columns = ['trip', 'dateandtime', 'lat', 'lon', 'vehicle', 'velocity']
df_all = pd.DataFrame(columns=columns)
for csv_filename in glob.glob(os.path.join(data_path, "output_*.csv")):
... | python|pandas|csv|datetime | 0 |
358,650 | 47,212,251 | Tensorflow Printing Predictions with featured Columns values | <p>
I'm using this custom regressor and having trouble to print the predictions with featured columns values.</p>
<p>I can only print my generator values but not my entire matrix.</p>
<p>How can i print the matrix? Here is the code. Is has a small modification in the code of <a href="https://github.com/tensorflow/ten... | <p>You can use 2 function for this purpose,</p>
<pre><code>get_variable_names()
get_variable_value(name)
</code></pre>
<p>call them in following manner,</p>
<pre><code>model.get_variable_names()
get_variable_value(name)
</code></pre>
<p>So whatever matrix of your model you may want to retrieve this is the only way.... | tensorflow|predict | 0 |
358,651 | 47,520,854 | What is supported by broadcasting in tensorflow? How dimensions matches determined? | <p>I raised an issue in github at: <a href="https://github.com/tensorflow/tensorflow/issues/14924" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/14924</a>. Here is the details.</p>
<p>This is OK:</p>
<pre><code>import tensorflow as tf
sess = tf.InteractiveSession()
xx = tf.constant(1, shap... | <p>As you may have already observed, at the moment Tensorflow has restricted the number of dimensions mismatch which it will correct to broadcast.</p>
<p>For that purpose, I have written my own broadcasting function which will broadcast the variable number of tensors to one common shape. However note that this functio... | tensorflow|array-broadcasting | 1 |
358,652 | 47,519,353 | Reshape Tensor from shape (n, h, w, c) to (n, h * w, c) | <p>Looking at <a href="https://stackoverflow.com/questions/34194151/best-way-to-flatten-a-2d-tensor-containing-a-vector-in-tensorflow">Best way to flatten a 2D tensor containing a vector in TensorFlow?</a> I see how to flatten a 2D tensor to a 1D tensor in TensorFlow but how do I flatten a 4D Tensor to a 3D Tensor with... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/reshape" rel="nofollow noreferrer"><code>tf.reshape()</code></a> function should work for you:</p>
<pre><code>Y = tf.reshape(X, (n, h*w, c))
</code></pre> | python|tensorflow | 4 |
358,653 | 47,193,088 | TensorFlow: Validation of model while using Monitored training session | <p>I am using dataset API to import training and validation data. I have TF 1.2. So I can use only reinitializable iterator and can't use feedable iterator since feedable iterator is available only from TF 1.4.</p>
<p>1) If we want to just train the network we can simply use Monitored training session. But when we wan... | <p>for your question 3, TensorFlow behaves poorly, I think. For that last batch, it may have a smaller number of samples. This will very often (always?) cause "Incompatible shapes" errors during training. Please see <a href="https://stackoverflow.com/a/48331954/2184122">https://stackoverflow.com/a/48331954/2184122<... | python|tensorflow|deep-learning | 2 |
358,654 | 47,406,587 | Testing pandas code | <p>I have a script of about 50 lines that reads data from a database, loads it into a pandas dataframe and then perform numerous operations on the dataframe.</p>
<p>I was wondering how people generally test this type of code? I'm not talking about tools like assert_frame_equal, but rather principles people follow.</p>... | <p>If you want to start to write python unit test, this <a href="https://stackoverflow.com/q/3371255/1278112">question</a> is recommended. </p>
<p>Since the 50 lines are relevant, you probably want a functional test.<br>
Read <a href="https://stackoverflow.com/q/4904096/1278112">the difference between unit, functiona... | pandas|testing | 3 |
358,655 | 47,463,145 | Panel data: mean, groupby and with a condition | <p>I want to calculate first the mean of jobs whenever <code>entr ==1</code> and second the mean of <code>jobs</code> by <code>year_of_life</code>.</p>
<pre><code>id year entry cohort jobs year_of_life
1 2009 0 NaN 10 NaN
1 2012 1 2012 12 0
1 2013 0 2012 12 1
1 ... | <p>For the first you can use boolean indexing to filter the dataframe for rows where the condition is True then take the mean <code>df[df.entry == 1].mean()</code>. For the second, groupby year_of_life then take the mean of each group <code>df.groupby('year_of_life').mean()</code>. If you want both of the condition to ... | python|pandas | 1 |
358,656 | 47,387,914 | Why does pandas python use disk space | <p>I have a PC with two disks:</p>
<ul>
<li>110GB SSD</li>
<li>1TB HDD</li>
</ul>
<p>There is around 18GB free in the SSD.</p>
<p>When I run the python code below, it "uses" all the space from my SSD (I end up having only 1GB free). This code iterates on all SAS files in a folder, performs a group by operation and a... | <p>You are copying all the data you have into RAM; you don't have enough in this case, so Python uses a page file or virtual memory instead. The only way to fix this would be to get more memory, or you could just not store everything in one big dataframe, e.g. write each file into a pickle with <code>outtable.to_pickle... | python-3.x|pandas|temporary-files | 2 |
358,657 | 47,402,225 | Python sqlalchemy trying to write pandas dataframe to SQL Server using .to_sql | <p>I have a python code through which I am getting a pandas dataframe "df". I am trying to write this dataframe to Microsoft SQL server. I am trying to connect through the following code by I am getting an error</p>
<pre><code>import pyodbc
from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc:///... | <p>I was finally able to make it run. </p>
<pre><code>import pyodbc
from sqlalchemy import create_engine
import urllib
params = urllib.quote_plus(r'DRIVER={SQL Server};SERVER=bidept;DATABASE=BIDB;Trusted_Connection=yes')
### For python 3.5: urllib.parse.quote_plus
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format... | python|sql-server|pandas|sqlalchemy | 3 |
358,658 | 47,480,958 | Selecting data spanning a range of UTC timestamps | <p>In my CSV file I have a column as follows </p>
<pre><code>UTC Time
2017-03-14 03:06:44
2017-03-14 03:06:53
2017-03-14 03:07:03
2017-03-14 03:07:12
2017-03-14 03:07:22
2017-03-14 03:07:31
2017-03-14 03:07:41
</code></pre>
<p>I would like to allow a person to enter a starting time such as <code>2017-03-14 08:00:00<... | <p>You can use .between()</p>
<pre><code>start = '2017-03-14 03:07:00'
end = '2017-03-19 04:30:00'
df['UTC Time'] = pd.to_datetime(df['UTC Time'])
df_slice = df.loc[df['UTC Time'].between(start, end)]
UTC Time
2 2017-03-14 03:07:03
3 2017-03-14 03:07:12
4 2017-03-14 03:07:22
5 2017-03-14 03:07:31
6 2017... | pandas | 0 |
358,659 | 47,170,917 | pandas search a value in a dataframe column | <p>I have following dataframe and i want to search apple in column fruits and display all the rows if apple is found.</p>
<pre><code>Before :
number fruits purchase
0 apple yes
mango
banana
1 apple no
cheery
2 mango yes
... | <p>Use <code>groupby</code> and <code>filter</code> to filter groups that contain 'apple':</p>
<pre><code>df['number'] = df['number'].ffill()
df.groupby('number').filter(lambda x: (x['fruits'] == 'apple').any())
df_out.assign(number = df_out['number'].mask(df.number.duplicated()))\
.replace(np.nan,'')
</code></pre... | pandas | 1 |
358,660 | 47,237,707 | pandas: finding and appending to first empty cell in specific columns | <p>I have the following excel file.</p>
<pre><code>1 | A | B | C |
---------------------------
2 | apple| banana | tomato|
---------------------------
3 | 3 | 4 | 4 |
---------------------------
4 | 9 | 7 | 3 |
---------------------------
5 | | 2 | 1 |
----------------... | <p>Best I could do for you</p>
<pre><code>d = defaultdict(list)
d['apple'] = [3, 9]
d['banana'] = [4, 7, 2, 8]
d['tomato'] = [4, 3, 1]
list_to_append = [
dict(apple=4, banana=2),
dict(apple=3),
dict(apple=3, banana=2, tomato=5)
]
for a in list_to_append:
for k, v in a.items():
d[k].append(v)... | pandas|dataframe | 0 |
358,661 | 47,394,941 | Error while installing Tensorflow on mac | <p>I have Python 3.5.4 running with Anaconda. I am getting the following error while installing Tensorflow on mac by using </p>
<pre><code>pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.4.0-py3-none-any.whl
</code></pre>
<p>It has something to do with numpy pac... | <p>Try <code>sudo easy_install numpy</code> Then reinstall TensorFlow. I hope this helps you.</p> | python|macos|tensorflow | 0 |
358,662 | 47,418,295 | Transforming string to datetime in dataframe is slow | <p>I have the following code:</p>
<pre><code>from dateutil import parser
df['time'] = df['time'].apply(lambda x: parser.parse(x))
</code></pre>
<p>I have few hundred thousand rows, and that line takes tens of seconds. Is there any way to optimize it?</p> | <p>Using <code>pd.to_datetime</code></p>
<pre><code>%timeit df['time'].apply(lambda x: parser.parse(x))
1 loop, best of 3: 812 ms per loop
%timeit pd.to_datetime(df.time)
100 loops, best of 3: 4.25 ms per loop
len(df)
Out[290]: 20000
</code></pre> | python|pandas|datetime|dataframe | 1 |
358,663 | 47,421,299 | Iterating over the rows of two dataframes | <p>I have two dataframes let's call first one df and the second one compare_df:
First one is like this: </p>
<pre><code>Date cell tumor_size (assume it is three dimensional)
25/10/2015 113 [51, 52, 55]
22/10/2015 222 [50, 68, 22]
22/10/2015 883 [45, 23, 67]
20/10... | <p>Your mistake is in trying to subtract a <code>pd.Series</code> of large size (<code>compare_df.tumor_size</code>) from a <code>list</code> of size three (<code>row.tumor_size</code>). When subtracting <code>list</code>/<code>tuple</code> from <code>pd.Series</code>, <code>pandas</code> tries to match both sequences ... | python|pandas|numpy | 2 |
358,664 | 11,340,299 | Appending/Merging 2D Arrays | <p>Is it possible to merge 2D Arrays in Python using numpy or something else ? I have about 200 2D arrays , all with the same Dimensions (1024,256) and want to add them to the lower end of each other. The final shape after adding e.g. 3 of them then should be (1024,768). </p> | <p>Three arrays of (1024,256) have to be appended to the <em>right</em> end, not the <em>lower</em> end. You are stacking them horizontally next to each other (1024 rows, 256 columns).</p>
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html"><code>numpy.hstack</code></a> (<em>h</em>... | numpy|2d|append | 7 |
358,665 | 11,334,098 | How to take out the column index name in dataframe | <pre><code> Open High Low Close Volume Adj Close
Date
1990-01-02 00:00:00 35.25 37.50 35.00 37.25 6555600 8.70
1990-01-03 00:00:00 38.00 38.00 37.50 37.50 7444400 8.76
1990-01-04 00:00:00 38.25 38.75 37.25 37.63 7928800 ... | <p>Try using the <code>reset_index</code> method which moves the DataFrame's index into a column (which is what you want, I think).</p> | python|pandas | 10 |
358,666 | 11,007,169 | What should I worry about if I compress float64 array to float32 in numpy? | <p>This is a particular kind of lossy compression that's quite easy to implement in numpy.</p>
<p>I could in principle directly compare original (float64) to reconstructed (float64(float32(original)) and know things like the maximum error.</p>
<p>Other than looking at the maximum error for my actual data, does anybod... | <p>The following assumes you are using standard IEEE-754 floating-point operations, which are common (with some exceptions), in the usual round-to-nearest mode.</p>
<p>If a double value is within the normal range of float values, then the only change that occurs when the double is rounded to a float is that the signif... | python|numpy|floating-point|compression | 7 |
358,667 | 10,935,629 | How to create identity matrix with numpy | <p>How do I create an identity <em>matrix</em> with numpy?
Is there a simpler syntax than</p>
<pre><code>numpy.matrix(numpy.identity(n))
</code></pre> | <p>Here's a simpler syntax:</p>
<pre><code>np.matlib.identity(n)
</code></pre>
<p>And here's an even simpler syntax that runs much faster:</p>
<pre><code>In [1]: n = 1000
In [2]: timeit np.matlib.identity(n)
100 loops, best of 3: 8.78 ms per loop
In [3]: timeit np.matlib.eye(n)
1000 loops, best of 3: 695 us per loop... | python|numpy | 16 |
358,668 | 68,176,484 | Convert numpy array shape to tensorflow | <p>I'm constructing an image array with numpy and then trying to convert it to a tensor to fit a tensorflow model but then I get an error</p>
<p>Data prep</p>
<pre><code>def prep_data(images):
count = len(images)
data = np.ndarray((count, CHANNELS, ROWS, COLS), dtype=np.uint8)
for i, image_file in enumerate... | <p>You don't need to convert the NumPy array to tensor, just change the shape of your input. <a href="https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html" rel="nofollow noreferrer">np.moveaxis</a> can do the trick. It works like this:</p>
<p><code>np.moveaxis(your_array, source, destination)</code>.</p... | python|numpy|tensorflow|keras | 1 |
358,669 | 68,248,577 | Print column content a if column content b != 0 | <p>I have a similar dataframe to this one:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Names</th>
<th>abandoned_calls</th>
<th>total_calls</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kerstin</td>
<td>0</td>
<td>50</td>
</tr>
<tr>
<td>Cathlyn</td>
<td>0</td>
<td>53</td>
</tr>
<tr>
<td>James</td... | <p>You can try:</p>
<pre><code>df.loc[df['abandoned_calls'] != 0, 'Names']
</code></pre>
<p>Result:</p>
<pre><code>2 James
4 Patrick
Name: Names, dtype: object
</code></pre> | python|pandas|printing|is-empty | 1 |
358,670 | 68,423,656 | How to merge (using DataFrame) two data sets with the same inputs but in a different order | <p>I have two datasets where one can be essentially thought of as a descriptor set and the other contains the information.</p>
<p>I have a simple example of what I mean here.</p>
<pre><code>import pandas as pd
</code></pre>
<p>The first dataset, i.e. descriptor:</p>
<pre><code>df1 = pd.DataFrame({"color": [&... | <p>A mapping Series can be created from <code>df1</code> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a>. Then the new columns can be added to <code>df2</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/refe... | pandas|dataframe|merge | 0 |
358,671 | 68,419,836 | Conditional combination of string column | <p>Here is the sample -</p>
<pre><code> tmp3
177 SADHASHIV CHINORE
249 MADHUSUMAN WADIKHAYE PLOT
250 MADHUSUMAN WADIKHAYE PLOT
260 SUKHRAM YADAV
404 BANGALORE RURAL DISTK
405 BANGALORE RURAL DISTK
784 chhotu mahto gosai
854 SUKHPAL HOUSE
85... | <p>Try:</p>
<pre><code>words = ['PLOT', 'HOUSE']
#your list of n elements
</code></pre>
<p>via <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>Series.replace()</code></a></p>
<pre><code>df['tmp3']=df['tmp3'].replace('|'.join(words),'',regex=True)
#If you... | python|pandas | 2 |
358,672 | 68,186,402 | python: How do I compare doc A and doc B and if it finds a string that matches in doc B how do I print the entire line? | <p>I have document A:</p>
<pre><code>['5a0cd3b5-4249-bf6f-d009-17a81532660e', '7e44fc1b-44fa-cdda-8491-f8a5bca1cfa3', 'daa73753-4b56-9d21-d73e-f3b3f4c9b1a6', 'f7425a39-43ca-e1fe-5b2b-56a51ed479c5']
</code></pre>
<p>I have document B:</p>
<pre><code>abc 5a0cd3b5-4249-bf6f-d009-17a81532660e
def CDA41B87-4D3A-C17C-5F6D-89... | <p>Using inputs:</p>
<p>Shopid.txt:</p>
<pre><code>['157BCEBE-484D-82E2-2A60-C8B4B11197EA', '7e44fc1b-44fa-cdda-8491-f8a5bca1cfa3', '65BAA0CD-42EC-F99D-54A0-338D795B5824', 'f7425a39-43ca-e1fe-5b2b-56a51ed479c5']
</code></pre>
<p>Otherfile.txt:</p>
<pre><code>Glitchpop Odin,97AF88E4-4176-9FA3-4A26-57919443DAB7
dot EXE O... | python|pandas | 0 |
358,673 | 68,371,863 | Conv1D: ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (None, 2) | <p>I am inputting data with dimensions (2363,2) in a Conv1D Model. The input_shape I'm specifying in the input layer is (202,2). Here's the CNN part of the model:</p>
<pre><code>model_2 = Sequential()
model_2.add(Conv1D(256, kernel_size=1, activation='relu', input_shape=(202,2)))
model_2.add(BatchNormalization())
mode... | <p>I found your problem<br />
You have to reshape your training data<br />
You can use numpy to do this,</p>
<pre><code> x_train = np.reshape(x_train, (-1,202,2))
</code></pre> | python|tensorflow|machine-learning|deep-learning|conv-neural-network | 0 |
358,674 | 68,249,037 | Month Filtration pandas dataframe Python | <p>The code below filters out the dates to get the first of each month. However for some reason it does not include the first month of each year, for example it disregards the date <code>'2020-01-01 00:00:00'</code> and goes straight to <code>'2020-02-01 00:00:00'</code>. How would i be able to fix this?</p>
<pre><code... | <p>Seem like it would be easier to just check that the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.day.html" rel="nofollow noreferrer"><code>day</code></a> was <code>1</code> (the first):</p>
<pre><code>monthly_changes = data.loc[datetime.dt.day == 1, 'Data'].tolist()
</code></p... | python-3.x|pandas|dataframe|numpy|date | 1 |
358,675 | 68,304,398 | How to make x*y with simple deep learning(linear regression) | <p>For my future use,I wanted to test multivariate multilayer perceptron.</p>
<p>In order to test it, I made a simple python program.</p>
<p>Here's the code.</p>
<pre><code>import tensorflow as tf
import pandas as pd
import numpy as np
import random
input = []
result = []
for i in range(0,10000):
x = random.rando... | <p>Neural networks are not able to adapt themself (without additional training) to a different domain, this means that you should train on a domain and run the inference on the same domain.</p>
<p>In images, we often just scale the input images from [0,255] to the [-1,1] and let the network learn from values in this ra... | python|keras|deep-learning|linear-regression|tensorflow2.0 | 0 |
358,676 | 68,433,429 | Multiple results for one row PANDAS | <p>I have a data frame with Names and departments. All these Names can map to 4 different departments(Department A, B, C, and D). For example, each name has to get mapped to Department A, B, C, D. In the initial data, each name is only mapped to one department. In the final dataset, each name maps to four different dep... | <p>Assuming just the <code>product</code> of values is needed <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product</code></a> has much less overhead than <code>pandas</code> functions:</p>
<pre><code>from itertools import product
import pandas a... | python|pandas|dataframe|dictionary | 2 |
358,677 | 68,242,549 | Imputing NAN values by pandas forward fill method with set pattern | <p>Suppose I am working on a Dataset where there is a column name "F_N" containing numeric values in a sequence like 10, 20, 30, nan, 50, nan, 70. Here I want these null places to fill by 40, and 60 in the respective place with pandas' help. I am aware of fillna(method=ffill), but it will give us 30 and 50 ex... | <p>You describe a sequence with missing values. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">fillna()</a> can take a series. Hence simplest is to fill with expected values. Code below demonstrates this:</p>
<pre><code>import pandas as pd
... | pandas|dataframe | 0 |
358,678 | 68,102,117 | row and column coordinates in a text file | <p>I have a text file with lots of data, and I only want to edit one column. Coordinates start at row 4, column 111 and end at row 55, column 111. Here an exemple :</p>
<pre><code>// typTpt TypTpt NomTypTpt LibTypTpt TypDem Medic Motif Mutat Classe Dispo Ann... | <p>Your CSV file has some consistency issues. At first glance, it looks like it is a comma-separated CSV file but not every line has the same amount of commas.
Make sure that every line in your CSV file has the same amount of commas and then you can read it with:</p>
<pre><code>df = pd.read_csv("d:/art80_typTpt_v2... | python|pandas|position | 0 |
358,679 | 68,155,678 | testing crs between geodataframe and rasterio object | <p>I check crs congruency as means of quality control prior to spatial analysis involving a geodataframe (gdf) and a raster (rstr).</p>
<pre><code>print(gdf.crs)
</code></pre>
<p>returns 'epsg:2193'</p>
<p>and</p>
<pre><code>print(rstr.crs)
</code></pre>
<p>returns 'EPSG:2193'</p>
<p>which is notionally OK as cross-che... | <p>CRS can be stored in many ways. For example PROJ, EPSG-Code or WKT-format (Well known text), which preferred as a lossless way of storing CRS information. For reference, check the PROJ explanation of the best format for describing coordinate reference systems <a href="https://proj.org/faq.html#what-is-the-best-forma... | python|logic|geopandas|rasterio | 2 |
358,680 | 68,388,599 | Group by for standard deviation pandas | <p>I have a dataset which resembles something like this:</p>
<pre><code>ID AMT TAG
1 100 A
2 120 B
1 25 B
1 110 A
</code></pre>
<p>I have to calculate the standard deviation of each tag for each ID,something like this:</p>
<pre><code>ID A_STD B_STD
1 5 0
2 0 0
</code></pre>
<p>I am trying something like ... | <p>Yes, use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFr... | python|pandas|numpy | 1 |
358,681 | 68,163,436 | Applymap a function according another dataframe value | <p><strong>General problem</strong> :
I have two similar data frames (same shape, same variables but different values).<br />
How to <code>applymap</code> a function on each cell of df1, according the value of the same cell from df2.</p>
<p><strong>My specific problem</strong> :
How to <code>applymap(round())</code> f... | <p>I usually use <a href="https://github.com/jmcarpenter2/swifter" rel="nofollow noreferrer">swifter</a> for this as it is the easiest option for vectorizing the <code>apply()</code> function in pandas.</p>
<p>Install it:</p>
<pre><code>$ pip install -U pandas # upgrade pandas
$ pip install swifter # first time install... | python|pandas|dataframe|vectorization|python-applymap | 0 |
358,682 | 68,240,359 | Save entire model but load weights only | <p>I have defined a deep learning model <code>my_unet()</code> in tensorflow. During training I set <code>save_weigths=False</code> since I wanted to save the entire model (not only the wieghts bu the whole configuration). The generated file is <code>path_to_model.hdf5</code>.</p>
<p>However, when loading back the mode... | <p>You can please see the documentation here for any future reference: <a href="http://davis.lbl.gov/Manuals/HDF5-1.8.7/UG/03_DataModel.html" rel="nofollow noreferrer">http://davis.lbl.gov/Manuals/HDF5-1.8.7/UG/03_DataModel.html</a></p> | python|tensorflow|deep-learning | 1 |
358,683 | 68,101,811 | Pandas dataframe scale column based on another column | <p>I've got a Dataframe that looks like this:</p>
<pre><code> cat val
0 1 10
1 1 4
2 2 6
3 2 2
4 1 8
5 2 12
</code></pre>
<p>Where <code>cat</code> is category, and <code>val</code> is value. I would like to create a column, called <code>scaled</code>, that is linearly... | <p>Your scaling is to subtract the min and divide by the range, so use <code>groupby</code> + <code>transform</code> to broadcast those properties back to every row for that group and do the math.</p>
<pre><code>import numpy as np
gp = df.groupby('cat')['val']
df['scaled'] = (df['val'] - gp.transform(min))/gp.transfo... | python|pandas|dataframe | 2 |
358,684 | 68,292,212 | Converting sympy expression to numpy expression before solving with fsolve( ) | <p>I have a system of equations expressed by sympy:</p>
<pre><code>def test1a(A):
t, tt = sym.symbols('t tt')
return sym.cos(t+tt+A)*A
def test1b(B):
t, tt = sym.symbols('t tt')
return sym.sin(t-tt+B)*B
</code></pre>
<p>That I want to convert to a numpy expression before evaluating the result with <cod... | <p>You've presented your code in a very convoluted way for an SO question. You don't need so many functions just to show what is basically 5 lines of code!</p>
<p>Please reduce your examples to something as simple as possible that is a single block of code that can be copy-pasted complete with all imports. Then please ... | python|numpy|sympy|nonlinear-optimization|lambdify | 2 |
358,685 | 68,078,750 | in a few conditions, compare row with a previous row and drop rows with condition in python pandas | <p>I have a concept of what I need to do, but I can't write the right code to run, please take a look and give some advice.</p>
<p>step 1. find the rows that contains values in the second column</p>
<p>step 2. with those rows, compare the value in the first column with their previous row</p>
<p>step 3. drop the rows wi... | <p>IIUC, you can try:</p>
<pre><code>m = df['diff'].notna()
df = (
pd.concat([
df[df['diff'].isna()],
df[m][df[m.shift(-1).fillna(False)]['missing'].values >
df[m]['missing'].values]
])
)
</code></pre>
<p>OUTPUT:</p>
<pre><code> missing diff
1 0 <NA>
3 1 &l... | python|pandas | 1 |
358,686 | 68,154,397 | Stratified Cross Validation or Sampling for train-test split based on multiple features in python | <p>sklearn's <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">train_test_split</a> , <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html" rel="nofollow noreferrer">StratifiedShuf... | <p>This can be achieved using pandas <code>groupby</code>:</p>
<p>Let us first check the population characteristics:</p>
<pre><code>grps = df.groupby(['state','income','gender'], group_keys=False)
grps.count()
</code></pre>
<p><a href="https://i.stack.imgur.com/3Idju.png" rel="nofollow noreferrer"><img src="https://i.s... | pandas|machine-learning|scikit-learn|cross-validation|train-test-split | 1 |
358,687 | 68,145,754 | Mask RCNN: No module named 'tensorflow.compat.v2' | <p>I used Mask RCNN to detect objects on colab.</p>
<ul>
<li>Tensorflow == 1.13.1</li>
<li>Keras == 2.0.8</li>
</ul>
<p>I have successfully trained the model with the dataset and it got a good results.</p>
<p>But now when I try to run the same code I get the error:</p>
<pre><code>No module named 'tensorflow.compat.v2'
... | <p>Try to change from:</p>
<pre><code>import keras
</code></pre>
<p>To:</p>
<pre><code>import tensorflow.keras
</code></pre>
<p><strong>Example to import TimeseriesGenerator from keras</strong>:</p>
<pre><code>from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
</code></pre>
<p>Credit to <a href="ht... | python|tensorflow | 0 |
358,688 | 68,030,904 | find string in pandas series python | <p>I cannot figure out how to find a string in a pandas series:</p>
<pre><code>mydata = np.array(['ab','ac','ad','ae'])
myserie = pd.Series(mydata) # this is because I don't know how to initialise a series directly ... :(
</code></pre>
<p>I am looking for the index of the string <code>ac</code>.</p>
<p>I have tried <co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> for test substring:</p>
<pre><code>idx = myserie.index[myserie.str.contains('ac')]
</code></pre>
<p>If need exact match use <code>==</code> or <a href... | python|pandas|series | 2 |
358,689 | 68,376,819 | Get video from .npy | <p>How i can get video from numpy array?</p>
<p>I have code:</p>
<pre><code>frame = np.load('dataset\123.npy')[:, 160:-215]
fig = plt.figure()
cmap = plt.cm.jet
norm = Normalize(vmin=450, vmax=550)
frame1 = ndimage.grey_closing(frame, size=(17, 17))
frame2 = cmap(norm(frame1))
plt.imshow(frame2, cmap=cmap)
plt.co... | <pre><code>import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from scipy import ndimage
from matplotlib import animation
files = os.listdir('dataset\{}'.format(folder_name))
fig = plt.figure()
myimages = []
for i in files:
frame = np.load('dataset\{}\\'.format(folder_name) + i)[:, 160:-215]... | python|numpy|opencv | 0 |
358,690 | 68,380,239 | Pandas merge dataframe with conditions depends on value in a column | <p>a help will be appreciated.</p>
<p>I have 2 DataFrames.</p>
<p>The first data frame consisted of an activity schedule of person,<code>schedule</code>, as following:</p>
<pre><code>PersonID Person Origin Destination
3-1 1 A B
3-1 1 B A
13-1 1 ... | <p>This is how I would do it if the real dataset is not more complicated than the given example. Other wise I would suggest looking at pd.melt() for more complex unpivoting.</p>
<pre><code>import pandas as pd
import numpy as np
# Create Dummy schedule DataFrame
d = {'PersonID': ['3-1', '3-1', '13-1', '13-1', '13-2', '... | python|pandas|merge | 2 |
358,691 | 68,351,824 | Multiple Condition Daily Counts by Month/Year in Pandas DF | <p>I have hourly data in a dataframe (df) and I need to count days that meet multiple data column conditions and then sum these counts by month and year in the df to describe a daily "event" where all 3 data conditions exist. My data looks like this:</p>
<pre><code> site wind time ... | <pre><code>df_final = df[(df['wind_speed_ms']<=5) & (df['air_temp_c']>=1) & (df['air_temp_c']<=5) & (df['relative_humidity_pct']<=30)].groupby(['Site','year','month']).day.nunique().reset_index()
df_final.columns = ['Site','year','month','event_days']
</code></pre> | pandas|events|conditional-statements|multiple-columns|multiple-conditions | 1 |
358,692 | 68,042,196 | Converting output into .csv file | <p>I am new to Python, and I am currently writing code to parse through an excel sheet of websites, look at websites that have been modified more than three months ago, and then pull out the names and emails of contacts at those sites. My problem now is that whenever I run the code in my terminal, it only shows me some... | <p>You can try converting it to a csv.</p>
<pre><code>data.to_csv('data.csv')
</code></pre>
<p>Alternately if you want to just view more records, for example 50, you could do this:</p>
<pre><code>print(data.head(50))
</code></pre> | python|pandas|dataframe|csv | 1 |
358,693 | 68,054,587 | Filtering a dataframe according to user input values in python | <p>I need to write a script in python prompting a user to select either the <strong>id is 19876/20807/13978/49999</strong>. Then taking in user input based on up to <strong>id</strong> <strong>column</strong> and <strong>their values</strong>, and returning the respective rows within a dataframe.</p>
<p>For example, if... | <p>Based on the edited code, your id column in df2 is a string but you are comparing the input data as int against it. So you have to change it to,</p>
<pre><code>filter_data = input('select movie writing the id: ')
filtered=(df2.loc[df2['id'] == filter_data])
print(filtered)
movie_ref id year
3 Aven... | python|pandas|dataframe|input | 1 |
358,694 | 68,146,536 | Apply Function With Multiple Arguments to Pandas Dataframe | <p>How to apply a function with multiple arguments to a dataframe? My function is something like this:</p>
<pre><code>def test(a,b,c,d,e,f):
if b == 1 :
if d == 0 :
return a-f
if b == 0 :
if c == 1 :
return a-e
</code></pre>
<p>My sample data is this :</p>
<div class="s-t... | <p>You could try changing your function like so:</p>
<pre class="lang-py prettyprint-override"><code>def test(row):
a,b,c,d,e,f = row
if b == 1 :
if d == 0 :
return a-f
if b == 0 :
if c == 1 :
return a-e
</code></pre>
<p>Then modify the way you apply the function like... | python|pandas|function|datetime|arguments | 1 |
358,695 | 68,275,877 | Python Transpose Dataframe Rows as Column names and columns as rows | <p>I have a big df with multi x and y columns data. I want to interpolate y-data to common x-values and then transpose data with common x-values as column names and y-values as rows.</p>
<p>My code:</p>
<pre><code>df = pd.DataFrame({'x1':np.linspace(0,10,5),'y1':np.linspace(0,50,5),'x2':np.linspace(0,8,5),'y2':np.linsp... | <p>Try the following:</p>
<pre><code>df.columns = pd.MultiIndex.from_arrays([[i[1] for i in df.columns],
[i[0] for i in df.columns]])
def y_over_x(d):
d = d.droplevel(0, axis=1)
return d['y']/d['x']
y = df.groupby(level=0, axis=1).apply(y_over_x).fillna(0).add_prefix('... | python|pandas|dataframe|numpy | 1 |
358,696 | 68,182,325 | Handling CSV with timezone-aware and timezone-naive datetime column | <p>I have a pandas dataframe that is imported from a csv that looks like this:</p>
<pre><code>|date time|id|value|
|------|-------|---------|
|2019-10-08T01:00:00+01:00|1|35|
|2019-10-08T02:00:00+01:00|1|32|
|2019-10-08T03:00:00+01:00|1|33|
|2019-12-08T01:00:00Z|1|25|
|2019-12-08T01:00:00Z|1|15|
|2019-12-08T01:00:00Z|1... | <p>for given example with column <code>date time</code> as string datatype,</p>
<pre><code>df['date time']
0 2019-10-08T01:00:00+01:00
1 2019-10-08T02:00:00+01:00
2 2019-10-08T03:00:00+01:00
3 2019-12-08T01:00:00Z
4 2019-12-08T01:00:00Z
5 2019-12-08T01:00:00Z
Name: date time, dtype: obj... | python|pandas|datetime | 1 |
358,697 | 68,259,128 | How to apply multiple condition on rows without changing the result from the previous condition? | <p>I have pandas dataframe where i need to apply multiple conditions. Here is the sample of my df</p>
<pre><code>Cond Samp
A_B_C Org
A_B_C Org
A_B_C Sea
A_B_C Paid
</code></pre>
<p>I need a new column based on this condition</p>
<pre><code>df['New'] = df[df['Samp'] ... | <p>Create a dictionary to map conditions:</p>
<pre><code>cond = {'Org': 0, 'Sea': 0, 'Paid': 2}
df['New'] = df.apply(lambda x: x['Cond'].split('_')[cond[x['Samp']],
axis="columns")
</code></pre>
<pre><code>>>> df
Cond Samp New
0 A_B_C Org A
1 A_B_C Org A
2 A_B_C ... | python|pandas|if-statement|conditional-statements | 3 |
358,698 | 68,420,253 | How to remove/ignore invalid formatted data while reading a huge csv file and creating a Dataframe using chunks in python | <p>I have a huge CSV log file (200,000+ entries). I am using chunks to read the file and then appending the chunks to get the entire file as data frame. Sometimes weird values/invalid formats arrive in the log file. I want to discard/ignore the wrong formatted data and filter out only the correct format and then work o... | <p>This is probably not the solution, but to offer some food for thought...</p>
<pre><code>import pandas as pd
import re
from dateutil import parser
'''
test_text.txt contains:
ddmmyyyy,hh:mm:ss,FileName,Function,Bytes,MsgText
17Jul2021,14:21:46,StatFile,Upload,1,"copy success"
17Jul2021,14:22:42,AuditFile,D... | python|pandas|dataframe|date|datetime | 1 |
358,699 | 68,158,819 | How to convert a style transfer tensorflow model to mlmodel with flexible input shape? | <p>I have read the Coreml guide which shows how to convert a pb model to mlmodel by using coremltools. However, I get the error below when trying to follow the guide. Which means the input shape must be specific.</p>
<blockquote>
<p><em>ValueError: "ResizeBilinear" op: the second input, which is the output si... | <p>please try my sample:
<a href="https://github.com/dhrebeniuk/RealTimeFastStyleTransfer" rel="nofollow noreferrer">https://github.com/dhrebeniuk/RealTimeFastStyleTransfer</a></p>
<p>And look my article with attached Google Colab Notebook in PyTorch.</p>
<p>There is instructions how run Style Transfer on iOS with maxi... | python|tensorflow|coremltools | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.