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 |
|---|---|---|---|---|---|---|
374,200 | 43,717,113 | Keras: ValueError: "concat" mode can only merge layers with matching output shapes | <p>I am facing this error in Keras 2. How can I resolve it?
I have imported</p>
<pre><code>from keras.layers import Input, merge
</code></pre>
<p>[...]</p>
<pre><code> up1 = merge([UpSampling2D(size=(2, 2))(conv3), conv2], mode='concat', concat_axis=1)
/usr/local/python/3.5.2-gcc4/externalmodules/lib/python3.5/s... | <p>It seems that you are using Keras version above <code>1.0.3</code>. Versions after 1.0.3 use tensorflow as backend by default <a href="https://github.com/orobix/retina-unet/issues/6" rel="nofollow noreferrer">Github Issues</a>. So you can do two things:</p>
<ol>
<li>Install <code>1.0.3</code> Version of Keras. [OR]... | tensorflow|keras|theano|keras-layer | 0 |
374,201 | 43,508,767 | pandas dataframe to nested dict | <p>I have a dataframe like this:</p>
<pre><code> aa phel ri_s
no
1 a 21 76
2 s 32 87
3 d 43 98
4 f 54 25
5 g 65 37
</code></pre>
<p>and I would like to create a dictionary that looks like this:</p>
<pre><code>{1: {aa: a, phel: 21, ri_s: 76}, 2: {aa: s, phel... | <p>You can zip the index and the rows as dictionaries together, and run a dictionary comprehension:</p>
<pre><code>{i:row for i,row in zip(df.index, df.to_dict(orient='row'))}
# returns
{1: {'aa': 'a', 'phel': 21, 'ri_s': 76},
2: {'aa': 's', 'phel': 32, 'ri_s': 87},
3: {'aa': 'd', 'phel': 43, 'ri_s': 98},
4: {'aa'... | python|pandas|dictionary|nested | 2 |
374,202 | 43,855,086 | Vectorized assignment for numpy array with repeated indices (d[i,j,i,j] = s[i,j]) | <p>How can I set</p>
<pre><code>d[i,j,i,j] = s[i,j]
</code></pre>
<p>using "NumPy" and without for loop?</p>
<p>I've tried the follow:</p>
<pre><code>l1=range(M)
l2=range(N)
d[l1,l2,l1,l2] = s[l1,l2]
</code></pre> | <p>If you think about it, that would be same as creating a <code>2D</code> array of shape <code>(m*n, m*n)</code> and assigning the values from <code>s</code> into the diagonal places. To have the final output as <code>4D</code>, we just need a reshape at the end. That's basically being implemented below -</p>
<pre><c... | python|numpy|multidimensional-array|indexing | 1 |
374,203 | 43,885,090 | Comparing NumPy object references | <p>I want to understand the NumPy behavior.</p>
<p>When I try to get the reference of an inner array of a NumPy array, and then compare it to the object itself, I get as returned value <code>False</code>.</p>
<p>Here is the example:</p>
<pre><code>In [198]: x = np.array([[1,2,3], [4,5,6]])
In [201]: x0 = x[0]
In [20... | <h2>2d slicing</h2>
<p>When I first wrote this I constructed and indexed a 1d array. But the OP is working with a 2d array, so <code>x[0]</code> is a 'row', a slice of the original.</p>
<pre><code>In [81]: arr = np.array([[1,2,3], [4,5,6]])
In [82]: arr.__array_interface__['data']
Out[82]: (181595128, False)
In [83... | python|arrays|numpy|identity | 4 |
374,204 | 43,583,869 | Transform from 2-level MultiIndex to 3-level MultiIndex | <p>I have something with the following data structure:</p>
<pre><code> foo year
par chi
10.0 900 0.024096 1983
901 0.200000 1983
902 0.300000 1983
900 0.027473 1984
901 0.023256 1984
902 0.400000 1984
900 0.018182 1985
</code></pre>
<p>That i... | <p>Solution plan:</p>
<ul>
<li>start with a dataframe with four columns (reset index if necessary)</li>
<li>for each <code>par</code> group apply a function that calculates child covariances</li>
<li>in the function unstack group so that its index is <code>year</code> and values of <code>foo</code> for each child are ... | python|pandas | 2 |
374,205 | 43,839,112 | Format the color of a cell in a pandas dataframe according to multiple conditions | <p>I am trying to format the color of a cell of an specific column in a data frame, but I can't manage to do it according to multiple conditions.</p>
<p>This is my dataframe (df):</p>
<pre><code> Name ID Cel Date
0 Diego b000000005 7878 2565-05-31 20:53:00
1 Luis b000000015 6464 20... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="noreferrer"><code>applymap</code></a>:</p>
<pre><code>from datetime import datetime, timedelta
import pandas as pd
name = ['Diego', 'Luis', 'Vidal', 'John', 'Yusef']
id = ['b000000005', 'b000000015', 'b000000002', 'b000000011', 'b000000013']... | python|pandas|formatting | 17 |
374,206 | 43,892,150 | Tensorflow on GPU | <p>I've been able to work with TensorFlow on CPU, Now I need to run it on a GPU device with the following specs: </p>
<p><strong>CPU: Intel Xeon(E5-2670) and win7 64bit and NVIDIA GeForce GTX 980 Ti</strong></p>
<p>I've installed python3.5 and Tensorflow for GPU just as described in TF homepage. when I run a test pro... | <ol>
<li>CUDNN might be one of the reasons. cuDNN v6.0 does not work for many people. Try with cuDNN v5.1.</li>
<li>Importing from inside GIT folder is also one of the reasons. </li>
</ol>
<p>Good to know 1 worked for you. </p> | python|tensorflow|gpu | 1 |
374,207 | 43,898,414 | find numeric column names in Pandas | <p>I need to select columns in Pandas which contain only numeric values in column names, for example:</p>
<pre><code>df=
0 1 2 3 4 window_label next_states ids
0 17.0 18.0 16.0 15.0 15.0 ddddd d 13.0
1 18.0 16.0 15.0 15.0 16.0 ddddd ... | <p>Try</p>
<pre><code>df.ids = df.ids.astype('object')
new_df = df.select_dtypes([np.number])
0 1 2 3 4
0 17.0 18.0 16.0 15.0 15.0
1 18.0 16.0 15.0 15.0 16.0
2 16.0 15.0 15.0 16.0 15.0
3 15.0 15.0 16.0 15.0 17.... | python|pandas|dataframe | 10 |
374,208 | 2,298,390 | Fitting a line in 3D | <p>Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D.</p>
<p>Thanks.</p> | <p>If you are trying to predict one value from the other two, then you should use <code>lstsq</code> with the <code>a</code> argument as your independent variables (plus a column of 1's to estimate an intercept) and <code>b</code> as your dependent variable. </p>
<p>If, on the other hand, you just want to get the best... | python|numpy|linear-algebra|curve-fitting | 59 |
374,209 | 73,090,197 | How to create pandas columns and fill with values according to values in another column | <p>I have this dataframe:</p>
<pre><code>text sentiment
asdasda positive
fsdfsdfs negative
sdfsdfs neutral
dfsdsd mixed
</code></pre>
<p><strong>and I want this outupu:</strong></p>
<pre><code>text positive negative neutral mixed
asdasda 1 ... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pandas.get_dummies</code></a> but before that you need to set <code>column "text"</code> as index and after getting result you need to rename all columns <code>sentiment_positive</code... | python|python-3.x|pandas|dataframe | 1 |
374,210 | 73,119,443 | compare sums of individuals columns and return name of max and min column pandas | <p>I have a df something like this</p>
<pre><code> date mon tue wed thu fri sat sun
01-01-2022 2 3 5 7 8 1 0
02-01-2022 3 4 7 6 3 0 4
03-01-2022 ... | <p>You can use <code>set_index</code>, <code>sum</code> and <code>agg</code>:</p>
<pre><code>df.set_index('date').sum().agg(['idxmin', 'idxmax'])
</code></pre>
<p>output:</p>
<pre><code>idxmin sat
idxmax wed
dtype: object
</code></pre>
<p>As a string:</p>
<pre><code>s = df.set_index('date').sum().agg(['idxmin', '... | pandas|max|multiple-columns | 2 |
374,211 | 73,116,292 | Pandas group by and row count by category | <p>I have a pandas df as follows:</p>
<pre><code>User Amount Type
100 10 Check
100 20 Cash
100 30 Paypal
200 50 Venmo
200 50 Cash
200 50 Check
300 20 Zelle
300 15 Zelle
300 15 Zelle
</code></pre>
<p>I want to organize it such that my e... | <p>You are looking for <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a>:</p>
<pre><code>pd.crosstab(df['User'], df['Type']).reset_index().rename_axis('',axis=1)
</code></pre>
<p>output:</p>
<pre><code> User Cash Check Paypal Venmo Zel... | pandas | 1 |
374,212 | 72,860,430 | How can I group by in python and create columns with information of a column if another column has a specific value? | <p>I have a data frame with "Team", "HA" (home away), "attack", "defense"</p>
<p><a href="https://i.stack.imgur.com/ceuEM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ceuEM.png" alt="input" /></a></p>
<p>And what I need to have is a table, grouped by Team wi... | <p>Just pivot your dataframe:</p>
<pre><code>out = df.pivot('Team', 'HA', ['attack', 'defense'])
out.columns = out.columns.swaplevel().to_flat_index().map(' '.join)
out = out.reset_index()
print(out)
# Output
Team Away attack Home attack Away defense Home defense
0 A. San Luis 1 3 ... | python|sql|pandas | 0 |
374,213 | 72,935,266 | Detecting anomalies among several thousand users | <p>I have this issue where I record a daily entry for all users in my system (several thousands, even 100.000+). These entries have 3 main features, "date", "file_count", "user_id".</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>date</th>
<th>file_count</th>
<... | <p>Article for anomaly detection in audit data can be found many on the Internet.
One simple article with many of examples/approaches can be found in original (Czech) language here: <a href="https://blog.root.cz/trpaslikuv-blog/detekce-anomalii-v-auditnich-zaznamech-casove-rady/" rel="nofollow noreferrer">https://blog.... | tensorflow|deep-learning|time-series|outliers|anomaly-detection | 1 |
374,214 | 73,070,654 | How to categorize one column value based on another column value | <p>I have a dataframe with 2 columns like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ColA</th>
<th>COLB</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABC</td>
<td>Null</td>
</tr>
<tr>
<td>Null</td>
<td>a</td>
</tr>
<tr>
<td>Null</td>
<td>b</td>
</tr>
<tr>
<td>DEF</td>
<td>Null</t... | <p>Lets start by creating the DataFrame:</p>
<pre><code>df1 = pd.DataFrame({'ColA':['ABC',np.NaN,np.NaN,'DEF',np.NaN,np.NaN,np.NaN,'GHI','IJK'],'ColB':[np.NaN,'a','b',np.NaN,'c','d','e',np.NaN,'f']})
</code></pre>
<p>Next we fill all NaN values with previous occurence:</p>
<pre><code>df1.ColA.fillna(method='ffill',inpl... | python-3.x|pandas | 1 |
374,215 | 72,899,364 | Output the confiendence / probability for a class of a CNN neuronal network | <p>I have a problem. I want to get the confiendence/ probability for my prediction. How could I get the confidence? I looked at <a href="https://stackoverflow.com/questions/38133707/how-can-i-implement-confidence-level-in-a-cnn-with-tensorflow">How can I implement confidence level in a CNN with tensorflow?</a> . But I ... | <p>The Softmax activation function normalises the output of the network, giving you the predicted probability of each of the 53 classes for a given sample.</p>
<pre><code>pred = pred.argmax(axis=1)
</code></pre>
<p>This line gives you the index of the node with the highest predicted probability.</p>
<pre><code>pred = p... | python|tensorflow|deep-learning|nlp|conv-neural-network | 1 |
374,216 | 72,894,227 | Why is np nan convertible to int by `astype` (but not by `int`)? | <p>This question comes from a finding that is very much not intuitive to me. If one tries the following:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
print(np.array([np.nan]).astype(int))
print(int(np.array([np.nan])))
</code></pre>
<p>then the output of the first is <code>[-922337203685477580... | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html" rel="nofollow noreferrer"><code>.astype</code></a> has optional argument <code>casting</code> whose default value is <code>'unsafe'</code>. Following values are allowed</p>
<ul>
<li>‘no’ means the data types should not be cast at al... | python|numpy|integer|nan | 2 |
374,217 | 72,940,115 | Applying Filter to Multi Dimensional Numpy Array ,eg: Cifar10 Data | <pre><code>from keras.datasets import cifar10
# load dataset
(trainX, trainy), (testX, testy) = cifar10.load_data()
# summarize loaded dataset
print('Train: X=%s, y=%s' % (trainX.shape, trainy.shape))
print('Test: X=%s, y=%s' % (testX.shape, testy.shape))
</code></pre>
<blockquote>
<p>Train: X=(50000, 32, 32, 3), y=(50... | <p>what you're looking for is <code>np.where()</code>. see the code</p>
<pre><code>TrainX = TrainX[np.where(trainMask)]
TestX = TestX[np.where(testMask)]
</code></pre> | python|numpy | 1 |
374,218 | 73,116,821 | How to replace only first Nan value in Pandas DataFrame? | <p>I am trying to replace Nan with a list of numbers generated by a random seed. This means each Nan value needs to be replaced by a unique integer. Items in the columns are unique, but the rows just seem to be replicating themselves? Any suggestions would be welcome</p>
<pre><code>np.random.seed(56)
rs=np.random.randi... | <p>the <code>df.fillna()</code> will replace <strong>all</strong> the values that contains NA. So your code is actually changing the NA values just at the first iteration of the forloop because than, no other values to fill remains.</p>
<p>You can use the applymap function to iterates through all the rows and fill the ... | python|pandas|dataframe|numpy | 0 |
374,219 | 73,126,473 | Can I visualize the content of a datasets.Dataset? | <p>I am using the Huggingface <code>datasets</code> library to load a dataset from a pandas dataframe.
The code is something similar to this:</p>
<pre><code>from datasets import Dataset
import pandas as pd
df = pd.DataFrame({"a": [1], "b":[1]})
dataset = Dataset.from_pandas(df)
</code></pre>
<p>Eve... | <p>The answer is simpler than you think. Just do</p>
<pre><code>print(dataset[i])
</code></pre>
<p>where <code>i</code> is the number of the row (first is 0).</p>
<p>The output will be a dictionary with the features as keys and the content of the row as values.</p>
<pre><code>print(dataset[0])
<<< {
"a&q... | python|pandas|huggingface-datasets | 1 |
374,220 | 72,849,150 | How do i get the year to change with each tournament? | <p>I don't understand why i am struggling with this but how do i get the year to change for each iteration. So when it goes through season 2020, all those tournaments and id's should say 2020 but its only saying the last iteration ran.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import pandas as pd
s... | <p>You can create list with all information as tuples and at the end create final dataframe. For example:</p>
<pre class="lang-py prettyprint-override"><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
seasonid = ["2021", "2020", "2019"]
all_data = []
for season in ... | python|pandas|dataframe|loops|beautifulsoup | 1 |
374,221 | 73,160,855 | How do I add data to a column only if a certain value exists in previous column using Python and Faker? | <p>I'm pretty new to Python and not sure what to even google for this. What I am trying to do is create a Pandas DataFrame that is filled with fake data by using Faker. The problem I am having is each column is generating fake data in a silo. I want to be able to have fake data created based on something that exists in... | <p>I'd slightly change the approach and generate a column <code>OS</code>. This column you can then transform into <code>With MacOS</code> etc. if needed.</p>
<p>With this approach its easier to get the 0.5 / 0.5 split within Windows right:</p>
<pre class="lang-py prettyprint-override"><code>from faker import Faker
fro... | python|pandas|function|faker | 1 |
374,222 | 73,036,681 | Counting elements in specified column of a .csv file | <p>I am programming in Python
I want to count how many times each word appears in a column. Coulmn 4 of my .csv file contains cca. 7 different words and need to know how many times each one appears. Eg. there are 700 lines and I need to count how many times the phrase HelloWorld appears in column 4.</p> | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>pandas.Series.value_counts()</code></a> on the column you want. Since you mentioned it's the fourth column, you can get it by index using <code>iloc</code> as well. Of course you have to... | python|pandas|dataframe | 0 |
374,223 | 73,061,746 | Local data that I can't save again gives "UnpicklingError: pickle data was truncated" while opening | <p>I have a pandas dataframe that I pickled to backup some data on a server.
Then I imported everything to my local machine using VSCode. Now the server is off and there is no way I can access the data again.</p>
<p>I pickled the data using pandas:</p>
<pre><code>import pandas as pd
congestion.to_pickle('/home/tugba/... | <p>When you use <code>pandas.to_pickle()</code> to pickle a dataframe, you should preferably use <code>pandas.read_pickle()</code> to unpickle.</p> | pandas|pickle | 0 |
374,224 | 72,972,933 | Convert a Tensorflow dataset containing inputs and labels to two NumPy arrays | <p>I'm using Tensorflow 2.9.1. I have a <code>test_dataset</code> object of class <code>tf.data.Dataset</code>, which stores both inputs and labels. The inputs are 4-dimensional Tensors, and the labels are 3-dimensional Tensors:</p>
<pre class="lang-py prettyprint-override"><code>print(tf.data.Dataset)
<PrefetchData... | <p>Instead of iterating over the dataset twice, you can unpack the dataset and concatenate the arrays inside the resulting tuples to get the final result.</p>
<p>The <code>zip(*ds)</code> is used to separate the dataset into two separate sequences (<code>X</code>'s and <code>y</code>'s). <code>X</code> and <code>y</cod... | python|arrays|numpy|tensorflow2.0|tensorflow-datasets | 1 |
374,225 | 72,988,605 | Pandas covert one dataframe to another | <p>I am making trouble on this matter. Would like to ask how to convert the following raw data to result data? Thanks</p>
<p>Raw data</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Board</th>
<th>Slot No.</th>
</tr>
</thead>
<tbody>
<tr>
<td>55</td>
<td>WD22UBBPe4</td>
<td>3<... | <p>Here is one way to do it</p>
<pre><code>df.pivot(index='Name', columns='Slot No.').add_prefix('Slot ').fillna('').reset_index()
</code></pre>
<pre><code>
Name Slot Board
Slot No. Slot 0 Slot 1 Slot 2 Slot 3 Slot 4
0 14 QWL1WBBPD2 WD22LBBPD2 WD22UBBPd6 QWL1WBBPF... | python|pandas | 2 |
374,226 | 73,113,834 | How to rewrite Pandas frame.append with concat | <p>I have the following code which works perfectly putting in subtotals and grand totals. With the frame.append method deprecated how should this be rewritten?</p>
<pre><code>pvt = pd.concat([y.append(y.sum()
.rename((x, 'Total')))
for x, y in table.groupby(level=0)
... | <p>Use</p>
<pre class="lang-py prettyprint-override"><code>pvt = pd.concat([y for x, y in table.groupby(level=0)] + \
[y.sum().rename((x, 'Total')) for x, y in table.groupby(level=0)] + \
[table.sum().rename(('Grand', 'Total'))])
# or
pvt = pd.concat([x for _, y in table.groupby(level=... | python|pandas|concatenation|deprecated | 0 |
374,227 | 72,929,317 | Concatenating two dataframes with no common columns but same row dimension | <p>I have two dataframes <strong>df1</strong> <em>(dimension: 2x3)</em> and <strong>df2</strong> <em>(dimension: 2x239)</em> taken for example - each having the same number of rows but a different number of columns.</p>
<p>I need to concatenate them to get a new dataframe <strong>df3</strong> <em>(dimension 2x242)</em>... | <p>You need to set the axis=1 parameter</p>
<pre><code>pd.concat([df1.reset_index(), df2.reset_index()], axis=1)
</code></pre> | python|pandas|dataframe|concatenation | 0 |
374,228 | 72,861,164 | Plot each value in a time series dataframe | <p>I have a CSV file that shows the price of a product's barcode for several supermarkets during the COVID pandemic.
The <code>dataframe.head()</code> looks like this:</p>
<pre><code> BARCODE AC BFRESH LIDL SUPERM
Date
2020-01-03 5201263086618 6.36 7.97 ... | <p>It is technically possible, but are you sure that's what you want?</p>
<p>You're asking for (968 unique barcodes * 4 shopping centers) 3872 individual lines on a single plot. It would be impossible to interpret. What is the question you're trying to answer? There are a few better ways to generate a meaningful plot, ... | python|pandas | 1 |
374,229 | 72,962,185 | How to create a new column from a constant value in a DateFrame | <pre><code>s = Service(executable_path=r'D:\Python3104\chromedriver.exe')
driver = webdriver.Chrome(service=s)
driver.maximize_window()
url = '''http://racing.hkjc.com/racing/information/Chinese/Reports/CORunning.aspx?
Date=20220701&RaceNo=2'''
driver.get(url)
time.sleep(3)
#Got the RaceNo from URL
soup = Beautif... | <p>The following code below should work. You just need to assign the <code>RACENo</code> as <code>str</code> (not <code>pandas.Series</code>) to the new column. I.e. there is no need to convert <code>RACENo</code> to a <code>pandas.Series</code>.</p>
<p>There are some ways to do it:</p>
<ol>
<li><code>df['RaceNo'] = RA... | python|pandas | 2 |
374,230 | 73,039,289 | Weird - Empty pd.dataframe after Excel import. But why? | <p>I'm afraid I'll despair soon.
I am importing an Excel file, and this always worked in this way for me. But nowI am getting an empty dataframe, and I don't know why?</p>
<p>My demo code looks like this:</p>
<pre><code>import pandas as pd
data = pd.read_excel ('import.xlsx', sheet_name=["Sheet 1", "She... | <p>I can't test it but it seems it gives dictionary with many dataframes and if you want to work with single sheet (single dataframe) then you should get it directly</p>
<pre><code>df = data["Sheet1"]
</code></pre> | python|excel|pandas|dataframe | 1 |
374,231 | 73,053,240 | Pytorch: Disable only nn.Dropout() without using model.eval() | <p>nn.Dropout() can be disabled by using model.eval().<br>However by using .eval(), nn.BatchNorm1d() are also disabled. Because the distributions between train and test sets are different, I'd like to disable only Dropout for generating data by GAN.<br>
Is there any way to disable only Dropout after training?<br>
Here ... | <p>The answer in the comment is right, you can run <code>eval()</code> on single modules.</p>
<p>But... why do you think you need to keep the BatchNorm active after training? By default, in eval mode it will use the running average/std computed during training (which is a good thing, and makes the model give the same o... | python|pytorch|generative-adversarial-network|batch-normalization|dropout | 0 |
374,232 | 72,920,150 | Why am I getting an error on trying to assign arrays to each element of a list? | <p>I am trying to create a list which should contain numeric values which I am trying to extract from a dataframe. The following is my code:</p>
<pre><code>list_values = []
j = 0
for i in country_list:
list_values[j] = df6['positioning'][i].to_numpy()
j = j + 1
print(list_values)
</code></pre>
<p>When ... | <p>At the beginning, <code>list_values</code> is an empty list and <code>j</code> is 0.</p>
<p>So if you use <code>list_values[j]</code>, 0 is an invalid index for an empty list. Therefore you get this error.</p>
<p>You cannot ever grow a list by using index assignment. Index assignment can only replace list items that... | python|arrays|list|numpy|for-loop | 1 |
374,233 | 73,069,965 | Converting column of floats to datetime | <p>I have a column of my dataframe that is made up of the following:</p>
<p><code>df['Year] = [2025, 2024, NaN, 2023, 2026, NaN]</code> (these are type <code>float64</code>)</p>
<p>How can I convert these years to something in datetime format? Since there are no months or days included I feel like they have to output a... | <p>You can use pandas' <code>to_datetime()</code> and set <code>errors='coerce'</code> to take care of the NaNs (-> NaT)</p>
<pre><code>df['Year'] = pd.to_datetime(df['Year'], format='%Y', errors='coerce')
</code></pre>
<p>The output is going to be like <code>01-01-2025, 01-01-2021 ...</code></p> | python|pandas|datetime | 2 |
374,234 | 72,951,491 | Python: Why can't I add a 3x1 array to one column of a 3x100 array? | <p>Variable <code>a</code> has the shape (3,1) and variable <code>b</code> has the shape (3,100). Now, I want to add variable <code>a</code> to just one column of variable <code>b</code>, meaning:</p>
<pre><code>x[:,ii] = a + b[:,ii]
</code></pre>
<p>However, I get this message:</p>
<pre><code>could not broadcast input... | <p>You need to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ravel.html" rel="nofollow noreferrer"><code>numpy.ravel()</code></a> Because <code>a.shape</code> is <code>(3,1)</code> and you need <code>(3,)</code>.</p>
<pre><code>x[:,ii] = a.ravel() + b[:,ii]
</code></pre> | python|arrays|numpy|indexing | 1 |
374,235 | 73,040,420 | Sum of values from multiple dicts | <p>I am iterating some code over a directory and I want to sum the values of same keys from dictionaries that I get.</p>
<p>The code is counting how many times a word appears in a column of a .csv file. It does that with every .csv file in the given folder.</p>
<p>I want an output of added values of same keys. Eg. firs... | <p>You can make a list of all the dicct_napake you have iterated through and do the following:</p>
<pre><code>import collections
import functools
import operator
dict_napake_1 = {'a': 5, 'b': 1, 'c': 2}
dict_napake_2 = {'a': 2, 'b': 5}
dict_napake_3 = {'a': 10, 'c': 10}
master_dict = [dict_napake_1,
di... | python|pandas|dataframe|dictionary | 1 |
374,236 | 73,034,118 | Efficient computation of entropy-like formula (sum(xlogx)) in Python | <p>I'm looking for an efficient way to compute the entropy of vectors, without normalizing them and while ignoring any non-positive value.</p>
<p>Since the vectors aren't probability vectors, and shouldn't be normalized, I can't use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html"... | <p>On my machine the computation of the logarithms takes about 80% of the time of <code>matmul</code> so it is definitively the bottleneck an optimizing other functions will result in a negligible speed up.</p>
<p>The bad news is that the default implementation <code>np.log</code> is not yet optimized on most platforms... | python|numpy|scipy|entropy | 1 |
374,237 | 73,126,923 | select rows based on a combination of strings without order in strings | <p>If I have the following code:</p>
<pre><code>df_ = df_[df_['summary'].str.contains('slow delivery', na=False)]
df_ = df_['summary']
print(df_)
</code></pre>
<p>And the following list:</p>
<pre><code>df_ = ['May be great product, but slow delivery is annoying',
'May be great product, but slow delivery is annoying',
'... | <p>Might as well just make separate masks for both words in this case. If you have a longer list of words, there are better solutions.</p>
<pre><code>df_ = df_[df_['summary'].str.contains('slow') & df_['summary'].str.contains('delivery')]
</code></pre> | pandas | 1 |
374,238 | 73,133,136 | Pandas column name missing depending on adressing | <pre><code>df.speed # so nice cause of autocomplete...
df['speed']
df.loc[:,'speed']
</code></pre>
<p>are returning my data like omitting the selected column name</p>
<pre><code>Time
2022-07-27 11:33:16.279157 45.000000
2022-07-27 11:33:16.628157 44.928571
2022-07-27 11:33:17.093157 44.857143
2022-07-27 11:33:... | <ul>
<li><code>df['speed']</code> and <code>df.speed</code> return a Series.</li>
<li><code>df[['speed']]</code> returns a DataFrame, which is what you're expecting.</li>
</ul> | python|pandas|matplotlib | 1 |
374,239 | 10,828,477 | Is there a way I can vectorize fsolve? | <p>I'm trying apply fsolve to an array:</p>
<pre><code>from __future__ import division
from math import fsum
from numpy import *
from scipy.optimize import fsolve
from scipy.constants import pi
nu = 0.05
cn = [0]
cn.extend([pi*n - pi/4 for n in range(1, 5 +1)])
b = linspace(200, 600, 400)
a = fsolve(lambda a: 1/b + f... | <p><code>fsum</code> is for python scalars, so you should look to numpy for vectorisation. Your method is probably failing because you're trying to sum a list of five numpy arrays, rather than five numbers or a single numpy array.</p>
<p>First I would recalculate <code>cn</code> using numpy:</p>
<pre><code>import num... | numpy|scipy | 3 |
374,240 | 3,718,791 | What is the reason for an unhandled win32 exception in an installer program? | <p>I got the following message:</p>
<p><code>An unhandled win32 exception occurred in numpy-1.5.0-sse3.exe [3324].</code></p>
<p>The exception occurred in the Numpy installer for Python 2.7---I have the latter on the machine.</p>
<p>When I clicked "Yes" for using the selected debugger, I got the following message:</... | <p>This is not the reason for the exception. Instead, when you tried to debug the original problem, you encountered a problem with Visual Studio. The Visual Studio error is resolved in the following manner:</p>
<p>Check your registry under the following path:</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\Wind... | python|windows|visual-studio-2008|winapi|numpy | 0 |
374,241 | 3,854,665 | Indexing with Masked Arrays in numpy | <p>I have a bit of code that attempts to find the contents of an array at indices specified by another, that may specify indices that are out of range of the former array.</p>
<pre><code>input = np.arange(0, 5)
indices = np.array([0, 1, 2, 99])
</code></pre>
<p>What I want to do is this:
print input[indices]
and ... | <p>Without using masked arrays, you could remove the indices greater or equal to 5 like this:</p>
<pre><code>print input[indices[indices<5]]
</code></pre>
<p>Edit: note that if you also wanted to discard negative indices, you could write:</p>
<pre><code>print input[indices[(0 <= indices) & (indices < 5)... | python|numpy|indexing | 5 |
374,242 | 3,734,776 | Translate matlab to python/numpy | <p>I am looking for an automatic code translator for Matlab to Python.
I downloaded and installed <a href="http://sourceforge.net/projects/libermate/" rel="nofollow noreferrer">LiberMate</a> but it is <strong>not</strong> documented anywhere and I wasn't able to make it work.</p>
<p>Has anybody dealt with this kind of... | <p>I've done it manually. Check <a href="http://www.scipy.org/NumPy_for_Matlab_Users" rel="nofollow noreferrer">this</a>.</p>
<p><strong>[EDIT]</strong></p>
<p>You can also try to call your MATLAB code from Python using <a href="http://mlabwrap.sourceforge.net/" rel="nofollow noreferrer">Mlabwrap</a>, a high-level Py... | python|matlab|numpy|scipy|code-translation | 9 |
374,243 | 3,650,194 | Are NumPy's math functions faster than Python's? | <p>I have a function defined by a combination of basic math functions (abs, cosh, sinh, exp, ...).</p>
<p>I was wondering if it makes a difference (in speed) to use, for example,
<code>numpy.abs()</code> instead of <code>abs()</code>?</p> | <p>Here are the timing results:</p>
<pre><code>lebigot@weinberg ~ % python -m timeit 'abs(3.15)'
10000000 loops, best of 3: 0.146 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'from numpy import abs as nabs' 'nabs(3.15)'
100000 loops, best of 3: 3.92 usec per loop
</code></pre>
<p><code>numpy.abs()</code> ... | python|performance|numpy | 87 |
374,244 | 70,565,279 | While applying qcut to a data series I am getting the below mentioned Index error | <p>Hi can anyone tell me what is the issue here?</p>
<pre><code>#How to bin a numeric series to 10 groups of equal size?
ser = pd.Series(np.random.random(20))
s=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
label=['1st','2nd','3rd','4th','5th','6th','7th','8th','9th','10th']
k=pd.qcut(ser,q=s,labels=label)
</code></pre>
<... | <p>Which pandas version do you have? In 1.3.5 everything works fine:</p>
<pre><code>ser = pd.Series(np.random.random(10))
s=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
label=['1st','2nd','3rd','4th','5th','6th','7th','8th','9th','10th']
k=pd.qcut(ser,q=s,labels=label)
</code></pre>
<p>Output:</p>
<pre><code>0 6th
1 ... | python|pandas | 0 |
374,245 | 70,392,819 | Problem with plotting/calculating exponential curve (python, matplotlib, pandas) | <p>I have some data that forms exponential curve and I'm trying to fit that curve to the data.</p>
<p>Unfortunately everything I have tried didn't work (I will spare you madness of the code).</p>
<p>The thing is that it works when I used <code>a*x**2 +b*x + c</code> or <code>a*x**3 + b*x**2 +c*x + d</code> with what I ... | <p>If you believe this is exponentiel curve i would find linear fit of the log of the data.</p>
<pre><code># your data in a Dataframe
import pandas as pd
import numpy as np
df = pd.read_csv("data.csv", sep=",")
# get log of your data
log_y = np.log(df["y"])
# linear fit of your log (as e... | python|pandas|matplotlib|scipy|scipy-optimize | 1 |
374,246 | 70,647,541 | Is there a way to reduce expected conv2d_Conv2D1_input from 4 dimensions to 3? | <p><strong>Problem</strong>:</p>
<ul>
<li>a ValueError is saying that <code>conv2d_Conv2D1_input</code> is expecting to have 4 dimension(s), but got array with shape [475,475,3]</li>
</ul>
<p>However:</p>
<ul>
<li>The inputShape is set to [475,475,3]</li>
<li>when logged, tensors have the shape [475,475,3]</li>
</ul>
<... | <p>The batch dimension is mission. It can be added by using <code>expandDims()</code></p>
<pre><code>const im = await loadImage(`./2.png`).expandDims()
model.predict(im)
</code></pre> | javascript|node.js|conv-neural-network|tensor|tensorflow.js | 1 |
374,247 | 70,515,094 | pandas: how to add date column into groupby result | <p>I have a csv file that is user behavior data in a web page. here is the sample data:</p>
<pre><code>_time,dataCenter,customer,user,SID,ACT,
2021-11-25T13:45:42.139+0000,dc1,customer1,user1,sid1,open_page,
2021-11-25T13:45:50.139+0000,dc1,customer1,user1,sid1,create_form,
2021-11-25T13:46:51.139+0000,dc1,customer1,us... | <p>IIUC:</p>
<pre><code>df = df.groupby(['dataCenter', 'customer', 'user', 'SID']).agg(date = ('_time', 'first'),
ACT= ('ACT', ','.join)).reset_index()
df['date'] = pd.to_datetime(df['date']).dt.date
</code></pre>
<p><code>OUTPUT</code></p>
<pre><code> dat... | pandas|dataframe|group-by | 1 |
374,248 | 70,605,545 | Position of legend in matplot with secondary y-axis (python) | <p>I try to create a plot in python with matplotlib consisting of two plots and one with a secondary y-axis. The first is a scatter and the second a line plot.
Now, I want to move the legend to somewhere else but whenever I use <code>ax.legend()</code> only the label of the first axis appears but the second vanishes.</... | <p>This approach (using your provided data):</p>
<pre class="lang-py prettyprint-override"><code># plot the flagged points as dots
data_flag = data[data["Flag"] == True]
ax = data_flag.plot.scatter(x="Date",
y="Value A",
c="black... | python|pandas|matplotlib|plot | 0 |
374,249 | 70,695,599 | How to impute nan values in a Pandas dataframe from a multi-index dataframe? | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame([[np.nan, 2, 20, 4],
[3, 1, np.nan, 1],
[3, 1, 15, 1],
[np.nan, 1, np.nan, 1],
[10, 1, 30, 4],
[50, 2, 35, 4],
[10, 1, 37, 4],
... | <p>You can use <code>combine_first</code>:</p>
<pre><code>out = df.combine_first(df.groupby(['B', 'D']).transform('mean'))
print(out)
# Output
A B C D
0 50.0 2 20.0 4
1 3.0 1 15.0 1
2 3.0 1 15.0 1
3 3.0 1 15.0 1
4 10.0 1 30.0 4
5 50.0 2 35.0 4
6 10.0 1 37.0 4
7 40.0 2 30.0... | python|pandas | 1 |
374,250 | 70,539,674 | Train neural network model on multiple datasets | <p>What I have:</p>
<ol>
<li>A neural network model</li>
<li>10 identically structured datasets</li>
</ol>
<p>What I want:</p>
<ol>
<li>Train model on all the datasets separately</li>
<li>Save their models separately</li>
</ol>
<p>I can train the datasets separately and save the single models one at a time. But I want ... | <p>You can use one of the concepts of <code>concurrency and parallelism</code>, namely <a href="https://www.geeksforgeeks.org/multithreading-python-set-1/" rel="nofollow noreferrer"><code>Multi-Threading</code></a>, or in some cases, <a href="https://www.geeksforgeeks.org/multiprocessing-python-set-1/" rel="nofollow no... | python|tensorflow|keras|deep-learning|neural-network | 2 |
374,251 | 70,424,990 | Drop a row in a tensor if the sum of the elements is lower than some threshold | <p>How can I drop rows in a tensor if the sum of the elements in each row is lower than the threshold -1? For example:</p>
<pre class="lang-py prettyprint-override"><code>tensor = tf.random.normal((3, 3))
tf.Tensor(
[[ 0.506158 0.53865975 -0.40939444]
[ 0.4917719 -0.1575156 1.2308844 ]
[ 0.08580616 -1.1503975 ... | <p><code>tf.boolean_mask</code> is all you need.</p>
<pre class="lang-py prettyprint-override"><code>tensor = tf.constant([
[ 0.506158, 0.53865975, -0.40939444],
[ 0.4917719, -0.1575156, 1.2308844 ],
[ 0.08580616, -1.1503975, -2.252681 ],
])
mask = tf.reduce_sum(tensor, axis=1) > -1
# <tf.Te... | python|tensorflow | 0 |
374,252 | 70,726,330 | Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu | <p>I get the following error message which I tried to deal with it by throwing <code>.to(self.device)</code> everywhere but it doesn't work.</p>
<pre><code> ab = torch.lgamma(torch.tensor(a+b, dtype=torch.float, requires_grad=True).to(device=local_device))
Traceback (most recent call last):
File "Script.py"... | <p>I am not sure if this is the "only" problem, but one of the device-related problems is this:</p>
<p><code> elbo = torch.tensor(0, dtype=torch.float)</code> <- this will create the elbo tensor on CPU</p>
<p>and when you do, <code>elbo -= <some result></code>,</p>
<p>The result is on cuda (or <code>... | deep-learning|pytorch|gpu | 1 |
374,253 | 70,404,137 | cannot concatenate object of type '<class 'numpy.ndarray'>'; only Series and DataFrame objs are valid | <p>I am intending to visualise the data using a pairplot after using StandardScaler,
But my code is producing the following error</p>
<pre><code> raise TypeError(msg)
TypeError: cannot concatenate object of type '<class 'numpy.ndarray'>'; only Series and DataFrame objs are valid
</code></pre>
<p>Full code</p>... | <p>After using <code>StandardScaler</code>, your X_train (which was a <code>pd.DataFrame</code> before) has become a <code>numpy.ndarray</code>, so that's why you cannot concat <code>X_train</code> and <code>y_train</code>. Because <code>X_train</code> is a NumPy array and <code>y_train</code> is a Pandas DataFrame</p>... | python|pandas|seaborn | 2 |
374,254 | 70,552,597 | How to shape and train multicolumn input and multicolumn output (many to many) with RNN LSTM model in TensorFlow? | <p>I am facing a problem with training an LSTM model with multicolumn input output. My code is below:</p>
<pre><code>time_step = 60
#Create a data structure with n-time steps
X = []
y = []
for i in range(time_step + 1, len(training_set_scaled)):
X.append(training_set_scaled[i-time_step-1:i-1, 0:len(training_set.co... | <p>Allright, after completing <a href="https://stackabuse.com/solving-sequence-problems-with-lstm-in-keras-part-2/" rel="nofollow noreferrer">this tutorial</a> i understood what should be done. Below is placed final code with comments:</p>
<pre><code>#Variables
future_prediction = 30
time_step = 60 #learning step
split... | python|tensorflow|many-to-many|lstm|recurrent-neural-network | 0 |
374,255 | 70,719,212 | Barplot of two columns based on specific condition | <p>I was given a task where I'm supposed to plot a element based on another column element.</p>
<p>For further information here's the code:</p>
<pre><code># TODO: Plot the Male employee first name on 'Y' axis while Male salary is on 'X' axis
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_excel(&qu... | <p>First generate the male rows separately and extract first name and salary for plotting.</p>
<p>The below code identifies first five male employees and converts their first name and salary as x and y lists.</p>
<pre><code>x = list(df[df['Gender'] == "Male"][:5]['Fname'])
y = list(df[df['Gender'] == "Ma... | python|pandas|matplotlib | 1 |
374,256 | 70,406,840 | Create columns in python data frame based on existing column-name and column-values | <p>I have a dataframe in pandas:</p>
<pre><code>import pandas as pd
# assign data of lists.
data = {'Gender': ['M', 'F', 'M', 'F','M', 'F','M', 'F','M', 'F','M', 'F'],
'Employment': ['R','U', 'E','R','U', 'E','R','U', 'E','R','U', 'E'],
'Age': ['Y','M', 'O','Y','M', 'O','Y','M', 'O','Y','M', 'O']
... | <p>You're looking for <a href="https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pd.get_dummies</code></a>.</p>
<pre><code>>>> pd.get_dummies(df)
Gender_F Gender_M Employment_E Employment_R Employment_U Age_M Age_O Age_Y
0 0 1 ... | pandas|dataframe|iteration | 2 |
374,257 | 70,557,782 | Long initialization time for model.fit when using tensorflow dataset from generator | <p><em>This is my first question on stack overflow. I apologise in advance for the poor formatting and indentation due to my troubles with the interface.</em></p>
<p><strong>Environment specifications:</strong></p>
<p>Tensorflow version - 2.7.0 GPU (tested and working properly)</p>
<p>Python version - 3.9.6</p>
<p>CPU ... | <p>I FOUND THE ANSWER</p>
<p>The problem was in the following code:</p>
<pre><code>TRAIN_NUM_FILES = 752803
train_images = train_images.shuffle(40)
val_size = int(TRAIN_NUM_FILES * 0.1)
val_images = train_images.take(val_size)
train_images = train_images.skip(val_size)
</code></pre>
<p>It takes an inordinate amount of ... | python|pandas|tensorflow|keras | 1 |
374,258 | 70,631,736 | how to compare two csv file in python and flag the difference? | <p>i am new to python. Kindly help me.
Here I have two set of csv-files. i need to compare and output the difference like changed data/deleted data/added data. here's my example</p>
<pre><code>file 1:
Sn Name Subject Marks
1 Ram Maths 85
2 sita Engilsh 66
3 vishnu science 50
4 balaji s... | <p>The idea here is to flatten your dataframe with <code>melt</code> to compare each value:</p>
<pre><code># Load your csv files
df1 = pd.read_csv('file1.csv', ...)
df2 = pd.read_csv('file2.csv', ...)
# Select columns (not mandatory, it depends on your 'Sn' column)
cols = ['Name', 'Subject', 'Marks']
# Flat your data... | python|python-3.x|pandas|csv|export-to-csv | 0 |
374,259 | 70,502,488 | How to get individual cell in table using Pandas? | <p>I have a table:</p>
<pre><code> -60 -40 -20 0 20 40 60
100 520 440 380 320 280 240 210
110 600 500 430 370 320 280 250
120 670 570 490 420 370 330 290
130 740 630 550 480 420 370 330
140 810 690 600 530 470 410 370
</code></p... | <p>You can select any cell from existing indices using:</p>
<pre><code>df.loc[120,-60]
</code></pre>
<p>The type of the indices needs however to be integer. If not, you can fix it using:</p>
<pre><code>df.index = df.index.map(int)
df.columns = df.columns.map(int)
</code></pre>
<p>For interpolation, you need to add the ... | python|pandas|dataframe|numpy | 3 |
374,260 | 70,606,281 | Can't get summary or weights from loaded keras model | <p>I saved a keras model using model.save(model_path). Now when I try to load it and apply model.summary() or model.get_weights() function I am getting following error:</p>
<pre><code>AttributeError: '_UserObject' object has no attribute 'summary'
</code></pre>
<p>Tried printing the data type of the model and got follo... | <p>The reproducible code above isn't complete I think. However, you need to change the code as follows to make it run. (I've tested on cpu/gpu with <code>tf 2.4/2.7</code>.)</p>
<pre><code>model_path = "https://tfhub.dev/google/universal-sentence-encoder/4"
def save_model(model_path):
model = tf.keras.Se... | tensorflow|keras|tensorflow2.0|tf.keras | 1 |
374,261 | 70,657,069 | How to plot a list of Points and LINESTRING? | <p>hello all is there a way to plot a list of LINESTRING and list of Points</p>
<p>for example I have</p>
<pre><code>line_string = [LINESTRING (-1.15.12 9.9, -1.15.13 9.93), LINESTRING (-2.15.12 8.9, -2.15.13 8.93)]
point = [POINT (5.41 3.9), POINT (6.41 2.9)]
</code></pre>
<p>My goal is to have a map or graph where th... | <p>You can access matplotlib easily using geopandas scripting layer.</p>
<pre><code>from shapely.geometry import LineString, Point
import geopandas as gpd
line_strings = [LineString([(-1.15, 0.12), (9.9, -1.15), (0.13, 9.93)]),
LineString([(-2.15, 0.12), (8.9, -2.15), (0.13 , 8.93)])]
points = ... | python|geometry|geopandas|geo|shapely | 4 |
374,262 | 70,716,860 | How to analyze external data using command line arguments | <p>I started to write a program analyzing external data. This is done with the help of command line arguments. However, i cant execute the program.. Is it wrong or am I on the right track...?</p>
<pre class="lang-py prettyprint-override"><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument("... | <p>If you were running the script from the command line, you would need to add arguments (e.g., <code>python3 tom_script.py avg delay flights.tsv</code>):</p>
<pre><code>$ python3 tom_script.py # Incorrect
usage: tom_script.py [-h] {avg,max} {distance,delay} tsvfile
tom_script.py: error: the following arguments are r... | python|pandas|command-line-arguments | 0 |
374,263 | 70,390,466 | Calculating correlation between points where each points has a timeseries | <p>I could use some advice how to make a faster code to my problem. I'm looking into how to calculate the correlation between points in space (X,Y,Z) where for each point I have velocity data over time and ideally I would like for each point P1 to calculate the velocity correlation with all other points.</p>
<p>In the ... | <p><strong>Solution 1:</strong></p>
<pre><code>groups = df.groupby(["X", "Y", "Z"])
</code></pre>
<p>You group the data by the points in space.</p>
<p>Than you iterate through all the combinations of points and calculate the correlation</p>
<pre><code>import itertools
import numpy as np
fo... | python|pandas|numpy|statsmodels | 0 |
374,264 | 70,661,024 | using warnings.filterwarnings() to convert a warning into an exception | <p>I want to programatically capture when statsmodels.api.OLS raises its "The smallest eigenvalue is ..." warning</p>
<p>This would enable me to filter a large number of OLS systems by whether or not they raise this warning</p>
<p>Ideally, I would like to pick off just particular warnings instead of a blanket... | <p>You can get the smallest eigenvalue using <code>model.eigenvals[-1]</code>, just check that it is less than <code>1e-10</code> to raise an exception. Here's the <a href="https://www.statsmodels.org/dev/_modules/statsmodels/regression/linear_model.html#OLS" rel="nofollow noreferrer">source</a> that generates the note... | python|pandas|numpy | 0 |
374,265 | 70,675,210 | Pandas: Count the occurrences of specific value in Column B...and display it in column C | <p>I have a Pandas dataframe where one of the columns tracks the state an accident occurred in. I want to add a column that totals the number of accidents from that state. For instance, if one of my rows shows an accident that happened in Utah, I want the last column to count the number of accidents in the dataframe th... | <p>You will want to read pandas docs on <code>assign</code> and <code>transform</code> to understand fully what each is doing.</p>
<p><code>transform</code> returns a series of counts in this case and <code>assign</code> will create your new column.</p>
<p>If your data is just columns model and state, try:</p>
<pre><co... | python|pandas | 0 |
374,266 | 70,656,917 | Read excel and get data of 1 row as a object | <p>I want to read a excel file using pandas and want row of the excel as object like</p>
<pre><code>{2, 3,'test data' , 1}
</code></pre>
<p>I am reading pandas file like</p>
<pre><code>excel_data = pd.read_excel(upload_file_url , index_col=None, header=None)
for name in excel_data:
print(name)
</code></pre>
<p>but ... | <p>The <code>iterrows()</code> method might help to get individual rows from the dataframe.</p>
<p>Consider the following crude solution</p>
<pre><code>excel_data = pd.read_excel(upload_file_url , index_col=None, header=None)
for name in excel_data.iterrows():
print(str(name[1].tolist()).replace("[","... | python|pandas | 1 |
374,267 | 70,584,848 | How to make output file name reflect for loop list in python? | <p>I have a function that does an action for every item in a list and then outputs a final product file for each item in that list. What I am trying to do is append a string to each of the output files that reflects the items in the initial list. I will explain more in detail here.</p>
<p>I have the following code:</p>... | <p>You need to use a formatted string (A string with an <em>f</em> at the beginning). For example:</p>
<pre><code>name = "foo"
greeting = f'Hello, {name}!'
</code></pre>
<p>Inside those curly brackets is the variable you want to put in the string. So here's the modified code:</p>
<pre><code>colors = ['Blue', ... | python|pandas|loops|csv | 2 |
374,268 | 70,443,472 | How to store after groupby | <p>How am I able to use the column after using groupby?
Let's say</p>
<pre><code>x = df_new.groupby('industry')['income'].mean().sort_values(ascending = False)
</code></pre>
<p>would give:</p>
<pre><code>"industry"
telecommunications 330
crypto. 100
gas 1... | <p><code>groupby(...).XXX()</code> (where <code>XXX</code> is some support method, e.g. <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.mean.html" rel="nofollow noreferrer"><code>mean</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.sort_values.html" rel="nofollow nore... | python|pandas|pandas-groupby | 1 |
374,269 | 70,517,273 | LSTM model training accuracy and loss not changing | <p>I am doing Sepsis Forecasting using Multivariate LSTM. The target variable is SepsisLabel. The time series data look like this where each row represent an hour, with 5864 patients (P_ID = 1 means its 1 patient data):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: cen... | <p>I tried the same code to reproduce the error. But I got this output.</p>
<pre><code>model.compile(optimizer='adam', loss='mse', metrics = ['accuracy'])
from livelossplot import PlotLossesKeras
loss_plot = PlotLossesKeras()
model.fit(x_train, y_train, epochs=50, batch_size=8, verbose=1, validation_split=0.2, shuffle... | python|pandas|tensorflow|keras|lstm | 0 |
374,270 | 70,700,626 | This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported | <p>I encountered this error, how do I resolve it?</p>
<pre><code>NotImplementedError: Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
</code></pre>
<pre><code># train the model
model = define_... | <p>As others have indicated elsewhere this is due to an incompatibility between specific tensorflow versions and specific numpy versions.</p>
<p>conda version 4.11.0</p>
<p>Commands to setup working environment:</p>
<pre><code>conda activate base
conda env remove -y --name myenv
conda create -y --name myenv tensorflow=... | python|numpy|tensorflow|tensorflow-datasets | 0 |
374,271 | 70,412,894 | Python Running Error on Macbook pro m1 max (Running on Tensorflow) | <p>I am trying to run this code from github <a href="https://github.com/ItamarRocha/binary-bot" rel="nofollow noreferrer">binary-bot</a> on my new macbook pro max M1 chip:</p>
<p>Metal device set to:</p>
<pre><code>Apple M1 Max
systemMemory: 32.00 GB
maxCacheSize: 10.67 GB
</code></pre>
<p>And I am getting the followin... | <p>It worked after I deleted the stored model and saved a new one</p> | python|tensorflow|deep-learning|lstm|apple-m1 | 1 |
374,272 | 70,685,859 | How can I save an image (nii.gz) after reshaping it? | <p>I'm trying to reshape an image after reshaping it, I'm facing problems when it comes to the saving method. Here's the code I'm trying to run:</p>
<pre><code>import nibabel as nib
import numpy as np
from nibabel.testing import data_path
import os
example_filename = os.path.join("D:/Volumes convertidos LIDC"... | <p>You are trying to save a <code>numpy</code> array, whereas the <code>nib.save</code> expects a <code>SpatialImage</code> object.</p>
<p>You should convert the <code>numpy</code> array to a <code>SpatialImage</code>:</p>
<pre><code>final_img = nib.Nifti1Image(newimg, img.affine)
</code></pre>
<p>After which you can s... | python|image|numpy | 3 |
374,273 | 70,708,241 | vectorize a dataframe in pandas | <p>Hi I have a dataframe in the tidy format such as</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c',3: 'a', 4: 'b', 5: 'c'},
'B': {0: 1, 1: 3, 2: 5,3: 1, 4: 3, 5: 5},
'C': {0: 2, 1: 4, 2: 6,3: 2, 4: 4, 5: 6}})
</code></pre>
<p>I made a functio... | <p>I think i figured it out by using the solution from @natnij but for strings</p>
<pre><code>df.pivot_table(index='A',columns='B',values='C',aggfunc=lambda x: ' '.join(x))
</code></pre>
<p>thank you</p> | python|pandas|dataframe | 0 |
374,274 | 70,449,461 | Add extra instances to my x_test and y_test after using train_test_split() | <p>I'm working on a multi-class classification problem in which I have my data categorized into 8 classes.</p>
<p>What I want to do is to extract out all the instances that are related to one classification from my training dataset and include in my testing dataset.</p>
<p>What I did until now is this:</p>
<pre><code>#... | <p>IIUC:</p>
<pre><code>for klass in df['y'].unique():
m = df['y'] != klass
X = df.loc[m, df.columns[:3]]
y = df.loc[m, df.columns[-1]]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.2)
X_test = X_test.append(df.loc[~m, df.columns[:3]])
y_test = y_test.appe... | python|pandas|scikit-learn|classification | 0 |
374,275 | 70,636,079 | Why would a much lighter Keras model run at the same speed at inference as the much larger original model? | <p>I trained a Keras model with the following architecture:</p>
<pre><code>def make_model(input_shape, num_classes):
inputs = keras.Input(shape=input_shape)
# Image augmentation block
x = inputs
# Entry block
x = layers.experimental.preprocessing.Rescaling(1.0 / 255)(x)
x = layers.Conv2D(32, 3, ... | <p>The number of parameters is at most and indication how fast a model trains or runs inference. It might depend on many other factors.</p>
<p>Here some examples, which might influence the throughput of your model:</p>
<ol>
<li>The activation function: ReLu activations are faster then e.g. ELU or GELU which have expone... | python|tensorflow|machine-learning|keras|computer-vision | 2 |
374,276 | 70,633,113 | Collecting features from network.foward() in TensorFlow | <p>So basically I want to achieve the same goal as in this code but in TensorFlow</p>
<pre><code>def get_function(network, loader):
''' Collect function (features) from the self.network.module.forward_features() routine '''
features = []
for batch_idx, (inputs, targets) in enumerate(loader):
inputs,... | <p>To answer your question, I just need to ensure that you understand your original <a href="/questions/tagged/torch" class="post-tag" title="show questions tagged 'torch'" rel="tag">torch</a> <a href="https://pastecode.io/s/b03cpoyv" rel="nofollow noreferrer">code</a> properly. So, here's your workflow</p>
<pr... | python|tensorflow|machine-learning|keras|pytorch | 1 |
374,277 | 42,888,300 | can we pass non tensor to tf.py_func input? | <pre><code>def np_function( np_array1, float_value):
np_array2 = ...
return np_array2
#tensorflow customised op
def tf_function( tf_tensor_in_gpu, float_value):
return \
tf.py_func(np_function,[tf_tensor_in_gpu, float_value],[tf.float32])
</code></pre>
<p>I want to make a customized tensorflow op from my fu... | <p>i solved this by:</p>
<pre><code>def np_function_generator(float_value):
def np_function(np_array1):
np_array2 = ...
... you can use float_value here ...
return np_array2
return np_function
#tensorflow customised op
def tf_function( tf_tensor_in_gpu, float_value):
np_fu... | tensorflow | 2 |
374,278 | 42,975,789 | Installing python packages without dependencies | <p>I am trying to install a specific version of a python package into a pre-installed python environment. The package is <a href="https://github.com/laspy/laspy" rel="nofollow noreferrer">laspy</a> and the version is an old one (1.2.5). The package is supposed to work with Python version 2.7, but I am trying to install... | <p>So stupid... The error message <code>PermissionError</code> was just because I opened cmd without administrative privileges...</p>
<p>Just installed <code>laspy</code> with <code>pip install laspy==1.2.5</code>. Hopefully it will work with this 64bit version of Python shipped with ArcGIS Pro (I was actually using i... | python|python-3.x|numpy|arcgis|arcpy | 1 |
374,279 | 42,902,944 | python pandas - how to merge date from one and time from another column and create new column | <p>I have a dataframe that comes from a database like this:
Both FltDate and ESTAD2 are datetime64[ns]</p>
<pre><code>>>> print df[['Airport', 'FltDate', 'Carrier', 'ESTAD2']]
Airport FltDate Carrier ESTAD2
0 EDI 2017-06-18 BACJ 1899-12-30 05:35:00
1 EDI 2017-06-18 BA... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>strftime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p>
<pre... | python|pandas | 2 |
374,280 | 42,837,067 | Python Pandas: Use regex to replace strings with hyperlink | <p>Beginner's question. </p>
<p>I'm scraping housing ads with BS4 and analyse the subsequent data with Pandas. </p>
<p>I have a DataFrame with several columns. This issue considers only one of the columns, which looks like, </p>
<pre><code>district | ... |
----------------
A | ... |
B | ... |
C ... | <p>It seem you need <code>apply</code> <code>format</code>:</p>
<pre><code>df = pd.DataFrame({'district':['A','B','C']})
df['url'] = df.district.apply('<a href="www.site.com/city/district-{0}/">{0}</a>'.format)
print (df)
district url
0 A <a href="ww... | python|regex|pandas|replace|hyperlink | 1 |
374,281 | 42,896,453 | Can numpy argsort return lower index for ties? | <p>I have a numpy array:</p>
<pre><code>foo = array([3, 1, 4, 0, 1, 0])
</code></pre>
<p>I want the top 3 items. Calling</p>
<pre><code>foo.argsort()[::-1][:3]
</code></pre>
<p>returns </p>
<pre><code>array([2, 0, 4])
</code></pre>
<p>Notice values <code>foo[1]</code> and <code>foo[4]</code> are equal, so <code>n... | <p>What about simply this?</p>
<pre><code>(-foo).argsort(kind='mergesort')[:3]
</code></pre>
<p>Why this works:</p>
<p>Argsorting in descending order (not what <code>np.argsort</code> does) is the same as argsorting in ascending order (what <code>np.argsort</code> does) the opposite values. You then just need to pick t... | python|arrays|numpy | 5 |
374,282 | 42,671,418 | Calculating Cumulative Compounded Returns in Pandas | <p>I have a series of daily percentage returns <code>returns</code>:</p>
<pre><code> Returns
Date
2003-03-03 0.0332
2003-03-04 0.0216
2003-03-05 0.0134
...
2010-12-29 0.0134
2010-12-30 0.0133
2010-12-31 -0.0297
</code></pre>
<p>I can calculate a return... | <p>For me it return a bit different results, but I think you need <code>groupby</code>:</p>
<pre><code>a = df.add(1).cumprod()
a.Returns.iat[0] = 1
print (a)
Returns
Date
2003-03-03 1.000000
2003-03-04 1.055517
2003-03-05 1.069661
2010-12-29 1.083995
2010-12-30 1.098412
2010-12-31 1.... | python|pandas|dataframe | 5 |
374,283 | 43,014,503 | save_npz method missing from scipy.sparse | <p>I am using 0.17 version of <code>scipy</code> library on ubuntu 16.04 64-bit system in <code>python v3.5</code>. I am unable to find <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.save_npz.html#scipy.sparse.save_npz" rel="nofollow noreferrer">scipy.sparse.save_npz</a> operation in the lib... | <p>Yes, <code>scipy.sparse.save_npz / load_npz</code> are new in version 0.19.0 <a href="http://scipy.github.io/devdocs/release.0.19.0.html" rel="nofollow noreferrer">http://scipy.github.io/devdocs/release.0.19.0.html</a></p> | python|numpy|scipy | 3 |
374,284 | 42,921,854 | How to check if a particular cell in pandas DataFrame isnull? | <p>I have the following <code>df</code> in pandas.</p>
<pre><code>0 A B C
1 2 NaN 8
</code></pre>
<p>How can I check if <code>df.iloc[1]['B']</code> is NaN?</p>
<p>I tried using <code>df.isnan()</code> and I get a table like this:</p>
<pre><code>0 A B C
1 false true fals... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="noreferrer"><code>pd.isnull</code></a>, for select use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>loc</code></a> or <a href="http://pandas.pydata.org/panda... | python|pandas|dataframe | 40 |
374,285 | 42,929,997 | How to replace non integer values in a pandas Dataframe? | <p>I have a dataframe consisting of two columns, Age and Salary</p>
<pre><code>Age Salary
21 25000
22 30000
22 Fresher
23 2,50,000
24 25 LPA
35 400000
45 10,00,000
</code></pre>
<p>How to handle outliers in Salary column and replace them with an integer? </p> | <p>If need replace non numeric values use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="noreferrer"><code>to_numeric</code></a> with parameter <code>errors='coerce'</code>:</p>
<pre><code>df['new'] = pd.to_numeric(df.Salary.astype(str).str.replace(',',''), errors='coerce')... | python|pandas|dataframe | 14 |
374,286 | 42,983,906 | How to use `apply()` or other vectorized approach when previous value matters | <p>Assume I have a DataFrame of the following form where the first column is a random number, and the other columns will be based on the value in the previous column.</p>
<p><a href="https://i.stack.imgur.com/sDcvN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sDcvN.png" alt="enter image descripti... | <p>What you're describing is a recurrence relation, and I don't think there is currently any non-loop way to do that. Things like <code>apply</code> and <code>rolling_apply</code> still rely on having all the needed data available before they begin, and outputting all the result data at once at the end. That is, they... | python|python-3.x|pandas | 4 |
374,287 | 42,981,493 | Weights and biases in tf.layers module in TensorFlow 1.0 | <p>How do you access the weights and biases when using tf.layers module in TensorFlow 1.0? The advantage of tf.layers module is that you don't have to separately create the variables when making a fully connected layer or convolution layer. </p>
<p>I couldn't not find anything in the documentation regarding accessing ... | <p>I don't think <code>tf.layers</code> (i.e. TF core) support summaries yet. Rather you have to use what's in contrib ...knowing that stuff in contrib, may eventually move into core but that the current API may change:</p>
<blockquote>
<p>The layers module defines convenience functions summarize_variables,
summar... | tensorflow | 2 |
374,288 | 42,796,332 | Run Apriori algorithm in python 2.7 | <p>I have a DataFrame in python by using pandas which has 3 columns and 80.000.000 rows.</p>
<p>The Columns are: {event_id,device_id,category}.
<a href="https://i.stack.imgur.com/mXKW9.png" rel="nofollow noreferrer">here is the first 5 rows of my df</a></p>
<p>each device has many events and each event can have more ... | <p>A little bit of a late response here, but to me it seems like apriori might not be the right choice for your data. Traditional apriori looks at binary data (either "in the cart" or "not in the cart" for the classic market basket example), for a list of transactions that are all of the same type. What you seem to hav... | python-2.7|pandas|dataframe|transactions|apriori | 0 |
374,289 | 42,683,189 | pandas series extractall error | <p>I have a pandas series (named df) in the following format:</p>
<pre><code> col1
a GEOS 13100
b MATH 13100-MATH 13200
c MATH 19100-19200
d SPAN 10300 or 20300
e EGPT 10101-10102-10103
f MOGK 10100/3010... | <p>If you are using an older version of pandas, you might have run into something like <a href="https://github.com/pandas-dev/pandas/pull/13156" rel="nofollow noreferrer">this issue</a> (although your indices appear to not be of the problematic form). In version 0.19.0, both cases run without errors:</p>
<pre><code>In... | python|pandas | 0 |
374,290 | 42,685,994 | How to get a tensorflow op by name? | <p>You can get a tensor by name with <code>tf.get_default_graph().get_tensor_by_name("tensor_name:0")</code></p>
<p>But can you get an operation, such as <code>Optimizer.minimize</code>, or an <code>enqueue</code> operation on a queue?</p>
<p>In my first model I returned all tensors and ops I would need from a <code>... | <p>You can use the <a href="https://www.tensorflow.org/api_docs/python/tf/Graph#get_operation_by_name" rel="noreferrer"><code>tf.Graph.get_operation_by_name()</code></a> method to get a <code>tf.Operation</code> by name. For example, to get an operation called <code>"enqueue"</code> from the default graph:</p>
<pre><c... | python|tensorflow | 31 |
374,291 | 43,004,991 | add one row from another dataframe in pandas | <p>Here's the thing, I need to put one row from other dataframe to the top of main dataframe in pandas, above first row where are columns named.</p>
<p>Sample : </p>
<pre><code> 1value 2value 3value 4value 5value
acity 4 3 6 2 6
bcity 2 6 6 4 1
ccity 5 1... | <p>Not sure if this is what you need, but a multi index data frame looks like the output:</p>
<p><em>df1 or second sample</em>:</p>
<p><a href="https://i.stack.imgur.com/HeKVW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HeKVW.png" alt="enter image description here"></a></p>
<p><em>df or the fi... | python|pandas|dataframe | 1 |
374,292 | 42,810,531 | NumPy doesn't recognize well array shape | <p>I have a code which is as follows:</p>
<pre><code>data = np.array([[[i, j], i * j] for i in range(10) for j in range(10)])
print(data)
x = np.array(data[:,0])
x1 = x[:,0]
x2 = x[:,1]
print(x)
</code></pre>
<p><code>data</code> correctly outputs <code>[[[0,0],0],[[0,1],0],[[0,2],0],...,[[9,9],81]]</code> which is,... | <p><code>data.dtype</code> is <code>object</code> because the elements of <code>[[i,j],k]</code> are not homogeneous. A workaround for you :</p>
<pre><code>data = np.array([(i, j, i * j) for i in range(10) for j in range(10)])
print(data)
x1 = data[:,:2]
x2 = data[:,2]
</code></pre>
<p><code>data.shape</code> is no... | python-3.x|numpy | 1 |
374,293 | 42,747,032 | Python linear least squares function not working | <p>Ok, so I'm writing a function for linear least squares in python and it's pretty much just one equation. Yet for some reason, I'm getting a ValueError. My best guess is it has something to do with the <code>.reshape</code> function, since in this question I had <a href="https://stackoverflow.com/questions/42737252/m... | <p>Assuming that <code>design_matrix</code> returns a matrix, this code</p>
<pre><code>design_matrix(x_train, M).T * design_matrix(x_train, M)
</code></pre>
<p>most likely does not do what is intended since <code>*</code> is performing element-wise multiplication (Hadamard product of two matrices). Because your matri... | python|numpy|linear-regression | 2 |
374,294 | 42,789,715 | How do I improve the performance in parallel computing with dask | <p>I have a pandas dataframe and converted to dask dataframe</p>
<p>df.shape = (60893, 2)</p>
<p>df2.shape = (7254909, 2)</p>
<pre><code>df['name_clean'] = df['Name'].apply(lambda x :re.sub('\W+','',x).lower(),meta=('x', 'str'))
names = df['name_clean'].drop_duplicates().values.compute()
df2['found'] = df2['name_cl... | <p>You can not iterate over a dask.dataframe or dask.array. You need to call the <code>.compute()</code> method to turn it into a Pandas dataframe/series or NumPy array first.</p>
<p>Note just calling the <code>.compute()</code> method and then forgetting the result doesn't do anything. You need to save the result a... | python|list|pandas|dask | 3 |
374,295 | 42,897,010 | Error while building list in python | <p>I' am trying to build a list in python. The list contains lists. A single inner list consists of various features of a audio signal like standard deviation, mean frequency etc. But when i print the outer list i get a blank list. Here is my code.</p>
<pre><code>from scipy.io.wavfile import read # to read wavfiles
i... | <p>The problem comes from the <code>fList[:] = []</code> you call at the end. I did a small example to test it:</p>
<pre><code>l = []
ml = []
def f(x):
for i in range(0, x):
l.append(i)
ml.append(l)
l[:] = []
f(10)
f(5)
print(ml)
</code></pre>
<p>This prints <code>ml</code> containing two empty ... | python|list|numpy|nested-lists | 0 |
374,296 | 42,626,676 | Comparing between two rows in pandas | <p>Is there any way I can compare between two rows in pandas? </p>
<p>I would do something like this in sql.</p>
<pre><code>Select * from table t1, table t2 where t1.price - t2.price > 10 and t1.type = 'abc' and t2.type = 'def'
</code></pre>
<p>The best way i can think of is subtracting rows in pandas Data-Frame... | <p>Aceminer, I'm still not totally clear what you're looking for on the comparison, but I set something similar up. The one caveat here is that this code compares one line to the following so that the last line you have doesn't show up since there is nothing to compare it to.</p>
<pre><code>df = pd.DataFrame({'price'... | python|pandas | 0 |
374,297 | 27,205,133 | Python numpy nan compare to true in arrays with strings | <p>I am trying to compare two numpy arrays which contain numbers, string and nans. I want to know how many items in the array are equal.</p>
<p>When comparing these two arrays:</p>
<pre><code>c =np.array([1,np.nan]);
d =np.array([2,np.nan]);
print (c==d)
[False False]
</code></pre>
<p>Which is the expected behaviour... | <p>If you examine the arrays, you'll see that <code>np.nan</code> has been converted to string (<code>'n'</code>):</p>
<pre><code>In [48]: a = np.array([1, 'x', np.nan])
In [49]: a
Out[49]:
array(['1', 'x', 'n'],
dtype='|S1')
</code></pre>
<p>And <code>'n' == 'n'</code> is <code>True</code>.</p>
<p>What I d... | python|arrays|numpy | 1 |
374,298 | 27,092,768 | Plotting sectionwise defined function with python/matplotlib | <p>I'm new to Python and Scipy. Currently I am trying to plot a p-type transistor transfer curve in matplotlib. It is sectionwise defined and I am struggeling to find a good way to get the resulting curve. What I have so far is:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.constants imp... | <p>Do you want to fill the array <code>Vds</code> according to your selectors?</p>
<pre><code>Vds = np.zeros_like(V_GS) # for the same shape
Vds[V_GS >= V_th] = Ids_cutoff
Vds[(V_GS < V_th) & (V_DS >= V_GS - V_th)] = Ids_lin
Vds[(V_GS < V_th) & (V_DS < V_GS - V_th)] = Ids_sat
</code></pre>
<p>... | python|numpy|matplotlib|plot|scipy | 1 |
374,299 | 27,321,299 | pandas function, use previously computed value | <p>Had a simple question that I have not found a simple answer to. As an example this data frame can be used: </p>
<pre><code>A = pd.Series([0.1,-0.2,0.14,0.12,-0.11])
B = pd.Series([1.0,3.0,2.0,6.0,9.0])
df = pd.DataFrame({'A':A,'B':B})
</code></pre>
<p>I now would like to create a column C as follows:</p>
<pre><c... | <p>One way to get this:</p>
<pre><code>df['C'] = df.A * df.B
df['C'] = df.C + (df.A * df.C.shift().fillna(0))
df
</code></pre>
<p>Which yields:</p>
<pre><code> A B C
0 0.10 1 0.100
1 -0.20 3 -0.620
2 0.14 2 0.196
3 0.12 6 0.754
4 -0.11 9 -1.069
</code></pre>
<p>Which looks like what you wanted... | pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.