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 |
|---|---|---|---|---|---|---|
375,700 | 72,321,381 | renaming the column names in dataframe using some parts of original column name | <p>I have this huge data frame with very long column names</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'mynumber': [11, 20, 25],
'Raja_trial1:gill234_pit_type_id@rng': [4, 5, 42],
'Raja_trial1:Perm_king_que@pmcx[x1]': [0, 2, 3],
'Dun_mere_fer45:Hisota_gul_har23@... | <p>You can achieve this with a single regex:</p>
<pre><code>df.columns = df.columns.str.replace(r'.*?([^_]+:).+?([^_]+_[^_]+)@.*',
r'\1\2', regex=True)
</code></pre>
<p>output:</p>
<pre><code> mynumber trial1:type_id trial1:king_que fer45:gul_har23 chb1:kaam_nix
0 11 ... | pandas|dataframe|multiple-columns | 2 |
375,701 | 72,333,215 | pandas data frame splitting by column values using Parallel Processing | <p>I have a really large pandas dataframe and I am trying split it into multiple ones by stock names and save them to csv.</p>
<pre><code> stock date time spread time_diff
VOD 01-01 9:05 0.01 0:07
VOD 01-01 9:12 0.03 0:52
VOD 01-01 10:04 0.02 0:11
... | <p>Being I/O involved I don't expect the selection of the dataframe to be the main blocking point.</p>
<p>So far, I can provide you two solutions to speed it up:</p>
<p><strong>Threading:</strong> Just launch each stock in a different thread or in a <a href="https://docs.python.org/3/library/concurrent.futures.html#con... | python|pandas|multiprocessing | 2 |
375,702 | 72,170,136 | Convert irregular array of arrays into an array | <p>I have an array of values and an array of arrays of indices that looks like this (the real arrays are way bigger):</p>
<pre><code>import numpy as np
A = np.array([np.array([0,1,2]),np.array([0,4]),np.array([1,3,5])])
B = np.array([5,10,3,7,8,4])
for a in A:
np.max(B[a])
</code></pre>
<p>The endgame would be ... | <p>In order for this to work, you need to concatenate your arrays into a single array.</p>
<pre><code>import numpy as np
A = np.array([np.array([0,1,2]),np.array([0,4]),np.array([1,3,5])])
B = np.array([5,10,3,7,8,4])
print(B[np.concatenate(A)].max())
</code></pre>
<p>This gives the same max result without the loop.... | python|numpy | 0 |
375,703 | 72,440,137 | Specifying dtype for parquet partition fields with dask.dataframe.read_parquet | <p>I have a parquet dataset structured like:</p>
<pre><code>/path/to/dataset/a=True/b=1/data.parquet
/path/to/dataset/a=False/b=1/data.parquet
/path/to/dataset/a=True/b=2/data.parquet
/path/to/dataset/a=False/b=2/data.parquet
...
</code></pre>
<p>how do i specify the dtypes of partition fields (here, <code>a</code> and... | <p>If you are using <code>pyarrow</code> as the underlying engine you can pass a <a href="https://arrow.apache.org/docs/python/dataset.html#different-partitioning-schemes" rel="nofollow noreferrer">partitioning argument</a> to specify the schema of the partition.</p>
<p><code>dask.dataframe.read_parquet</code> will pas... | python|pandas|dask|parquet|pyarrow | 0 |
375,704 | 72,206,172 | What is the time complexity of numpy.linalg.det? | <p>The documentation for <a href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html" rel="nofollow noreferrer"><code>numpy.linalg.det</code></a> states that</p>
<blockquote>
<p>The determinant is computed via LU factorization using the <a href="https://en.wikipedia.org/wiki/LAPACK" rel="nofollow no... | <p><strong>TL;DR</strong>: it is between <code>O(n^2.81)</code> and <code>O(n^3)</code> regarding the target BLAS implementation.</p>
<p>Indeed, Numpy uses a LU decomposition (in the log space). The actual implementation can be found <a href="https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/... | python|numpy|time-complexity|linear-algebra|determinants | 1 |
375,705 | 72,262,198 | How can I save multiple dataframes onto one excel file (as separate sheets) without this error occurring? | <p>I have the following Python code:</p>
<pre><code>import pandas as pd
path=r"C:\Users\Wali\Example.xls"
df1=pd.read_excel(path, sheet_name = [0])
df2=pd.read_excel(path, sheet_name = [1])
with pd.ExcelWriter(r"C:\Users\Wali\Example2.xls") as writer:
# use to_excel function and specify the sh... | <p>Change [0] to 0 in pd.read_excel(path, sheet_name = [0]) will resolve this issue</p>
<pre><code>import pandas as pd
path=r"test_book.xlsx"
df1=pd.read_excel(path, sheet_name = 0)
df2=pd.read_excel(path, sheet_name = 1)
with pd.ExcelWriter(r"test_book1.xlsx") as writer:
# use to_excel functi... | python|pandas|dataframe | 0 |
375,706 | 72,347,136 | Is there a way to iterate through list of string in a dataframe? | <p>I wrote the following code. I want to replace the number "1" with "0" whenever it appear twice or more for a particular universal_id and the number "1" that is left should be in the row where days are the lowest. The below code does the work but I want to iterate over more then one univ... | <p>You can use:</p>
<pre><code>df2 = pdf1.sort_values(by='days')
m1 = df2['A'].eq(1)
m2 = df2[['A', 'universal_id']].duplicated()
pdf1.loc[m1&m2, 'A'] = 0
</code></pre>
<p>output:</p>
<pre><code> A B c d e days universal_id
0 1 0 1 0 1 60 fdaf
1 0 1 0 0 1 350 fdaf
2 1 1 0 ... | python|pandas|dataframe|iterator | 0 |
375,707 | 72,363,673 | groupby and join with pandas dataframe | <p>Here is part of the data of scaffold_table
<a href="https://i.stack.imgur.com/uLcHO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uLcHO.png" alt="enter image description here" /></a></p>
<pre><code>import pandas as pd
scaffold_table = pd.DataFrame({
'Position':[2000]*5,
'Company':['Amazon', 'Am... | <p>I solved the problem with the following code</p>
<pre><code># we want the overall yield per ticker, so total PnL/Position on the last date
summary_table['Yield'] = summary_table['total PnL']/summary_table.loc['2022-04-29']['Position']
</code></pre>
<p>This does not specify the date for total PnL since it's the sum b... | python|pandas | 0 |
375,708 | 72,277,791 | Finding the line number of specific values in pandas dataframe - python | <p>I am working on a school project and I am trying to simulate a library's catalogue system. I have .csv files that hold all the data I need but I am having a problem with checking if an inputted title, author, bar code, etc. is in the data set. I have searched around for quite a while trying different solutions but n... | <p>Pandas does not really need to find the numeric index of something, to do indexing.</p>
<p>Since you have not provided any starting point or data, I'll just provide a few pointers here as there are mans ways to <a href="https://pandas.pydata.org/docs/user_guide/10min.html#boolean-indexing" rel="nofollow noreferrer">... | python|pandas|dataframe | 0 |
375,709 | 72,143,352 | Round number down to the next 1000 in python | <p>can somebody tell me how i can round down to the nearest thousand. So far I tried it with math.round(), the truncate function but i couldn't find my math skills to work out for me. As a example for some people I want that 4520 ends up in beeing 4000.</p> | <p>In Python, you can do</p>
<pre><code>print((number // 1000)*1000)
</code></pre> | python|numpy|rounding | 2 |
375,710 | 72,356,325 | Python - When plotting using both matplotlib and pandas, the x-axis is accurate using pandas, but not matplotlib | <p>(This is my first StackOverflow question ever!)</p>
<p>I have a pandas dataframe that contains solar irradiance values in 15-minute intervals over the course of a single day. This dataframe's index is a "DatetimeIndex" (dtype='datetime64[ns, America/New_York]', and is localized to its respective timezone. ... | <p>Can't really reproduce your problem, but maybe you can try passing the index and values of the series by separate to the plot function.</p>
<pre><code>...
axs[0,0].plot(poa_irradiance_swd_flat.index, poa_irradiance_swd_flat.values)
...
</code></pre>
<p>Also, note that you can pass an <code>ax</code> attribute to the... | python|pandas|matplotlib|pvlib | 0 |
375,711 | 72,244,954 | Pandas - Setting column value, based on a function that runs on another column | <p>I have been all over the place to try and get this to work (new to datascience). It's obviously because I don't get how the datastructure of Panda fully works.</p>
<p>I have this code:</p>
<pre class="lang-py prettyprint-override"><code>def getSearchedValue(identifier):
full_str = anedf["Diskret data"]... | <p>With regex you could do something like:</p>
<pre><code>def map_(list_) -> pd.Series:
if list_:
idx, values = zip(*list_)
return pd.Series(values, idx)
else:
return pd.Series(dtype=object)
series = pd.Series(
['CCC#111~1|BBB#2323~2234', 'JJSDJ#1234~Heart attack']
)
reg_series =... | pandas|jupyter-notebook | 0 |
375,712 | 72,438,669 | GeoPandas - MultiPolygon to Polygon geometry | <p><code>geometry</code> in my geopandas dataframe is of type <code>Polygon</code> and <code>MultiPolygon</code>. I'd like to convert the <code>MultiPolygons</code> to <code>Polygons</code> as I am having issues with running some spatial functions on the data.</p>
<p>Sample data file: <a href="https://www.dropbox.com/s... | <p>There are bad geometries in your example data. This will convert the valid ones and store the bad ones in the bad_geom_dict for further investigation. Explode works on the valid geoms.</p>
<pre><code>bad_geom_dict = {}
for idx, row in gdf.iterrows():
try:
value = row['zip_code_geom']
wkt.loads(v... | pandas|geospatial|geopandas | 0 |
375,713 | 72,312,508 | How to do regex split and replace on dataframes columns in Pandas? | <p>QUESTION: Is there a function to simplify this whole process?</p>
<p>So I was trying to clean data.
Data source: <a href="http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls" rel="nofollow noreferrer">UN Energy Table</a> (will automatically download xls file) And the data in questio... | <p>You can use</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Country':['XXX(12)', 'YYYY5000', '(ZZZ)15', np.nan]})
df.loc[pd.isna(df['Country']), 'Country'] = ""
df['Country'] = df['Country'].astype(str).str.replace(r'[0-9()]+', '', regex=Tru... | python|regex|pandas|dataframe | 0 |
375,714 | 50,516,450 | mysqlsh in Python mode, cannot import modules | <p>New to Mysqlsh I'm trying to import module pandas, but I'm getting:</p>
<pre><code> MySQL Py > import pandas as pd
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named pandas
Mysqlsh ver. 8.0.11
Python ver. 2.7.15
Updated OSX
</code></pre>
<p>I can... | <p>Your module has to be in one of those paths listed by <code>sys.path</code>.</p>
<pre><code> MySQL Py > import sys
MySQL Py > sys.path
</code></pre>
<p>Install <code>pandas</code> globally, or append your <code>pandas</code> install path to <code>sys.path</code> in <code>mysqlsh</code>.</p> | python|pandas|import | 0 |
375,715 | 50,499,223 | Make subplots of the histogram in pandas dataframe using matpolot library? | <p><strong>I have the following data separate by tab:</strong></p>
<pre><code>CHROM ms02g:PI num_Vars_by_PI range_of_PI total_haplotypes total_Vars
1 1,2 60,6 2820,81 2 66
2 9,8,10,7,11 94,78,10,69,25 89910,1102167,600,1621365,636 5 276
3 5,3,4,6 6,12,14,17 908,394,759,115656 4 49
4 17,18... | <p>Your first problem comes from the fact that you are using <code>plt.ylabel()</code> at the end of your loop. pyplot functions act on the current active axes object, which, in this case, is the last one created by <code>subplots()</code>. If you want your label to be centered over your subplots, the easiest might be ... | python-3.x|pandas|matplotlib|plot|histogram | 2 |
375,716 | 50,667,036 | Dataframe slicing from cell after reading csv | <p>I am reading data from Twitter analytics with CSV and DataFrames. </p>
<p>I want to <strong>extract url from certain cell</strong></p>
<p>The output is this process is the following</p>
<pre><code>tweet number tweet id tweet link tweet text
1 1.0086341313026E+018 "tweet lin... | <p>I believe that you want:</p>
<pre><code>print (df['tweet text'].str[-12:-1])
0 example.com
Name: tweet text, dtype: object
</code></pre>
<p>More general solution is with <a href="https://stackoverflow.com/a/37807990/2901002">regex</a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Se... | python|string|python-3.x|pandas|series | 3 |
375,717 | 50,449,876 | Getting the sum of groupby as a new column with distinct values in Pandas | <p>This is how my data look like:</p>
<pre><code>id date rt dnm
101122 2017-01-24 0.0 70
101122 2017-01-08 0.0 49
101122 2017-04-13 0.02976 67
101122 2017-08-03 1.02565 39
101122 2016-12-01 0.0 46
101122 2017-01-25 0.0 69
101122 2017-01-02 0.0 76
101122 2017-07-18 0... | <p><strong><code>groupby</code></strong> with <strong><code>sum</code></strong></p>
<pre><code>d = df.groupby('id')['dnm'].sum()
</code></pre>
<p><strong><code>indexing</code></strong></p>
<pre><code>d[d > 500]
id
101122 574
221344 1050
Name: dnm, dtype: int64
</code></pre>
<p>If you want the column name... | python|pandas|dataframe | 5 |
375,718 | 50,471,122 | linalg.matrix_power(A,n) for a huge $n$ and a huge $A$ | <p>I'm trying to use linalg to find $P^{500}$ where $ P$ is a 9x9 matrix but Python displays the following:
<a href="https://i.stack.imgur.com/ll47k.png" rel="nofollow noreferrer">Matrix full of inf</a></p>
<p>I think this is too much for this method so my question is, there is annother library to find $P^{500}$? Must... | <p>Use the eigendecomposition and then exponentiate the matrix of eigenvalues. Like this. You end up getting an inf up in the first column. Unless you control the type of matrix by their eigenvalues this won't happen I believe. In other words, your eigenvalues have to be bounded. You can generate a random matrix by the... | numpy|linear-algebra|matrix-multiplication | 1 |
375,719 | 50,552,756 | From pandas dataframe, how to find the number of duplicate comments for each user? | <p>I have dataframe with list of usernames and their comments, see format below.</p>
<p>What would be the quickest and most efficient approach to find repetitive duplicate comments (spam) for each user? </p>
<p>Dataframe format: </p>
<pre><code>Author | Comment
casy Nice picture!
linda I like this
casy Ni... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a> first, then <... | python|pandas|dataframe | 4 |
375,720 | 50,251,750 | How to normalize a seaborn countplot with multiple categorical variables | <p>I have created a seaborn <code>countplot</code> for multiple categorical variables of a dataframe but instead of count I want to have percentages?</p>
<p>What is the best option to use? Barplots? Can I use a query like the below one to get the barplots at once?</p>
<pre><code>for i, col in enumerate(df_categorical... | <p>Consider a <code>groupby.transform</code> to calculate percentage column, then run <code>barplot</code> with <em>x</em> for original value column and <em>y</em> for percent column.</p>
<p><strong>Data</strong> <em>(only converted two No to Yes responses to original posted data)</em></p>
<pre><code>from io import S... | python|pandas|matplotlib|seaborn | 0 |
375,721 | 50,366,851 | Postpone function execution syntactically | <p>I've got a quite extensive simulation tool written in <code>python</code>, which requires the user to call functions to set up the environment in a strict order since <code>np.ndarrays</code> are at first created (and changed by appending etc.) and afterwards memory views to specific cells of these arrays are define... | <p>Using a generators here doesn't make much sense. You are essentially simulating partial-application. Therefore, this seems like a use-case for <code>functools.partial</code>. Since you are sticking with key-word only arguments, this will work just fine:</p>
<pre><code>In [1]: def fun1(*, x, y): # easy minimal exam... | python|numpy|generator|decorator | 3 |
375,722 | 50,660,820 | Transforming dates in chronological order using pandas dataframe | <p>I need help with comparing dates in different rows and in different columns and making sure that they follow a chronological order.</p>
<p>First, I group data based on <strong>Id</strong> and <strong>group</strong> columns. Next, each date value is supposed to occur in the future. </p>
<p>The first group [1111 + A... | <p>One way is to apply your logic to each group, then concatenate your groups.</p>
<pre><code># convert series to datetime
df['start'] = pd.to_datetime(df['start'])
df['end'] = pd.to_datetime(df['end'])
# iterate groups and add results to grps list
grps = []
for _, group in df.groupby(['id', 'group'], sort=False):
... | python|pandas|datetime|dataframe|pandas-groupby | 2 |
375,723 | 50,287,517 | Distributed tensorflow source code | <p>I wanted to check the source code of the distributed training feature of tensorflow and its overall structure. Worker-PS relations, etc. However I am lost in tensorflow's repository. Can someone guide me through the repository and point the source code I am looking for? </p> | <p>Unfortunately, not all tensorflow code (especially the part related to distributed computation) is open source. To quote Aurélien Géron from <a href="http://shop.oreilly.com/product/0636920052289.do" rel="nofollow noreferrer">Hands-On Machine Learning with Scikit-Learn and TensorFlow</a>:</p>
<blockquote>
<p>The ... | github|tensorflow|distributed-computing|distributed | 1 |
375,724 | 50,632,993 | trouble converting object to float | <p>I have an object that I would like to convert to a currency format:</p>
<pre><code>df_final.sum_funded.head()
0 472161.07
1 719768.97
2 23148.11
3 1215078.15
4 0
Name: sum_funded, dtype: object
</code></pre>
<p>I've tried numerous iterations, including:</p>
<pre><code>"${:,.0f}".form... | <p>You have to use pandas Series's <code>map</code> function to apply the formatter on <strong>each</strong> element.</p>
<pre><code>df_final.sum_funded.map("${:,.0f}".format)
</code></pre> | python|pandas|numpy | 2 |
375,725 | 50,265,938 | Select rows for a specific month in Pandas | <p>I have a dataframe with 12 hourly data for over 10 years. All data are stored in date wise. I would like to extract columns containing the data from a specific month (note that month is not in standard 1, 2, 3, format). The rows of the 'date' column which I have looks like this:</p>
<pre><code>01-May-07
02-May-07
.... | <p>I think need convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> and then compare with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="noreferrer"><code>month</code></a> or <a hr... | python|pandas | 12 |
375,726 | 50,308,569 | Switch fasta seq depending on a dataframe | <p>I have actually 2 fasta file named: </p>
<pre><code>result1_aa.fasta
result2_aa.fasta
</code></pre>
<p>In these files I have my sequences such :</p>
<p>file <code>result1_aa.fasta</code>:</p>
<pre><code>>gene1_B
ATTGGACCA
>gene2_A
ATTAGGAC
>gene90_B
ATTAGCCACA
>gene65_B
ATTGAG
</code></pre>
<p>file ... | <p>Let's do the first file. Again using <a href="http://biopython.org/wiki/SeqIO" rel="nofollow noreferrer">BioPython</a>, </p>
<pre><code>from Bio import SeqIO
results1 = list(SeqIO.parse("result1_aa.fasta", "fasta"))
results1 = pd.DataFrame({'f_id': [r.id for r in results1], 'f_seq': results1})
</code></pre>
<p>Now... | python-3.x|pandas|parsing|fasta | 2 |
375,727 | 50,237,486 | tf.data.Iterator.get_next(): How to advance in tf.while_loop? | <p>Currently I try to implement all training in a Tensorflow while loop, but I've got problems with the Tensorflow dataset API's Iterator.</p>
<p>Usually, when calling sess.run(), Iterator.get_next() advances to the next element.
However, I need to advance to the next element INSIDE one run. How do I do this?</p>
<p>... | <p>You need to call <code>iterator.get_next()</code> every time you want to "iterate inside one run".</p>
<p>For instance in your toy example, just replace your <code>body_op</code> with:</p>
<pre class="lang-python prettyprint-override"><code> body_op=lambda i: tf.Print(i, [iterator.get_next()], message="This is sam... | python|python-3.x|tensorflow | 2 |
375,728 | 50,547,249 | Tensorflow tutorial on MNIST | <p><a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">This</a> Tensorflow tutorial loads an already existing dataset (MNIST) into the code. Instead of that I want to insert my own training and testing images.</p>
<pre><code>def main(unused_argv):
# Load training and eval data
mnist = tf.con... | <p><em>1. How do I create such a numpy array for my own image set?</em></p>
<p>TensorFlow accepts data in multiple ways (tf.data, feed_dict, QueueRunner).
What you should be using is TFRecord which is accessible via tf.data API. It is also <a href="https://www.tensorflow.org/api_guides/python/reading_data" rel="nofoll... | python|numpy|tensorflow|deep-learning|tensor | 0 |
375,729 | 50,499,144 | Dynamically Change Lookback Period | <p>I am trying to dynamically adjust the lookback period of a pandas dataframe to run regressions on different lengths of stock data. As an easy example take an MA cross.</p>
<pre><code>date Prices Diff signal
20150101 8.5 -1.5 FALSE
20150101 11.5 0.3 TRUE
20150102 14.5 4.5 F... | <p>I have actually solved this problem, but the solution is not very elegant. If anyone has an elegant solution, please let me know.</p>
<pre><code> if diff[-1] > 0 and diff[-2] < 0:
signal = True
over_count += 1
under_count = 0
elif diff[-1] < 0 and diff[-2] > 0:
sig... | python|pandas | 0 |
375,730 | 50,447,683 | Merge 2 dataframe an add NaN if no hit | <p>I have 2 dataframes:</p>
<pre><code>qseqid sseqid pident length mismatch
seq1 seq24 78 789 45
seq2 seq12 73 790 44
seq3 seq34 12 77 42
seq4 seq90 70 790 41
</code></pre>
<p>and another one such:</p>
<pre><code>seq2_id tax_inf
seq3 Virus
... | <p>I believe you need,</p>
<pre><code> pd.merge(df1,df2.rename(columns={'seq2_id':'qseqid'}),on='qseqid',how='outer')
</code></pre> | python|pandas|merge | 1 |
375,731 | 50,594,318 | numpy array indicator operation | <p>I want to modify an empty bitmap by given indicators (x and y axis).
For every coordinate given by the indicators the value should be raised by one.</p>
<p>So far so good everything seems to work. But if I have some similar indicators in my array of indicators it will only raise the value once.</p>
<pre><code>>... | <p>This is one way. Counting algorithm <a href="https://stackoverflow.com/a/27001112/9209546">courtesy of @AlexRiley</a>.</p>
<p>For performance implications of relative sizes of <code>img</code> and <code>inds</code>, see <a href="https://stackoverflow.com/a/50594865/9209546">@PaulPanzer's answer</a>.</p>
<pre><code... | python|arrays|numpy | 6 |
375,732 | 50,424,151 | How to solve an equation which has a solution variable in form of function at both side of equation | <p>I want to plot a graph of an equation in Python which has a solution variable at both sides in form of some function.
The equation is:</p>
<pre><code>i = Ip - Io*(exp((V+i*R1)/(n*Vt)) - 1) - (V +I*R1)/(R2)
</code></pre>
<p>where <code>Ip, Io, n, R1, R2, Vt</code> are some constants.</p>
<p>I want to iterate <code... | <p>It seems, your problem is that you mix <code>numpy</code> arrays with a scalar <code>math</code> function. <a href="https://stackoverflow.com/questions/48226089/scipy-curve-fit-doesnt-like-math-module">Don't do this.</a> Substitute it with the appropriate <code>numpy</code> function:</p>
<pre><code>import numpy as ... | python|python-3.x|numpy|sympy | 1 |
375,733 | 50,521,987 | Match column values to dict | <p>I have a dict and a dataframe like the examples v and df below. I want to search through the items in df and return the item that has the maximum number of field values in common with the values in the dict. In this case it would be item 3. I was thinking maybe using apply with a lambda function, or transposing t... | <p>Create one line <code>DataFrame</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with original:</p>
<pre><code>a = pd.DataFrame(v, index=[0]).merge(df)['item']
print (a)
0 3
Name: item, dtype: int64
</code></pr... | python|python-2.7|pandas | 2 |
375,734 | 50,585,096 | Pandas Dataframe to_sql with a Decimal type | <p>My Dataframe won't send to a SQLite database using the "to_sql" method, when the datatype is Decimal:</p>
<pre><code>con = sqlite3.connect("test.db")
df = pd.DataFrame({"a":[decimal.Decimal(0)]})
df.to_sql(name="table", con=con)
</code></pre>
<p>error:</p>
<blockquote>
<p>sqlite3.InterfaceError: Error binding p... | <p>Hi I had the same problem, I solved it by converting the Decimal column in the Dataframe into a SQLAlchemy Numeric datatype:</p>
<pre><code>import pandas as pd
from sqlalchemy import Numeric
from sqlalchemy import create_engine
engine = create_engine("sqlite:////test.db")
df = pd.DataFrame({"a":[decimal.Decimal(0)... | python|pandas|sqlite | 2 |
375,735 | 50,660,949 | Moving a dataframe column and changing column order | <p>I have a dataframe called <code>df</code> which has the following columns header of data:</p>
<pre><code>date A B C D E F G H I
07/03/2016 2.08 1 NaN NaN 1029 2 2.65 4861688 -0.0388
08/03/2016 2.20 1 NaN NaN 1089 2 2.20 5770819 -0.0447
: ... | <p>Use <code>df.insert</code> with <code>df.columns.get_loc</code> to dynamically determine the position of insertion.</p>
<pre><code>col = df['F'] # df.pop('F') # if you want it removed
df.insert(df.columns.get_loc('H') + 1, col.name, col, allow_duplicates=True)
</code></pre>
<p></p>
<pre><code>df
date ... | python|pandas|dataframe | 9 |
375,736 | 50,349,209 | Excel query automation in pandas | <p>I am working on automation with Python. In one step, I need to take a column and check that only the required values are in the sheet. (We use filter in Excel and select the required values.)</p>
<p>What function in pandas can help me?</p> | <p>you can use pandas to achieve any tasks with a table. </p>
<pre><code> import pandas as pd
df = pd.read_csv('myexcelfile.xlsx')
df.filter(items=['one', 'three'])
</code></pre>
<p>for more on filter refrer [pandas filter]:<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fi... | python|pandas | 1 |
375,737 | 50,489,949 | How to split and store data from dataframe in pandas | <p>I have an Xl which as values mentioned below:</p>
<pre><code>KF <-- Col Name
Values:
Ab122323,pop
89,HG903434
FG903434,99
</code></pre>
<p>I need to split the values using ',' and then count the length of each value and just store the value which as len = 8 and store it as a list --> into an excel</p> | <p>You can use <code>pd.Series.apply</code> with a generator expression. You will meet a <code>StopIteration</code> error if an item of length 8 cannot be found.</p>
<pre><code>df = pd.DataFrame({'KF': ['Ab122323,pop', '89,HG903434', 'FG903434,99']})
df['Filter'] = df['KF'].apply(lambda x: next(i for i in x.split(','... | python|pandas|dataframe|split | 1 |
375,738 | 50,445,428 | Why did pandas give "0.66-0.36" when I tried to add two columns? | <p>I am trying to do a simple summation with column name <code>Tangible Book Value</code> and <code>Earnings Per Share</code>: </p>
<pre><code>df['price_asset_EPS'] = (df["Tangible Book Value"]) + (df["Earnings Per Share"])
</code></pre>
<p>However, the result doesn't evaluate the numbers and also the plus is missin... | <p><strong>Looks like both columns are strings (not float):</strong> </p>
<pre><code>0.66-0.36
1.440.0
</code></pre>
<p>see how <strong>'+' on those columns did string concatenation instead of addition</strong>? It concatenated "0.66" and "-0.36", then "1.44" and "0.0".</p>
<p>As to <strong>why</strong> those colum... | python|pandas | 2 |
375,739 | 50,295,457 | Euler rotation of ellipsoid expressed by coordinate matrices in python | <p>Objective: Apply an Euler rotation to an ellipsoid, then plot it using matplotlib and mplot3d.</p>
<p>I found a function which applies an Euler rotation to a vector or array of vectors:</p>
<pre><code>import numpy as np
from scipy.linalg import expm
def rot_euler(v, xyz):
''' Rotate vector v (or array of vectors)... | <p>While I don't think you can do much better than applying the rotation point-wise there still is room for significant economy.</p>
<p>(1) Using the matrix exponential to compute simple rotation matrices is ridiculously wasteful. Much better to use the scalar exponential or sine and cosine</p>
<p>(2) To a lesser ext... | python|numpy|matplotlib|rotation | 2 |
375,740 | 50,653,962 | pandas.read_excel with identical column names in excel | <p>When i import an excel table with pandas.read_excel there is a problem (or a feature :-) ) with identical column names. For example the excel-file has two columns named "dummy", after the import in a datframe the second column is named "dummy.1".
Is there a way to import without the renaming option ?</p> | <p>Now I don't see the point why you would want this. However, as I could think of a workaround I might as well post it.</p>
<p><a href="https://i.stack.imgur.com/mDjBF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mDjBF.png" alt="enter image description here"></a></p>
<pre><code>import pandas as... | python|excel|pandas | 3 |
375,741 | 50,348,640 | NP.max function error in Python 3 | <p>I am learning Background removal with OpenCV code from
<a href="http://www.codepasta.com/site/vision/segmentation/" rel="nofollow noreferrer">http://www.codepasta.com/site/vision/segmentation/</a></p>
<p>The error is from np.max</p>
<pre><code>edgeImg = np.max( np.array([ edgedetect(blurred[:,:, 0]), edgedetect(b... | <p>From the numpy documentation <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.maximum.html" rel="nofollow noreferrer">here</a>: <code>numpy.maximum</code> expects two input arrays as arguments:</p>
<pre><code>numpy.maximum(arr1, arr2)
</code></pre>
<p>Whereas <code>numpy.max</code> only r... | python|numpy|opencv | 3 |
375,742 | 50,558,768 | .how to get top 5 most occurring names in a column | <p>My Dataframe looks something like this.</p>
<p><img src="https://i.stack.imgur.com/8OuCu.png" alt="enter image description here"></p>
<p>I need to find top 5 most occurring names in Name column of this table </p> | <p>try</p>
<pre><code>Dataframe.Name.value_counts().head()
</code></pre> | python|python-3.x|pandas | 0 |
375,743 | 50,246,105 | Pandas - Resample/GroupBy DateTime Index and perform calculations | <p>I will try my best to explain what I need help with. I have the following df (thousands if not millions of rows) with a datetime index like the sample below:</p>
<pre><code>INDEX COL A COL B
2018-05-07 21:53:13.731 0.365127 9391.800000
2018-05-07 21:53:16.201 0.666127 9391.800000
2018-... | <p>I believe need for percentage of positive values need mean of values <code>>0</code>:</p>
<pre><code>df = df.resample('5S').agg({'COL A': lambda x: (x > 0).mean() * 100, 'COL B': 'min'})
print (df)
COL A COL B
INDEX
2018-05-07 21:53:10 1... | python|pandas|datetime|time-series | 3 |
375,744 | 50,645,240 | Pandas json_normalize fails with null values in JSON | <p>i have below json which i get from external webservice :</p>
<pre><code>text="""
[{
"id":"1",
"name" : "abc",
"address":{
"flat":"123",
"city":"paris",
"street":null
},
"error":null
}]
</code></pre>
<p... | <p>This appears to be a bug in the latest version of pandas:</p>
<p><a href="https://github.com/pandas-dev/pandas/issues/21158" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/21158</a></p>
<p>I'm running pandas '0.23.0' and I can reproduce the same error.
You can see in the github discussion th... | python|json|python-3.x|pandas | 1 |
375,745 | 50,464,140 | How to plot a power curve by following code? | <p>In the code, I tried to plot a graph Power(p) vs voltage (Vpv) but my code is not giving the result. </p>
<pre><code>import numpy as np
import math
from numpy import *
import matplotlib.pyplot as plt
plt.style.use('ggplot')
r = 50
Vpv = np.linspace(0,0.6,r) # Vpv = panel voltage
Rs = 0 # series resistance
Rsh = ... | <p>I have solved my problem. I got correct graphs.</p>
<pre><code>import numpy as np
import math
from numpy import *
import matplotlib.pyplot as plt
plt.style.use('ggplot')
r = 50
Vpv = np.linspace(0,1.1,r) # Vpv = panel voltage
Rs = 0 # series resistance
Rsh = math.inf # parallel resistance
n = 2 # ideality... | python|numpy|matplotlib|python-3.6 | 0 |
375,746 | 50,512,655 | Saving numpy arrays as a dictionary | <p>I'm saving 2 Numpy arrays as a dictionary.<br>
When I load the data from the binary file, I get another <code>ndarray</code>. Can I use the loaded Numpy array as a dictionary?
<br/>
<br/>
Here is my code and the output of my script:</p>
<pre><code>import numpy as np
x = np.arange(10)
y = np.array([100, 101, 102, 1... | <p>Yes, you can access the underlying dictionary in a 0-dimensional array. Try <code>z1[()]</code>.</p>
<p>Here's a demo:</p>
<pre><code>np.save('./data.npy', z)
d = np.load('./data.npy')[()]
print(type(d))
<class 'dict'>
print(d['X'])
[0 1 2 3 4 5 6 7 8 9]
</code></pre> | python|arrays|numpy|dictionary | 5 |
375,747 | 50,501,480 | How to create a DataFrame of a single column from a list where the first element is the column name in python | <p>I have the below data in a csv and I am trying to create a dataframe of 1 column by selecting each column from the csv at a time.</p>
<pre><code>sv_m1 rev ioip
0 15.31 40
0 64.9 0
0 18.36 20
0 62.85 0
0 10.31 20
0 12.84 10 ... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> here with <code>usecols</code> parameter for filter second column:</p>
<pre><code>df = pd.read_csv('df_seg_sample.csv', usecols=[1])
print (df)
rev
0 15.31
1 6... | python|list|pandas | 1 |
375,748 | 45,324,695 | TensorFlow error: "logits and labels must be same size", warmspringwinds "tutorial" | <p>I'm currently following this <a href="http://warmspringwinds.github.io/tensorflow/tf-slim/2016/12/18/image-segmentation-with-tensorflow-using-cnns-and-conditional-random-fields/" rel="nofollow noreferrer"> tutorial</a> and after I did some changes because of the tensorflow update, I got this error:</p>
<blockquote>... | <p>The error is raised because the number of logits is <code>399360</code> while you are providing to the function with <code>409920</code> labels. The function <code>tf.nn.softmax_cross_entropy_with_logits</code> expects one label for each logit, and it crashes because you are providing more labels than logits.</p>
<... | machine-learning|tensorflow|image-segmentation | 0 |
375,749 | 45,570,773 | How to input a condition into df.assign? | <p>I have the following datatype:</p>
<pre><code>id arrival_time departure_time start end capacity
Train A 0 2016-05-19 08:25:00 A B 2
Train A 2016-05-19 13:50:00 2016-05-19 16:00:00 B H 2
Train A 2016-05-19 21:25:00 2016-05-20 07:2... | <p>It's kind of hazy what your question is, so I'll just address the error you have been getting.</p>
<p>Your n1 calculation hinges on an expression <code>statement 1 & statement 2</code>, if you have written it correctly. Right now it executes: <code>df['end'] == (df['start'.shift() & df.timediff.dt.seconds /... | python|pandas | 0 |
375,750 | 45,428,574 | Actor-Critic model never converges | <p>I'm trying to implement Actor-Critic using Keras & Tensorflow.
However, it never converges and I can't figure out why. I decreased the learning rate but it did not change.</p>
<p><em>The code is in python3.5.1 and tensorflow1.2.1</em></p>
<pre><code>import gym
import itertools
import matplotlib
import numpy as... | <p>First obvious thing is wrong gradient being stopped in advantage:</p>
<pre><code>advantage = tf.stop_gradient(target) - state_value
</code></pre>
<p>should be</p>
<pre><code>advantage = target - tf.stop_gradient(state_value)
</code></pre>
<p>Since there is no gradient for target either way (it is a constant) and... | python|tensorflow|deep-learning|keras|reinforcement-learning | 1 |
375,751 | 45,709,488 | If one row in two columns contain the same string python pandas | <p>I have a dataframe looking like this:</p>
<pre><code> id k1 k2 same
1 re_setup oo_setup true
2 oo_setup oo_setup true
3 alerting bounce false
4 bounce re_oversetup false
5 re_oversetup alerting false
6 alerting_s re_setup... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a>, b... | python|string|pandas|dataframe | 4 |
375,752 | 45,429,652 | How do I repeat or tile a numpy array but change the value in one element each time it is tiled? | <p>Let's say there is a numpy array
<code>a = [1,1,1,0]</code></p>
<p>I want to tile or repeat this array 3 times, but make the last element increase by 1 every time it is tiled/repeated.</p>
<p>That is, I want </p>
<pre><code>result = [[1,1,1,0], [1,1,1,1], [1,1,1,2]]
</code></pre>
<p>in the end.</p>
<p>I think ... | <pre><code>import numpy as np
a = np.array([1, 1, 1, 0])
#how often to repeat the array along first dimension?
b = 20
#repeat b times along first dimension, one time along second
x = np.tile(a, (b,1))
print(x)
#just some consecutive numbers
y = np.arange(20)
print(y)
#overwrite fourth column of array
x[:, 3] = y... | numpy|repeat|tile | 4 |
375,753 | 45,538,740 | How to let Tensorflow object detection api use gray image to train(just 1 channel for input tensor)? | <p>I just want to get real time speed when using model trained by tensorflow object detection api, the input tensor has shape[1, width, height,3], it is 3 channels,but I think if I can just use 1 channel to train my model, it just need gray images as input, therefore , this can reduce the computational complexity, whic... | <p>We don't have any pretrained models that do one channel images. If you're interested in creating a new model, consider adding a new <a href="https://github.com/tensorflow/models/blob/4f32535fe7040bb1e429ad0e3c948a492a89482d/research/object_detection/g3doc/defining_your_own_model.md#defining-a-new-faster-r-cnn-or-ssd... | tensorflow|object-detection | 2 |
375,754 | 45,577,884 | Pandas value counts save output to file | <p>I use pandas's value_counts() method to get the number of times each value in a column appears. Although the output looks like what I expected, attempting to save it using numpy savetxt or pandas to_csv returns only one column (with counts). I'd like to be able to save both.</p> | <p>One way would be to use reset_index and then to_csv</p>
<pre><code>df['key'].value_counts().reset_index().to_csv('df.csv')
</code></pre> | pandas|numpy | 14 |
375,755 | 45,293,449 | Creating a New Numpy Array from Elements in a Numpy Array | <p>Can't seem to figure this one out. Very new to numpy.</p>
<p>I have a numpy array of shape <code>(200,1,1000,1000)</code> which corresponds to (number of images, channel, x_of_image, y_of_image). So I have 200 images with 1 channel that are 1000x1000 pixels each.</p>
<p>I want to take each of the 200 images <code>... | <p>Avoid calling <code>np.concatenate</code>in a loop. It allocates a new array and copies everything. This is slow and you may run into memory problems if the discarded copies pile up without being garbage collected.</p>
<p>How this should be done depends mostly on the operations you perform on the images. Most numpy... | image|numpy | 3 |
375,756 | 45,527,627 | Pandas copy dataframe keeping only max value for rows with same index | <p>If I have a dataframe that looks like</p>
<pre><code> value otherstuff
0 4 x
0 5 x
0 2 x
1 2 x
2 3 x
2 7 x
</code></pre>
<p>what is a succinct way to get a new dataframe that looks like</p>
<pre><code> value otherstuff
0 5 ... | <p>You can use <code>max</code> with <code>level=0</code>:</p>
<pre><code>df.max(level=0)
</code></pre>
<p>Output:</p>
<pre><code> value otherstuff
0 5 x
1 2 x
2 7 x
</code></pre>
<p>OR, to address other columns mentioned in comments:</p>
<pre><code>df.groupby(level=0,gr... | python|pandas|dataframe | 5 |
375,757 | 45,608,960 | tensorflow multi gpu tower error: loss = tower_loss(scope) . ValueError: Variable tower_1/loss/xentropy_mean/avg/ does not exist | <p>When I use multi gpu in tensorflow, and Errors came out as follows:</p>
<pre><code> Traceback (most recent call last):
File "multi_gpu_train.py", line 290, in <module>
tf.app.run()
File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.arg... | <p>I have found the answer, The code below is a old version, and the newest code is posted in <a href="https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu... | tensorflow|multi-gpu | 1 |
375,758 | 45,368,931 | cost function outputs 'nan' in tensorflow | <p>While studying the tensorflow, I faced a problem.<br>
The cost function output 'nan'. </p>
<p>And, if you find any other wrong in source code let me know the links for it.</p>
<p>I am trying to send the cost function value to my trained model, but its not working.</p>
<pre><code>tf.reset_default_graph()
tf.set_... | <p>You use a cross entropy loss without a sigmoid activation function to <code>hypothesis</code>, thus your values are not bounded in ]0,1]. The log function is not defined for negative values and it most likely get somes. Add a sigmoid and epsilon factor to avoid negative or 0 values and you should be fine.</p> | python|tensorflow|neural-network|deep-learning | 4 |
375,759 | 45,607,589 | Resetting the shape of input placeholder in a tensorflow meta graph | <p>I trained a neural network in tensorflow. At the time of training, I explicitly defined the shape of my input placeholder for a batch size of 20, like this <code>[20,224,224,3]</code>. I defined the batch size explicitly because thee was a <code>split</code> layer in the network and passing <code>None</code> as a ba... | <p>If you have the *.meta file of saved checkpoint you can reset the input to the graph.</p>
<pre><code># Set the correct data type and shape; shape can be (None, 224, 224, 3) also
new_placeholder = tf.placeholder(tf.float32, shape=(1, 224, 224, 3), name='inputs_new_name')
# here you need to state the name of the pla... | machine-learning|tensorflow|neural-network|deep-learning|conv-neural-network | 3 |
375,760 | 45,365,300 | sk-learn saved model to disk, but get only array | <p>When storing a <code>fitted_clf</code> sk-learn classifier like:</p>
<pre><code>joblib.dump(fitted_clf, some_path)
</code></pre>
<p>Most of the time when loading it back into memory like:</p>
<pre><code>joblib.load(some_path)
</code></pre>
<p>only an array of <code>array(['col1', 'col2], dtype=object)</code> is ... | <p>confirmed. Using <code>sklearn.externals import joblib</code> is fixing this to have consistent behavior.</p> | python|numpy|scikit-learn|pickle|joblib | 4 |
375,761 | 45,332,960 | Interweave two dataframes | <p>Suppose I have two dataframes <code>d1</code> and <code>d2</code></p>
<pre><code>d1 = pd.DataFrame(np.ones((3, 3), dtype=int), list('abc'), [0, 1, 2])
d2 = pd.DataFrame(np.zeros((3, 2), dtype=int), list('abc'), [3, 4])
</code></pre>
<hr>
<pre><code>d1
0 1 2
a 1 1 1
b 1 1 1
c 1 1 1
</code></pre>
<h... | <p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>pd.concat</code></a> to combine the DataFrames, and <a href="http://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.interleave" rel="noreferrer"><code>toolz.interleave</code></a> reorder the colum... | python|pandas|numpy|dataframe | 20 |
375,762 | 45,645,276 | Negative dimension size caused by subtracting 3 from 1 for 'conv2d_2/convolution' | <p>I got this error message when declaring the input layer in Keras.</p>
<blockquote>
<p>ValueError: Negative dimension size caused by subtracting 3 from 1 for
'conv2d_2/convolution' (op: 'Conv2D') with input shapes: [?,1,28,28],
[3,3,28,32].</p>
</blockquote>
<p>My code is like this</p>
<pre><code>model.add(C... | <p>By default, Convolution2D (<a href="https://keras.io/layers/convolutional/" rel="noreferrer">https://keras.io/layers/convolutional/</a>) expects the input to be in the format (samples, rows, cols, channels), which is "channels-last". Your data seems to be in the format (samples, channels, rows, cols). You should be ... | python|tensorflow|neural-network|keras|keras-layer | 45 |
375,763 | 45,447,182 | python, numpy - in an array of string, compare element with previous for equality | <p>Let's consider the following array:
<code>x = np.array(["john", "john", "ellis", "lambert", "john"])</code></p>
<p>Is there a way to compare every element of the array to the previous and return a boolean array.
In the present example, the result would be <code>[True,False,False,False]</code>.</p>
<p>Is there any ... | <p>You can do this with indexing:</p>
<pre><code>array[:-1] == array[1:]
</code></pre> | python|numpy | 3 |
375,764 | 45,335,053 | Reverse string columns in a pandas subset dataframe | <p>I have the following dataframe. </p>
<pre><code> ID LOC Alice Bob Karen
0 1 CH 9|5 6|3 4|4
1 2 ES 1|1 0|8 2|0
2 3 DE 2|4 6|6 3|1
3 4 ES 3|9 1|2 4|2
</code></pre>
<p>Alice and Bob columns contain string values. I want to reverse the strings in these columns conditional on the value of ano... | <pre><code>#cols = ['Alice','Bob']
In [17]: cols = df.columns.drop(['ID','LOC'])
In [18]: df.loc[df.LOC=='ES', cols] = df.loc[df.LOC=='ES', cols].apply(lambda x: x.str[::-1])
In [19]: df
Out[19]:
ID LOC Alice Bob Karen
0 1 CH 9|5 6|3 4|4
1 2 ES 1|1 8|0 0|2
2 3 DE 2|4 6|6 3|1
3 4 ES 9|... | python|string|pandas|reverse | 5 |
375,765 | 45,288,990 | why does .str method change the shape of a pandas' series? | <h1>the type of the data</h1>
<pre><code> In [1]: print(type(ebola_melt))
<class 'pandas.core.frame.DataFrame'>
</code></pre>
<h1>the column of interest is created such this</h1>
<pre><code> In [2]: ebola_melt['str_split'] = ebola_melt['type_country']
.str.split('_')
In [3]: print(type(ebola_... | <p>pandas.Series.str.get extracts elements from lists in the Series/Index.</p>
<p>pandas.Series.get gets items from object for a given index value</p>
<p>Please refer documentation
<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get.html" rel="nofollow noreferrer">https://pandas.pyda... | python|pandas|dataframe | 0 |
375,766 | 45,444,606 | Creating a standalone file using Pandas code | <p>I have little to no background in Python or computer science so I’ll try my best to explain what I want to accomplish. I have a Pandas script in Jupyter notebook that edits an Excel .csv file and exports it as an Excel .xlsx file. Basically the reason why we want to do this is because we get these same Excel spreads... | <p>First, you need to change some parts in your code to make it work for anybody, without the need for them to edit the Python code.
Secondly, you will need to convert your file to an executable (.exe).</p>
<p>There is only one part in your code that needs to be changed to work for everyone: the csv file name and dire... | python|excel|pandas | 1 |
375,767 | 45,469,953 | Lookup values from one dataframe in multiple columns of another dataframe? | <p>I currently have a dataframe (df1) with one columns being a list of numbers. I want to look up those numbers in another dataframe (df2) that has two integer columns and see if the number from df1 falls in between the range of those two columns and get the data from the matching row. Below is my current approach, is ... | <p>Basic use of <code>.loc</code> and boolean array logic : </p>
<pre><code># parentheses are mandatory here
result = df2.loc[(df1.num < df2.end) & (df1.num > df2.start), "organization_name"]
</code></pre>
<p>Test with Minimal Wirking Example : </p>
<pre><code>df1 = pd.DataFrame(np.random.randint(0, 10, 5)... | pandas|dataframe | 2 |
375,768 | 45,465,117 | Reverse every other row in TensorFlow | <p>Given a tensor <code>input</code> of undefined shape <code>H x W</code>, I would like to reverse every other row.</p>
<p>In numpy, I would simply do</p>
<pre><code>input[1::2, :] = input[1::2, ::-1]
</code></pre>
<p>but this is apparently not possible in TensorFlow.</p>
<p>Note that the input shape is only <em>p... | <p>You can achieve the same using placeholder</p>
<pre><code>input = tf.placeholder(shape=(None, None), dtype=tf.int32)
# define axis to reverse
axis_to_reverse=1
input_reversed = tf.reverse(input, [axis_to_reverse])
sess = tf.Session()
_input_reversed = sess.run(input_reversed, {input: your array})
</code></pre> | python|tensorflow | 0 |
375,769 | 45,385,661 | Object Detection API - How to create an Ensemble of trainings? | <p>I already created an Ensemble for classification (average -or so- of predictions per images), or for Semantic Segmentation (average -or so- of predictions per pixels), but I don't really know how to proceed for Object Detection.. My guess would be to extract all the region proposals of all my networks, then to run m... | <p>That's the basic idea, yes (the Resnet paper has a good explanation of how this is done for Faster R-CNN). Unfortunately we haven't released code to automate this ensembling process (and don't have any plans to). It's possible of course; you will have to manually set this up yourself.</p> | tensorflow|object-detection|ensemble-learning | 2 |
375,770 | 45,366,998 | AWS Jupyter Notebook EC2 Instance: Getting error while reading pandas csv from S3 | <p>While reading a CSV from S3, the kernel is restarting with the below pop up:</p>
<pre><code>Kernel Restarting
The kernel appears to have died. It will restart automatically
</code></pre>
<p>Below is the code snippet:</p>
<pre><code>import boto3
import pandas as pd
from boto.s3.connection import S3Connection
YOUR... | <p>It appears to be the bug with pyTorch.</p>
<p><a href="https://github.com/jupyter/notebook/issues/2784" rel="nofollow noreferrer">https://github.com/jupyter/notebook/issues/2784</a></p>
<p>Alternatives and multiple solutions discussed around there, the ticket is still open.</p>
<p>Hope it helps.</p> | python|pandas|amazon-web-services|amazon-s3|jupyter-notebook | 0 |
375,771 | 45,444,705 | sympy expression that lambdify's to numpy maximum | <p>I'd like to create a sympy expression that lambdify's to numpy.maximum(). How can I do this? Attempt:</p>
<pre><code>import numpy as np
import sympy
x = sympy.Symbol('x')
expr = sympy.Max(2, x)
f = sympy.lambdify(x, expr)
f(np.arange(5))
</code></pre>
<p>This leads to:</p>
<pre><code>ValueError: setting an array ... | <p>The maximum of two numbers x, y is the same as <code>(x+y+abs(x-y))/2</code>. And <code>abs</code> lambdifies easily: </p>
<pre><code>expr = (x + 2 + sympy.Abs(x-2))/2
f = sympy.lambdify(x, expr)
f(np.arange(5)) # prints [ 2. 2. 2. 3. 4.]
</code></pre> | numpy|sympy | 2 |
375,772 | 45,550,006 | Different x values with sharex | <p>I have two time indexed Series, and I want to plot them and share the x axis (the range of FEATURE contains the range of X):</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import datetime
start = pd.Timestamp('2017-01-01 08:00:00')
end = pd.Timestamp('2017-01-01 10:00:00')
X = pd.Series([1, 2, ... | <p>A possible solution is to plot the data with matplotlib instead of using the pandas plot wrapper.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
start = pd.Timestamp('2017-01-01 08:00:00')
end = pd.Timestamp('2017-01-01 10:00:00')
X = pd.Series([1, 2, 3],
... | pandas|matplotlib | 1 |
375,773 | 45,477,265 | how to sum by different level with a dict in python | <p>e.g.:</p>
<pre><code>example = {
'1': nan, '1.1': nan, '1.1.1': nan, '1.1.1.1': 3.45,
'1.1.1.2': 6.72, '1.1.1.3': 2.89, '1.1.1.4': 4.62,
'1.1.2': 5.35, '1.1.3': 1.21, '1.1.4': 9.86,
'1.2': 3.36, '1.3': 8.92
}
</code></pre>
<p>Of course it is only a part. The whole has 5 level at most.</p>
<p>I wan... | <p>You can create <code>Series</code> first and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow noreferrer"><code>Series.groupby</code></a> by count of <code>.</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.h... | python|pandas | 0 |
375,774 | 62,679,353 | Docker GPU enabled version (>19.03) does not load tensorflow successfully | <p>I want to use docker 19.03 and above in order to have GPU support. I currently have docker 19.03.12 in my system. I can run this command to check that Nvidia drivers are running:</p>
<pre><code>docker run -it --rm --gpus all ubuntu nvidia-smi
Wed Jul 1 14:25:55 2020
+-----------------------------------------... | <p><strong>tldr;</strong></p>
<p>A base Dockerfile which seems to work with docker 19.03+ & cuda 10 is this:</p>
<pre><code>FROM nvidia/cuda:10.0-base
</code></pre>
<p>which can be conbined with tf 1.14 but for some reason could not found tf 1.15.</p>
<p>I just used this Dockerfile to test it:</p>
<pre><code>FROM n... | docker|tensorflow | 1 |
375,775 | 62,849,131 | filtering data in pandas where string is in multiple columns | <p>I have a dataframe that looks like this:</p>
<pre><code>team_1 score_1 team_2 score_2
AUS 2 SCO 1
ENG 1 ARG 0
JPN 0 ENG 2
</code></pre>
<p>I can retreive all the data from a single team by using:
<strong>#list specifiying team of interest</strong></p>
<pre><code>team = ['E... | <pre><code>new_df_1 = df[df.team_1 =='ENG'][['team_1', 'score_1']]
new_df_1 =new_df_1.rename(columns={"team_1":"team", "score_1":"score"})
# team score
# 0 ENG 1
</code></pre>
<h3></h3>
<pre><code>new_df_2 = df[df.team_2 =='ENG'][['team_2', 'score_2']]
new_df_2 = new_d... | python|pandas|dataframe | 1 |
375,776 | 62,662,468 | Pandas set date as day(int)-month(str)-year(int) | <p>I am trying to change the formatting of a date column</p>
<p>original: 2020/05/22</p>
<p>Desired outcome: <strong>22/may/2020</strong></p>
<p>so far I've done:</p>
<p><code>.to_datetime</code></p>
<p><code>dt.strftime('%d-%m-%Y')</code></p>
<p>converting into: 22/05/2020</p>
<p>how can I get the middle part to conve... | <p>Try this, all the format codes are given here <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">date formats</a>:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%b/%Y')
print(df)
Date
0 22/May/2020
</code></pre> | python-3.x|pandas | 1 |
375,777 | 62,705,854 | np Select Rows that Match Edning | <p>I have a numpy 2-D array with rows as observations and columns as covariates. I would like to select the rows that match a specified example of the last <em>n</em> columns. For example with n=2:</p>
<p><code>A = [[0,1,0],[3,0,1],[5,1,0]]</code> with <code>target=[1,0]</code> would return <code>B = [[0,1,0],[5,1,0]]<... | <pre><code>import numpy as np
A = np.array([[0,1,0],[3,0,1],[5,1,0]])
target = [1,0]
B = A[(A[:, -len(target):] == target).all(axis=1)]
print(B)
# [[0 1 0]
# [5 1 0]]
</code></pre>
<p><strong>Explanation</strong></p>
<pre><code>print(A[:, -len(target):])
# [[1 0]
# [0 1]
# [1 0]]
print(A[:, -len(target):] == target... | python|numpy | 3 |
375,778 | 62,506,502 | Only want to consider a dataframe up to the present point | <p>I have a dataframe and I am trying to do something along the lines of</p>
<pre><code>df['foo'] = np.where(myfunc(df) == 1, 10, 20)
</code></pre>
<p>but I only want to consider the dataframe up to the present, for example if my dataframe looked like</p>
<pre><code> A B C
1 0.3 0.3 1.6
2 0.6 0.6 0.4
3 ... | <p>It is certainly possible. The dataframe up to the present is given by</p>
<pre><code>df.iloc[:present],
</code></pre>
<p>and you can do whatever you want with it, in particular, use <code>where</code>, as described here: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html... | python|pandas | 0 |
375,779 | 62,543,116 | Pandas append if groupby sum condition is met | <p>Apologies if this is a repeated question Im not sure the specific syntax of what I want to do.</p>
<p>I would like to iterate through large df where A and B are Index values and x,y,z are data columns</p>
<pre><code>df=
A B x y z
0.1 0.2 2 2 0
0.1 0.3 1 3 0
0.1 0.4 3 3 0
0.2 0.2 4 1 -1
0.2 0.3 5 ... | <p>Do a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> using <code>level=0</code> in combination with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="nofollow ... | python|pandas | 0 |
375,780 | 62,550,733 | Pandas aggregate - Counting values over x | <p>I'm playing around with a data set and everything is sailing smoothly. I'm currently having an issue with generating a count of values over the value of 0.</p>
<p>What I have is:</p>
<pre><code>zz = g.aggregate({'Rain':['sum'],'TotalRainEvent':['max'],'TotalRainEvent':['count']})
print(zz)
</code></pre>
<p>Which ret... | <p>How about you do <code>g = g.replace(0,np.nan)</code> at the beginning and <code>g = g.replace(np.nan, 0)</code> at the end? I don't think np.nan values will be counted, per documentation.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.aggregate.html" rel="nofollow norefe... | python-3.x|pandas|dataframe | 1 |
375,781 | 62,838,401 | How can I add a random catergory to a dataframe? | <p>I can't figure this out. I am doing some testing and trying to add random categories into a dataframe for testing but when I do it, it adds it for the all rows instead of randomly distributing it.</p>
<p>Here's my code:</p>
<pre><code>import random
catergory = ['dog', 'cat', 'monkey']
df['animal'] = random.choice(ca... | <p>Use <a href="https://docs.scipy.org/doc//numpy-1.15.0/reference/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>np.random.choice</code></a> along with <code>size</code> equal to length of dataframe to generate a random sample of given size:</p>
<pre><code>df['animal'] = np.random.choice(catergory... | python|pandas | 4 |
375,782 | 62,665,001 | Why are there two sets of polynomial tools in numpy? Is one preferable to the other, or is it purely opinion? | <p><code>numpy</code> has two sets of polynomial tools, one in the base numpy library, and another in <code>numpy.polynomial</code>. Why are there two? Is one preferable over the other? Is this to maintain backwards compatibility perhaps, or are there significant differences I should be aware of?</p>
<p>For example, <c... | <p>I ran across this in the <a href="https://numpy.org/doc/stable/reference/routines.polynomials.html" rel="nofollow noreferrer">docs</a>:</p>
<blockquote>
<p>Prior to NumPy 1.4, numpy.poly1d was the class of choice and it is still available in order to maintain backward compatibility. However, the newer Polynomial pac... | python|numpy|polynomials | 0 |
375,783 | 62,874,134 | Optimizing an edge search | <p>I have an Pandas dataframe in which I store binary data in an column of ~360.000 entries.
I am looking for a way to find the changes between 0 -> 1 and 1 -> 0 in a more efficient way.</p>
<p>Currently I iterate through it and check for the specific conditions by evaluating it for each index, which is maybe qui... | <p>The method you mentioned will indeed yield quite slow results for large sets of data, due to the way that append() methods interact with memory. Essentially you are rewriting the same part of memory ~360,000 times, extending it with a single entry. You can speed this up significantly by converting to numpy arrays an... | python|pandas|list|search|optimization | 0 |
375,784 | 62,620,832 | How to use query inside a function and apply to other dataframes? | <p>I have a dataframe user and calls where common column is user_id. I need to drop values in user dataframe where churn is not null and remove those user_id rows in calls.</p>
<pre><code>users = user_id,first_name,last_name,age,city,reg_date,plan,churn_date
1000,Anamaria,Bauer,45,"Atlanta-Sandy Springs-Roswell, G... | <p>You can try with simple filtering using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>.query</code></a></p>
<pre><code>def filter_calls_df(user_id_df, calls_df):
# filter out churn user_id
usr_id = user_id_df.query("chur... | python|pandas|numpy|data-science | 0 |
375,785 | 62,574,697 | Complicated JSON to Pandas Dataframe | <p>I have a somewhat complicated json structure</p>
<pre><code>[
{
"name": "iphone 6",
"vol": 1600,
"keywords": [
{
"positions": [
{
"date": "2020-06-18&qu... | <p>If <code>results</code> is your json (dictionary):</p>
<pre><code>rows = []
for item in result:
row = {
'Keyword Name': item['name'],
'Volume': item['vol']
}
for idx, pos in enumerate(item['keywords'][0]['positions'], 1):
row[f"Date {idx}"] = pos["pos"]... | python|json|python-3.x|pandas|dataframe | 2 |
375,786 | 62,639,478 | Split column of list of names into all combinations of initials | <p>I have a dataframe with a column "First names" e.g. John Richard.
I want to look for all 4 combinations of name + initial and store it in a seperate column. So in this case I would want to return [(J R, John R, J Richard, John Richard)]. I know I could write a for loop and loop over each element of the lis... | <p>Yes, python has efficient <code>itertools</code> implementation:</p>
<pre><code>import pandas as pd
from itertools import product
df = pd.DataFrame([['John Richard'],['John Fitz Kennedy']],columns=['name'])
def cart_prod(lst):
for i in range(len(lst)): lst[i] = [lst[i],lst[i][0]]
return [" ".join... | pandas|dataframe|split|names | 0 |
375,787 | 62,479,022 | Pandas Create DF for Table | <p>i'm trying to create a table but first a DF that has the elements i need for the table and I get this error: </p>
<pre><code>File "<ipython-input-400-241c1509eba9>", line 4, in <module>
[c1.iloc[:,1]],
TypeError: 'module' object is not callable
</code></pre>
<p>This is the command I'm using to create ... | <p>To create the new dataframe <code>c1t</code> the same as <code>c1</code> but with an index you can assign it (which returns a copy) and set the index on this copy:</p>
<pre><code>c1t = c1.set_index(pd.Index(["50-75%", "75-90%", "90-110%","110-125%","125-150%"], name=... | pandas|format|callable | 0 |
375,788 | 62,751,785 | How can I modify the single row in a Datafram while it is returning multiple rows at a time? | <p>I have a Dataframe with two columns, i.e, Transaction, & Status.</p>
<p>Expected Dataframe:</p>
<pre><code>Transaction | Status
-------------------------
57230477 | Completed
57232288 | Completed
57232288 |
57232288 |
57228666 | Completed
57229869 | Completed
57233318 | Complet... | <p>One way is to use <code>drop_duplicates</code> and get the index, then assign directly:</p>
<pre><code>df.loc[df.drop_duplicates(keep="first").index, "Status"] = "Completed"
print (df)
Transaction Status
0 57230477 Completed
1 57232288 Completed
2 57232288 ... | python|python-3.x|pandas|dataframe | 3 |
375,789 | 62,699,592 | TypeError: unsupported operand type(s) for |: 'float' and 'bool' for if else condition | <p>I know this topic has been discussed a lot like <a href="https://stackoverflow.com/questions/49364654/typeerror-unsupported-operand-types-for-str-and-bool">TypeError: unsupported operand type(s) for |: 'str' and 'bool'</a>,
but I found no one can solve my question.
I have a massive dataframe:
one col... | <pre><code>df['Returns'] = 0
df.loc[(df['Closed P/L'] != 0) & (df['Floating P/L'] != 0), 'Returns']
= df['New_Balance']/df['New_Balance'].shift(1) - 1
</code></pre> | python|pandas|dataframe | 2 |
375,790 | 62,638,658 | Calculating time difference between two different date formats in Python | <p>I am trying to identify hours between two dates. Date format is not consistent between two columns</p>
<p>The below code works when the date format is similar. How can I convert the UTC date format into normal date month year</p>
<pre><code>df['timebetween'] = (pd.to_datetime(df['datecolA'],dayfirst = True) - pd.to_... | <p>I think you need to remove <code>UTC</code> from <code>datecolB</code>:</p>
<pre><code>df['datecolB'] = df.datecolB.dt.tz_localize(None)
# or extract the time delta directly
df['timebetween'] = (df.datecolA - df.datecolB.dt.tz_localize(None))/np.timedelta64(1,'h')
</code></pre>
<p>Output:</p>
<pre><code> ... | python|pandas|datetime-format|python-datetime | 0 |
375,791 | 62,620,819 | NumPy - formatting two arrays to one multi-dimensional array | <p>I have the following values:</p>
<pre><code>grade_list = [[99 73 97 98] [98 71 70 99]]
excercise_list = ['1' '2']
</code></pre>
<p>Using Numpy, I want to convert it to one multidimensional array to have the average grade for each exercise (the first item in grade_list refers to the exercise number 1)</p>
<p>The outp... | <p>Axis 0 is the first nesting level (the two lists), axis 1 is the second level (four grades per entry in axis 0). You want to compute the mean along axis 1, so that axis 0 remains. So the mean grades are</p>
<p><code>mean_grades = np.mean(grade_list, axis=1)</code>.</p>
<p>Then you stack the two lists in another nest... | python|numpy | 0 |
375,792 | 62,665,293 | How to extract only cetain part of a column | <p>I have a dataframe that looks like below.I want to keep only first percentage from column 3 and 4. How can this be achieved.Any help is appreciated</p>
<pre><code>Metric Group Metric Type Tue23rd Week24
Productive % Available 83.2%Best Class:D7-92.6% 92.6%... | <p>You can use the built in <code>pd.Series.str.extract</code> method using regex:</p>
<pre><code>df["Tue23rd"].str.extract("([0-9\.%]+)Best")
</code></pre> | python|pandas | 0 |
375,793 | 62,634,062 | How to export from NetwokX / OSMnx and back? | <p>I want to be able to export a graph made by OSMnx (in other words, NetworkX graph) into CSV and to call it back later. Couldn't find any good way to do that so I try to export it into Numpy / Pandas and to export that.
So I built this little example:</p>
<pre><code>import networkx as nx
import osmnx as ox
G = ox.gra... | <p>The osmnx graph's nodes look like this:</p>
<pre><code>G.nodes(data=True)
NodeDataView({970069268: {'y': 32.0682358, 'x': 34.841011, 'osmid': 970069268}, 970069273: {'y': 32.0722176, 'x': 34.8442006, 'osmid': 970069273}, 970069285: {'y': 32.0695886, 'x': 34.8419506, 'osmid': 970069285, 'highway': 'mini_roundabout'}... | python|pandas|numpy|networkx|osmnx | 2 |
375,794 | 62,641,136 | How can I fill missing value in a particular case? | <p>I have a Dataframe which has two columns 'Key_Skills and 'Job_Title',(both of the column containing few missing values). Now, I want to impute '(Null) Key_Skills' value with the 'Job_Title' column which has filled 'Key_Skills' values.</p>
<p><a href="https://i.stack.imgur.com/IWjUb.png" rel="nofollow noreferrer"><im... | <p>I am not sure if i completely understand, but if I am interpreting this correctly the code below should work. What the code below does is group by job title, and if there are any NaN's as a skill set for the same title, it will fill it in. If you wanted to do it specifically for Account Manager, use the ffill and bf... | python|pandas|dataframe|missing-data | 0 |
375,795 | 62,720,605 | Average datetime.time Series | <p>I am trying to figure out the best way to average a series of <code>datetime.time</code> values with about 40 records in the format of <code>23:19:30</code> or <code>HH:MM:SS</code>, however, when I attempt to use the <code>to_timedelta</code> method and apply <code>.mean()</code> I run into an error:</p>
<pre><code... | <p><code>pd.to_timedelta</code> accepts strings in H:M:S format as input, so you could convert your column with datetime.time objects to string first. Ex:</p>
<pre><code>from datetime import time
import pandas as pd
df = pd.DataFrame({'t':[time(1,2,3), time(2,3,4), time(3,4,5)]})
pd.to_timedelta(df['t'].astype(str)).... | pandas|datetime|time | 1 |
375,796 | 62,565,448 | standardizing data column-wise before using keras models | <p>I'm working with a large dataset whose data I want to standardize to use with a CNN.</p>
<p>Does keras have a quick utility to standardize a block of numbers column-wise that you can use inside a Sequential model? I'm asking this as i expect eventually the data to be used on-line so ideally this standardization feat... | <p>I am not sure about online, but using <code>sklearn</code>'s <code>StandardScaler()</code> should do the right thing, as described <a href="https://stackoverflow.com/questions/43816718/keras-regression-using-scikit-learn-standardscaler-with-pipeline-and-without-pip">here</a>, seems like the right thing.</p> | python|pandas|numpy|keras | 1 |
375,797 | 62,837,561 | Pandas Remove Outliers from DataFrame | <p>I am following the below logic,</p>
<pre><code>from scipy import stats
df = pd.DataFrame(np.random.randn(100, 3))
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]
</code></pre>
<p>My df has multiple columns included value1, value2, description, task, etc. so I am having trouble dealing with A) half of my columns be... | <p>You can use <code>loc</code> to filter the dataframe based on only the value1 column like this</p>
<pre><code>df.loc[np.abs(stats.zscore(df['value1'])) < 3]
</code></pre> | python|pandas | 0 |
375,798 | 62,583,490 | Label areas within an image with Tensorflow | <p>I am new to the whole realm of machine learning, but I do have some prior experience with AWS' Rekognition. Within Rekognition, you're able to custom label different sections within your images, rather than just the entire image as a whole. I was looking to do something similar within Tensorflow, but despite looking... | <p>It is possible to classify different areas of images in tensorflow using its object detection api.
<a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">See tensorflow object detection api</a></p>
<p>You can work through the examples there, they also offer pre... | python|tensorflow|machine-learning|image-recognition|amazon-rekognition | 2 |
375,799 | 62,817,662 | using 2d array as indices of a 4d array | <p>I have a Numpy 2D array (4000,8000) from a <code>tensor.max()</code> operation, that stores the indices of the first dimension of a 4D array (30,4000,8000,3). I need to obtain a (4000,8000,3) array that uses the indices over this set of images and extract the pixels of each position in the 2D max array.</p>
<pre><co... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.take_along_axis.html#numpy.take_along_axis" rel="nofollow noreferrer"><code>np.take_along_axis</code></a>.</p>
<p>First let's create some data (you should have provided a <a href="http://stackoverflow.com/help/minimal-reproducible-example">r... | arrays|numpy|pytorch|indices | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.