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 |
|---|---|---|---|---|---|---|
1,900 | 73,821,175 | Sum values in specific rows and place value in first column of that row | <p>I wish to sum values in the row that contains 'BB' and place that value in first column of that row.</p>
<p><strong>Data</strong></p>
<pre><code>ID Q121 Q221 Q321 Q421
AA 8.0 4.8 3.1 5.3
BB 0.6 0.7 0.3 0.9
</code></pre>
<p><strong>Desired</strong></p>
<pre><code>ID Q121 Q221 Q321 ... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame</code></strong></a> with a boolean mask to assign the new values :</p>
<pre><code>mask = df['ID'].eq('BB')
cols = df.columns.difference(['ID'])
update = [df.sum(axis=1, numeric_on... | python|pandas|numpy | 2 |
1,901 | 73,556,640 | How to select multiple columns from two different Pandas dataframes in Python | <p>I have the following dataframes D1 and D2.</p>
<pre><code># importing sparksession from pyspark.sql module
from pyspark.sql import SparkSession
# creating sparksession and giving an app name
spark = SparkSession.builder.appName('sparkdf').getOrCreate()
# list of employee data
data = [["1", "sra... | <p>As per the syntax of <code>pd.merge()</code>, the <code>left_on</code> and <code>right_on</code> can be column names or pre-computed list of values with length same as dataframe (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">official documentation</a>). ... | python|pandas|dataframe|join|pyspark | 0 |
1,902 | 71,372,883 | Constrain tensorflow probability to positive coefficients | <p>I have a tensorflow sts model I wish to constrain the Linear Regression coefficients to greater than zero. I understand this can be achieved by passing a HalfNormal distribution as a prior:</p>
<pre><code>network_effects = tfp.sts.LinearRegression(
design_matrix=tf.stack((df-df.mean()).values.astype(np.float32)),
... | <p>Not at all obvious how this is done, but I'm not overly familiar with Tensorflow. However the answer is to set the scale argument to float64 as follows:</p>
<pre><code>tfd.HalfNormal(scale=np.float64(2.0))
</code></pre>
<p>The answer came from this post here:
<a href="https://stackoverflow.com/questions/55258627/how... | python|tensorflow|tensorflow-probability|sts | 0 |
1,903 | 71,264,782 | Filtering Boolean in Dataframe | <p>I have a df with ±100k rows and 10 columns.
I would like to find/filter which rows contain at least 2 to 4 True values.
For simplicity's sake, let's say I have this df:</p>
<pre><code> A B C D E F
1 True True False False True
2 False True True True False
3 False False False False Fals... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a> for only boolean columns, count <code>True</code>s by <code>sum</code> and then filter values by <a href="http://pandas.pydata.org/pandas-docs... | python|pandas|dataframe|filter|boolean | 0 |
1,904 | 71,113,830 | Pandas/Python: Store values of columns into list based on value in another column | <p>I have the following problem:</p>
<p>I want to store the values of the four different columns (Age_1 - Age_4) within a dataframe into a list, which is depending on the first column 'Year'.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Year</th>
<th>Age_1</th>
<th>Age_2</th>
<th>Age_3</... | <p>IIUC,</p>
<pre><code>df.melt('Year',
value_vars=['Age_1', 'Age_2', 'Age_3', 'Age_4'])\
.groupby('Year')['value'].agg(list).to_dict()
</code></pre> | python|pandas | 0 |
1,905 | 71,142,498 | calculate new mean using old mean | <p>I had a dataset <code>df</code>that looked like this:</p>
<pre><code>Value themes country date
-1.975767 Weather Brazil 2022-02-13
-0.540979 Fruits China 2022-02-13
-2.359127 Fruits China 2022-02-13
-2.815604 Corona China 2022-02-13
-0.712323 Weath... | <p>Please see this: <a href="https://math.stackexchange.com/questions/784874/how-to-calculate-new-mean-if-population-is-unknown">Calculate new mean from old mean</a></p>
<p>Since you are maintaining a count (if not, it is pretty trivial) you can use that along with existing mean to calculate updated mean using the new ... | python|pandas|dataframe|numpy|mean | 0 |
1,906 | 52,251,517 | Fix duplicate index names in dataframe | <p>I am looking for the simplest solution to create a Python data frame from a CSV file that has duplicate index names (s1 and s2 in the example below). </p>
<p>Here is how the CSV file looks like:</p>
<pre><code> var1 var2 var3
unit x 8 4 12
temp y -1 -4 -3
time
s1 9 ... | <p>Use:</p>
<pre><code>#convert index to Series
s = df.index.to_series()
#identify duplicated values
m = s.duplicated(keep=False)
#replace dupes by NaNs and then by forward filling
df.index = np.where(m, s.mask(m).ffill() + ' ' + s.index, s)
#remove only NaNs rows
df = df.dropna(how='all')
print (df)
var1 v... | python|pandas|csv|dataframe | 3 |
1,907 | 60,589,367 | Use pandas element as key in dictionary | <p>I have a dictionary:
<code>fdict={"X":['tf','pytorch','keras'],"Y":['Gym','Scikit']}</code>
and a dataframe <code>df</code> with columns <code>c1</code> and <code>c2</code>:</p>
<ol>
<li>c1 c2</li>
<li>X pesos</li>
<li>Y long </li>
<li>X Myst</li>
</ol>
<p>and I want to get:
<code>'pytorch' in fdict[df[... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a> with lambda function and <code>get</code>, output is boolean <code>Series</code>:</p>
<pre><code>m = df['c1'].apply(lambda x: 'pytorch' in fdict.get(x, None))
prin... | python|pandas|dictionary | 1 |
1,908 | 60,435,692 | NOTHING PROVIDES 'virtual/x86_64-oesdk-linux-compilerlibs' | <p>I'm banging my head against the wall on this - mostly because I'm really new to Yocto and just getting into the swing of things. I've been building the image github.com/EttusResearch/oe-manifests and been successfully.</p>
<p>Now, I'd like to add tensorflow as a package, avoiding it's bazel and java dependancies I ... | <p>Bitbake has a tool to create a file with the dependencies tree.</p>
<pre><code>bitbake -g
</code></pre>
<p>or, for a specific recipe:</p>
<pre><code>bitbake -g {recipe name}
</code></pre>
<p>There is a dedicated tool too display these trees, like kgraphviewer and also online tools.
I personally just open these f... | python|tensorflow|yocto|bitbake | 0 |
1,909 | 60,618,799 | How to subtract values in a column using groupby | <p>I have the following dataframe:</p>
<pre><code>ID Days TreatmentGiven TreatmentNumber
--- ---- -------------- ---------------
1 0 False NaN
1 30 False NaN
1 40 True 1
1 56 False NaN
2 0 False NaN
2 14 True ... | <p>Idea is filter rows with <code>1</code> in <code>TreatmentNumber</code>, then convert to <code>Series</code> for <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by <code>ID</code> used for subtract by <code>Days</code> c... | python|pandas|pandas-groupby | 2 |
1,910 | 60,680,091 | How to compare one picture to all data test in siamese neural network? | <p>I've been build siamese neural network using pytorch. But I've just test it by inserting 2 pictures and calculate the similarity score, where 0 says that picture is different and 1 says picture is same. </p>
<pre><code>import numpy as np
import os, sys
from PIL import Image
dir_name = "/Users/tania/Desktop/Aksara/C... | <p>Yes there is a way, you could use the softmax function:</p>
<pre><code>output = torch.softmax(output)
</code></pre>
<p>This returns a tensor of 26 values, each corresponding to the probability that the image corresponds to each of the 26 classes. Hence, the tensor sums to 1 (100%). </p>
<p>However, this method is... | pytorch|prediction|siamese-network | 2 |
1,911 | 60,481,202 | Groupby and Normalize selected columns Pandas DF | <p>I have a sample DF which I want to normalize based on 2 condtions</p>
<p>Creating sample DF:</p>
<pre><code>sample_df = pd.DataFrame(np.random.randint(1,20,size=(10, 3)), columns=list('ABC'))
sample_df["date"]= ["2020-02-01","2020-02-01","2020-02-01","2020-02-01","2020-02-01",
"2020-02-02","2020-02... | <p>Hope I got your question right. Do you just want to group by index, select values from Aand B AND CALCULATE THE PERCENTAGE?</p>
<pre><code> sample_df.reset_index(inplace=True)
sample_df['date']=pd.to_datetime(sample_df['date'])
sample_df.set_index('date', inplace=True)
df2=sample_df[(sample_df['A']&g... | python|pandas|scikit-learn|pandas-groupby|sklearn-pandas | 1 |
1,912 | 72,698,645 | Create a new column that starts counting from 0 until the value in another column changes | <p>I have a dataframe df that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Months</th>
<th>Borrow_Rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>1</td>
</... | <pre><code>import pandas as pd
df = pd.DataFrame({'Borrow_Rank':[1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,1,1,1]})
selector = (df['Borrow_Rank'] != df['Borrow_Rank'].shift()).cumsum()
df['Months_Adjusted'] = df.groupby(selector).cumcount()
</code></pre> | python|pandas|dataframe | 1 |
1,913 | 72,504,065 | Iterating through a DataFrame using Pandas UDF and outputting a dataframe | <p>I have a piece of code that I want to translate into a Pandas UDF in PySpark but I'm having a bit of trouble understanding whether or not you can use conditional statements.</p>
<pre class="lang-py prettyprint-override"><code>def is_pass_in(df):
x = list(df["string"])
result = []
for i in x:
... | <p>There is no need to use a UDF. This can be done in pyspark as follows. Even in pandas, I would advice you dont do what you have done. use <code>np.where()</code></p>
<pre><code>df.withColumn('result', when(col('store')=='target','YES').otherwise('NO')).show()
</code></pre> | pyspark|apache-arrow|pandas-udf | 2 |
1,914 | 59,811,117 | how to combine years in group to 10 in a sqlite query | <p>MOVIE (Mid, name, year, rank)
i want to count the number of movies in a decade. Suppose year in the table start from 1931
then years from 1931 to 1940 will form a decade.</p>
<p>My Query:</p>
<pre><code>query_7 = pd.read_sql_query('''SELECT yr.year as dec_start,yr.year + 9 as dec_end,COUNT(DISTINCT m.MID) as num_... | <p>If you want decades starting with the minimum year in the table use this:</p>
<pre><code>SELECT
(year - s.start_from) / 10 * 10 + s.start_from as dec_start,
(year - s.start_from) / 10 * 10 + s.start_from + 9 as dec_end,
COUNT(DISTINCT MID) as num_movies
FROM Movie CROSS JOIN (SELECT MIN(year) % 10 start_fr... | python|sql|pandas|sqlite|date | 1 |
1,915 | 59,498,558 | Dataframe to resample an unbalanced dataset | <p>The <a href="https://datahub.io/machine-learning/glass/r/glass.csv" rel="nofollow noreferrer">Glass Identification Database</a> is an unbalanced dataset and I want to do some resampling.</p>
<p>There are 214 rows data of 5 types of glass. Each type has different number of rows. With below I want to perform random u... | <p>First idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>GroupBy.head</code></a> with minimal of counts of <code>Type</code> column:</p>
<pre><code>dataset1 = dataset.groupby('Type').head(dataset.Type.value_counts().m... | python|pandas|dataframe|resampling | 1 |
1,916 | 59,505,743 | Separate JSON elements into columns of pandas dataframe | <p>I'm trying to separate elements from a list into different columns of a pandas dataframe. Essentially I want, for every <code>tenure</code> option - i.e. Detached, Semi-detached, columns like <code>detached_price</code>, <code>detached_cost</code>, <code>detached_rooms</code> and <code>detached_asking</code>, then t... | <p>This will be quite a long dataframe, but the below should work : </p>
<p>first we import some modules, and assign your columns, I'm assuming you have a full set of data and no NA values. if you do, you'll need to figure out a way to map your ask, cost, room into your dataframe. </p>
<pre><code>from collections imp... | python|pandas | 1 |
1,917 | 54,762,245 | tensorflow TF lite android app crashing after detection | <p>I have trained my model using <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">ssd_mobilenet_v2_quantized_coco</a>, which was also a long painstaking process of digging. Once training was successful, the model was correctly de... | <p>Yes it is because the output of labels at times gets garbage value. For a quick fix you can try this:</p>
<p>add a condition:</p>
<pre><code> if((int) outputClasses[0][i]>10)
{
outputClasses[0][i]=-1;
}
</code></pre>
<p>here 10 is the number of classes for which the model was trained for. You can chan... | android|python|tensorflow|object-detection|tensorflow-lite | 0 |
1,918 | 54,799,384 | Is concatenated matrix multiplication faster than multiple non-concatenated matmul? If so, why? | <p>The definition of the LSTM cell involves 4 matrix multiplications with the input, and 4 matrix multiplications with the output. We can simplify the expression by using a single matrix multiply by concatenating 4 small matrices (now the matrix are 4 times larger).</p>
<p>My question is: does this improve the efficie... | <p>The structure of LSTM isn't about improving multiplication efficiency but more so for bypassing diminishing / exploding gradients (<a href="https://stats.stackexchange.com/questions/185639/how-does-lstm-prevent-the-vanishing-gradient-problem">https://stats.stackexchange.com/questions/185639/how-does-lstm-prevent-the... | tensorflow|matrix|lstm|pytorch|gpu | 0 |
1,919 | 54,934,049 | pandas reset cumsum when the previous value is negative | <p>I need to perform a cumulative sum on a data frame that is grouped, but I need to have it reset when the previous value is negative and the current value is positive.</p>
<p>In R I could apply a condition to the groupby with ave() function, but I can't do that in python, so I am having a bit of trouble thinking of ... | <p>This solution will work to reset the sum for any example where the values to be summed change from negative to positive (regardless of whether the dataset is nice and periodic as it is in your example)</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'PRODUCT': ['A'] * 40, 'GROUP': ['1'] * ... | python|pandas|dataframe | 1 |
1,920 | 49,539,178 | Generate random int in 3D array | <p>l would like to generate a random 3d array containing random integers (coordinates) in the intervalle [0,100].</p>
<p>so, <code>coordinates=dim(30,10,2)</code></p>
<p>What l have tried ?</p>
<pre><code>coordinates = [[random.randint(0,100), random.randint(0,100)] for _i in range(30)]
</code></pre>
<p>which ret... | <p>Use the <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randint.html" rel="noreferrer"><code>size</code> parameter</a>:</p>
<pre><code>import numpy as np
coordinates = np.random.randint(0, 100, size=(30, 10, 2))
</code></pre>
<p>will produce a NumPy array with integer values betwe... | python-3.x|numpy|random | 23 |
1,921 | 49,624,840 | Confusing behavior of np.random.multivariate_normal | <p>I am sampling from a multivariate normal using numpy as follows.</p>
<pre><code>mu = [0, 0]
cov = np.array([[1, 0.5], [0.5, 1]]).astype(np.float32)
np.random.multivariate_normal(mu, cov)
</code></pre>
<p>It gives me the following warning.</p>
<blockquote>
<p>RuntimeWarning: covariance is not positive-semidefini... | <p><em>This has been <a href="https://github.com/numpy/numpy/pull/12547" rel="nofollow noreferrer">fixed</a> in March 2019. If you still see the warning consider updating your numpy.</em></p>
<p>The warning is raised even for very small off-diagonal elements > 0. The default tolerance value does not seem to work well ... | python|numpy | 10 |
1,922 | 73,447,978 | Pandas, 'nan' fields after changing column datatypes | <p>I am changing the datatype of a determined columns in pandas and I would like to keep the nan values as np.nan</p>
<p>After executing the following command:</p>
<pre><code>df = df.astype({"raw_salary_from": str, "raw_salary_to": str})
</code></pre>
<p>What I get is that all the nan's transformed ... | <p>You can store the index of those nan's first and then convert them to <code>np.nan</code> with <code>mask</code>. So:</p>
<pre><code>idx_nan = df["raw_salary_from"].isna()
df["raw_salary_from"] = df["raw_salary_from"].astype(str).mask(idx_nan, np.nan)
</code></pre> | python|pandas|dataframe | 1 |
1,923 | 73,368,599 | Neural Network From Scratch - Forward propagation error | <p>I wanna implement the backward propagation concept in python with the next code</p>
<pre><code>class MLP(object):
def __init__(self, num_inputs=3, hidden_layers=[3, 3], num_outputs=2):
self.num_inputs = num_inputs
self.hidden_layers = hidden_layers
self.num_outputs = num_outputs
... | <p>a couple of major problems with <code>forward_propagate</code>:</p>
<ol>
<li>change <code>net_inputs</code> to <code>activations</code> - otherwise you always compute and return the activations from the first layer</li>
<li>remove <code>for j, b in enumerate(self.bias):</code> - biases from other layers have no busi... | python|numpy|machine-learning|neural-network | 1 |
1,924 | 73,239,293 | How to find index that has same value in another array by python? | <p>I'm a beginner of Python. I would like to find indexes that have two largest values in ndarray. For example, ndarray x like this.</p>
<pre><code>x = np.array([2,3,5,3,7,3,1,5])
</code></pre>
<p>Because the two largest values are 7 and 5. The answer should be</p>
<pre><code>ind = [2,4,7]
x[ind] = [5,7,5]
</code></pre... | <p>You can accomplish this in 3 steps:</p>
<ol>
<li>Sort your unique array values (np.unique also sorts) <code>np.unique(…)</code></li>
<li>Slice the last N values (the maximums) from the sorted unique array <code>…[-max_n:]</code></li>
<li>Find the indices where your array has those maximums via <code>np.where(np.isin... | python|numpy-ndarray | 1 |
1,925 | 67,592,831 | How do I incorporate absolute value within my Pandas dataframe? | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">id</th>
<th style="text-align: center;">Impressions_Source</th>
<th style="text-align: right;">Impressions_Source2</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">15020</td>
<td style="text-align: center;">... | <p>You can call <code>.abs()</code> afterwards:</p>
<pre class="lang-py prettyprint-override"><code>df["Discrepancy_Num"] = (
(df["Impressions_Source"] - df["Impressions_Source2"])
/ (df["Impressions_Source"] * 100)
).abs()
print(df)
</code></pre>
<p>Prints:</p>
<pre cla... | python|pandas|dataframe|absolute-value | 1 |
1,926 | 60,158,212 | How can i find unique record in python by row count? | <p>df:</p>
<pre><code> Country state item
0 Germany Augsburg Car
1 Spain Madrid Bike
2 Italy Milan Steel
3 Paris Lyon Bike
4 Italy Milan Steel
5 Germany Augsburg Car
</code></pre>
<p>In the above dataframe, if we take unique record Appearance.</p>
<pre><code> Country s... | <p>You can first get the <code>Appreared</code> column by <code>groupby().cumcount</code>, then add the suffixes:</p>
<pre><code># unique values
duplicates = df.duplicated(keep=False)
# Appearance count
df['Appeared'] = df.groupby([*df]).cumcount().add(1)
# add the suffixes
suffixes = np.array(list('ABC'))
df.loc[du... | python|python-3.x|pandas|python-2.7 | 2 |
1,927 | 60,237,047 | How to Decompose and Visualise Slope Component in Tensorflow Probability | <p>I'm running tensorflow 2.1 and tensorflow_probability 0.9. I have fit a Structural Time Series Model with a seasonal component. I am using code from the Tensorflow Probability Structural Time Series Probability example:
<a href="https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/... | <p>We didn't write a separate STS interface for this, but you can access the posterior on latent states (in this case, both the level and slope) by directly querying the underlying state-space model for its marginal means and covariances:</p>
<pre class="lang-py prettyprint-override"><code>ssm = model.make_state_space... | time-series|tensorflow-probability|state-space | 0 |
1,928 | 65,174,525 | How to convert a boolean array into a matrix? | <p>I am a beginner, and I want to know is it possible to convert a boolean array into a matrix in NumPy?</p>
<p>For example, we have a boolean array <code>a</code> like this:</p>
<pre><code>a = [[False],
[True],
[True],
[False],
[True]]
</code></pre>
<p>And, we turn it into the following matrix:</p>... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.diagflat.html#numpy.diagflat" rel="nofollow noreferrer"><code>np.diagflat</code></a> which <em>creates a two-dimensional array with the flattened input as a diagonal</em>:</p>
<pre><code>np.diagflat(np.array(a, dtype=int))
#[[0 0 0 0 0]
# [... | python|arrays|numpy|matrix | 4 |
1,929 | 65,068,605 | How to convert pandas <NA> to numy Nan? | <p>I have following data set</p>
<p><a href="https://i.stack.imgur.com/1EUfT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1EUfT.png" alt="enter image description here" /></a></p>
<p>I would like to convert float values to int, so i did <code>data.convert_dtypes()</code></p>
<p><a href="https://i.stack.imgu... | <p>If need <code>np.nan</code> what is float need your solution, but <code>NA ineteger</code>s columns are converted to <code>float</code>s columns:</p>
<pre><code>df = df.replace({pd.NA: np.nan})
</code></pre>
<p>If need integers, onky ways is replace <code>NA</code> to some integer:</p>
<pre><code>df = df.replace(pd.... | pandas|dataframe | 7 |
1,930 | 65,413,883 | Why isn't my plt.plot() working when graphing projectile motion? | <p>I'm graphing projectile motion without/with air friction and I'm now on the first part, which is the one without air friction.</p>
<p>After I've put the plt.plot(x_nodrag,y_nodrag), it suppose to draw a curved line of the projectile motion. But for some reasons it's not being drawn even as the data of the them are b... | <p>The command <code>plt.plot</code> does not work for individual points. Use <code>plt.scatter(x_nodrag, y_nodrag)</code> instead, or collect the consecutive coordinates into lists or arrays and then plot the entire graph at once.</p> | python|numpy|matplotlib|physics | 0 |
1,931 | 65,351,504 | Finding if values in multiple columns greater than constant in pandas Dataframe | <p>This is how my data frame (df) looks:</p>
<pre><code>id,activity_date,status01_1,status01_2,status02,status03_01,status03_02, status04
1,2020-12-09 22:13:16,0,0,3560,0,0,0
1,2020-12-10 01:02:33,8327,0,0,0,0,0
1,2020-12-11 01:02:33,0,0,230,0,0,0
</code></pre>
<p>I would like to find if any of the status 01 and 03 c... | <p>Let's try:</p>
<pre><code>df1['ge_2000'] = df1.filter(like='status01').max(axis=1).ge(2000).astype(int)
</code></pre>
<p>Or</p>
<pre><code>df1['ge_2000'] = df1.filter(like='status01').ge(2000).any(axis=1).astype(int)
</code></pre>
<p>Output:</p>
<pre><code> id activity_date status01_1 status01_2 ... | python|python-3.x|pandas | 0 |
1,932 | 49,963,694 | Delete a row in pandas given a conditions data cleansing? | <p>I have a DataFrame like </p>
<pre><code>Classification Value_1 Value_2
churn 1.0 2.0
not_churn 2.0 3.0
not_churn 0.0 0.0
churn 0.0 1.0
</code></pre>
<p>I know that with all values = 0, t... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with change conditions for not equal <code>!=</code> and change <code>&</code> to <code>|</code> (or):</p>
<pre><code>df = df[(df['Value_1'] != 0 ) | (df['Value_2'... | python-3.x|pandas | 0 |
1,933 | 49,934,787 | Recursively calculating ratios between parents and children in pandas dataframe | <p>I looked around for a solution to this to the best of my ability. The closest I was able to find was <a href="https://stackoverflow.com/questions/46521390/getting-all-descendants-of-a-parent-from-a-pandas-dataframe-parent-child-table">this</a>, but it's not really what I'm looking for. </p>
<p>I am trying to model ... | <p>The first part is just merges:</p>
<pre><code>with_parent = pd.merge(df, df, left_on='parent_id', right_on='id', how='left')
with_parent['child_parent_ratio'] = with_parent.score_y / with_parent.score_x
with_parent = with_parent.rename(columns={'id_x': 'id', 'parent_id_x': 'parent_id', 'score_x': 'score'})[['i... | python|pandas|recursion | 3 |
1,934 | 63,884,811 | how initialize a torch of matrices | <p>Hello I m trying to create a tensor that will have inside N matrices of n by n size. I tried to initialize it with</p>
<pre><code>Q=torch.zeros(N, (n,n))
</code></pre>
<p>but i get the following error</p>
<pre><code>zeros(): argument 'size' must be tuple of ints, but found element of type tuple at pos 2
</code></pre... | <p><code>N</code> matrices of <code>n x n</code> size is equivalent to three dimensional tensor of shape <code>[N, n, n]</code>. You can do it like so:</p>
<pre><code>import torch
N = 32
n = 10
tensor = torch.randint(0, 10, size=(N, n, n))
</code></pre>
<p>No need to fill it with <code>zeros</code> to begin with, you ... | python|pytorch | 3 |
1,935 | 46,830,781 | Pandas qcut binning returning only one group | <p>I am working with pandas pcut and somethimes (when a lot of data are equal to the min) it returns either an error:</p>
<pre><code>Bin edges must be unique
</code></pre>
<p>Or I have to drop the non-unique bins that I get, but then all my data are in one bin.</p>
<p>For example:
dataset: </p>
<pre><code>import pa... | <p>I found a very ugly way to solve it...:</p>
<pre><code>try:
pd.qcut(data, n_bins)
except ValueError:
pd.qcut(data, n_bins+1, duplicates = 'drop')
</code></pre> | python-2.7|pandas | 0 |
1,936 | 46,964,552 | Regex in pandas: Match vs Findall | <p>I am confused about when to use both str.findall and str.match.</p>
<p>For example, I have a df that has many lines of text where I need to extract dates.</p>
<p>Let us say I want to extract check the lines where there is a work Mar (as of the abbreviation of March).</p>
<p>I if I broadcast the df where there is ... | <p>I try to use the documentation to explain this:</p>
<pre><code>s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"])
s
</code></pre>
<p>output:</p>
<pre><code>A a1a2
B b1
C c1
dtype: object
</code></pre>
<p>We first make the Series like this,and then use the <code>extract,extractall,find,findal... | regex|pandas|match|findall | 1 |
1,937 | 63,261,148 | Pandas count groupbyed elemenys by condition | <p>I have dataframe like this:</p>
<pre><code>df = pd.DataFrame({
'user': ['1', '1', '1', '2', '2', '2', '3', '3', '3'],
'value': ['4', '4', '1', '2', '2', '2', '3', '1', '1']
})
</code></pre>
<p>'value' sorted by date, so i need to count users for which the last element is smaller than the other elements in th... | <p>You can compare all values by last one with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.la... | python|pandas | 1 |
1,938 | 63,065,554 | Can pandas replace method be used on a view or slice to modify the original dataframe? | <p>I want to replace certain cell values in a dataframe if they are within one group(s), but not if they are the other group(s).</p>
<p>For example I create the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['a',2,3],['b',2,3],['a',3,3]], columns = ['1st', '2nd', '3rd'])
df
1st 2nd 3rd
... | <p>Try with <code>update</code></p>
<pre><code>df.update(df.loc[(df['1st']=='a')].replace({2:9, 3:7}))
df
1st 2nd 3rd
0 a 9.0 7.0
1 b 2.0 3.0
2 a 7.0 7.0
</code></pre>
<p>If not want to change the type</p>
<pre><code>df.loc[(df['1st']=='a')]=df.loc[(df['1st']=='a')].replace({2:9, 3:7})
df
1st 2nd 3r... | python|pandas|dataframe | 3 |
1,939 | 67,899,215 | Matplotlib or seaborn or pandas : Plot with "deep" discretization | <p>I have data in the following form :</p>
<pre><code>pkgSpot state id_data_x id_data_y pkgSpot_y delay_mean delay_max delay_min
0 1 Free 7.245899e+08 7.245899e+08 1.0 0.334572 292.0 -161.0
1 1 Occupied 7.245876e+08 7.245876e+08 ... | <p>Here is an approach using filled areas to show the minimum, mean and maximum:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO
data_str = '''pkgSpot state delay_mean delay_max delay_min
1 Free 0.334572 292.0 -... | pandas|matplotlib|seaborn | 1 |
1,940 | 67,864,964 | Merge multiple dataframes on date with not same values | <p>I have 4 dataframes: <code>jpn</code>, <code>swe</code>, <code>svk</code>, <code>aut</code>, where every dataframe has two columns <code>year</code> and <code>~_co2</code> and some index, which I dont care about.</p>
<pre class="lang-py prettyprint-override"><code>
>>>swe
year swe_co2
20105 183... | <p>You can use <code>pd.concat</code></p>
<pre><code>pd.concat([swe, svk], ignore_index=True)
year swe_co2 svk_co2
0 1834 0.033 NaN
1 1839 0.044 NaN
2 1840 NaN 0.013
3 1841 NaN 0.023
</code></pre>
<p>If you have more than two dataframes, just append them in that list <code>[swe, ... | python|pandas | 2 |
1,941 | 61,275,706 | Inserting into array with known positions and values | <pre><code>import numpy as np
a = np.zeros([2,2])
b = np.array([[0,0],
[0,1],
[1,0],
[1,1]])
values = np.array([[10,20,30,40]]).T
#some function
#desired outcome for a as numpy array:
a = [[10,20],
[30,40]]
</code></pre>
<p>As you can see from code, I have a zero val... | <p>On simple approach is to use numpy indexing:</p>
<pre><code>import numpy as np
a = np.zeros([2, 2])
b = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
values = np.array([10, 20, 30, 40])
rows, cols = zip(*b)
a[rows, cols] = values
print(a)
</code></pre>
<p><strong>Output</... | python|numpy | 1 |
1,942 | 61,602,178 | custom layer with Tensorflow 2.1 problem with the output shape | <p>I am trying to have custom layer returning a tensor of (25,1) however there is a batch_size which should be passed through (I get an error from the next layer). I looked for examples, but could not figure how to specify the output shape. </p>
<p>Further I need an arbitrary output shape independent from the input si... | <p>I suggest you use the inputs data defined in the call methods otherwise the layer makes no sense</p>
<p>I provide a dummy example and works perfectly</p>
<pre><code>class SimpleLayer(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(SimpleLayer, self).__init__(**kwargs)
self.baseline... | python|tensorflow | 1 |
1,943 | 68,565,190 | What is the difference between SeedSequence.spawn and SeedSequence.generate_state | <p>I am trying to use numpy's <a href="https://numpy.org/doc/stable/reference/random/bit_generators/generated/numpy.random.SeedSequence.html" rel="nofollow noreferrer"><code>SeedSequence</code></a> to seed RNGs in different processes. However I am not sure whether I should use <code>ss.generate_state</code> or <code>ss... | <p>Well the <code>SeedSequence</code> is intended to generate good quality seeds from not so good seeds.</p>
<h3>Performance</h3>
<p>The <code>generate_state</code> is much faster than <code>spawn</code></p>
<p>The difference of time for transfering the object or the state should not be the main reason for the differen... | numpy|random | 1 |
1,944 | 68,866,740 | import image-plot the SentinelHub-py utils issue | <p>I am trying to plot an image using <a href="https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/utils.py" rel="nofollow noreferrer">SentinelHub-py</a>. This is part of my the code:</p>
<pre><code>from sentinelhub import SHConfig
config = SHConfig()
config.sh_client_id = "76186bb6-a02e-4457-9... | <p>You have to navigate to your utils.py. In my computer is:</p>
<p>(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/utils).</p>
<p>Later, you have to copy and paste the next script from:</p>
<p><a href="https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/utils.py" rel="n... | python|numpy|matplotlib|syntax-error|sentinel | 1 |
1,945 | 68,726,290 | Setting learning rate for Stochastic Weight Averaging in PyTorch | <p>Following is a small working code for Stochastic Weight Averaging in Pytorch taken from <a href="https://pytorch.org/docs/1.8.1/optim.html#putting-it-all-together" rel="noreferrer">here</a>.</p>
<pre><code>loader, optimizer, model, loss_fn = ...
swa_model = torch.optim.swa_utils.AveragedModel(model)
scheduler = torc... | <ul>
<li>
<blockquote>
<p>does the above code imply that for the first <em>160</em> epochs the learning rate for training will be <code>1e-4</code></p>
</blockquote>
<p>No it won't be equal to <code>1e-4</code>, during the first 160 epochs the learning rate is managed by the first scheduler <code>scheduler</code>. This... | python|machine-learning|optimization|pytorch | 8 |
1,946 | 68,552,532 | Series objects are mutable, thus they cannot be hashed on Python pandas dataframe | <p>I have the following dataframe:</p>
<p>df1:</p>
<pre><code> Revenue Earnings Date
Year
2017 43206832000 4608790000 2017-01-01
2018 43462740000 8928258000 2018-01-01
2019 44268171000 5001014000 2019-01-01
2020 43126472000 4770527000 2020-01-01
</code></pre>
<p>I am using an api to get the ex... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>from currency_converter import CurrencyConverter
# if "Date" column isn't already converted:
df["Date"] = pd.to_datetime(df["Date"])
c = CurrencyConverter(fallback_on_missing_rate=True) # without fallback_on_missing_rate=True... | python|pandas|dataframe|api | 1 |
1,947 | 52,983,468 | How is the data of a numpy.array stored? | <p>This is my simple test code:</p>
<pre><code>data = np.arange(12, dtype='int32').reshape(2,2,3);
</code></pre>
<p>so the data is:</p>
<pre><code>array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]], dtype=int32)
</code></pre>
<p>but why does <code>data.data[:48]</code> look like this:</p... | <p><code>\t</code> is the tab character, of <a href="http://man7.org/linux/man-pages/man7/ascii.7.html" rel="nofollow noreferrer">ASCII</a> value 9. <code>\n</code> is the LF character, of ASCII value 10. <code>\x00</code> is a NUL character, of ascii value 0. Thus,</p>
<p>'\t\x00\x00\x00' represents a sequence of byt... | python|numpy | 3 |
1,948 | 53,198,344 | Pandas DataFrame: difference between rolling and expanding function | <p>Can anyone help me understand the difference between rolling and expanding function from the example given in the pandas docs.</p>
<pre><code>df = DataFrame({'B': [0, 1, 2, np.nan, 4]})
df
B
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
df.expanding(2).sum()
B
0 NaN # 0 + NaN
1 1.0 # 1 + 0
2 3.0 # 2 + 1
3 3... | <p>The 2 in <code>expanding</code> is <code>min_periods</code> not the <code>window</code> </p>
<pre><code>df.expanding(min_periods=1).sum()
Out[117]:
B
0 0.0
1 1.0
2 3.0
3 3.0
4 7.0
</code></pre>
<p>If you want the same result with <code>rolling</code> <code>window</code> will be equal to the length of da... | python|pandas | 4 |
1,949 | 53,104,887 | Access internal tensors and add a new node to a tflite model? | <p>I am fairly new to TensorFlow and TensorFlow Lite. I have followed the tutorials on how to quantize and convert the model to fixed point calculations using <code>toco</code>. Now I have a <code>tflite</code> file which is supposed to perform only fixed point operations. I have two questions</p>
<ol>
<li>How do I te... | <blockquote>
<p>Is there a way to add a new node or operation in this tflite file? If so how?</p>
</blockquote>
<p>Unfortunately, <strong>no</strong>, and it is actually a <em>good thing</em>. TF-Lite was designed to be extremely light yet effective, using mapped files, flat buffers, static execution plan and so on ... | python|tensorflow|tensorflow-lite | 2 |
1,950 | 53,260,050 | How to Group by column value in Pandas Data frame | <p>I have pandas dataframe like this. I want group by App_Name in seperate variable</p>
<pre><code>App_Name Date Response Gross Revenue
com.apple.tiles2 2018-10-13 3748.723574 24133394
com.orange.thescore 2018-10-13 2034.611964 8273607
com.number.studio 2018-10-13 1807.756545 33736740
com.orange.t... | <p>Convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> object to dictionary of DataFrames:</p>
<pre><code>d = dict(tuple(df.groupby('App_Name')))
print (d['com.alpha.studio'])
App_Name Date Resp... | python|pandas|pandas-groupby|data-science | 3 |
1,951 | 65,565,974 | How to update the empty dataframe values with values from another dataframe(Pandas)? | <p>I want to update empty rows in dataframe1 with the equivalent values from dataframe2 only if the rows in dataframe1 is empty.</p>
<p>Cases:</p>
<p><a href="https://i.stack.imgur.com/HD5CI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HD5CI.png" alt="Dataframe1" /></a></p>
<p>fig 1</p>
<p><a href... | <p>Try this:</p>
<pre><code> df2dict = df2.set_index(['Product Code'])['Price'].squeeze().to_dict()
# maps from df2['Product Code'] to empty columns in df
df['Price'] = df['Price'].fillna(df['Product Code'].map(df2dict))
</code></pre> | python|python-3.x|pandas|dataframe|numpy | 2 |
1,952 | 65,820,991 | Melt multiple columns to correspondent columns based on prefix in Pandas | <p>Assuming the following dataframe:</p>
<pre><code> id transaction seller0 seller1 seller2 buyer0 buyer1
0 1 Subject1 Tim Jamie Melissa Rosie NaN
1 2 Subject2 Rima Derren NaN Annalise Hania
2 3 Subject3 Rosa NaN NaN Joshua NaN
</code></pre>
<p>How could I... | <p>Use <a href="https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwiynYLhkqzuAhUH4jgGHZ_tDiIQFjADegQIARAC&url=https%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Freference%2Fapi%2Fpandas.wide_to_long.html&usg=AOvVaw2x0C-DKYYiPjJpu1JxRkeW... | python-3.x|pandas|dataframe | 3 |
1,953 | 53,567,745 | installing tensorflow on anaconda (error occurred : matplotlib and user permission(13)) | <p>While installing tensorflow on anaconda version 5.3.0 cmd environtment by running <code>conda install -c conda-forge tensorflow</code>, it came up with the following error:</p>
<p><a href="https://i.stack.imgur.com/LW9PW.png" rel="nofollow noreferrer">click here for print screen of error</a></p>
<p>I have tried fo... | <p>fixed it by installing python 3.6.7 (which was a downgrade from 3.7)</p> | python|tensorflow | 0 |
1,954 | 71,865,538 | When concatenating DataFrame and Series, the series is inserted in "vertical" | <p>I'm iterating over a DataFrame with <code>DataFrame.iterrows()</code>:</p>
<pre><code>for index, row_to_append in source_dataframe.iterrows():
</code></pre>
<p>Then I want to add some of the rows to some other DataFrames. For the appending I'm using:</p>
<pre><code>pd.concat([destination_dataframe, row_to_append], a... | <p>You can convert the <code>row_to_append</code> to dataframe</p>
<pre><code>row_to_append = pd.Series(row_to_append).to_frame().T
out = pd.concat([destination_dataframe, row_to_append], axis=0, join='outer', ignore_index=True)
</code></pre> | python|pandas|dataframe|append|concatenation | 1 |
1,955 | 72,001,640 | python: processing data so that only constant values remain | <p>I have data from a measurement and I want to process the data so that only the values remain, that are constant. The measured signal consists of parts where the value stays constant for some time then I do a change on the system that causes the value to increase. It takes time for the system to reach the constant v... | <p>Here is a very performant implementation using itertools (based on <a href="https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical">Check if all elements in a list are identical</a>):</p>
<pre class="lang-py prettyprint-override"><code>from itertools import groupby
def all_equal(i... | python|pandas|dataframe | 0 |
1,956 | 71,872,873 | Tensorflow CNN Image Classification - Using ImageDataGenerator and then Next&Model.fit gives error | <p>I have a CNN model, which is basically processing images and classifying them at the end. There are four class labels, which are UN, D1, D2 and D3. If you look at train_batches, you will see that it already labels them as an integer from 0 to 3. Before I send those images into CNN model, I been doing preprocessing. ... | <p>You are getting the error because <code>tf.keras.applications.vgg16.preprocess_input</code> takes an input tensor with 3 channels, according to its <a href="https://www.tensorflow.org/api_docs/python/tf/keras/applications/vgg16/preprocess_input" rel="nofollow noreferrer">documentation</a>. You don't need this functi... | tensorflow|image-processing|conv-neural-network | 0 |
1,957 | 71,886,922 | NameError: name 'mode' is not defined | <p>Bonjour,</p>
<pre><code>import pandas as pd
import numpy as np
</code></pre>
<p>df is:</p>
<pre><code> month year sale name
0 1 2012 55 A
1 4 2014 40 B
2 7 2013 84 C
3 10 2014 31 d
</code></pre>
<p>code is:</p>
<pre><code>agg_func_text = {'name': [ 'nunique', mode, set]}
df.... | <p><code>mode</code> is Series method; <code>groupby</code> objects don't have it. You have to specify that <code>Series.mode</code> is the one you want to call.</p>
<pre><code>agg_func_text = {'name': [ 'nunique', pd.Series.mode, set]}
out = df.groupby(['year']).agg(agg_func_text)
</code></pre>
<p>Output:</p>
<pre><co... | pandas|numpy | 1 |
1,958 | 72,101,088 | Display column names in seaborn boxplot | <p>I have this code.</p>
<pre><code>l = df.columns.values
number_of_columns=5
number_of_rows = len(l)-1/number_of_columns
plt.figure(figsize=(number_of_columns * 2, 5*number_of_rows))
for i in range(0,len(l)):
plt.subplot(number_of_rows + 1, number_of_columns, i+1)
sns.set_style('whitegrid')
sns.boxplot(dat... | <p>You should collect the <a href="https://matplotlib.org/stable/api/axes_api.html#matplotlib-axes" rel="nofollow noreferrer"><code>matplotlib.axes</code></a> object returned by <a href="https://seaborn.pydata.org/generated/seaborn.boxplot.html" rel="nofollow noreferrer"><code>sns.boxplot</code></a> and <a href="https:... | python|pandas|matplotlib|seaborn | 1 |
1,959 | 47,385,719 | Date Time difference and dataframe filtering | <p>I have Panda dataframe df of following structure, Start and End Time are string values.</p>
<pre><code> Start Time End Time
0 2007-07-24 22:00:00 2007-07-25 07:16:53
1 2007-07-25 07:16:55 2007-07-25 08:52:19
2 2007-07-25 09:45:53 2007-07-25 10:30:00
3 2007-07-25 12:32:00... | <p><strong>Question 1</strong><br>
Use <code>pd.to_datetime</code>, and then subtract the columns.</p>
<pre><code>for c in df.columns:
df[c] = pd.to_datetime(df[c])
(df['End Time'] - df['Start Time']).dt.total_seconds() / 3600
0 9.281389
1 1.590000
2 0.735278
3 1.693889
4 14.733333
dtype: floa... | python|pandas | 2 |
1,960 | 47,178,371 | Where is the code for gradient descent? | <p>Running some experiments with TensorFlow, want to look at the implementation of some functions just to see exactly how some things are done, started with the simple case of <code>tf.train.GradientDescentOptimizer</code>. Downloaded the zip of the full source code from github, ran some searches over the source tree, ... | <p>The implementation further goes to the native c++ code. Here's <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/training_ops_gpu.cu.cc#L29" rel="noreferrer"><code>ApplyGradientDescent</code></a> GPU implementation (<code>core/kernels/training_ops_gpu.cu.cc</code>):</p>
<pre clas... | python|tensorflow|machine-learning|gradient-descent | 10 |
1,961 | 68,128,088 | filter a pandas datafram based on the last rows of a key | <p>i have a pandas dataframe with some thousand of rows. this dataframe is ordered by two columns: name (a hundred unique values), and date.
i want to create a fraction of this dataframe that took only the last like 50 rows of each unique value of name.
so if i have:</p>
<pre><code> Name Date
0 A da... | <p>Use:</p>
<pre><code>df.groupby("Name").tail(4).reset_index(drop=True)
Name Date
0 A date5
1 A date6
2 A date7
3 A date8
4 B Date5
5 B Date6
6 B Date7
7 B Date8
</code></pre> | python|pandas | 1 |
1,962 | 68,067,438 | Python: how to reshape a dataframe based on a condition?` | <p>I have a dataframe that looks like the following</p>
<pre><code>df
Name Val1 Val2
0 Mark 0 3
1 Mark 2 3
2 Mark 5 6
3 Mark 7 8
</code></pre>
<p>I would like to have something like this</p>
<pre><code>df
Name Val1_0 Val1_1 Val1_2 Val1_3 Val2_0 Val... | <p>try via <code>set_index()</code>,<code>reset_index()</code> and <code>unstack()</code>:</p>
<pre><code>out=df.set_index('Name',append=True).unstack(0)
</code></pre>
<p>Finally :</p>
<pre><code>out.columns=out.columns.map(lambda x:'_'.join(map(str,x)))
out=out.reset_index()
</code></pre>
<p>output of <code>out</code>... | python|pandas | 2 |
1,963 | 68,354,602 | How do I know which spectrogram frames belong to which audio samples? | <p>I’ve been using this script:</p>
<pre><code>spgram = torchaudio.transforms.Spectrogram(512, hop_length=32)
audio = spgram(audio)
</code></pre>
<p>to get the spectrogram of some stereo music audio. I expected that the resulting spectrogram has the shape [2, 257, audio.shape[1]/32] However, that’s not the case. For ex... | <p>See <code>center</code> parameter.</p>
<blockquote>
<p>whether to pad <code>waveform</code> on both sides so that the <code>t</code>-th frame is centered at time t x hop_length. (Default: <code>True</code>)</p>
</blockquote>
<p>So, by default, the signal is padded with zeros. The padding length is probably (<code>wi... | audio|pytorch|torchaudio | 0 |
1,964 | 57,229,479 | DataFrame: how can I groupby Z and calculate the mean X in Y range | <p>I have a data frame which includes 3 columns - <code>Test</code>, <code>X</code> and <code>Y</code>. I want to add new columns <code>Xmean</code> which include the mean value of <code>X</code> with a condition on <code>Y</code> for each <code>Test</code>.</p>
<p>For example <code>Xmean</code> include the mean value... | <p>import pandas as pd</p>
<p>df=pd.read_csv(r'Downloads\test.txt',delimiter=',',encoding='utf-8')</p>
<p>df_sort=df.sort_values("test")</p>
<p>df_filter=df_sort[df_sort['y']>=5]</p>
<h1>applying aggregates function to find mean</h1>
<p>df_agg=df_filter.groupby(['test'])['x'].mean()</p>
<h1>join two datafr... | python-3.x|dataframe|pandas-groupby | 0 |
1,965 | 57,255,942 | object detection using tensorflow by own classifier | <p>When I try training my train.py for object detection using the tensorflow/models repository using the code </p>
<pre><code>python train.py --logtostderr --train_dir=training_dir/ --pipeline_config_path=training/faster_rcnn_inception_resnet_v2_atrous_pets.config
</code></pre>
<p>I am unable to run this command.</p>... | <p>I've managed to solve this problem in my system (windows 10). The solution is not very straight forward but:</p>
<p>1) First u need to clone Tensorflow Object Detection API repository <a href="https://github.com/tensorflow/models" rel="nofollow noreferrer">https://github.com/tensorflow/models</a>.</p>
<p>2) Follow... | python|tensorflow|computer-vision | 1 |
1,966 | 57,099,019 | Transforming Multiindex into single index after groupby() Pandas | <p>Probably this question is a bundle of some functions. I am having trouble renaming multiple index and transforming into simple index.</p>
<p>Lets say I have the following DF</p>
<pre><code>Customer Date Amount
John 10-10-2016 100,00
Mark 12-10-2016 50,00
John ... | <p>We can using <code>droplevel</code></p>
<pre><code>df_final.columns=df_final.columns.droplevel(0)
df_final.reset_index(inplace=True)
</code></pre> | python|pandas | 1 |
1,967 | 56,982,447 | horizontal stacked bar chart with a single series? | <p>My simple Dataframe produces a plot with 4 single, horizontal bars, rather than one stacked horizontal bar. I've tried transposing it etc - without success. I'm sure I'm doing something simple wrong - but I can't work it out. Help much appreciated!</p>
<pre class="lang-py prettyprint-override"><code>
import pandas ... | <p>I think you need create one row <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_frame.html" rel="nofollow noreferrer"><code>Series.to_frame</code></a> and transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.T... | python|pandas|matplotlib | 0 |
1,968 | 45,747,393 | Convert column with mixed text values and None to integer lists efficiently | <p>Imagine I have a column with the values</p>
<p><code>data = pd.DataFrame([['1,2,3'], ['4,5,6'], [None]])</code></p>
<p>I want the output to be:</p>
<p><code>[[1,2,3]], [[4,5,6]], [None]]</code></p>
<p>In other words, splitting up the comma-delimited strings into lists while ignoring the None values.</p>
<p>This... | <p>Use <code>df.str.split</code> and then convert to a list:</p>
<pre><code>In [9]: df
Out[9]:
Col1
0 1,2,3
1 4,5,6
2 None
In [10]: df.Col1.str.split(',').tolist()
Out[10]: [['1', '2', '3'], ['4', '5', '6'], None]
</code></pre>
<p>To convert the inner list elements to integers, you can do a conversion with ... | python|pandas|dataframe | 2 |
1,969 | 45,791,419 | reading data from csv files in python | <p>I am trying to extract data from a dummy csv file to use inside tensorflow.
The dummy data only has 2 columns: X (single feature column) and Y (expected output). </p>
<pre><code>X Y
11.0 13.0
23.0 33.3
... ... and so on
</code></pre>
<p>Right now I am reading the data like so:</p>
<pre><code>import pandas... | <p>There is no need to reshape or use <code>.loc</code> or <code>.values</code>:</p>
<pre><code>inputX = dummy_data[['X']]
</code></pre>
<p>(Mind the list of lists <code>[[]]</code>!)</p> | python|pandas|csv | 1 |
1,970 | 50,683,039 | Conv2D transpose output shape using formula | <p>I get <code>[-1,256,256,3]</code> as the output shape using the transpose layers shown below. I print the output shape. My question is specifically about the height and width which are both <code>256</code>. The channels seem to be the number of filters from the last transpose layer in my code.</p>
<p>I assumed rat... | <p>Regarding <code>'SAME'</code> padding, the <a href="https://www.tensorflow.org/api_guides/python/nn#Convolution" rel="noreferrer"><code>Convolution</code></a> documentation offers some detailed explanations (further details in those <a href="https://www.tensorflow.org/api_guides/python/nn#Notes_on_SAME_Convolution_P... | python|tensorflow|convolutional-neural-network | 8 |
1,971 | 66,426,905 | pandas merge python sort data frame | <pre><code>Name Sex Age Height Weight
0 Alfred M 14 69.0 112.5
1 Alice F 13 56.5 84.0
2 Barbara F 13 65.3 98.0
3 Carol F 14 62.8 102.5
4 Henry M 14 63.5 102.5
5 James M 12 57.3 83.0
6 Jane F 12 59.8 84.5
7 Janet F 15 62.5 112.5
8 Jeffre... | <p>You can use <code>groupby().cumcount()</code> to enumerate the rows within the group then <code>sort_values</code>:</p>
<pre><code>(df.assign(order=df.groupby(['Sex']).cumcount())
.sort_values(['order','Sex'])
.drop('order',axis=1)
)
</code></pre>
<p>Output:</p>
<pre><code> Name Sex Age Height Weight
... | python|pandas|dataframe|sorting|merge | 0 |
1,972 | 66,546,790 | .get(0) in a JS machine learning Algo Don't work | <p>I'm on my way to create my first KNN Algo to learn machine learning.
I'm looking after a basic course online that's explaining it, I'm feeling that I did exactly the same as he did.</p>
<p>But when I'm running it I get this pretty basic error of js.
I am using TensorFlow.</p>
<pre><code>.sort((a, b) => (a.get(0) ... | <p>After long research, and a lot of time.</p>
<p>TensorFlow removed the .get function you would use instead arraySync.
for example.</p>
<pre><code>pair.get(1)[0]
</code></pre>
<p>will be:</p>
<pre><code>pair.arraySync(1)[0]
</code></pre> | javascript|node.js|tensorflow.js | 1 |
1,973 | 66,341,942 | How to find the first row with a different value within a column for a pandas df? | <p>I have a pandas dataframe, like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020/01/01</td>
<td>1</td>
</tr>
<tr>
<td>2020/01/02</td>
<td>1</td>
</tr>
<tr>
<td>2020/01/03</td>
<td>2</td>
</tr>
<tr>
<td>2020/01/04</td>
<t... | <p>It seems like you want to keep the first row and every row in which the quantity changes, right? So you can do</p>
<pre class="lang-py prettyprint-override"><code>
q = df['Quantity'].values
sel = np.r_[True, q[1:] != q[:-1]]
df = df.loc[sel, :]
</code></pre>
<p>where I've called df your DataFrame. What this is doing... | pandas | 2 |
1,974 | 66,384,463 | Filling aggregated column in Python | <p>Using the input below as an example, I am trying to create an aggregated column in a dataframe in Python based on unique instances of others. The best attempt I can make leaves some NaN in the new column though</p>
<pre><code>raw_data = {'RegionCode' : ['10001', '10001', '10001', '10001', '10001', '10001', '10002', ... | <p>To fill the column and repeat each Total_Pop per Region, you can use a simple grouped (by Region per se) <code>ffill()</code>:</p>
<pre><code>Data['Total_Pop_new'] = Data.groupby('RegionCode')['Total_Pop'].ffill()
</code></pre>
<p>Will give you back:</p>
<pre><code>Data
RegionCode Stratum LaStratum ... Q_respo... | python|pandas|aggregation | 2 |
1,975 | 66,605,765 | Use a matrix to inform where pixels should be on or off (Numpy) | <p>I am not sure how to word this. I am sure there is an operation that describes what I am trying to do I just don't have a lot of experience manipulating image arrays.</p>
<p>I have a 2D array (matrix) of 1s and 0s which specify if a group of pixels should be the color [255,255,255] or the color [0,0,0] in rbg. It se... | <p>How about reshaping pixel into a 3D matrix and using dot?</p>
<pre><code>pixel = np.array([0,1,1,1]).reshape(2,2,-1)
rgb = np.array([255,255,255]).reshape(1,3)
pixel.dot(rgb)
</code></pre>
<p>Output</p>
<pre><code>array([[[ 0, 0, 0],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255]]])... | python|arrays|image|numpy | 1 |
1,976 | 66,557,738 | Exploding memory consumption when training FL model with varying number of participants per round | <p>I'm running FL algorithm following the <a href="https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification" rel="nofollow noreferrer">image classification</a> tutorial. The number of participants vary at each round according to a predefined list of participants number.</p>
<pre class=... | <p>The issue was a bug in the <code>executor stack</code> of the TFF runtime process.</p>
<p>Complete details and bug fix below</p>
<p><a href="https://github.com/tensorflow/federated/issues/1215" rel="nofollow noreferrer">https://github.com/tensorflow/federated/issues/1215</a></p> | tensorflow-federated | 2 |
1,977 | 57,718,244 | Unable to call a function inside groupby.agg | <p>New to python. So please excuse mistakes. I am writing a script to group a pandas dataframe using groupby.agg. I get errors while trying to call a function that takes as input, the output of a lambda function</p>
<p>Here is the sample of the merged dataframe</p>
<pre><code>cprdf.iloc[5:10,5:20]
Out[237]:
L... | <p>After some research, I found a solution. One issue that i noticed( not 100% sure) is that NamegAgg does not accept the same column for multiple custom function for aggregation. So I created a dummy SMM column. I modified the CPR function by returning the lambda instead of assigning it to a new variable and returnin... | python|pandas-groupby | 1 |
1,978 | 57,309,280 | filtering and make a list of lists from a csv file in python | <p>I have a csv file which looks like the small example:</p>
<p>small example:</p>
<pre><code>Id sv item1 item2 item3
pos ab 4 5 8
reg ad 7 85 96
neg af 14 78 32
neg ab 47 5 6
</code></pre>
<p>I would like to make a list of lists in python from this csv file. I want to skip the first 2 columns ... | <p>Using the <code>csv</code> module</p>
<p><strong>Ex:</strong></p>
<pre><code>import csv
results = []
with open(filename, "rU") as infile:
reader = csv.reader(infile, delimiter=" ")
for row in reader:
if row[0] == 'neg':
results.append(list(filter(None, row[2:])))
print([i for i in zip... | python-3.x|pandas|csv | 0 |
1,979 | 70,820,024 | Comparison between numpy array and float number of the same data type? | <p>np.arange(0, 1, 0.1) initializes an float point array with the defualt data type float64. However, when I use <= to compare it to, say, np.float64(0.6), the 7th element (0.6) returns False. What's even more weird is that if I use float32 for initialization and comparison, the result becomes just right.
What's the... | <p>The answer is pretty obvious if you do this:</p>
<pre><code>import numpy as np
a = np.arange(0, 1, 0.1)
print('\n'.join(map(str, zip(a, a >= np.float64(0.6)))))
</code></pre>
<p>Result:</p>
<pre><code>(0.0, False)
(0.1, False)
(0.2, False)
(0.30000000000000004, False)
(0.4, False)
(0.5, False)
(0.60000000000000... | python|numpy | 5 |
1,980 | 71,039,745 | Painting cells using pandas and complex conditions | <p>I have a data frame that contains the std, mean and median for several chemical elements. Sample data:</p>
<pre><code>test = pd.DataFrame({('Na', 'std'):{'A': 1.73, 'B':0.95, 'C':2.95}, ('Na', 'mean'):{'A': 10.3, 'B':11, 'C':20}, ('Na', 'median'):{'A':11, 'B':22, 'C':34},('K', 'std'):{'A': 1.33, 'B':1.95, 'C':2.66},... | <p>Use <code>df.style</code>:</p>
<pre class="lang-py prettyprint-override"><code>def styler(col):
chem, stat = col.name
if stat == 'std':
return np.where(col.isin(col.nsmallest(2)), 'color: red', '')
elif stat in ['mean', 'median']:
delta = (df[(chem, 'mean')] - df[(chem, 'median')]).abs()
... | python|pandas|pandas-styles | 1 |
1,981 | 51,665,052 | Groupby with Apply Method in Pandas : Percentage Sum of Grouped Values | <p>I am trying to develop a program to convert daily data into monthly or yearly data and so on.
I have a DataFrame with datetime index and price change %:</p>
<pre><code> % Percentage
Date
2015-06-02 0.78
2015-06-10 0.32
2015-06-11 0.34
2015-06-12 -0.06
2015-06-15 -0.41
...
</cod... | <p>Your <code>apply</code> is applying to all rows individually because you're grouping by the <code>date</code> column. Your date column looks to have unique values for each row, so each group has only one row in it. You need to use a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html"... | python|python-3.x|pandas | 0 |
1,982 | 51,645,982 | Pandas groupby and replace duplicates with empty string | <p>I have a dataframe like the following:</p>
<pre><code>import pandas as pd
d = {'one':[1,1,1,1,2, 2, 2, 2],
'two':['a','a','a','b', 'a','a','b','b'],
'letter':[' a','b','c','a', 'a', 'b', 'a', 'b']}
df = pd.DataFrame(d)
> one two letter
0 1 a a
1 1 a b
2 1 a c
3 1 ... | <p>You can mask your columns where the value is not the same as the value below, then use <code>where</code> to change it to a blank string:</p>
<pre><code>df[['one','two']] = df[['one','two']].where(df[['one', 'two']].apply(lambda x: x != x.shift()), '')
>>> df
one two letter
0 1 a a
1 ... | python|pandas|pandas-groupby | 2 |
1,983 | 51,576,125 | Python Pandas- Find the first instance of a value exceeding a threshold | <p>I am trying to find the first instance of a value exceeding a threshold based on another Python Pandas data frame column. In the code below, the "Trace" column has the same number for multiple rows. I want to find the first instance where the "Value" column exceeds 3. Then, I want to take the rest of the information... | <p>By using <code>idxmax</code></p>
<pre><code>df.loc[(df.Value>3).groupby(df.Trace).idxmax]
Out[602]:
Date Trace Value
2 3 1 3.1
5 2 2 3.6
</code></pre> | python|pandas | 4 |
1,984 | 35,856,567 | How to efficiently remove duplicate rows from a DataFrame | <p>I'm dealing with a very large Data Frame and I'm using <code>pandas</code> to do the analysis.
The data frame is structured as follows</p>
<pre><code>import pandas as pd
df = pd.read_csv("data.csv")
df.head()
Source Target Weight
0 0 25846 1
1 0 1916 1
2 25846 0 1
... | <p>Create two temp columns to save <code>minimum(df.Source, df.Target)</code> and <code>maximum(df.Source, df.Target)</code>, and then check duplicated rows by <code>duplicated()</code> method:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0, 5, (20, 2)), columns=["Source"... | pandas | 4 |
1,985 | 35,886,028 | Populate python array without double loop | <p>Can anyone advise me on how to use pandas more efficiently, currently I am doing the following to find out the correlation of two items but this isn't very fast.</p>
<pre><code>for i in range(0, df.shape[0]):
for j in range(0, df.shape[0]):
if i<j:
## get the weights
wgt_i = ... | <p>This is not as short as the solution from @larsbutler, but much faster for large n: </p>
<pre><code>import numpy as np
n = 5
M = np.zeros((n,n))
M[np.triu_indices_from(M)] = 1
M[np.diag_indices_from(M)] = 0
</code></pre>
<p>gives:</p>
<pre><code>array([[ 0., 1., 1., 1., 1.],
[ 0., 0., 1., 1., 1.... | python|loops|pandas|correlation | 0 |
1,986 | 37,533,956 | Getting the index of pandas dataframe for matching row values | <p>I have to dataframes in pandas , <code>A</code> and <code>B</code>: </p>
<p>A:</p>
<pre><code>A = pd.DataFrame({0:[1.24, 8.75, 4.32]})
0 1.24
1 8.75
2 4.32
</code></pre>
<p>where the <code>0 1 2 3 4 5</code> is the index of the dataframe</p>
<p>and another dataframe with strings as index:</p>
<pre><co... | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow">isin()</a> function for that:</p>
<pre><code>In [141]: B[B[0].isin(A[0])].index
Out[141]: Index(['p_21', 'p_05', 'p_76'], dtype='object')
In [142]: B[B[0].isin(A[0])]
Out[142]:
0
p_21 1.2... | python|pandas | 2 |
1,987 | 37,553,397 | Python Applymap taking time to run | <p>I have a matrix of data ( 55K X8.5k) with counts. Most of them are zeros, but few of them would be like any count. Lets say something like this: </p>
<pre><code> a b c
0 4 3 3
1 1 2 1
2 2 1 0
3 2 0 1
4 2 0 4
</code></pre>
<p>I want to binaries the cell values. </p>
<p>I did the following: </p>
<... | <p><strong>UPDATE:</strong></p>
<p>read <a href="https://github.com/pydata/pandas/issues/3699" rel="nofollow noreferrer">this topic</a> and <a href="https://github.com/pydata/pandas/issues/12712" rel="nofollow noreferrer">this issue</a> in regards to your error</p>
<p>Try to save your DF as HDF5 - it's much more conv... | python|pandas|dataframe | 3 |
1,988 | 37,435,468 | pandas SettingWithCopyWarning when using a subset of columns | <p>I am trying to understand pandas SettingWithCopyWarning, what exactly triggers it an how to avoid it. I want to take a selection of columns from a data frame and then work with this selection of columns. I need to fill missing values and replace all values larger than 1 with 1. </p>
<p>I understand that sub_df=df[[... | <p>Your 2 code snippets are semantically different, in the first it's ambiguous whether you want to operate on a view or a copy of the original df, in the second you overwrite <code>df</code> with a subset of the <code>df</code> so there is no ambiguity.</p>
<p>If you want to operate on a copy then do this:</p>
<pre>... | python|pandas | 1 |
1,989 | 37,956,400 | Using a pandas DataFrame to get the count of the 10th most frequent value | <p>I have a DataFrame that contains entries of place_ids such as:</p>
<pre><code>place_id
11111
11111
22222
33333
44444
44444
...
</code></pre>
<p>I would like to get the count of the 10th most frequent value.</p>
<p>Here's what I've come up with:</p>
<pre><code>print df.place_id.value_counts().nlargest(10).tail(1)... | <p>try:</p>
<pre><code>import pandas as pd
import numpy as np
from string import ascii_letters
np.random.seed([3,1415])
s = pd.Series(np.random.choice(list(ascii_letters), (10000,)))
vc = s.value_counts().sort_values()
vc.loc[[vc.index[-10]]]
j 204
dtype: int64
</code></pre> | python|numpy|pandas|dataframe|series | 2 |
1,990 | 64,565,273 | Trying to repeat a pair of values in a numpy array | <p>I have a coordinate saved as a numpy array <code>x = np.array([1,2])</code> and I am trying to create an array that repeats [1,2] n times. For example, to repeat 4 times, I would want the array to look like this:</p>
<pre><code>array([1,2],[1,2],[1,2],[1,2])
</code></pre>
<p>I have tried using the function:</p>
<pre... | <p>Simplest way should be <code>[[1,2]]*4</code></p>
<blockquote>
<p><code>[[1,2]]*4</code></p>
</blockquote>
<p><code>[[1, 2], [1, 2], [1, 2], [1, 2]]</code></p>
<p>If you wanna make it array, <code>np.array([[1,2]]*4)</code> would work.</p> | python|arrays|numpy|repeat | 4 |
1,991 | 47,854,438 | How to check column value among all others values in same column in Pandas Data frame? | <p>I have a pandas data frame which having three columns. Normally for the Loan type it has 5 values. Let's say Conso, Immo, Pro, Autre, Tous. For this data frame only contain loan type 'Immo'. (At the beginning we don't know what the Loan type is). How do I check what the loan type is among all this loan type?</p>
... | <p>If want check if exist all values in <code>L</code> in column <code>LoanType</code> use:</p>
<pre><code>L = ['Immo', 'Conso', 'Pro', 'Autres', 'Tous']
a = all([(df['LoanType'] == x).any() for x in L])
print (a)
False
</code></pre>
<p>Or:</p>
<pre><code>s = set(['Immo', 'Conso', 'Pro', 'Autres', 'Tous'])
a = s.iss... | python|pandas|dataframe | 1 |
1,992 | 47,575,063 | Is there a sci.stats.moment function for binned data? | <p>I'm looking for a function which calculates the n-th central moment
(same as the one out of scipy.stats.moment)
for my binned data (Out of the numpy.histogram function).</p>
<pre><code># Generate normal distributed data
import numpy as np
import matplotlib.pyplot as plt
data = np.random.normal(size=500,loc=1,scale=... | <p>Working with binned data is essentially the same as working with weighted data. One uses the midpoint of each bin as a data point, and the count of that bin as its weight. If <code>scipy.stats.moment</code> supported weights, we could do this computation directly. As is, use the method <a href="https://docs.scipy.or... | python|numpy|scipy | 1 |
1,993 | 47,852,014 | LabelEncoding to multiple columns in pandas | <p>I'm currently working on Titanic dataset. It consists of 4-5 non numeric columns. I want to apply <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow noreferrer">sklearn.LabelEncoder</a> class to get encoded values for these non-numeric columns. I can, no ... | <p>Just run a loop after selecting object types</p>
<pre><code>obj_cols = df.select_dtypes(include=[object])
for i in obj_cols:
df[i+'label'] = le.fit_transform(df[i])
</code></pre> | python|machine-learning|scikit-learn|dataset|sklearn-pandas | -1 |
1,994 | 48,907,175 | Pandas not replacing strings in dataframe | <p>I have seen this question but it isn't working for me, I am sure I am making a blunder but please tell me where I am doing wrong, I want values "Street", "LandContour" etc to be replaced from "pave" to 1 and so on.</p>
<p><a href="https://stackoverflow.com/questions/17114904/python-pandas-replacing-strings-in-dataf... | <p>Try:</p>
<pre><code>df = pd.read_csv('train.csv') # reset
df.fillna(-99999, inplace=True) # refill
df['Street'].replace('Pave', 0, inplace=True) # replace
</code></pre>
<p>The problem with your previous approaches is that they don't apply replace to the correct column with the corr... | python|pandas|dataframe | 3 |
1,995 | 70,166,010 | How to extract date time from dtype('<M8[ns]') in pandas? | <p>my ots column has : <code>2021-04-03 14:01:22.791856</code>
its dtype is <code>dtype('<M8[ns]')</code>
how do I get only <code>2021-04-03 14:01:22</code> ?</p> | <p>use this:
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html</a></p>
<p>considering that is your time column in the pandas dataframe:</p>
<pre><code>df[... | python|pandas|datetime | 1 |
1,996 | 70,236,626 | Exact Value In Determinant Using Numpy | <p>I want to compute the determinant of a 2*2 matrix , and I use linalg.det from Numpy like this:</p>
<pre><code>import numpy as np
a = np.array([
[1,2],
[3,4]
])
b=np.linalg.det(a)
</code></pre>
<p>In other hand, We know that we also can compute it by a multiplication and a subtract like this:</p>
<pre><code>1*4 - 2*3... | <p>If you're working with integers, you can use</p>
<pre class="lang-py prettyprint-override"><code>b = int(np.linalg.det(a))
</code></pre>
<p>To just make it into an integer. This should give you the following</p>
<pre class="lang-py prettyprint-override"><code>int(b) == -2 ## Returns True
</code></pre>
<p>Edit: This ... | python|python-3.x|numpy|math|determinants | 0 |
1,997 | 56,371,979 | Time difference between row and its previous/next row for the same customer in pandas dataframe | <p>I have a dataframe:</p>
<pre><code>In [1]: import pandas as pd;import numpy as np
In [2]: df = pd.DataFrame(
...: [
...: ['A', '2019-05-10 23:59:59', 'NOT_WORKING'],
...: ['A', '2019-05-11 00:05:00', 'WORKING'],
...: ['B', '2019-05-13 07:55:... | <p>First just make sure the sorting is correct for 'cust' and 'event_date', and then groupby customer, then take the difference for each row. </p>
<pre><code>df = df.sort_values(['cust', 'event_date'])
df.groupby('cust')['event_date'].diff()
event_date
0 NaT
1 0 days 00:05:01
2 NaT
3 2... | python|pandas|diff|difference|datediff | 1 |
1,998 | 56,393,308 | How to create a scatter plot in pandas grouped by time of day | <p>I would like to create a scatter plot using Pandas where the values are grouped by time of day and coloured/styled differently based on the day. The code snippet below will create a scatter plot of two time-series.</p>
<pre><code>import pandas as pd
idx = pd.date_range('2019-01-01', periods=48, freq='H')
x = pd.Ser... | <p>Since you want to perform a scatter plot and keep all the data, I suggest not using <code>groupby</code>. Instead, the <code>hour</code> and <code>day</code> methods of DatetimeIndex objects provide a simple way to color by day and plot by daytime hour.</p>
<pre class="lang-py prettyprint-override"><code>import pan... | pandas|pandas-groupby | 2 |
1,999 | 55,913,093 | Element-wise matrix multiplication for multi-dimensional array | <p>I want to realize component-wise matrix multiplication in MATLAB, which can be done using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>numpy.einsum</code></a> in Python as below:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as n... | <h3>Option 1: Calling numpy from MATLAB</h3>
<p>Assuming your system is set up <a href="https://www.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html" rel="nofollow noreferrer">according to the documentation</a>, and you have the numpy package installed, you could do (in MATLAB):</p>
<pre class="la... | matlab|multidimensional-array|sum|elementwise-operations|numpy-einsum | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.