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 |
|---|---|---|---|---|---|---|
11,800 | 60,896,416 | Tensorflow Keras model: how to get the best score from a history object | <p>I'm trying to train multiple machine learning models using tensorflow keras, I was just wondering is there a way to obtain the best score achieved while training after training is complete. I found online that the .fit function returns a history object which can be accessed to get the best score, though from code i'... | <p>I'm assuming you just want the best score from the history object.</p>
<pre><code>hist = model.fit(...)
print(hist.history) # this will print a dictionary object, now you need to grab the metrics / score you're looking for
# if your score == 'acc', if not replace 'acc' with your metric
best_score = max(hist.histo... | python|tensorflow|keras | 6 |
11,801 | 71,622,969 | How to sum up pandas columns only if the last digit of a column is less equal the last digit of this one | <p>So I have a pandas dataframe like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>contract</th>
<th>account</th>
<th>number1</th>
<th>number2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>A</td>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>B1</td>
<td>B</td>
<td>2</td>
<td>2</td>
</tr>
<... | <p>assign, groupby and cumsum</p>
<pre><code>df=df.assign(sum1=df.groupby('account')['number1'].cumsum(),sum2=df.groupby('account')['number2'].cumsum())
contract account number1 number2 sum1 sum2
0 A1 A 3 1 3 1
1 B1 B 2 2 2 2
2 A2 ... | pandas|dataframe | 2 |
11,802 | 42,327,528 | pandas HDFStore select rows with non-null values in the data column | <p>In pandas Dataframe/Series there's a <code>.isnull()</code> method. Is there something similar in the syntax of <code>where=</code> filter of the select method of HDFStore? </p> | <p><strong>WORKAROUND SOLUTION:</strong></p>
<p>The <code>/meta</code> section of a data column inside hdf5 can be used as a <em>hack</em> solution:</p>
<pre><code>import pandas as pd
store = pd.HDFStore('store.h5')
print(store.groups)
non_null = list(store.select("/df/meta/my_data_column/meta"))
df = store.sele... | pandas|hdf5 | 0 |
11,803 | 69,889,734 | Python Pandas : Getting only 3 first elements from table | <p>I using pandas to webscrape this site <a href="https://www.mapsofworld.com/lat_long/poland-lat-long.html" rel="nofollow noreferrer">https://www.mapsofworld.com/lat_long/poland-lat-long.html</a> but i only gettin 3 elements. How could I get all elements from table?</p>
<pre><code>import numpy as np
import pandas as p... | <p>It looks like if you install and <a href="https://stackoverflow.com/questions/65288453/why-do-only-the-first-two-rows-of-html-table-from-web-page-get-read">use <code>html5lib</code> as your parser</a> it may fix your issues:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.read_html("https://www.maps... | python|pandas|web-scraping | 1 |
11,804 | 69,941,417 | Checking value in different df and summing up values in an other df | <p>Im' struggling to do something easy on panda (by the way I'm not really confortable with pandas).</p>
<p>I have 2 dataframes :</p>
<p>df1</p>
<pre><code>Thing 2010 2011 2012
Banana 37 40 56
Pear 15 37 55
Carrot 7 4 30
</code></pre>
<p>And an other one</p>
<p>df2</p>
<pre><code> Fruits Banana... | <p>Idea is create dictionary by values by <code>Fruits,Vegetables</code> and then aggregate <code>sum</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>:</p>
<pre><code>df2 = pd.DataFrame({'a': {'Fruits': 'Banana',... | python|pandas|dataframe | 1 |
11,805 | 69,951,279 | Pandas dataframe remove rows by aggregated data | <p>I have a dataframe like this</p>
<pre><code>test1 = pd.DataFrame(np.array([[1, 9, 3], [1, 5, 6], [2, 1, 9]]),
columns=['a', 'b', 'c'])
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td... | <p>Group by 'a' and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.transform.html?highlight=series%20groupby%20transform#pandas.core.groupby.SeriesGroupBy.transform" rel="nofollow noreferrer"><code>transform</code></a></p>
<pre><code>test1 = pd.DataFrame(np.array([[1, 9, 3],... | python|pandas|dataframe | 4 |
11,806 | 72,232,860 | copy/clone of keras subclassed models with custom attributes | <p>I have a subclassed model with some custom attributes like this:</p>
<pre><code>class MyModel(tf.keras.Model):
def __init__(self, *args, my_var, **kwargs):
super().__init__(*args, **kwargs)
self.my_var = my_var
def my_func(self):
pass
def get_config(self):
config = super... | <p>You need to add</p>
<pre><code>cloned = model.__class__.from_config(model.get_config())
</code></pre>
<p>as shown in the doc <a href="https://www.tensorflow.org/api_docs/python/tf/keras/models/clone_model#example" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/models/clone_model#exampl... | python|tensorflow|keras | 1 |
11,807 | 50,575,056 | Grouping by preserving hours in pandas | <p>I have the following dateframe. I would like to groupby mean every hour but still preserv the hours datetime info.</p>
<pre><code> date A I r z
0 2017-08-01 00:00:00 3 56 4 6.
1 2017-08-01 00:00:01 3 57 1 6
2 2017-08-01 00:00:03 ... | <p>Using <code>resample</code></p>
<pre><code>df.set_index('date').resample('H').mean()
Out[179]:
A I r z
date
2017-08-01 00:00:00 3.0 55.75 6.0 5.0
2017-08-01 01:00:00 NaN NaN NaN NaN
2017-08-01 02:00:00 NaN NaN NaN NaN
2017-08-01... | python|pandas|datetime|dataframe|pandas-groupby | 3 |
11,808 | 50,498,561 | How to access tensorflow::Tensor C++ | <p>I am running Tensorflow using its C++ API.</p>
<p>I have the following call that returns four tensors in finalOutput:</p>
<pre><code> std::string str1 = "detection_boxes";
std::string str2 = "detection_scores";
std::string str3 = "detection_classes";
std::string str4 = "num_detection... | <p>I'm able to do like this</p>
<pre><code>// tensor<float, 3>: 3 here because it's a 3-dimension tensor
auto output_detection_boxes = outputs[0].tensor<float, 3>();
std::cout << "detection boxes" << std::endl;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 4; ++j)
// using (in... | c++|tensorflow|eigen | 5 |
11,809 | 45,556,197 | get US Census regions using states | <p>The US Census designates each state to a <a href="https://www2.census.gov/geo/pdfs/maps-data/maps/reference/us_regdiv.pdf" rel="nofollow noreferrer">region</a> (ie New York is in NorthEast). I have a dataset of states for which I would like to look up the states' corresponding US Census region. </p>
<p>The <a href=... | <p>Assuming the link is stable (which it may not be of course) you can get by with reading the csv directly:</p>
<pre><code>pd.read_csv('https://raw.githubusercontent.com/cphalpert/census-regions/master/us%20census%20bureau%20regions%20and%20divisions.csv')
</code></pre>
<p>For the record, should you need to go back ... | python|database|pandas|geography | 2 |
11,810 | 45,449,703 | Saving with numpy savetxt. Array elements as columns | <p>I am pretty new to Python and trying to kick my Matlab addiction. I am converting a lot of my lab's machine vision code over to Python but I am just stuck on one aspect of the saving. At each line of the code we save 6 variables in an array. I'd like these to be entered in as one of 6 columns in a txt file with bump... | <pre><code>In [160]: for x in range(0, 9):
...: variable = np.array([2,3,4])
...: output = x*variable+1
...: output.astype(float)
...: print(output)
...:
[1 1 1]
[3 4 5]
[5 7 9]
[ 7 10 13]
[ 9 13 17]
[11 16 21]
[13 19 25]
[15 22 29]
[17 25 33]
</code></pre>
<p>So you are w... | numpy | 1 |
11,811 | 62,841,222 | Seperate gpu tensorlfow scripts running on seperate gpu's | <p>I have recently purchased a second gpu with the thought that I could take advantage of tensorflow-gpu to run some tensorflow script on one gpu and then continue to run other gpu intensive programs on the other.</p>
<p>I was successful in running the tensorflow script on the gpu alone, but when I run another tensorfl... | <pre><code>os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0" #select 0 for first GPU or 1 for second
</code></pre>
<p>Put this script at the very top of any python file to manually assign a GPU.</p> | python|tensorflow|gpu|tensorflow2.0 | 1 |
11,812 | 62,720,078 | Arrange horizontal DF entries according to another DF | <p>My DataFrame 1 looks like this:</p>
<pre><code>ID group_1 area_1 group_2 area_2 group_3 area_3
1 basketball 250 scoccer 500 swimming 100
2 volleyball 100 np.nan np.nan np.nan np.nan
3 football 10 basketball 1000 np.nan... | <p>Does this work?</p>
<p>First, reshape df1</p>
<pre><code>new_rows = []
for k, v in df.iterrows():
for group in range(1,4):
new_rows.append([v['ID'], v[f'group_{group}'], v[f'area_{group}']])
new_df = pd.DataFrame(new_rows, columns=['ID', 'group', 'area']).dropna()
display(new_df)
ID group are... | python|pandas|dataframe|sorting|unique | 0 |
11,813 | 62,512,959 | Remove outlier from time series data using pandas | <p>I have one-minute data:</p>
<pre><code># Import data
import yfinance as yf
data = yf.download(tickers="MSFT", period="7d", interval="1m")
print(data.tail())
</code></pre>
<p>I would like to remove observations where minute difference is grater than daily difference, where we refere to d... | <p>I have found the solution:</p>
<pre><code>daily_diff = data.resample('D').last().dropna().diff() * 25
daily_diff['diff_date'] = daily_diff.index.strftime('%Y-%m-%d')
data_test = data.diff()
data_test['diff_date'] = data_test.index.strftime('%Y-%m-%d')
data_test_diff = pd.merge(data_test, daily_diff, on='diff_date')
... | python|pandas|outliers | 0 |
11,814 | 62,512,609 | Reading RGB raw input, converting to openCV object, then converting to .JPEG bytes - without PIL | <p>I am struggling to read raw RGB image stream from buffer, converting to openCV (numpy) array and encoding back to .jpg Bytes without using PIL. I can achieve this using PIL, but can't figure out how to achieve the same just using numpy/opencv:</p>
<p>Reading in RBG raw stream with PIL (works):</p>
<pre><code>PILFr =... | <p>I figured this out. Further improvements welcome. Still not entirely sure I understand the shape and contents of the imencode returned tuple.</p>
<p>See below my working numpy/opencv alternative to the PIL approach above:</p>
<p>Read in RBG 24bit image from buffer and convert to numpy array (opencvFr) for openCV:</p... | python-3.x|image|numpy|opencv|streaming | 1 |
11,815 | 62,590,325 | Pandas: Detect single words that have certain length | <p>In my.csv file I'm trying to detect and pull rows that have long single words (it can either be one word, or multiple words but one of them is super long) - please note im not looking for the total char in the string but only long words detection so this for example won't work for me: <code>longtitles = df['name'].s... | <p>One way using <code>pandas.Series.extract</code>:</p>
<pre><code>mask = df["name"].str.findall("(\S{16,})").astype(bool)
print(df[mask])
</code></pre>
<p>Output:</p>
<pre><code> id name
1 2 thisismysecondsamplevalue
2 3 this ismythirdsamplevalue
</code></pre> | python|pandas|csv | 4 |
11,816 | 54,451,105 | How to do prediction using trained and stored tensorflow model | <p>I have an existing trained model (specifically tensorflow word2vec <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb</a>). I restore th... | <p>Based on how you are loading the checkpoint I assume this should be the best way to use it for inference.</p>
<p>Load the placeholders:</p>
<pre><code>input = tf.get_default_graph().get_tensor_by_name("Placeholders/placeholder_name:0")
....
</code></pre>
<p>Load the op you use to perform prediction:</p>
<pre><co... | python|tensorflow|word2vec | 1 |
11,817 | 54,341,945 | Insert new column based on column in other dataframe pandas | <p>I have two dataframe, dataframe <code>A</code>:</p>
<pre><code>---------------
A1 A2 A3
1 aa 101
2 bb 130
3 aa 160
4 cc 190
5 aa 200
---------------
</code></pre>
<p>dataframe <code>B</code>:</p>
<pre><code>---------------
B1 B2 B3
1 aa 111 ... | <p>First need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with outer join, filter by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>between</code><... | python-3.x|pandas | 1 |
11,818 | 54,655,369 | transpose column and bind it to a row in pandas | <p>I have a dataset with the following format:</p>
<pre><code>df
----------------------------
ID | T1 | C1 | C2 | C3
----------------------------
ID1 1-0w Yes No
ID1 1-0a Yes No XYZ
ID2 1-2w No Yes
ID2 1-0a Yes No YZ
</code></pre>
<p>I am interested in transposing column T1 such tha... | <p>IIUC <code>pivot</code> + column flatten </p>
<pre><code>s=df.pivot_table(['C1','C2','C3'],index='ID',columns='T1',aggfunc='sum').sort_index(level=1,axis=1)
s.columns=s.columns.map('{0[1]}-{0[0]}'.format)
s
Out[297]:
1-0a-C1 1-0a-C2 1-0a-C3 1-0w-C1 ... 1-0w-C3 1-2w-C1 1-2w-C2 1-2w-C3
ID ... | pandas|python-2.7 | 2 |
11,819 | 71,204,493 | Convert array to a single float in Python | <p>I am trying to write a function which would estimate data noise (σ2) based on three NP arrays - One augmented X-matrix and the two vectors - the y-target and the MAP weights:</p>
<p><a href="https://i.stack.imgur.com/ab7uc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ab7uc.png" alt="MAP estimat... | <p>You forgot to sum over <code>i=1 to n</code>. Therefore <code>mult_right</code> should be defined as:</p>
<pre><code>mult_right=np.sum((output_y-matmul)**2, axis=0)
</code></pre> | python|arrays|numpy | 1 |
11,820 | 71,336,084 | Numpy: Most computationally efficient way to get the mean of slices along an axis where the slices indices value are defined on that axis | <p>For a 2D array, I would like to get the average of a particular slice in each row, where the slice indices are defined in the last two columns of each row.</p>
<p>Example:</p>
<pre><code>sample = np.array([
[ 0, 1, 2, 3, 4, 2, 5],
[ 5, 6, 7, 8, 9, 0, 3],
[10, 11, 12, 13, 14, 1, 4],
[15,... | <p>Bit of hacky, but one way using <code>numpy.cumsum</code> about 200x faster:</p>
<pre><code>def faster(arr):
ind = arr[:, -2:]
padded = np.pad(arr.cumsum(axis=1), ((0, 0), (1, 0)))
res = np.diff(np.take_along_axis(padded, ind, axis=1))/np.diff(ind)
return res.ravel()
faster(sample)
</code></pre>
<p>... | arrays|numpy | 1 |
11,821 | 52,221,761 | selecting a column from pandas pivot table | <p>I have the below pivot table which I created from a dataframe using the following code:</p>
<pre><code>table = pd.pivot_table(df, values='count', index=['days'],columns['movements'], aggfunc=np.sum)
movements 0 1 2 3 4 5 6 7
days
0 2777 51 2
1 6279 200 7 3 ... | <p>You cannot select ndarray for <code>y</code> if you need those two column values in a single plot you can use:</p>
<pre><code>plt.plot(table['0'])
plt.plot(table['2'])
</code></pre>
<p>If column names are intergers then:</p>
<pre><code>plt.plot(table[0])
plt.plot(table[2])
</code></pre> | python|pandas|pivot-table|python-3.5 | 1 |
11,822 | 52,170,006 | How to access data from a MMAX2 annotated XML corpus | <p>I have an annotated corpus for the task of Coreference Resolution. Can you let me know how to extract the data from xml file. I did the following but not work.</p>
<pre><code>from lxml import objectify
import pandas as pd
xml = objectify.parse(open('Dari_Coref_2_coref_level.xml'))
root = xml.getroot()
... | <p>Try this, </p>
<pre><code>import lxml.html
with open('Dari_Coref_2_coref_level.xml', 'rb') as file:
xml = file.read()
tree = lxml.html.fromstring(xml)
#Use Xpath to extract the data you want.
# For example to extract ids of the tag markable, you can do
ids = tree.xpath("//markable/@id")
print(ids) # ['markab... | python|xml|python-3.x|pandas|nlp | 1 |
11,823 | 60,508,349 | Get indexes for Subsample of list of lists | <p>I have several lists of data in python:</p>
<pre><code>a = [2,45,1,3]
b = [4,6,3,6,7,1,37,48,19]
c = [45,122]
total = [a,b,c]
</code></pre>
<p>I want to get <code>n</code> random indexes from them:</p>
<pre><code>n = 7
# some code
result = [[1,3], [2,6,8], [0,1]] # or
result = [[0], [0,2,6,8], [0,1]] # or
result ... | <p>You could flatten the list first and then take your samples:</p>
<pre><code>total_flat = [item for sublist in total for item in sublist]
inds = random.sample(total_flat , k=n)
</code></pre> | python|python-3.x|pandas|list|random | 2 |
11,824 | 60,708,779 | Pandas remove group if difference between first and last row in group exceeds value | <p>I have a dataframe df:</p>
<pre><code>df = pd.DataFrame({})
df['X'] = [3,8,11,6,7,8]
df['name'] = [1,1,1,2,2,2]
X name
0 3 1
1 8 1
2 11 1
3 6 2
4 7 2
5 8 2
</code></pre>
<p>For each group within 'name' and want to remove that group if the difference between the first and la... | <p>If your data is increasingly in <code>X</code>, you can use <code>groupby().transform()</code> and <code>np.ptp</code></p>
<pre><code>threshold = 5
ranges = df.groupby('name')['X'].transform(np.ptp)
df[ranges > threshold]
</code></pre>
<p>If you only care about <code>first</code> and <code>last</code>, then <c... | python-3.x|pandas|filtering | 1 |
11,825 | 59,848,864 | pandas plot one line graph with color change on column | <p>My dataframe</p>
<p><code>df = pd.DataFrame({'date': ['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05'], 'b': ['a', 'a', 'b', 'b', 'c'], 'c': [1,2,3,4,5]})</code></p>
<pre><code> date b c
0 2018-01-01 a 1
1 2018-01-02 a 2
2 2018-01-03 b 3
3 2018-01-04 b 4
4 2018-01-05 c ... | <p>You basically want to create a new series for each value in column <code>b</code>. One way to do that is to group on <code>date</code> and <code>b</code> and then unstack <code>b</code>, and the other method is to use <code>pivot</code>. Then just plot the result.</p>
<pre><code>df.pivot(index='date', columns='b'... | python|pandas|matplotlib|seaborn | 6 |
11,826 | 59,667,404 | Use tensorflow.train.SequenceExample to save variable 2D data | <p>I got time series data samples, each sample contains 3 time-steps and in each time-step, there is a vector contains scalar values and variable length Lists. For example</p>
<p></p>
<pre><code>sample_1 = [ [1, 2, [3, 4, 5] ],
[3, 4, [3, 2] ],
[1, 2, [4, 5, 6, 7]]
]
</code... | <p>I came up with a very easy to understand workaround, although some features have variable length lists, I can save each row of each feature into a FeatureList and save it separately with a separate name and save its dimension in the context respectively.</p>
<p>The code to save the data</p>
<pre><code>import tenso... | python|tensorflow | 0 |
11,827 | 59,477,547 | Fill missing date for each group and impute empty values in Pandas | <p>For the following dataframe, how can I fill missing date for each group <code>city</code> and <code>district</code>, let's say full date range is from <code>2019/1/1</code> to <code>2019/6/1</code>, then fill empty <code>value</code>s with <code>mean</code>s before and after cells, if there are no values before or a... | <p>We could do:</p>
<pre><code>df['date']=pd.to_datetime(df['date'],format ='%YYYY/%dd/%mm' )
</code></pre>
<hr>
<pre><code>( df.set_index('date')
.groupby(['city','district'],as_index=False)
.apply(lambda x: x.reindex(pd.date_range(df.date.min(),df.date.max()))
.interpolate()
... | python-3.x|pandas|dataframe|datetime | 2 |
11,828 | 59,597,672 | How should I solve the following tensorflow package error? | <p>I tried to import tensor flow after installing the package from the command prompt. I got this error:</p>
<blockquote>
<p>ERROR:root: Internal Python error in the inspect module.</p>
</blockquote>
<p>Below is the traceback from this internal error.</p>
<blockquote>
<p>TypeError: can only concatenate str (not ... | <p>Open a new anaconda prompt (close all running prompt), enter "pip install -q tensorflow==2.0.0-beta1" <a href="https://stackoverflow.com/questions/59750730/tensorflow-internal-python-error-module-not-found">From Michael Grogan.</a></p> | python|python-2.7|tensorflow|package | -1 |
11,829 | 62,018,005 | create new column in pandas raises AttributeError: ("'str' object has no attribute 'str'", 'occurred at index 0') | <p>I have a data frame that looks the following:</p>
<pre><code> variable value
0 TrafficIntensity_end 217.0
1 TrafficIntensity_end+105 213.0
2 TrafficIntensity_end+120 204.0
3 TrafficIntensity_end+15 489.0
4 TrafficIntens... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>:</p>
<pre><code> m1 = df['variable'].str.contains('TrafficIntensity')
m2 = df['variable'].str.contains('pred_rf_end')
a['category'] = np.select([m1, m2],
... | python|pandas|dataframe | 2 |
11,830 | 61,891,181 | How to use multiple inputs in Tensorflow 2.x Keras Custom Layer? | <p>I'm trying to use multiple inputs in custom layers in Tensorflow-Keras. Usage can be anything, right now it is defined as multiplying the mask with the image. I've search SO and the only answer I could find was for TF 1.x so it didn't do any good.</p>
<pre><code>class mul(layers.Layer):
def __init__(self, **kwar... | <p>EDIT: Since TensorFlow v2.3/2.4, the contract is to use a list of inputs to the <code>call</code> method. For <code>keras</code> (not <code>tf.keras</code>) I think the answer below still applies.</p>
<p>Implementing multiple inputs is done in the <code>call</code> method of your class, there are two alternatives:</... | python|tensorflow|keras|layer | 14 |
11,831 | 58,100,513 | Pandas conditional groupby | <p>I have a dataframe like below:</p>
<pre><code>df = pd.DataFrame({'col_1': [6ai,6aii,6aii,6b],
'col_2': [1,1,5,1],
'col_3':[True,False,True,False]})
col_1 col_2 col_3
0 6a1 1 True
1 6aii 1 False
2 6aii 5 True
3 6b 1 False
</code></pre>
<p... | <p>You can use <code>groupby().transform('count')</code> to find those occur exactly once:</p>
<pre><code>df[df['col_3'] | df.groupby('col_1')['col_3'].transform('count').eq(1)]
</code></pre>
<p>Output:</p>
<pre><code> col_1 col_2 col_3
0 6ai 1 True
2 6aii 5 True
3 6b 1 False
</code></pr... | python|pandas|dataframe|conditional-statements|selection | 1 |
11,832 | 57,931,131 | subset pandas DataFrame and split into 3 DataFrames | <p>How can I subset the pandas DataFrame by the values in one column? For example, I want to separate the dataset below by the names of each Company. </p>
<p>So I want to split the <code>keywords</code> data frame into 3 different data frames.
I tried to def a function that would split the dataset by the name value i... | <p>the following assumes <code>df</code> is a dataframe loaded with your keywords data</p>
<pre class="lang-py prettyprint-override"><code>amazon_df = df.query('Company == "amazon"')
</code></pre>
<p>this will return a new dataframe where the company column matches the string 'amazon'. To pass in a variable to <code>... | python|python-3.x|pandas|loops|dataframe | 0 |
11,833 | 55,024,529 | How to use math.log10 function on whole pandas dataframe | <p>I want to take the logarithm of every value in a pandas dataframe. I have tried this but it does not work:</p>
<pre><code>#Reading data from excel and rounding values on 2 decimal places
import math
import pandas as pd
data = pd.read_excel("DataSet.xls").round(2)
log_data= math.log10(data)
</code></pre>
<p>It giv... | <p>Use the numpy version, not math</p>
<pre><code>import numpy as np
np.log10(df)
</code></pre> | python|pandas|numpy | 33 |
11,834 | 54,866,933 | Numpy python R eqivalent indexing | <pre><code>import numpy as np
o = np.array([
[
[1,2,3,4],
[5,6,7,8]
],
[
[9,10,11,12],
[13,14,15,16]
]
])
print(o.flatten())
# array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ... | <p>You can start by doing a <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>np.concatenate</code></a> on the second dimension, and then <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ndarray.flatten.html" rel="nofol... | python|r|numpy|data-science | 3 |
11,835 | 55,106,218 | Counting Unique Values from multiple dataframe columns | <p>I have a dataframe of sales quotes with id, date and status (won, lost, open). </p>
<pre><code>Quotes = pd.DataFrame({
'Quote_ID': [1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112],
'Quote_Date': ['2018-11-15', '2018-11-15', '2018-11-15', '2018-11-15',
'2018-11-15', '2018-11-16', ... | <p>Create a Boolean Series, then sum it in a <code>groupby</code></p>
<pre><code>(Quotes.assign(Won = Quotes.Status.eq('won'))
.groupby("Quote_Date").agg({'Won': 'sum', 'Quote_ID': 'nunique'})
.rename(columns={'Quote_ID': 'Quotes'}))
Won Quotes
Quote_Date
2018-11-15 3.0 5
20... | python-3.x|pandas|dataframe | 1 |
11,836 | 54,695,231 | how write complex numbers to one csv file in each row? | <p>I want to <strong>to store a complex number of each image</strong> which is generated by using <strong>Fast Fourier transform</strong> which is of type <strong>complex 128</strong>.
the code is as follow:</p>
<pre><code>import cv2
import glob
import numpy as np
bloodVessal=[]
for file in glob.glob('/home/raviraj/P... | <p>I'm assuming you want to save the list <code>bloodVessel</code> to a plain text file. To do so with a single column, append the following after the loop:</p>
<pre><code>np.savetxt('data.csv',bloodVessel,delimiter=',')
</code></pre>
<p>This will create a file called <code>data.csv</code> that looks like,</p>
<pre>... | python-3.x|csv|numpy|fft | 1 |
11,837 | 54,861,810 | Python numpy mask a range of values | <p>I have a 2D array called img of size 100x100. I am trying to mask all values bigger than -100 and lesser than 100 as folows.</p>
<pre><code>img = np.ma.masked_where(-100 < img < 100, img)
</code></pre>
<p>However, the above gives me an error saying</p>
<pre><code>ValueError: The truth value of an array with... | <p>You can also use <a href="https://numpy.org/devdocs/reference/generated/numpy.ma.masked_inside.html#numpy.ma.masked_inside" rel="nofollow noreferrer">masked inside</a>, for instance we can mask the value between the 2 and 5 range:</p>
<pre><code>import numpy as np
from numpy import ma
img = np.arange(9).reshape(3... | python|numpy|mask | 1 |
11,838 | 49,628,353 | Convert Python Dictionary to Pandas Dataframe | <p>I am converting a python list/dictionary to a pandas dataframe:</p>
<pre><code>import numpy as np
import pandas as pd
points = [
{'coords': (100.5, 100), 'class': 1},
{'coords': (300, 300), 'class':2},
{'coords': (50, 200), 'class':4},
{'coords': (550, 400), 'class':10},
{'coords': (550, 300), ... | <blockquote>
<p>Why this (all columns have <code>object</code> dtype) is happening?</p>
</blockquote>
<p>after this line:</p>
<pre><code>In [100]: data = np.array([['x', 'y', 'class']])
</code></pre>
<p>array <code>data</code> will have <code>object</code> (string) dtype:</p>
<pre><code>In [101]: data.dtype
Out[1... | python|pandas | 0 |
11,839 | 73,521,658 | Forward filling missing dates into Python Panel Pandas Dataframe | <p>Suppose I have the following pandas dataframe:</p>
<pre><code>df = pd.DataFrame({'Date':['2015-01-31','2015-01-31', '2015-02-28', '2015-03-31', '2015-04-30', '2015-04-30'], 'ID':[1,2,2,2,1,2], 'value':[1,2,3,4,5,6]})
print(df)
Date ID value
2015-01-31 1 1
2015-01-31 2 2
2015-02-28 2 3
2015-03-31 2... | <p>You can <code>pivot</code> then fill value with <code>reindex</code> + <code>ffill</code></p>
<pre><code>out = df.pivot(*df.columns).reindex(pd.date_range('2015-01-31',periods = 5,freq='M')).ffill().stack().reset_index()
out.columns = df.columns
out
Out[1077]:
Date ID value
0 2015-01-31 1 1.0
1 2015-... | python|pandas|dataframe|group-by | 1 |
11,840 | 73,186,024 | How to use a NumPy slice as a function argument? | <p>Currently extracting frames from a video to be processed later on. I have different areas of the video frames that I want to process so I need to be able to pass a numpy slice into a variable to be used as the function's argument. What's the syntax for that?</p>
<p><code>frame[5:49, 879:938]</code> is the slice that... | <p>When you say <code>frame[5:49, 879:938]</code> you are indexing into <code>frame</code> using a pair of <code>slice</code>s. The <code>slice</code> type is built in to Python, and you can pass two of them to your function like this:</p>
<pre><code>extractFrames("filename", "folder", x=slice(5, 4... | python|numpy|image-processing|slice | 4 |
11,841 | 67,376,123 | Is it possible to reshape pandas DataFrame using parts of column names? | <p>I am just getting started with working in pandas and with dataframes. I'd like to reshape some data but I'm not sure the best approach to do so. My instinct says to iterate over the frame but I'm hoping there is some better way.</p>
<p>So, I have an initial dataframe that looks like this:</p>
<div class="s-table-con... | <p>via <code>stack unstack</code>:</p>
<pre><code>df = (df.set_index(['vendor_state','client_state','date'])
.stack()
.unstack(2)
.reset_index()
.rename(columns={'level_2': 'widget type'})
.fillna(0)
)
df['widget type'] = df['widget type'].str.extract(pat = ("(widget_[a|b])"))
</code></pre>
<p><strong>... | python|pandas|dataframe | 4 |
11,842 | 60,258,379 | Accessing elements of series object without using index python, accessing values of correlation or other matrices | <p>I have a dataframe df. I have taken its correlation and then found out the first four highly correlated values. These values I have named as relevant features. I wish to access the values of these relevant features (relevant features is series object)</p>
<pre><code>correlation_matrix=df.corr() #taking correlati... | <p>You are really close, need:</p>
<pre><code>relevant_features.iloc[:4].to_numpy()
</code></pre> | python|pandas|correlation|series | 2 |
11,843 | 60,059,543 | How to add an index label using pandas MultiIndex.insert to an existing MultiIndex? | <p>With below code I tried to insert a new row label (two name-levels) but it appears that <code>MultiIndex.insert()</code> does not work according to the printed output. User xyzjayne mentions <a href="https://stackoverflow.com/questions/51309742/pandas-multiindex-add-labels-to-an-index-level">here</a> <strong><em>"Mu... | <p>You can assign back, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.insert.html" rel="nofollow noreferrer"><code>Index.insert</code></a> not working inplace:</p>
<pre><code>print (pd.__version__)
0.25.1
# add row at position 6
row_labels = row_labels.insert(6, (('D', '9')))
# chec... | python|python-3.x|pandas|multi-index | 1 |
11,844 | 65,402,052 | Cosine Similarity rows in a dataframe of pandas | <p>I have a CSV file which have content as belows and I want to calculate the cosine similarity from one the remaining ID in the CSV file.</p>
<p>I have load it into a dataframe of pandas as follows:</p>
<pre><code> old_df['Vector']=old_df.apply(lambda row:
np.array(np.matrix(row.Vector)).ravel(), axis = 1)
... | <p>Example code to get top k cosine similarities and they corresponding GUID and row ID:</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
data = {"GUID": ["b770", "808f", "b111"], "Vector": [[-0.1, -0.2, 0.3],... | python-3.x|pandas|dataframe|cosine-similarity | 1 |
11,845 | 65,166,640 | How can I permute only certain entries of numpy 2d-array? | <p>I have a numpy 2d-array of shape (N, N) representing a NxN correlation matrix. This matrix is symmetric. Say N=5, then an example of this 2d-array would be:</p>
<pre><code>x = np.array([[1.00, 0.46, 0.89, 0.76, 0.65],
[0.46, 1.00, 0.83, 0.88, 0.29],
[0.89, 0.83, 1.00, 0.57, 0.84],
... | <p>You can try this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
x = np.array([[1.00, 0.46, 0.89, 0.76, 0.65],
[0.46, 1.00, 0.83, 0.88, 0.29],
[0.89, 0.83, 1.00, 0.57, 0.84],
[0.76, 0.88, 0.57, 1.00, 0.39],
[0.65, 0.29, 0.84, 0.39, 1.00... | python|arrays|numpy | 1 |
11,846 | 65,192,453 | Convert a simple cnn from keras to pytorch | <p>Can anyone please help me to convert this model to PyTorch? I already tried to convert from Keras to PyTorch like this <a href="https://stackoverflow.com/questions/60172607/how-can-i-convert-this-keras-cnn-model-to-pytorch-version">How can I convert this keras cnn model to pytorch version</a> but training results we... | <p>Your PyTorch equivalent of the Keras model would look like this:</p>
<pre class="lang-py prettyprint-override"><code>class CNN(nn.Module):
def __init__(self, ):
super(CNN, self).__init__()
self.maxpool = nn.MaxPool3d((2, 2, 2))
self.conv1 = nn.Conv3d(in_channels=1, ... | keras|pytorch | 3 |
11,847 | 65,385,662 | Logarithmic returns in pandas dataframe groupby ticker | <p>I like to calculate the <em>log return</em> based on stock prices (adjclose) for each ticker in a dataframe with several tickers and prices.</p>
<p>A sample of such a dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
f = {'date': ['2020-11-25', '2020-11-24', '2020-11-23', '2020-11-25', '2020-11-24', '... | <p>You can do something like this where we apply the log return calc to each <code>d</code> which is the group in the groupby:</p>
<pre><code>df.groupby('ticker').apply(lambda d: d.assign(log_return = np.log(d['adjclose'] / d['adjclose'].shift(1)) ))
</code></pre>
<p>output</p>
<pre><code> date ticker... | python|pandas | 1 |
11,848 | 49,859,025 | Pandas: replace a single column (field) of strings with one column for each string | <p>Say I have the following dataframe:</p>
<pre><code> Colors
0 red, white, blue
1 white, blue
2 blue, red
3 white
4 blue
</code></pre>
<p>where each unique value in column "Colors" needs to become an individual column, so that these columns can be populated with Boolean indices. Exampl... | <p>Use:</p>
<pre><code>df = pd.get_dummies(df['Colors'])
print (df)
blue blue, red red, white, blue white white, blue
0 0 0 1 0 0
1 0 0 0 0 1
2 0 1 0 0 0
3 0 0 ... | python|pandas|boolean-operations | 2 |
11,849 | 49,960,597 | Pandas: using iloc to retrieve data does not match input index | <p>I have a dataset which contains contributor's id and contributor_message. I wanted to retrieve all samples with the same message, say, contributor_message == 'I support this proposal because...'. </p>
<p>I use data.loc[data.contributor_message == 'I support this proposal because...'].index -> so basically you can g... | <p>This occurs when your indices are not aligned with their integer location.</p>
<p>Note that <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>pd.DataFrame.loc</code></a> is used to slice by index and <a href="https://pandas.pydata.org/pandas-docs/stabl... | python|pandas|dataframe|indexing | 5 |
11,850 | 50,189,300 | How to reuse a trained model to perform classification - Tensorflow | <p>I've trained a CNN model on Tensorflow and I'd like to reuse to perform classification and test it.
This is what I'm currently doing:</p>
<pre><code>def test(trained_model):
# returns a iterator.get.next()
x_test, y_test = inputs('test_set.tfrecords', batch_size=128, training_size=10000, shuffle=False, num_... | <p>What you're doing is right and there's no "right workflow" (tl;dr: they're logically equivalent).</p>
<p>When you save a model using a <code>Saver</code>, Tensorflow automatically creates for you the <code>.meta</code> and <code>.ckpt</code> files, where the <code>.meta</code> contains the graph definition (the li... | tensorflow | 1 |
11,851 | 49,808,467 | How is the print and view functions works in pytorch? | <p>This is a convolutional neural network which I found in the web</p>
<pre><code>class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
... | <p>1) <code>x.view</code> can do more than just flatten: It will keep the same data while reshaping the dimension. So using <code>x.view(batch_size, -1)</code>will be equivalent to <code>Flatten</code></p>
<p>2) In the <code>__repr__</code>function of <a href="https://github.com/pytorch/pytorch/blob/master/torch/nn/mo... | pytorch | 2 |
11,852 | 64,005,732 | Why can't i use pandas.DataFrame.plot.bar() properly? | <p>This is my dataframe:</p>
<pre><code>Month January February March April May June \
Year
2016 NaN NaN NaN NaN 97162.0 415627.0
2017 1016340.0 871166.0 910442.0 926362.0 1061... | <p>You can check <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.bar.html" rel="nofollow noreferrer"><code>DataFrame.plot.bar</code></a>:</p>
<blockquote>
<p><strong>x</strong> - <strong>label or position, optional</strong><br />
Allows plotting of one column versus another. If ... | python|pandas | 1 |
11,853 | 46,774,792 | Extract numpy arrays from pandas dataframe as matrix | <p>I ended up with the following data structure:</p>
<pre><code>import numpy as np
import pandas as pd
my_df = pd.DataFrame({'col_1': [1,2,3]})
my_df['col_1'] = my_df['col_1'].apply(lambda x: np.array([1,2,3]))
my_df.as_matrix()
</code></pre>
<p>it looks like this:</p>
<pre><code>array([[array([1, 2, 3])],
[... | <p>If you just want an array, you can</p>
<pre><code>np.array(my_df.col_1.tolist())
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre> | python|arrays|pandas|numpy | 2 |
11,854 | 46,775,668 | Need help in removing duplicate dates and merging values of two rows in Pandas Dataframe (python) | <p>I am following data in pandas dataframe. Some date vales are repeating(2010-07-31,2010-10-31). How to remove repeated dates and merge the values between two rows. Take A % B values from 1st row and C & D values from 2nd row. </p>
<pre><code> Date A B C D
1 20... | <p>Use pandas groupby and aggregate it by sum (use Dated as column name, instead of the reserved Date):</p>
<pre><code>df.groupby(['Dated']).sum()
</code></pre>
<p><a href="https://i.stack.imgur.com/QallD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QallD.gif" alt="enter image description here">... | python|pandas|dataframe | 3 |
11,855 | 62,927,963 | Writing Data from pandas dataframe to PostgreSQL gives error of 'DataFrame' objects are mutable, thus they cannot be hashed | <p>i am trying to save a data frame which was first imported in pandas from postgresql as dfraw and then do some manipulation and create another dataframe as df and save it back in postgresql same database using sql alchemy. but when i am trying to save it back its giving error of 'DataFrame' objects are mutable, thus ... | <p>Found basic error in the code I just missed putting the inverted comma before the data frame name to be published. The basic hygiene was missed</p>
<pre><code>df.to_sql(name = "df",
con=engine,
index = False,
if_exists= 'replace'
)
</code></pre> | pandas|postgresql|sqlalchemy | 0 |
11,856 | 63,253,517 | pandas groupby shift is not respecting the groups | <p>I have the following DataFrame and an arbitrary function</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(
{'grp': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3],
'val': [0.80485036, 0.30698609, 0.33518013, 0.12214516, 0.66355629,
0.71277808, 0.07193942, 0.971287... | <p>The problem is, when breaking into pieces, the code</p>
<pre><code>df.groupby('grp')['val'].rolling(3).apply(myfunc).shift(-5)
</code></pre>
<p>is equivalent to</p>
<pre><code>tmp = df.groupby('grp')['val'].rolling(3).apply(myfunc)
out = tmp.shift(-5)
</code></pre>
<p>Here, <code>tmp</code> is a normal <code>pd.Seri... | python|pandas|dataframe|split-apply-combine | 3 |
11,857 | 67,764,935 | Remove duplicate documents from a dataframe? | <p>I have a dataframe of documents. It has columns 'title', 'description' and 'body'.</p>
<p>Using Python, I need to find all rows that share the same title and description, and only keep the rows that match that have the longest body if the titles and descriptions match.</p>
<p>For example, if I had:</p>
<div class="s... | <p>You can get the string length of column <code>body</code> by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>.str.len()</code></a>, then group these string lengths by <code>title</code> and <code>description</code> and use <a href="https... | python|python-3.x|pandas|dataframe | 1 |
11,858 | 67,889,929 | I got some incorrect datetime format, and I want to convert it to correct format using Pandas | <p>Here is the input data 2019-09-06 00:00:1567702800
I have tried a lot of method to change it to YYYY-MM-DD format but it doesn't work, because of this part "00:00:1567702800" does not the correct format. It should be 00:00:15.67702800. How can I change the format from 00:00:1567702800 to 00:00:15.677028... | <p>I assume someone will have a better answer but one way would be:</p>
<pre><code>s = "2019-09-06 00:00:1567702800"
s = ''.join([s[:19],".",s[19:]])
</code></pre>
<p>which could be applied on a pandas series using:</p>
<pre><code>df[col].astype(str).apply(lambda x: ''.join([x[:19], "."... | python|pandas | 1 |
11,859 | 61,383,562 | How to zero pad all states per date and case type where cumulative covid-19 cases are 0 | <p>I have collected data for Covid-19 per state in India. The first date is 2020-03-10, regardless of case_type. For each day, the API returns only the set of states which have cumulative cases > 0. Therefore I want to zero pad all states in the DataFrame per date and case_type where they have not had any cases yet.</p... | <p>You can try Pivot and melt. Probably not the best solution but will work fine for small dataset.</p>
<pre><code>import pandas as pd
from io import StringIO
data = """
Date|State|Case_Type|Cases
2020-03-10|Delhi|Confirmed|4
2020-03-10|Delhi|Deaths|0
2020-03-26|Andamanand Nicobar Islands|Confirmed|1
"""
output = io... | python|pandas | 1 |
11,860 | 61,332,263 | Compare two date columns in pandas DataFrame to validate third column | <p><strong>Background info</strong><br>
I'm working on a DataFrame where I have successfully joined two different datasets of football players using fuzzymatcher. These datasets did not have keys for an exact match and instead had to be done by their names. An example match of the name column from two databases to merg... | <p>IICU:
Please Try <code>np.where</code>.
Works as follows;</p>
<pre><code>np.where(if condition, assign x, else assign y)
</code></pre>
<p><code>if condition</code>=df.loc[(df['birth_date'] != df['dob'],
<code>x</code>=np.nan and
<code>y</code>= prevailing df.value</p>
<pre><code>df['value']= np.where(df.loc[(df['... | python|pandas|numpy|dataframe|fuzzy-logic | 1 |
11,861 | 61,590,526 | Possible reason for discrepancy in keras h5 model confidence and the same model converted to tflite? | <p>Recently I used keras to transfer train the mobilenet model. I reconfigured the output layer to predict on two classes. </p>
<p>I then converted the saved .h5 file to a .tflite file. Once ran in Android Studio according to TensorFlow's ImageClassification example: </p>
<p><a href="https://github.com/tensorflow/exa... | <p>Tensorflow Lite could have a slight difference from keras model since they don't share the same runtime kernel. Also it happens if the tflite model is quantized.</p> | android|tensorflow|keras|tensorflow-lite | 0 |
11,862 | 68,642,306 | Fill cell containing NaN with average of value before and after considering groupby | <p>I would like to fill missing values in a pandas dataframe with the average of the cells directly before and after the missing value considering that there are different IDs.</p>
<pre><code>maskedid test value
1 A 4
1 B NaN
1 C 5
2 A 5
2 B NaN
2 ... | <p>Try to <a href="https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.Series.interpolate.html" rel="nofollow noreferrer"><code>interpolate</code></a>:</p>
<pre><code>df['value'] = df['value'].interpolate()
</code></pre>
<p>And by group:</p>
<pre><code>df['value'] = df.groupby('maskedid')['value']... | python|pandas|dataframe|pandas-groupby | 2 |
11,863 | 68,744,488 | Send panda DataFrame's between processes | <p>I do not want to <em>share</em> but just <em>send</em> a <code>DataFrame</code> from one process to another.</p>
<p>The primary <code>DataFrame</code> is cutted into pieces and each piece is processed by a separate process (in the meaning of pythons <code>multiprocessing</code>) on its own CPU core. After the "... | <p>You have several problems:</p>
<ol>
<li>According to the documentation for <code>Queue.full()</code>:</li>
</ol>
<blockquote>
<p>Return True if the queue is full, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.</p>
</blockquote>
<p>So you should <em>not</em> be using this ... | python|pandas|multiprocessing | 2 |
11,864 | 68,581,423 | Pandas to remove value if it exists in any other column in the same row | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame({'c1': ["dog", "cat", "bird"], 'c2': ["rabbit", "rat", "snake"], 'c3': ["dog", "fish", "snake"]})
</code></pre>
<p>It looks like:</p>
<p><a href="https://i.stack.imgur.com/Er... | <p>Another approach based on testing equality across columns and replacing with <code>np.where</code>:</p>
<pre><code>df['c3'] = np.where(df[df.drop('c3', axis=1).columns].eq(df['c3'], axis=0).any(axis=1),
"", df['c3'])
</code></pre>
<pre><code> c1 c2 c3
0 dog rabbit
... | python|pandas|dataframe | 2 |
11,865 | 53,351,415 | Reshaping and Pivot Tables - ValueError: Index contains duplicate entries, cannot reshape | <p>My dataframe <code>df</code> has the following structure:</p>
<pre><code>product_id url type
0 2013367 7405e0c483323f78b A
1 2013367 ea919d2276f60f31e B
2 452998 117312244aa203a03 A
3 452998 1a6a41a6141235d68 B
4 2196333 cd66f91431fbae2d4 A
</code></pre>
<p>I am trying to use... | <p>Okay I just figured out that the problem was due to fact that there were product_id's in my dataset that are associated with type A multiple times. Like so:</p>
<pre><code>product_id url type
0 2013367 7405e0c483323f78b A
1 2013367 ea919d2276f60f31e B
2 452998 117312244aa203a03 A < ... | python|pandas | 0 |
11,866 | 53,000,874 | Splicing 2 dataframes together by columns with python and pandas | <p>I have two data frames in pandas</p>
<p>df1:</p>
<pre><code> Genes N1 N2 N3 N4 N5 \
1 100130426 0 0 0.2262 0 0
2 100133144 6.0377 4.3819 15.9742 4.5751 14.5776
3 100134869 3.9512 2.37... | <p>You can do:</p>
<pre><code>merged = df1.merge(df2).set_index('Genes')
merged = merged[sorted(merged.columns,key=lambda x: int(x[1:]))].reset_index()
</code></pre>
<p>This will sort the columns by the number <em>after</em> the letter on all the columns except the gene column:</p>
<pre><code> Genes N... | python|pandas | 4 |
11,867 | 53,081,877 | Pandas idxmax() doesn't work on Series grouped by time periods which contain NaNs | <p>I have a Series that contains scalar values indexes by days over several years. For some years there are not data.</p>
<pre><code>2014-10-07 5036.883410
2013-10-11 5007.515654
2013-10-27 5020.184053
2014-09-12 5082.379630
2014-10-14 5032.669801
2014-10-30 5033.276159
2016-10-03 5046.921912
2016... | <p>The problem is that you have no records during 2015, but a time period for 2015 is created since it is inside your years' range. You need to manually process this case:</p>
<pre><code>data.resample('A').agg(
lambda x : np.nan if x.count() == 0 else x.idxmax()
)
</code></pre>
<p>Output:</p>
<pre><code>time
201... | python|pandas | 8 |
11,868 | 65,859,341 | Pandas merging two dataframes by removing only one row for every duplicate row between dataframes | <p>I have two dataframes and I am merging it. While merging it should remove duplicates. But for one duplicate row in frame 1 it should remove only one duplicate row in frame 2 even if there are two such rows like below
df1:</p>
<pre><code>colA colB colC
1 2 3
1 1 2
1 5 4
</code></pre>
<p>df2:</... | <p>This is one way:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'colA': [1, 1, 1],
'colB': [2, 1, 5],
'colC': [3, 2, 4]})
df2 = pd.DataFrame({'colA': [1, 1, 1],
'colB': [2, 2, 1],
'colC': [3, 3, 2]})
df1 = df1.groupby(['colA',... | python|pandas|dataframe | 1 |
11,869 | 65,900,147 | Preparing SQL query statement condition using one of column of panda dataframe | <p>#I would like to prepare SQL query statement using panda dataframe column in condition. Example</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
#My desire output should be like
sqlquery = "select * from database where country in ('US','UK','Germany','China'... | <pre><code>import pandas as pd
df=pd.read_excel(r"D:\Stack_overflow\test7.xlsx")
list1=df['Country'].unique()
Sql_string='(';
for item in list1:
Sql_string= Sql_string + " '" + str(item) + "',"
Sql_string=Sql_string[:-1] + ")"
query='''select * from database wjere co... | mysql|python-3.x|pandas|dataframe | 0 |
11,870 | 65,898,994 | How to drop NaN from one column according to another columns specific value | <p>Can't figure out how to drop NaN values from specific column according to another column specific value.
Part of DataFrame(<code>df</code>):</p>
<pre><code> vol. group
1186 10,448,898 1
1187 nan 0
1188 35,047,520 1
...
8329 130,... | <p>You can change logic - select all values without <code>1</code> with <code>nan</code>s in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>#if necessary convert strings nan to missing values `Na... | python|pandas|dataframe|nan|drop | 3 |
11,871 | 65,698,406 | Adding values from previous row/value python | <p>is it possible to add values from each row with value from previously define number in Python just like this:</p>
<pre><code>base_value = 10
a b c
2 3 (expected. 2+3+base_value=10)
4 3 (expected. 4+3+15=22)
1 9 (expected. 1+9+22=32)
5 7 (expected. 5+7+32=44)
1 1 (expected. 1+1+44=46)
...
</code></pre>
<p>Thank you... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.add.html" rel="nofollow noreferrer"><code>Series.add</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum</code></a>:</p>
<pre><c... | python|pandas|numpy|sum|add | 3 |
11,872 | 63,320,488 | Python pandas, stock portfolio value timeseries | <p>I'm trying to build a time series consisting of the market value of my portfolio. The whole website is build on django framework. So the datasets will be dynamic.</p>
<p>I have a dataset named <strong>dataset</strong>, this dataset is containing stocks close price:</p>
<pre><code> YAR.OL NHY.OL
dat... | <p>Overview / summary</p>
<ul>
<li>Keep one data frame for each 'concept' -- closing prices, positions, etc.</li>
<li>Then multiply data frames (value = positions x price).</li>
<li>Separate into multiple data frames for reporting.</li>
</ul>
<pre><code>from io import StringIO
import pandas as pd
# create data frame w... | python|django|pandas|data-science | 2 |
11,873 | 63,606,731 | Pandas: How to conditionally sum values in two different dataframes | <p>I have the following dataframes:</p>
<pre><code>df1
Name Leads
0 City0 22
1 City1 11
2 City2 28
3 City3 15
4 City4 14
5 City5 15
6 City6 25
df2
Name Leads
0 City1 13
1 City2 0
2 City4 2
3 City6 5
</code></p... | <p>Assume <code>df2.Name</code> values are unique and <code>df2</code> has exact 2 columns as your sample. Let's try something different by using <code>map</code> and <code>defaultdict</code></p>
<pre><code>from collections import defaultdict
df1.Leads + df1.Name.map(defaultdict(int, df2.to_numpy()))
Out[38]:
0 22... | python|pandas | 1 |
11,874 | 63,488,014 | How to get multiple elements on a page using flask (tables, pie charts, etc.) | <p>I am trying to get multiple elements to a single page using flask. I am able to do so for the most part with the code below, but unable to get multiple charts. I am using python with chart.js along with pandas for the data. I am also using html and CSS.</p>
<p>Python:</p>
<pre><code>d1 = {'Fruits' : pd.Series([10]),... | <p>That error is because your zip object has 7 values to unpack, not 3.
If you did <code>{% for a, b, c, d, e, f, g in set %}</code> it should work.</p>
<p>You could also arrange your data like a list of dicts instead, something like:</p>
<pre><code>[{"item": ..., "label": ..., "color": ..... | python|html|pandas|flask|chart.js | 1 |
11,875 | 53,466,086 | Looping over pandas DataFrame | <p>I have a weird issue that the result doesn't change for each iteration. The code is the following:</p>
<pre><code>import pandas as pd
import numpy as np
X = np.arange(10,100)
Y = X[::-1]
Z = np.array([X,Y]).T
df = pd.DataFrame(Z ,columns = ['col1','col2'])
dif = df['col1'] - df['col2']
for gap in range(100):
... | <p>Found the root of the problem 5 mins after posting this question. I just needed to reset the dataFrame to the original to fix the problem.</p>
<pre><code>import pandas as pd
import numpy as np
X = np.arange(10,100)
Y = X[::-1]
Z = np.array([X,Y]).T
df = pd.DataFrame(Z ,columns = ['col1','col2'])
df2 = df.copy()#a... | python-3.x|pandas|numpy|loops | 2 |
11,876 | 53,376,996 | Cannot concatenate Keras Lambda layers | <p>I need to process some layers in a different way, doing some OR operations. I've found how to do it, I create a Lambda Layer and process the data with <code>keras.backend.any</code>. I am also doing a split, because I need to operate 2 separates groups with my logical OR.</p>
<pre><code>def logical_or_layer(x):
... | <p>Wrap the <code>K.stack</code> inside a <code>Lambda</code> layer like this:</p>
<pre><code>from keras import backend as K
y = Lambda(lambda x: K.stack([x[0], x[1]]))([y_0, y_1])
</code></pre> | python|tensorflow|keras | 3 |
11,877 | 71,904,215 | How to make a dataframe from a nested JSON and pandas? | <p>Here is a sample of a json file that I have of data from my Apple Health app. How can I take this json and turn it into a pandas dataframe? The dataframe structure I am hoping to make is shown below.</p>
<pre class="lang-json prettyprint-override"><code>{
"data": {
"workouts": [],
"... | <p>Panda has a helpful function method for this</p>
<pre><code>metrics = data['data']['metrics']
dataframe = pd.json_normalize(
metrics,
record_path=['data'],
meta=['name','units']
)
</code></pre>
<p>You can read more about converting json to dataframes here <a href="https://towardsdatascience.com/how-to-convert-... | python|ios|json|pandas | 1 |
11,878 | 71,817,440 | What is the difference between activation layer and activation kwarg? | <p>What is the difference between activation layer and activation kwarg?</p>
<p>for instance :</p>
<p><code>activation</code> kwarg :</p>
<pre><code>model.add(tf.keras.layers.Dense(10,activation="relu"))
</code></pre>
<p><code>Activation</code> layer :</p>
<pre><code>model=Sequential([
tf.keras.layers.Den... | <p>From the <a href="https://keras.io/api/layers/activations/" rel="nofollow noreferrer">docs</a>:</p>
<blockquote>
<p>Activations can either be used through an Activation layer, or through the activation argument supported by all forward layers</p>
</blockquote>
<p>This quote is then followed by a specific example, wh... | python|tensorflow|keras | 2 |
11,879 | 72,003,641 | How to average every 50 values inside a larger matrix in Python | <p>I have an array of 7000 images and those images are of size 224x224x3. Therefore the entire matrix shape is <code>(7000, 224, 224, 3)</code>. What I want to do is select every 50 images and calculate their mean obtaining 1 frame averaged out of 50, so in total I'd have an array of size <code>(140, 224, 224, 3)</code... | <p>One way you can do it is to reshape the array so that it becomes <code>140 x 50 x 224 x 224 x 3</code> then take the average along the second axis:</p>
<pre><code>mean_frame = np.mean(np.reshape(array, (140, 50, 224, 224, 3)), axis=1)
</code></pre>
<p>By reshaping your array this way, each element in the first dimen... | python|python-3.x|numpy|image-processing|matrix | 1 |
11,880 | 55,207,352 | Make 8 images using each bit of each pixel of an image | <p>so I have a 512x512 grayscale image and I want to use each bit of the pixels of the image to make 8 different black and white images, each one with the respective bits. To achieve this I'm using the opencv library.
The grayscale image <code>x_img_g</code> is represented by a matrix:</p>
<pre><code>[[162 162 162 ...... | <p>Extend to <code>3D</code> with a new axis at the end and use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html" rel="nofollow noreferrer"><code>np.unpackbits</code></a> along the same -</p>
<pre><code>np.unpackbits(a[...,None], axis=-1) # a is input array
</code></pre>
<p>Sample r... | python-3.x|image|numpy|opencv|matrix | 1 |
11,881 | 56,570,767 | Use result of pandas groupby to query date from column's pandas cut date range | <p>So I've got the result of a <code>pandas.groupby()</code> call, and I'm wanting to query the result in a mysql <code>select</code> style query. Here is a MWE of the code I'm trying to work from:</p>
<pre><code>import pandas as pd
import numpy as np
from datetime import datetime as dt
dates = np.array([dt(2012, 9, ... | <p>You can use <code>.loc</code> </p>
<pre><code>s=df1.groupby(pd.cut(df1['date'], df2['bin_dates'])).agg({'value':np.nanmean})
s.loc['2012-10-11 3:00:00']
Out[94]:
value 5.53283
Name: (2012-10-10 14:00:00, 2012-10-14 14:00:00], dtype: float64
</code></pre> | python|python-3.x|pandas|pandas-groupby | 2 |
11,882 | 47,126,121 | Understanding Michael Nielsen's backpropagation code | <p>I'm trying to understand/run the code in Michael Neilsen's Neural Networks and Deep Learning chapter 2, on backpropagation: <a href="http://neuralnetworksanddeeplearning.com/chap2.html#the_code_for_backpropagation" rel="nofollow noreferrer">http://neuralnetworksanddeeplearning.com/chap2.html#the_code_for_backpropaga... | <h2>Why the shapes in backprop match</h2>
<p>Suppose the network architecture is <code>[...,N,M]</code>, that is the last layer outputs the vector of size <code>M</code>, the one before of size <code>N</code> (let's focus on the last two layers and ignore the rest). <code>N</code> and <code>M</code> can be arbitrary. ... | python|numpy|machine-learning|neural-network|backpropagation | 1 |
11,883 | 47,091,818 | Numpy : What does this einsum expression mean and is there an alternative? | <p>How do I understand following expression (A is an [200, 2] array) :</p>
<pre><code>B = numpy.einsum('...i,...j->...ij',A,A)
</code></pre>
<p>And how to write it in another way not using <code>numpy.einsum</code>?</p> | <p>Well that basically does element-wise multiplication between the elements along the last axis for <code>A</code> for all pairs. Now, since that <code>einsum</code> expression isn't doing any sum-reduction and is simply doing the job of <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" r... | python|numpy | 2 |
11,884 | 68,425,569 | Rolling windows with column based condition? | <p>How could I join the rows based on the <strong>resume</strong> column?<br />
I mean, go joining the rows until in <strong>resume</strong> column there is a <strong>1</strong>.<br />
For joined rows I want to use an aggregate function for each column, something like that:</p>
<pre><code>{ 'tunein': 'first', 'tuneout'... | <p>Let's create groups with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> based on where there are <code>0</code> in the <code>resume</code> column:</p>
<pre><code>df = (
df.groupby(df['resume'].eq(0).cumsum())
.agg({'accou... | python|pandas|numpy|data-science | 1 |
11,885 | 59,431,797 | Nifi ExecuteStreamCommand returns UnicodeEncodeError | <p>I am executing a python script within Nifi via ExecuteStreamCommand. When I run the file within the command line, I do not get any errors, and the output is correct. When I run the same file within Nifi- I recieve a unicode error. Is there a workaround for this?</p>
<p><strong>error log:</strong></p>
<pre><code>'u... | <p>Forcing utf-8 encoding on each column with text seemed to do the trick. I don't know why applying the encoding when saving the output didn't do the trick. I used the following code:</p>
<pre><code>x.str.encode('utf-8')
</code></pre> | python|pandas|unicode|apache-nifi|unicode-normalization | 0 |
11,886 | 59,137,920 | Return a list of column names as new column based on a condition in pandas | <p>My data for each customer and product looks like below : </p>
<pre><code>Customer P1 P2 P3 P4 P5 P6
c1 10 2 43 21 11 4
c2 1 3 32 1 6 3
c3 20 4 20 72 78 80
c4 30 80 31 31 29 20
</code></pre>
<p>I want the output as follows : </... | <p>First get all <code>P</code> columns with <code>iloc</code> and get positions of sorted values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>numpy.argsort</code></a>, use indexing and last convert values to lists:</p>
<pre><code>df1 = df.iloc[:... | python|python-3.x|pandas | 2 |
11,887 | 46,026,127 | tensorflow NotFoundError (see above for traceback): Key decode/rnn/multi_rnn_cell/cell_1/basic_rnn_cell/ | <p>I got error, trying to chatbot example in tensorflow( <a href="https://github.com/golbin/TensorFlow-Tutorials/tree/master/08%20-%20RNN/ChatBot" rel="nofollow noreferrer">https://github.com/golbin/TensorFlow-Tutorials/tree/master/08%20-%20RNN/ChatBot</a>)</p>
<p>I have no idea what error is.
bellow is error </p>
<p... | <p>You need to apply <a href="https://github.com/tensorflow/models/issues/466#issuecomment-286953049" rel="nofollow noreferrer">this solution</a>
by using the appropriate <code>vars_to_rename</code>
likely using this<br>
<code>"lstm/BasicLSTMCell/Linear/Bias": "lstm/basic_lstm_cell/biases"</code></p> | python|tensorflow | 0 |
11,888 | 46,010,035 | Python Data-Scraping Differentiation - millions vs. ones | <p>I'm currently scraping some tables on the internet where numbers are posted in varying numerical formats:</p>
<pre><code>Animal - Left in Wild
Tigers - 18
Deer - 18m
Pigs - 180000
</code></pre>
<p>I've managed to strip the m away from the number, but I am wondering if/how I could use a if statement to allow some m... | <p>A simple IF statement could help with what you're looking for:</p>
<pre><code>animal = "18m"
if 'm' in animal:
print animal.strip('m') + ",000,000"
if 'k' in animal:
print animal.strip('k') + ",000"
</code></pre>
<p>returns:</p>
<pre><code>18,000,000
</code></pre> | python|pandas|csv|web-scraping|python-requests | 1 |
11,889 | 50,979,208 | aggregating within multiindex dataframe pandas | <p>I am looking for help relating to this multiindex dataframe</p>
<pre><code>import numpy as np
import pandas as pd
array = [np.array(['jan','jan','feb','feb','mar','mar']), np.array(['food','rent','food','rent','food','rent'])]
df = pd.DataFrame(np.random.randint(0,high=100,size=(6,1)),index=array,columns=['expens... | <p>You can <code>groupby</code> index level (<code>food</code> and <code>rent</code> are at level 1 index):</p>
<pre><code>df.groupby(level=1).sum()
# expense
#food 166
#rent 161
</code></pre> | python-2.7|pandas|dataframe|multi-index | 0 |
11,890 | 50,671,842 | Tensorflow : NotFoundError: No such file or directory | <p>I am facing tensorflow model weight restoring issue. </p>
<p>So during training the model , I have saved my model checkpoint after each 500 iteration ,</p>
<pre><code>if j%500==0:
with open('iterres.txt','a') as f:
f.write(str({'epoch': i, 'test_accuracy': evaluate_(mode... | <p>I tried to found the answer but no luck , Then i did some experiment , so when you save your model you will get four files :</p>
<pre><code>model.data
model.index
model.meta
checkpoint
</code></pre>
<p>Now open checkpoint as .txt file where you will see some paths :</p>
<pre><code>model_checkpoint_path: "/home/g_... | python|python-3.x|tensorflow|checkpoint | 6 |
11,891 | 66,604,036 | Tensorflow / keras issue when optimizing with optuna | <p>I'm pretty new to machine learning, I've been trying to teach myself neural networks from following sentdex tutorials. I followed his tutorial on using recurrent neural networks for predicting the price of various crypto-currencies and succeeded after changing NumPy arrays and some of the syntax. Now I've been tryin... | <p>I believe the issue was in building the model using optuna. After several errors and fixing a lot of issues, I got it all working. If anyone's interested here's the section relevant to the errors I was getting.</p>
<pre><code> def create_model(trial):
# We optimize the numbers of layers, their units and weight de... | python|keras|tensorflow2.0|recurrent-neural-network|optuna | 1 |
11,892 | 66,522,854 | pytorch deep learning loading data sequentially and efficiently | <p>I have been doing neural network analysis on 20 thousand "images", each image represented in the form of the intensity of 100 * 100 * 100 neurons.</p>
<pre><code>x = np.loadtxt('imgfile')
x = x.reshape(-1, img_channels, 100, 100, 100)
//similarly for target variable 'y'
</code></pre>
<p>Above, the first di... | <p>Digging a while after posting the question, found out there is, of course, a way using torch.utils.data.Dataset. Each image-data can be saved in a separate file and all the filenames are listed in 'filelistdata'. Only the batch_size number of images will be loaded into memory when called using DataLoader (in the bac... | python|machine-learning|deep-learning|pytorch|resnet | 1 |
11,893 | 57,619,464 | After slicing some values from the edges, how to put the remaining values in exactly the same bins of histogram where they were before slicing? | <p>In the following code I have sliced first and last 5 values from array a. Now I want to plot a new histogram in which values of b should be exactly in the same bins where they were. How can I do that? After slicing the information that a value belongs to a certain bin is completely lost and also the if I plot new hi... | <p>You can specify the bins you want when plotting the second histogram. So take the generated bins from using vector a, and use them to plot histogram b</p>
<pre><code>a = np.sort(np.array([1,3,5,6,10,0,0,0,0,49,49,49,70,100,0,0,0]))
print(a)
n,bins,hist = plt.hist(a,bins=10)
b=a[5:-5]
new_count, new_bins, new_hist =... | python|numpy|matplotlib | 1 |
11,894 | 70,560,576 | Pandas calculated column to accrue information | <p>I have a data frame like so which records the type of an IP at a specific time.</p>
<pre><code>IP Time Type
101 2018-10-16 01:07:11 A
101 2018-10-16 01:08:34 A
101 2018-10-16 02:54:11 B
101 2018-10-16 14:07:39 A
</code></pre>
<p>How can I create a new column <code>NumSwitches</code> which... | <p>Try this:</p>
<pre><code>df['NumSwitches'] = (df['Type'] != df['Type'].shift()).cumsum() - 1
</code></pre> | python|pandas | 0 |
11,895 | 51,384,324 | How to use a variable on numpy mgrid input (numpy) | <p>I am unable to use the numpy mgrid function inclusively with a variable.
For example this works:</p>
<pre><code>grid_x, grid_y,grid_z = np.mgrid[0:10000:100j, 0:10000:200j,0:10000:100j]
</code></pre>
<p>While this fails:</p>
<pre><code>shape=(1137,1925,332)
inputHHb=35
inputHHv=35
inputNk=190
inputxi,inputyi,inpu... | <p>It is quite hard to answer your question with such sparse information, but I ll give it a try. Replace <code>inputShape[0]j</code> with <code>inputShape[0]*1j</code>:</p>
<pre><code>inputxi, inputyi, inputzi = np.mgrid[0:inputShape[0]*inputHHb:inputShape[0]*1j,
0:inputShape[0]*i... | python|numpy | 0 |
11,896 | 51,748,215 | Why is my NumPy array taking much *less* memory than it should? | <p>I am working with large matrices, like the <a href="https://grouplens.org/datasets/movielens/20m/" rel="nofollow noreferrer">Movielens 20m dataset</a>. I restructured the online file such that it matches the dimensions mentioned on the page (138000 by 27000), since the original file contains indices that are more of... | <p>I think your problem lies in the <code>todense()</code> call, which uses <code>np.asmatrix(self.toarray(order=order, out=out))</code> <a href="https://github.com/scipy/scipy/blob/v1.1.0/scipy/sparse/base.py#L816-L846" rel="nofollow noreferrer">internally</a>.
<code>toarray</code> creates its output with <code>np.ze... | python|numpy | 3 |
11,897 | 35,788,626 | How to plot a heatmap from pandas DataFrame | <p>Here is my dataframe:</p>
<pre><code> jan f m a m j \
2000 -7.894737 22.387006 22.077922 14.5455 15.8038 -3.33333
2001 -3.578947 11.958763 28.741093 5.05415 74.7151 11.2426
2002 -24.439661 -2.570483 1.810242 8.56044 84.5474 -26.9... | <p>That is straightforward using <a href="http://seaborn.pydata.org/" rel="noreferrer"><code>seaborn</code></a>; I demonstrate how to do it using random data, so all you have to do is to replace <code>data</code> in the example below by your actual dataframe.</p>
<p>My dataframe looks like this:</p>
<pre><code> ... | python|pandas|matplotlib|heatmap|seaborn | 22 |
11,898 | 36,176,769 | Rearrange numpy vector according to mapping rule | <p>I have a vector withs 0s and 1s. I want to have a new vector with rearranged values, whereas I have another vector with a mapping rule:</p>
<p>Example:</p>
<pre><code>input: 1,0,0,1
rule: 0,3,2,1
after mapping:1,1,0,0
</code></pre>
<p>The mapping vector determines for each index at which index in the new vector t... | <p>Let's say <code>a</code> is the original array and <code>b</code> is the mapping rule. Since the mapping rule says "at which index in the <strong>new</strong> vector the value can be found", you need to compute <code>a[c]</code> where <code>c</code> is the <strong>inverse</strong> of the permutation <code>b</code>. ... | python|numpy | 0 |
11,899 | 37,585,698 | Reuse an exisiting numpy array or create a new one? | <p>In iterative algorithms, it is common to use large numpy arrays many times. I want to fill value into a big existing numpy array, but I found create a new array is even faster. </p>
<pre><code>>>>import numpy as np
>>>a=np.arange(10000)
>>>b=a.copy()
>>>%timeit b=a+a # Every ti... | <ul>
<li><code>np.copyto(b,a);b+=a</code> is faster, but not the fastest way.</li>
<li><code>np.add(a,a,b)</code> is the best choice for now, 100000 loops, best of 3: 8.66 µs per loop. </li>
</ul>
<p>Maybe <code>b[:]=a+a</code> will genarate some temporary calculation spaces? I don't konw. But use "+=, -=, *=, add" th... | python|performance|numpy | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.