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 |
|---|---|---|---|---|---|---|
359,700 | 64,266,515 | Compare two 3d Numpy array and return unmatched values with index and later recreate them without loop | <p>I am currently working on a problem where in one requirement I need to compare two 3d NumPy arrays and return the unmatched values with their index position and later recreate the same array. Currently, the only approach I can think of is to loop across the arrays to get the values during comparing and later recreat... | <p>I think this may be what you're looking for:</p>
<pre><code>base_array = np.array([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]])
array_1 = b = np.array([[[1, 2,3], [3, 4,8]], [[5, 6,7], [7, 8,10]]])
match_mask = (base_array == array_1)
idx_unmatched = np.argwhere(~match_mask)
# idx_unmatched:
# array([[0, 1, ... | python|arrays|numpy|comparison | 1 |
359,701 | 64,303,825 | Accessing intermediate tensors of a Keras Model that were not explicitly exposed as layers in TF 2.0 | <p>Is it possible to access pre-activation tensors in a Keras Model? For example, given this model:</p>
<pre class="lang-python prettyprint-override"><code>import tensorflow as tf
image_ = tf.keras.Input(shape=[224, 224, 3], batch_size=1)
vgg19 = tf.keras.applications.VGG19(include_top=False, weights='imagenet', input... | <p>There is a way to access pre-activation layers for pretrained Keras models using TF version 2.7.0. Here's how to access two intermediate pre-activation outputs from VGG19 in a <em>single</em> forward pass.</p>
<p>Initialize VGG19 model. We can omit top layers to avoid loading unnecessary parameters into memory.</p>
... | python|tensorflow|keras|tensorflow2.0 | 1 |
359,702 | 64,524,795 | How to create a new column based on matching ID's and string's in names of other columns in the same data frame? | <p>I have tried to find a solution online but I cannot. I have a dataframe with 10 separate id columns, and 10 separate corresponding value columns for each ID. A brief example is shown below</p>
<p>Example:</p>
<pre><code>player_id_1 player_1_x player_id_2 player_2_x shooter_id
300 10 ... | <p>Let's <code>filter</code> the <code>player_id</code> like columns, the use <code>.eq</code> + <code>idxmax</code> to get the <code>player_id</code> columns where the match is found, finally use <code>lookup</code> to get values corresponding to <code>player_id's</code>:</p>
<pre><code>c = df.filter(like='player_id'... | python|pandas|dataframe|join|merge | 2 |
359,703 | 64,197,239 | KeyError: "None of [Index([...] are in the [columns] | <p>I've got numpy array with shape of (3, 50):</p>
<pre><code>data = np.array([[0, 3, 0, 2, 0, 0, 1, 2, 2, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 7, 0, 0, 0, 0,
1, 1, 2, 0, 0, 2],
[0, 0, 0, 0, 0, 3, 0, 1, 6, 1, 1, 0, 0, 0, 0, 2, 0, 0, 1, 0, 1, 0,... | <p>Suppose you have a df like this:</p>
<pre><code>df = pd.DataFrame({'person': [1,1,1], 'event': ['A','B','C']})
</code></pre>
<p>You can add new columns like this:</p>
<pre><code>import pandas as pd
import numpy as np
data = np.array([[0, 3, 0, 2, 0, 0, 1, 2, 2, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0,
0, 0,... | pandas | 3 |
359,704 | 64,532,940 | Multi-Head attention layers - what is a warpper multi-head layer in Keras? | <p>I am new to attention mechanisms and I want to learn more about it by doing some practical examples. I came across a Keras implementation for multi-head attention found it in this website <a href="https://pypi.org/project/keras-multi-head/#description" rel="nofollow noreferrer">Pypi keras multi-head</a>. I found two... | <p>I understand your confusion. From my experience, what the Multihead (<a href="https://pypi.org/project/keras-multi-head/#description" rel="nofollow noreferrer">this wrapper</a>) does is that it duplicates (or parallelize) layers to form a kind of multichannel architecture, and each channel can be used to extract dif... | tensorflow|keras|deep-learning|transformer-model|attention-model | 0 |
359,705 | 64,588,382 | Finding correlation between multiple variables and a target value | <p>I have an array of words, taken from a review of a hotel.
E.g</p>
<pre><code>array(['advantage', 'advice', 'anniversary', 'arrived', 'aveda', 'bangs',
'bath', 'bed', 'check', 'clean', 'closing', 'comfortable', 'deal',
'did', 'disappointed', 'distance', 'doors', 'easy', 'evening',
'existent', 'ex... | <p>You need to come up with a code that would give each of the words <strong>a rank from good to bad</strong>, starting with the good adjective with lower rank up to the bad ones with higher rank. I would start by sorting them and then giving them a numerical code that would reflect how good/bad a word is. <strong>Not... | python|pandas|numpy|correlation | 1 |
359,706 | 64,523,689 | Binarize a lot of features with condition | <p>I have Pandas dataframe with hundreds of categoric features (in numbers). I want to leave only top values in columns. I do already know, that there are only 3 or 4 most frequent values in each column, but I want to select it automatically. I need two ways to do it:</p>
<p>1)leave only 3 most frequent values. <em>Not... | <p>I will showcase what I'd like to use myself at work with a 2-columned data. <strong>Limitation</strong>: simultaneous ties in the 2nd, 3rd, and 4th places are not collected into the same cell in this solution. You may have to further customize this behavior depending on your purpose.</p>
<h2>Sample Data</h2>
<p>Ther... | python|pandas|dataframe|frequency|categorical-data | 0 |
359,707 | 64,412,896 | Can't import the movie_lens datasets from tensorflow_datasets in google colab | <p>I am learning python now.
When i am trying to import the movie_lens/100k-ratings data to my project, an error occur</p>
<pre><code>DatasetNotFoundError: Dataset movie_lens not found.
</code></pre>
<p>Here is my code</p>
<pre><code>import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommen... | <p>The movielens data set isn't in the <code>tensorflow-datasets</code> version that Google Colab currently uses by default (2.1.0 as of this writing).</p>
<p>Before trying to load the data set, you currently need to install the more up-to-date version of tensorflow datasets. Try running <code>!pip install tfds-nightly... | tensorflow|google-colaboratory | 2 |
359,708 | 64,405,516 | Find the number of mutual friends in Python | <p>I have a dataframe of users and their friends that looks like:</p>
<pre><code>user_id | friend_id
1 3
1 4
2 3
2 5
3 4
</code></pre>
<p>I want to write a function in <code>python</code> to compute the number of mutual friends for each pair:</p>
<pre><code>user_id | friend_id | ... | <p>The [ugly] idea is to construct a 4 point path that starts with a <code>user_id</code> and ends with the same <code>user_id</code>. If such a path exists, then 2 starting points have mutual friends.</p>
<p>We start with:</p>
<pre><code>df
user_id friend_id
0 1 3
1 1 4
2 ... | python|python-3.x|pandas|dataframe|mutual-friendship | 3 |
359,709 | 64,211,260 | How can I use a for loop in Python to create a string? | <p>For homework we were given the following problem:</p>
<blockquote>
<p>Use a for loop to create a string called chant with the value "Gimme a 1! Gimme a 2! Gimme a 3!..." all the way up to "Gimme a 5578!"</p>
</blockquote>
<p>I tried something like this:</p>
<pre><code>numbers=np.arange(1,5579)
fo... | <p>Try this:</p>
<pre><code>s=''
for i in range(1,5579):
s+='Gimme a '+str(i)+'!'
</code></pre>
<p>Output:</p>
<pre><code>print(s)
'Gimme a 1!Gimme a 2!Gimme a 3!Gimme a 4!...Gimme a 5578!'
</code></pre> | python|numpy|loops | 0 |
359,710 | 64,317,381 | 2D Heat equation -adding initial condition and checking if Dirichlet boundary conditions are right | <p>I am still fairly new to using the numpy and sympy library. Apologies if I have quite a few prints on there, I just wanted to check if the code was working.
I am trying to solve this 2D heat equation problem, and kind of struggling on understanding how I add the initial conditions (temperature of 30 degrees) and add... | <p>I think I have managed to sort it out and have checked the values after adding in the temperatures for each of the side from @chris's recommendation on looking at.<a href="https://scipython.com/book/chapter-7-matplotlib/examples/the-two-dimensional-diffusion-equation/" rel="nofollow noreferrer">https://scipython.com... | python|numpy|sympy|pde|dirichlet | 1 |
359,711 | 64,314,287 | Subtract 0.5 from every element of a numpy "array" | <p>With "a" a numpy array, sometimes</p>
<pre><code>a = a - 0.5
</code></pre>
<p>works, sometimes it doesn't. There are several variations on an array that I don't understand. When I print it out somehow it has gotten into this form.</p>
<pre><code>[list([0.5, 0.5, 0.2, 1])]
</code></pre>
<p>I've got to ei... | <pre><code>import numpy as np
def flatten(l):
if l == []:
return l
if isinstance(l[0], list):
return flatten(l[0]) + flatten(l[1:])
return l[:1] + flatten(l[1:])
inp = [[[.5,.5,2.,1.],0.,2.5]]
flat = flatten(inp)
r = np.array(flat)
p = r.copy()
print(p)
r = (p - 1/2) * 2
</code></pre>
<p... | python|arrays|numpy | 0 |
359,712 | 47,971,127 | Weighted cross-entropy tensorflow | <p>I couldn't find a tensorflow built-in that allows you to pass in labels which don't sum to 1, so tried writing my own: (Input is [batch_size,labels])</p>
<pre><code>tf.reduce_mean(tf.reduce_sum(y_true,axis=1) * tf.reduce_logsumexp(y_pred_logits,axis=1)
- tf.reduce_sum(y_true * y_pred_logits,axis=1))
</code></pre>
... | <p>I think it was correct, but I set the "epsilon" of Adam optimizer too low.</p> | tensorflow|cross-entropy|numerical-stability | 0 |
359,713 | 47,680,315 | Pandas: Calculating value of difference between current column value and the closest column value depending if it meets criteria at a different column | <p>This question is an extension of this one: <a href="https://stackoverflow.com/questions/47671075/pandas-calculating-value-of-difference-between-current-column-value-and-next-co">Pandas: Calculating value of difference between current column value and next column value depending if it meets criteria at a different co... | <p>One way would be to apply the previous answer to the reverse-ordered dataframe and then combine the results.</p>
<pre><code># do solution from previous answer
print(df)
position foobar difference
A 10 foo 780.0
B 440 foo 350.0
C 790 bar 6210.0
D 800 bar ... | python|pandas|dataframe | 1 |
359,714 | 47,920,624 | Convert pandas multiindex dataframe to nested dictionary | <p>I have a pandas multiindex dataframe that I'm trying to output as a nested dictionary. </p>
<pre><code># create the dataset
data = {'clump_thickness': {(0, 0): 274.0, (0, 1): 19.0, (1, 0): 67.0, (1, 1): 12.0, (2, 0): 83.0, (2, 1): 45.0, (3, 0): 16.0, (3, 1): 40.0, (4, 0): 4.0, (4, 1): 54.0, (5, 0): 0.0, (5, 1): 69.... | <p>For me working:</p>
<pre><code>d = {l: df.xs(l)['clump_thickness'].to_dict() for l in df.index.levels[0]}
</code></pre>
<p>Another solution similar like <a href="https://stackoverflow.com/questions/39067831/dataframe-with-multiindex-to-dict">DataFrame with MultiIndex to dict </a>, but is necessary filter column fo... | python|pandas | 5 |
359,715 | 47,877,516 | Dataframes columns get lost after using pd.concat | <p>I have the following situation:
I have a dataframe with a column 'revisions' which is formated as a dictionary containing multiple other dictionaries with the keys 'a' and 'b'.
The revisions belong to the key column id. What I was trying to do is get rid of the dict format. Thus I wanted to list for every subdiction... | <p>You are expanding the Series column2 into a data frame and then reassigning that data frame to df. Everything going on inside of pd.concat does not include column3. So when you reassign this result to df, you lose column3. The best way I know how to solve this is to assign the expansion of column2 into a new variabl... | python|pandas|dictionary|dataframe|concatenation | 0 |
359,716 | 47,554,397 | Count the number of user sessions, defined as intervals | <p>I have a dataset of user sessions, loaded into a Pandas DataFrame: </p>
<pre><code>SessionID, UserID, Logon_time, Logoff_time
Adx1YiRyvOFApQiniyPWYPo,AbO6vW58ta1Bgrqs.RA0uHg,2016-01-05 07:46:56.180,2016-01-05 08:04:36.057
AfjMzw8In8RDqK6jIfItZPs,Ae8qOxLzozJHrC2pr2dOw88,2016-01-04 14:48:47.183,2016-01-04 14:53:30.21... | <p>IIUC, we can do it this way:</p>
<pre><code>df.apply(lambda x: pd.Series([1] * len(pd.date_range(x.Logon_time, x.Logoff_time, freq='T')),
index=pd.date_range(x.Logon_time, x.Logoff_time, freq='T')), axis=1)\
.stack().reset_index(level=0, drop=True).resample('T').count()
</code></pre>
<p>Output(head):</... | python|pandas|intervals | 2 |
359,717 | 47,785,317 | Wrong version of function getting called in Python | <p>I am working on retrieving Inception V3 model's top layer in Keras/Tensorflow (in Jupyter Notebook).</p>
<p>I could retrieve the Inception V3 model and its weights correctly.
Now, I am trying to get Fully Connected layer (top layer) using following code snippet.</p>
<pre><code>base_model = InceptionV3(weights=weig... | <p>It turned out that name of these layers keep on changing. So best way is to enumerate all the layer names using <code>Model.layers[].name</code> or <code>Model.summary()</code> and use whichever name you want that is listed in the output.</p> | python|tensorflow|deep-learning|keras | 0 |
359,718 | 47,625,283 | "ModuleNotFound" for a pip install of tensorflow to Anaconda on Mac OS | <p>After a successful install in an <em>Anaconda</em> environment, on <em>Mac OS</em> using the recommended <a href="https://www.tensorflow.org/install/install_mac" rel="nofollow noreferrer">Tensorflow install</a>, trying it --</p>
<pre><code>import tensorflow
</code></pre>
<p>returns "ModuleNotFoundError"</p> | <p>The tensorflow install page recommends installing under Anaconda on the Mac by </p>
<pre><code>(tensorflow)$ pip install --ignore-installed --upgrade <URL of the tensor flow package>
</code></pre>
<p>See <a href="https://www.tensorflow.org/install/install_mac" rel="nofollow noreferrer">Installing with Anacon... | macos|tensorflow|pip|anaconda | 0 |
359,719 | 47,851,482 | Column compare and return values | <p>I got two dataframes df1 and df2. I am comparing column values from dataframe one against many column values in df2 and returning unique intersection without duplicates in another dataframe.</p>
<p>df1</p>
<pre><code> WORD
0 This
1 is
2 a
3 sample
4 sentence
5 ... | <p>By using <code>numpy.intersect1d</code></p>
<pre><code>pd.DataFrame([np.intersect1d(x,df1.WORD.values) for x in df2.values.T],index=df2.columns).T
Out[147]:
Noun Verb
0 Sample is
</code></pre>
<p>If you want to using pandas </p>
<pre><code>df2.mul(df2.apply(lambda x : x.isin(df1.WORD))).apply(lambda x : ... | pandas | 3 |
359,720 | 47,952,632 | Pandas - Check if a column label exists in another column's value and update the column | <p>I have a long list of glossary word and would like to check if in a passage contains the glossary and mark 1 as yes, 0 as no, simplify as below:</p>
<pre><code>>>> glossary = ['phrase 1', 'phrase 2', 'phrase 3']
>>> glossary
['phrase 1', 'phrase 2', 'phrase 3']
>>> df= pd.DataFrame(['Thi... | <p>You can use list comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</co... | python|pandas | 2 |
359,721 | 47,725,144 | How to read multiple files and load them into dataframe | <p>I have a list of csv's in a folder called 11 in C:\1. All the data has same number of columns.</p>
<p>A.csv</p>
<pre><code>aa zz 1 AA
aab qq 3 FF
ca qq 5 QQ
</code></pre>
<p>B.csv </p>
<pre><code>aa GG 09 VV
aab HH 03 WW
ca CC 0 UU
</code></pre>
<p>How ... | <p>You can add a spacer Data Frame on each file read, like this:</p>
<pre><code>import os
import pandas as pd
# with directory name 1, located at ~/1:
dir_name = "1"
path = "~"
dfs = []
# with files A.csv, B.csv in ~/1 (e.g. ~/1/A.csv):
for fname in os.listdir(f"{path}/{dir_name}"):
df = pd.read_csv(f"{path}/{d... | python|pandas|csv|path|glob | 0 |
359,722 | 47,984,547 | Sort a 2 index pivot table: values within group, index based on values | <p>I have a dataframe like this:</p>
<pre><code>x = pd.DataFrame({'col1':['bul', 'eng','eng', 'ger','ger', 'fra','fra'],
'col2':['fra', 'ger','fra', 'fra','eng', 'ger','eng'],
'col3':[ 1, 4, 2, 6, 7, 20, 5]})
pt = pd.pivot_table(x, index = ['col1', 'col2'], va... | <p>We can using a new para to achieve this </p>
<pre><code>pt['New']=pt.groupby(level='col1').col3.transform('max')
pt=pt.sort_values(['New','col3'],ascending=False).drop('New',1)
pt
Out[1445]:
col3
col1 col2
fra ger 20
eng 5
ger eng 7
fra 6
eng ger 4
fra ... | pandas|sorting|pivot-table | 4 |
359,723 | 47,592,386 | ValueError: Shape of passed values is X, indices imply Y in pandas apply and transform | <p>I've got 8-column data frame and would like to have another one with 2 columns. Values in those 2 columns are calculated from original 8 values.</p>
<p>Is it possible to do with <code>apply</code> or <code>transform</code>?</p>
<p>Example:</p>
<pre><code>jnd = pd.DataFrame(np.random.rand(18, 8))
def appl(s):
... | <p>You can convert output to <code>Series</code> with index which create new columns names:</p>
<pre><code>def appl(s):
"""particular processing is not important, only shapes matter.
Therefore just randomly select 2 of passed values"""
return pd.Series(np.random.choice(s, size=2), index=['a','b'])
prin... | python|pandas|transform|apply | 1 |
359,724 | 47,731,175 | How to only restore variables in the checkpoint in Tensorflow? | <p>In Tensorflow, my model is based on a pre-trained model, and I added a few more variables and remove some in the pre-trained model. When I restore the variables from the checkpoint file, I have to explicitly specify all variables I added to the graph that need to be excluded. For example, I did</p>
<pre><code>exclu... | <p>You should first find out all those variable that are useful(meaning also in your graph) and then add the joint set of the intersection of the two from the checkpoint rather than all from it. </p>
<pre><code>variables_can_be_restored = list(set(tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES)).intersection(tf.t... | tensorflow | 3 |
359,725 | 47,662,143 | What is the difference between tensors and sparse tensors? | <p>I am having troubles understanding the meaning and usages for Tensorflow <em>Tensors</em> and <em>Sparse Tensors</em>. </p>
<p>According to the documentation</p>
<p>Tensor</p>
<blockquote>
<p>Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of float... | <p>Matthew did a great job but I would love to give an example to shed more light on Sparse tensors with a example.</p>
<p><strong>If a tensor has lots of values that are zero, it can be called sparse.</strong></p>
<p>Lets consider a sparse 1-D Tensor</p>
<pre><code>[0, 7, 0, 0, 8, 0, 0, 0, 0]
</code></pre>
<p>A sp... | python|tensorflow | 34 |
359,726 | 47,775,512 | Emulate Excel AverageIFs with Pandas | <p>I am trying to emulate Excel's AVERAGEIFs function in Pandas on a date range, and so far have been unsuccessful. I understand that I need to use apply and groupby, but I obviously don't have the syntax correct as I receive this error: </p>
<pre><code>TypeError: can only concatenate list (not "Timedelta") to list
... | <p>IIUC, I think you want something like this:</p>
<pre><code>df['Avg Qty'] = (df.groupby([pd.Grouper(freq='180D', key='Date'),'A','B'])['Qty']
.transform('mean'))
</code></pre>
<p>Output:</p>
<pre><code> Date A B Qty Cost Avg Qty
0 2017-12-11 Cancer Golf 1 100 ... | python|pandas|pandas-groupby | 1 |
359,727 | 47,714,900 | How to merge two different pandas data frame in python | <p><em>by thought is using iterate the data frame column and check for required data in another column using condition checks.
suggest is it correct or any other way.</em></p> | <p>Merge, join and concatenate: look <a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow noreferrer">here</a></p> | python|pandas | 1 |
359,728 | 47,584,414 | pandas groupby on multiple columns | <p>I have a data set which contains state code and its status.</p>
<pre><code> code status
1 AZ a
2 CA b
3 KS c
4 MO c
5 NY d
6 AZ d
7 MO a
8 MO b
9 MN b
10 NV a
11 NV e
12 MO f
13 NY a
14 NY a
15 NY b
</code></pre>
<p>I want to filter out this data set which code contains onl... | <p>Let's filter the dataframe first for a, then groupby and count.</p>
<pre><code>df[df.status == 'a'].groupby('code').size()
</code></pre>
<p>Output:</p>
<pre><code>code
AZ 1
MO 1
NV 1
NY 2
dtype: int64
</code></pre> | python|pandas|data-science|data-cleaning | 2 |
359,729 | 47,818,822 | Can I use TensorBoard with Google Colab? | <p>Is there any way to use TensorBoard when training a TensorFlow model on Google Colab?</p> | <p><strong>EDIT:</strong> You probably want to give the official <a href="https://github.com/tensorflow/tensorboard/blob/master/docs/r2/tensorboard_in_notebooks.ipynb" rel="noreferrer"><code>%tensorboard</code> magic</a> a go, available from TensorFlow 1.13 onward.</p>
<hr>
<p>Prior to the existence of the <code>%t... | tensorflow|tensorboard|google-colaboratory | 93 |
359,730 | 47,817,250 | Filling Missing Values in a Time Series with Next and Prev Values | <p>I am trying to fill in the missing values of a time series like the one below. I am using Python3. </p>
<pre><code>Week Rainfall(cm)
1 1
2 NaN
3 9
4 10
5 11
6 NaN
7 NaN
8 14
</code></pre>
<p>I do not want to fill the missing values with the mean. If I were going in by hand and filling in t... | <p>You seem to be referring to the process of <a href="http://pandas.pydata.org/pandas-docs/version/0.16.2/generated/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer">linear interpolation</a>. If <code>rf</code> is your DataFrame:</p>
<pre><code>rf.interpolate()
Week Rainfall(cm)
0 1 1.0... | python|pandas|dataframe|linear-interpolation | 4 |
359,731 | 47,678,507 | PIL remove colour mixing between colour regions | <p>I have images with very few colours in them. (5 different colours max, and all are quite distinct.)</p>
<p>At the boundaries of the regions between colours, there is a (usually single pixel wide) line of a mix between these colours. How can I remove this?</p>
<p>I do manipulation with them as a numpy array afterwa... | <p>You can use <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.quantize" rel="nofollow noreferrer"><code>Image.quantize</code></a> to force all colors to match your palette. This changes the mode of your image to <code>P</code>, convert it back to <code>RGB</code> when you're done.</... | python|numpy|image-processing|pillow | 2 |
359,732 | 47,759,009 | get list of unique months from pandas column | <p>Let's say I have the following pandas <code>date_range</code>:</p>
<pre><code>rng = pd.date_range('9/1/2017', '12/31/2017')
</code></pre>
<p>I want to get a list of the unique months. This is what I've come up with so far but there has to be a better way:</p>
<pre><code>df = pd.DataFrame({'date': rng})
months = d... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a> because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetmeIndex.strftime.html" rel="nofollow noreferrer"><code>DatetmeIndex.strftime</code></a> retur... | python|pandas | 6 |
359,733 | 47,847,156 | Finding matching columns in pandas including NaNs | <p>I have a quite specific question regarding <code>pandas</code>. I have two DataFrames, both are binary : One containing multiple patterns to match lets say :</p>
<pre><code>0 : 1,NaN,1,Nan,Nan
1 : Nan,1,1,Nan,Nan
</code></pre>
<p>and one containing records of actual data</p>
<pre><code>0 : 1,0,0,1,0
1 : 0,0,0... | <p>If is binary we can using <code>duplicated</code></p>
<pre><code>df=pd.concat([df1.fillna(0),df2],keys=['df1','df2'])
df[df.astype(int).duplicated(keep=False)]
Out[37]:
1 2 3 4 5
df1 0 1.0 0.0 1 0.0 0.0
df2 2 1.0 0.0 1 0.0 0.0
</code></pre>
<p>EDIT </p>
<pre><code>dd=df1.stack().rese... | python|pandas | 2 |
359,734 | 47,575,000 | Data Manipulation - using data frame aggregation function | <p>You guys were very helpful with my question before - see link below. I was looking to sort the index which had alphanumeric values.
I have run this script which was successful today but have been receiving an error:</p>
<pre><code>/Library/Python/2.7/site-packages/pandas/core/groupby.py:4036: FutureWarning: using a... | <p>You can use instaed <code>agg</code> function <code>sum()</code> and then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>:</p>
<pre><code>import natsort as ns
df = df.groupby(['customer', 'Duration'])['sum'].su... | pandas|sorting|indexing|aggregate|pandas-groupby | 1 |
359,735 | 47,680,732 | Pandas - how do you create a new data frame based on another dataframe? | <p>I have a dataframe that contains school types and their locations. One of the columns is "Institude_Type" and the two school types are "Secondary (non-grammar) School" and "Secondary (grammar) School". I want to take all of the Secondary (non-grammar) School's information and put it into another dataframe - but I'm ... | <p>use the built-in copy function:</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html</a></p>
<p>For example:</p>
<pre><code>schoolCopy = schoolDataFrame[allTheC... | python|pandas|dataframe | 2 |
359,736 | 47,651,708 | Iteration over the dictionary and extracting values | <p>I have a dictionary (result_dict) as follows.</p>
<pre><code>{'11333216@N05': {'person': {'can_buy_pro': 0,
'description': {'_content': ''},
'has_stats': '1',
'iconfarm': 3,
'iconserver': '2214',
'id': '11333216@N05',
'ispro': 0,
'location': {'_content': ''},
'mbox_sha1sum': {'_content': '8e... | <p>I think you could also try to do it more of a pandas way instead of pure dictionary iteration. it's not necessarily the fastest but given you are new to python and pandas, I think it's good thing to know that pandas can handle this well.</p>
<p>I am assuming you are using pandas <code>DataFrame</code>, not just dic... | python|json|pandas|dictionary|flickr | 0 |
359,737 | 47,722,603 | Pandas to_csv - Not save index values repeatedly? | <p>Pandas 0.20.3 - Excuse the poor title. I don't know the best way to describe it.</p>
<p>DataFrame:</p>
<pre><code>In [363]: df
Out[363]:
IP Jroid ST
0 127.0.0.3 Joid12 stq
1 127.0.0.2 Jroid2 stt
2 127.0.0.1 Jroid1 sth
3 127.0.0.1 Jroid1 stl
4 127.0.0.1 Jroid3 stj
5 127.0.0.1 ... | <p>As DeepSpace stated <em>it won't be a valid CSV format</em></p>
<p>You can do it within <code>.xlsx</code> </p>
<pre><code>df.to_excel('df.xlsx', engine='xlsxwriter')
</code></pre>
<p><a href="https://i.stack.imgur.com/F3mOn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F3mOn.png" alt="enter ... | python|pandas | 2 |
359,738 | 47,947,391 | How to find quantile from frequency data? | <p>Suppose I have a table of data where customers have purchased things as such:</p>
<pre class="lang-none prettyprint-override"><code>Customer|Price|Quantity Sold
a | 200 | 3.3
b | 120 | 4.1
c | 040 | 12.0
d | 030 | 16.76
</code></pre>
<p>This is supposed to be a crude represe... | <p>For a set of discrete values, the median is found by sorting and taking the central value. However since you have continuous values of <code>Quantity</code>, it seems like you're really looking for the median of a probability distribution, where <code>Price</code> is distributed with relative frequencies given by <c... | python|pandas|statistics|quantile | 4 |
359,739 | 47,579,422 | Already implemented neural network on Google Cloud Platform | <p>I have implemented a neural network model using Python and Tensorflow, which normally runs on my own computer.
Now I would like to train it on new datasets on the Google Cloud Platform. Do you think it is possible? Do I need to change my code? </p>
<p>Thank you very much for your help!</p> | <p>Google Cloud offers the <a href="https://cloud.google.com/ml-engine/" rel="nofollow noreferrer">Cloud ML Engine</a> service, which allows to train your models and perform predictions without the need of running and maintaining an instance with the required software.</p>
<p>In order to run the TensorFlow NN models y... | tensorflow|neural-network|deep-learning|google-cloud-platform|google-cloud-ml | 1 |
359,740 | 47,552,767 | How can I randomize the values within my numpy array? | <pre><code>[[ 208.47 26. ]
[ 202.84 17. ]
[ 143.37 10. ]
...,
[ 45.99 3. ]
[ 159.31 10. ]
[ 34.12 4. ]]
[[ 58.64 1. ]
[ 44.31 19. ]
[ 37.89 14. ]
...,
[ 46.86 4. ]
[ 60.73 5. ]
[ 41.91 6. ]]
[[ 36.6 4. ]
[ 219.29 17. ]
[ 64.77 5. ]
...,
[ 51.85 3... | <p>As @kazemakase has commented, the answer is simply using: </p>
<pre><code>np.random.rand(k, 2) * [300, 100]
</code></pre> | python|numpy | 0 |
359,741 | 47,803,233 | Do python's numeric types impact the low-level precision of a number? | <p>For example, I understand <code>float</code> is usually represented by a C <code>double</code>, and integers have unlimited precision, per the <a href="https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex" rel="nofollow noreferrer">docs</a>. <a href="https://docs.scipy.org/doc/numpy-1.13.0... | <p>The above comment is completely right and also mentions some form of checking.</p>
<p>But let's do some tiny demo where we <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.nbytes.html#numpy.ndarray.nbytes" rel="nofollow noreferrer">read out</a> the consumed memory:</p>
<pre><code>... | python|numpy | 3 |
359,742 | 47,896,617 | How do you delete rows with a certain object in pandas, python? | <p>I have a column in my data that contains these kind of values</p>
<p>2</p>
<p>2</p>
<p>yes</p>
<p>2</p>
<p>yes</p>
<p>In python pandas how would I identify the entire row containing a string of letters and then delete or drop the entire row?</p>
<p>Thanks</p> | <p>IIUC:</p>
<pre><code>df = df[~pd.to_numeric(df['col'], errors='coerce').isna()]
</code></pre>
<p>or</p>
<pre><code>df = df[pd.to_numeric(df['col'], errors='coerce').notna()]
</code></pre> | python|pandas|jupyter-notebook | 1 |
359,743 | 47,841,790 | Efficient calculation of the diagonal of hat matrix: inv(X'WX)'X' | <p>As part of a disease risk model I'm trying to implement a computation from a paper (in Python/numpy), part of which is the following matrix computation:</p>
<p><img src="https://chart.googleapis.com/chart?cht=tx&chl=Q%20%3D%20X%28X%5ETWX%29%5E%7B-1%7DX%5ET%0D%0A" alt="foo+baz"></p>
<p>where:</p>
<ul>
<li>X an... | <p>(In a now deleted comment i said it's impossible given some density- and hardware-assumptions treating it as black-box. But it seems it can be done. That does not mean it's the correct approach!)</p>
<p>So without analyzing the background of this formula, we can do some basic approaches given minimal assumptions an... | numpy|matrix | 3 |
359,744 | 47,710,707 | Cuda GPU is slower than CPU in simple numpy operation | <p>I am using this code based on <a href="https://devblogs.nvidia.com/parallelforall/numba-python-cuda-acceleration/" rel="noreferrer">this article</a> to see the GPU accelerations, but all I can see is slowdown:</p>
<pre><code>import numpy as np
from timeit import default_timer as timer
from numba import vectorize
im... | <p>Probably your array is too small and the operation too simple to offset the cost of data transfer associated to the GPU. Other way to see it, is that you're not being fair in your timing since for the GPU it also is timing the memory transfer time and not only the processing time.</p>
<p>Try some more challenging e... | python|numpy|cuda|nvidia | 8 |
359,745 | 47,768,406 | Extract Uniques and loop | <p>I have a dataframe that looks like this: </p>
<pre><code> A B C
0 1 2 PRODUCT_1
1 3 2 PRODUCT_2
2 3 2 PRODUCT_4
3 3 2 PRODUCT_5
4 5 2 PRODUCT_1
5 3 2 PRODUCT_3
</code></pre>
<p>I want to, for each unique product, perform a model prediction with A and B columns, and store the correspon... | <p>Starting with - </p>
<pre><code>df = pd.DataFrame(...) # your data
df
A B C
0 1 2 PRODUCT_1
1 3 2 PRODUCT_2
2 3 2 PRODUCT_4
3 3 2 PRODUCT_5
4 5 2 PRODUCT_1
5 3 2 PRODUCT_3
</code></pre>
<p>Find uniques first, using </p>
<pre><code>uniques = df.C.unique()
uniques
array(['PRODUCT_1... | python|pandas|group-by|unique | 0 |
359,746 | 47,865,986 | Numpy TypeError for function | <p>I have been implementing an algorithm that requires I take the average of vectors from a specific point to a set of other points and "unitise" it. As such, I use this function:</p>
<pre><code>import numba
import numpy
def dist(a,b):
return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
@jit
def point_average(o, points)... | <p><code>points</code> is a <code>list</code> of <code>arrays</code>, not a 2D <code>array</code>. Hence you cannot do</p>
<pre><code>points[i, 0]
</code></pre>
<p>you could only do</p>
<pre><code>points[i][0]
</code></pre>
<p>Also, if you consequently use NumPy arrays instead of lists and arrays, you don't need Nu... | python|numpy | 0 |
359,747 | 47,770,575 | CSV file is being created larger than the size of my original data in python/pycharm? | <p>I am trying to load a set of around 10000 images as numpy arrays into a CSV file to train a model. My problem is that my original data is of 40 MB while the csv that is created is of 3 GB which i cannot figure out why. ideally it should be less than the data. i am working on ubuntu 16.04 with pycharm using python 3 ... | <p>To me it seems like having a 3Gb file is to be expected given your data and how you are storing it:</p>
<p>So you are starting with compressed JPEG images, <strong>jpeg with high quality (Q=50) have a compression ratio of about 15</strong> <a href="https://en.wikipedia.org/wiki/JPEG#Effects_of_JPEG_compression" rel... | python|csv|numpy|bigdata | 4 |
359,748 | 49,003,555 | Pass complex numpy array to C++ in Cython | <p>I want to Cythonize portion of a <code>pyx</code> script which involves work with numpy arrays with complex numbers. The relevant portion of the python script looks like this:</p>
<pre><code>M = np.dot(N , Q)
</code></pre>
<p>In my work, <code>N</code>, <code>Q</code> and <code>M</code> are numpy arrays with compl... | <p>This error message is telling you what's wrong:</p>
<p>mat.pyx:17:27: Cannot assign type 'double complex *' to 'double *'</p>
<p>That is, you have a double complex pointer from numpy (pointer to complex128 numpy dtype) and you're trying to pass that into the C++ function using double pointers. C++ needs to be abl... | python|c++|numpy|cython|cythonize | 1 |
359,749 | 49,100,865 | Why "softmax_cross_entropy_with_logits_v2" backprops into labels | <p>I am wondering why in Tensorflow version 1.5.0 and later, <a href="https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits_v2" rel="noreferrer">softmax_cross_entropy_with_logits_v2</a> defaults to backpropagating into both labels and logits. What are some applications/scenarios where you w... | <p>I saw the github issue below asking the same question, you might want to follow it for future updates.</p>
<p><a href="https://github.com/tensorflow/minigo/issues/37" rel="nofollow noreferrer">https://github.com/tensorflow/minigo/issues/37</a></p>
<p>I don't speak for the developers who made this decision, but I w... | tensorflow|machine-learning|neural-network|cross-entropy | 6 |
359,750 | 48,952,134 | The tf.train.batch function is generating tensors batch of shape (8, 8, 299, 299, 3) | <p>I am using Tensorflow 1.5 GPU version on Windows 10.</p>
<p>This is the code.</p>
<pre><code>targets = convert_to_onehot(labels_dir, no_of_features = num_classes)
assert targets.shape == (8,120), 'THE TARGETS SHAPE IS NOT CORRECT'
targets = tf.constant(targets, dtype = tf.float32)
Images = [] #TO STORE THE RESIZE... | <p>To the arguments in tf.train.batch add in the argument <code>enqueue_many = True</code>, the default is <code>False</code>. This tells tensorflow that the first dimension is an index of your samples. </p>
<p>Source: tensorflow documentation. <a href="https://www.tensorflow.org/api_docs/python/tf/train/batch" rel="n... | python|tensorflow | 0 |
359,751 | 49,201,236 | Check the total number of parameters in a PyTorch model | <p>How do I count the total number of parameters in a PyTorch model? Something similar to <code>model.count_params()</code> in Keras.</p> | <p>PyTorch doesn't have a function to calculate the total number of parameters as Keras does, but it's possible to sum the number of elements for every parameter group:</p>
<pre><code>pytorch_total_params = sum(p.numel() for p in model.parameters())
</code></pre>
<p>If you want to calculate only the <em>trainable</em... | python|pytorch | 231 |
359,752 | 49,036,714 | expanding each row in a dataframe | <p>Consider this simple example</p>
<pre><code>data = pd.DataFrame({'mydate' : [pd.to_datetime('2016-06-06'),
pd.to_datetime('2016-06-02')],
'value' : [1, 2]})
data.set_index('mydate', inplace = True)
data
Out[260]:
value
mydate
2016-06-06... | <p>I modify little bit of your function </p>
<pre><code>def expand_onerow(df, ndaysback = 2, nhdaysfwd = 2):
new_index = pd.date_range(pd.to_datetime(df.index[0]) - pd.Timedelta(days=ndaysback),
pd.to_datetime(df.index[0]) + pd.Timedelta(days=nhdaysfwd),
... | python|pandas | 1 |
359,753 | 49,291,382 | Overlay histograms in one plot | <p>I have two dataframes that I'm trying to make histograms of. I would like to overlay one histogram over the other and show them in the same cell, so I can easily compare the distributions. Can anyone suggest how to do that? I have example code and data below. This will plot the histograms separately one above th... | <p>Use <code>ax</code>:</p>
<pre><code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
fig = plt.figure()
ax = fig.add_subplot(111)
df = pd.DataFrame([1, 3, 5, 1], columns=["bob"], index=[1, 2, 3, 4])
df2 = pd.DataFrame([3, 3, 2, 1], columns=["bob"], index=[1, 2, 3, 4])
ax.hist([df, df2], la... | python-2.7|pandas | 2 |
359,754 | 48,976,142 | Python Pandas rolling sum place value at the top of window | <p>I would like to use the rolling method of Pandas. I need a slight adjustment, however, I would like the 'value' placed at the top of the 'window'.</p>
<p>Currently, I am using this:</p>
<pre><code>self.df['new_col'] = self.df['Zone3'].rolling(4).sum()
</code></pre>
<p>Which is producing this:</p>
<pre><code> ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a>:</p>
<pre><code>self.df['new_col'] = self.df['Zone3'].rolling(4).sum().shift(-3)
</code></pre>
<p>Or more general:</p>
<pre><code>N = 4
df['new_col'] = df['Zone3'].rolling(... | python|pandas|dataframe|rolling-sum | 3 |
359,755 | 48,968,681 | Java incompatible type error | <p>The following code is a part of a java program for making predictions with inception v3 model using Tensorflow library.</p>
<pre><code>private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
try (Graph g = new Graph()) {
g.importGraphDef(graphDef);
try (Session s = new Sess... | <p>Okay I figured it out.Replace the following</p>
<pre><code>result.copyTo(new float[1][nlabels])[0];
</code></pre>
<p>to the following:</p>
<pre><code> float[][] res = new float[1][nlabels];
result.copyTo(res);
return res[0];
</code></pre>
<p>Perhaps the first line of code wor... | java|tensorflow|incompatibletypeerror | 0 |
359,756 | 49,302,465 | Drop Pandas columns with a high percentage of NaN values | <p>Let's say I have the following data.</p>
<pre><code>df = pd.DataFrame({'group':list('aaaabbbb'),
'val':[1,3,3,np.NaN,5,6,6,2],
'id':[1,np.NaN,np.NaN,np.NaN,np.NaN,3,np.NaN,3]})
df
</code></pre>
<p>I want to drop columns where the percentage of NaN values is over 50%. I cou... | <p>Could use <code>thresh</code> param of dropna.</p>
<pre><code>df.dropna(axis=1, thresh=int(0.5*len(df)))
</code></pre> | python|pandas | 9 |
359,757 | 49,180,662 | Tensorflow download_and_convert_mnist_m.py No such file or directory: '~/dsn_data/mnist_m/mnist_m_train' | <p>I have a weird error message using the download_and_convert_mnist_m.py script from github <a href="https://github.com/tensorflow/models/tree/master/research/domain_adaptation/datasets" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/domain_adaptation/datasets</a>. </p>
<p>The com... | <p>I solved it. The correct command is without the equal sign.</p>
<pre><code>python domain_adaptation/datasets/download_and_convert_mnist_m.py --dataset_dir=~/dsn_data/
</code></pre> | python|tensorflow|mnist | 0 |
359,758 | 48,951,622 | wrong output size after conv2d function | <p>the image size is [m,32,32,3] (m = no. of training examples) </p>
<p>the filter size is [3,3,3,10] </p>
<p>stride = 1</p>
<p>padding = None</p>
<p>if I convolve this using tensorflow.nn.conv2d then the output shape should be this, according to the formula</p>
<pre><code>out ={ ( 32 - 3 + 2*(0) ) / 1 }+ 1 = 30
<... | <p>padding = "SAME" means:</p>
<pre><code>input = [1, 2, 3, 4, 5, 6, 7, 8]
filter size = [1, 3]
stride = [2]
so input to filter will be [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 0]]
</code></pre>
<p>padding = "VALID" means:</p>
<pre><code>input = [1, 2, 3, 4, 5, 6, 7, 8]
filter size = [1, 3]
stride ... | tensorflow|computer-vision|deep-learning | 3 |
359,759 | 49,322,481 | split data frame pandas if sequence of column value change | <p>I have a dataset in a form of:</p>
<pre><code>A B C D label
6 2 6 8 0
2 5 3 6 0
4 3 4 9 1
5 7 5 5 1
6 4 5 8 0
</code></pre>
<p>in which each row is a label with a unique value, and that unique value is repeating after some lines, so there are 7 labels to ... | <p>We may need a new parameter here </p>
<pre><code>df=df.assign(new=df.label.diff().ne(0).cumsum())
df[df.new==df.groupby('label').new.transform('min')]
Out[206]:
A B C D label new
0 6 2 6 8 0 1
1 2 5 3 6 0 1
2 4 3 4 9 1 2
3 5 7 5 5 1 2
</code></pre>
<p>Save t... | python|pandas | 2 |
359,760 | 49,110,112 | concatenate multiindex into single index in pandas series | <p>I have a <code>pandas.Series</code> with multiindex:</p>
<pre><code>index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
('two', 'a'), ('two', 'b')])
s = pd.Series(np.arange(1.0, 5.0), index=index)
print(s)
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float... | <p>Use <code>map</code> with <code>join</code>:</p>
<pre><code>s.index = s.index.map('_'.join)
</code></pre>
<p>Alternative is <code>list comprehension</code>:</p>
<pre><code>s.index = ['{}_{}'.format(i, j) for i, j in s.index]
print (s)
one_a 1.0
one_b 2.0
two_a 3.0
two_b 4.0
dtype: float64
</code></pr... | python|pandas | 21 |
359,761 | 48,898,665 | Generate a random symmetric tensor in python | <p>I want to generate a random (gaussian) tensor symmetric with respect to all the permutations of the axes. In the end I want all the entries with the same distribution, so tricks like summing over all the permutation and rescaling by sqrt(k!), where k is the order of my tensor, don't work. eg:</p>
<pre><code>import ... | <p>Actually, the method you present works; it just needs a small modification.</p>
<p>Use the fact that the sum of normal random variables, is another normal random variable with the variances summed, <a href="https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables" rel="nofollow noreferrer">e.g. see... | python|random|tensorflow|tensor|symmetric | 0 |
359,762 | 49,222,414 | Joining letters using lambdas | <p>I have a DataFrame that contains a column with lists of letters:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id': [1, 2, 3, 4, 10],
'date': [4, 5, 6, 7, 8],
'str': [["a", "b"],["b", "c"],["c", "d"],["d", "e"],["e", "f"]]})
</code></pre>
<p>I want to joi... | <p>You can <code>apply</code> <code>join</code></p>
<pre><code>df.str.apply(' '.join)
Out[162]:
0 a b
1 b c
2 c d
3 d e
4 e f
Name: str, dtype: object
</code></pre>
<p>Also without apply </p>
<pre><code>df['str'].str.join(sep=' ')
Out[163]:
0 a b
1 b c
2 c d
3 d e
4 e f
Name: str, dty... | python|pandas|lambda | 3 |
359,763 | 48,953,875 | Copying data from one pandas dataframe to other based on column value and separated by comma | <p>I have two dataframes viz., df1 and df2.</p>
<p><strong>df1</strong> is like</p>
<pre><code>Index YH HE MT CU EI
0 Dot Sf Sy Lc
1 Rls Bd Sa Ta
2 Fs Ft Rg
</code></pre>
<p>And <strong>df2</strong> is like </p>
<pre><code>Index Z1 Z2 Z3
0 YH HE
1 HE ... | <p>The answer already contain in the previous question </p>
<pre><code>s=df2.set_index('Index').astype(object).apply(lambda x : x.map(df1.set_index('Index').to_dict('l')))
pd.concat([df2.set_index('Index'),s.fillna('').applymap(','.join)])
Out[1798]:
Z1 Z2 Z3
Index
0 ... | python|pandas|dataframe | 1 |
359,764 | 49,111,859 | how to merge two dataframes and sum the values of columns | <p>I have two dataframes</p>
<pre><code>df1
Name class value
Sri 1 5
Ram 2 8
viv 3 4
df2
Name class value
Sri 1 5
viv 4 4
</code></pre>
<p>My desired output is,</p>
<pre><code>df,
Name class value
Sri 2 10
Ram 2 8
viv 7 8
</code></pre>
<p>Please help, thanks in adva... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a> for both <code>DataFrame</code>s, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="noreferrer"><code>add</code></a> an... | python|pandas|dataframe|data-analysis | 18 |
359,765 | 49,228,131 | Subtract two columns of two data frames | <p>I have two data frames:</p>
<p>dt1:</p>
<pre><code> date value
0 20000101 2
1 20100101 5
</code></pre>
<p>dt2:</p>
<pre><code> date value
0 20000101 1
1 20100101 1
</code></pre>
<p>The new data frame is the subtraction of dt1.value and dt2.value:</... | <p>You can try setting <code>index</code> on <code>index</code> and <code>date</code> columns and subtract two <code>dataframe</code>:</p>
<pre><code>dt = (dt1.set_index(['index', 'date'])- dt2.set_index(['index', 'date'])).reset_index()
dt
</code></pre>
<p>Result:</p>
<pre><code> index date value
0 0 ... | python|pandas|dataframe | 2 |
359,766 | 49,199,943 | Not able to generate correct English to SQL translations using LSTM for machine translation | <p>I'm using recurrent neural networks to train a model to translate sample english sentences such as "fetch all employee data" into sql such as "SELECT * FROM EMPLOYEE". Right now my program takes 100 epochs of training time but translates all the inputs the same. Required libraries are tensorflow and keras. Could som... | <p><strong>TLDR;</strong> Your dataset is very small, biased and lacks the variety needed for RNNs. So you need 'some tricks' to make your code work. </p>
<p>The problem is <strong>you</strong> <strong>didn't shuffle your input data.</strong> (The fully working source code is <a href="https://drive.google.com/file... | tensorflow|machine-learning|nlp|deep-learning|machine-translation | 1 |
359,767 | 48,933,697 | Pandas itertuples are not named tuples as expected? | <p>Using this page from the Pandas documentation, I wanted to read a CSV into a dataframe, and then turn that dataframe into a list of named tuples.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.itertuples.html?highlight=itertuples" rel="nofollow noreferrer">https://pandas.pyd... | <p>"Named tuple" is not a type. <code>namedtuple</code> is a type <em>factory</em>. <code>pandas.core.frame.Synonym</code> is the type it created for this call, using the name <em>you</em> picked:</p>
<pre><code>for row in df.itertuples(index=False, name="Synonym"):
# ^^^^^^^^^^^^^^... | python|pandas|csv|python-collections | 1 |
359,768 | 49,289,451 | Pandas to_csv() always give TimeoutError: [Errno 60] Operation timed out | <p>I have a huge dataset that I need to write to csv into a shared file drive.
I did this before and worked on the same data.
The only difference this time is that I changed the deliminator from a comma "," into a semicolon ";", but that shouldn't change anything right?</p>
<p>My data is a pandas dataframe; it has s... | <p>Try toggling the delimiter back to ',' to make sure it still works that way</p>
<p>Assuming it does, likely it's a formatting problem - something somewhere along the way has an extra semi-colon in it, is messing up the table structure, and the resulting cascade results in way too much data written to disk or some o... | python|pandas | 0 |
359,769 | 48,915,426 | How works ANeuralNetworksMemory_createFromFd? | <p>In Android Neural Network API docs says: Creates a shared memory object from a file descriptor.</p>
<p>But I can't find any place that specifies how is the format of this file, on TFL source code:</p>
<p>allocation.cc:</p>
<pre><code>MMAPAllocation::MMAPAllocation(const char* filename,
... | <p>The loading of the model file and the parsing of it are done separately. This makes it easier to mix-and-match between different memory models and different file formats. It also makes it possible to use these building blocks for other functions, like loading inputs from a file.</p>
<p>ANeuralNetworksMemory_createF... | android|c++|c|tensorflow-lite|nnapi | 1 |
359,770 | 49,189,496 | Can symmetrically paddding be done in convolution layers in Keras? | <p>I read that the <code>padding</code> is <code>same</code> or <code>avlid</code> in convolution layers in Keras, and I think zeros are padded.</p>
<p>Is there any way to do a symmetrically padding in Keras?</p>
<p>It seems that this can be done with TensorFlow's <a href="https://www.tensorflow.org/api_docs/python/t... | <p>I've written an example layer in keras which calls the tensorflow padding backend. </p>
<pre><code>import keras.backend as K
from keras.layers import Layer
class SymmetricPadding2D(Layer):
def __init__(self, output_dim, padding=[1,1],
data_format="channels_last", **kwargs):
self.outp... | python|tensorflow|keras | 2 |
359,771 | 49,304,817 | PyTorch: Comparing predicted label and target label to compute accuracy | <p>I'm trying to implement <a href="http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#test-the-network-on-the-test-data" rel="nofollow noreferrer">this</a> loop to get the accuracy of my PyTorch CNN (The complete code of it is <a href="https://github.com/philippHRO/Customized_Dataloader_two/blob/master/... | <p>Indexing in <code>pytorch</code> works mostly like indexing in <code>numpy</code>. To index all rows of a certain column <code>j</code> use: </p>
<pre><code>tensor[:, j]
</code></pre>
<p>Alternatively, the <a href="http://pytorch.org/docs/0.3.1/tensors.html#torch.Tensor.select" rel="nofollow noreferrer">select</a>... | python|python-3.x|torch|pytorch|tensor | 0 |
359,772 | 49,039,465 | What are other methods to find curvature of a polynomial apart from np.polyfit() | <p>I am trying to find the curvature of a polynomial. X and Y are python lists of X and Y coordinates respectively. I use <code>scipy.interpolate</code> because I am able to see better curves in my image. But once I find the coefficients of a 2D polynomial and re-plot them back into the image, the replotted curve looks... | <p>Use <code>np.polyval</code> instead of list comprehension to calculate the polynomial values at the given coordinates. It's usually faster, and less error-prone than typing out the terms by hand. The result will be <code>ndarray</code> instead of Python list.</p>
<pre><code>poly_y = np.polyval(z, X)
</code></pre>
<p... | python|numpy|scipy|curve-fitting | 0 |
359,773 | 48,918,639 | python dataframe replace partial strings in a column based on other column's condition | <p><a href="https://i.stack.imgur.com/Uf4Mg.png" rel="nofollow noreferrer">Dataframe</a> click to see the screenshot because I am new here, I need 10 reputation to embed pics </p>
<p><a href="https://i.stack.imgur.com/jrkhu.png" rel="nofollow noreferrer">Expected result</a></p>
<p>Dataframe is imported from a csv fil... | <p>This emulates the input you are showing in your screenshot:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"type": ["a", "c", "d", "a", "b", "a", "a", "c"],
"tags": ["col_t1, col_red, large", np.nan, "col_t2, col_black, small",
"col_t4, large... | python|string|pandas|dataframe|conditional-statements | 1 |
359,774 | 49,171,660 | ValueError when reading a sas file with pandas | <p><strong>pandas.read_sas()</strong> prints traceback messages that I cannot remove. The problem is it prints messages for EACH row it's reading, so when I try to read the whole file it just freezes printing too much.</p>
<p>I tried from other stackoverflow answers</p>
<pre><code>import warnings
warnings.simplefilte... | <p>As highlighted in the traceback, the error is caused by a bug in the <code>pandas</code> implementation of RLE decompression, which is used when the SAS dataset is exported using CHAR (RLE) compression.</p>
<p>Note the <code>pandas</code> issue created for this topic: <a href="https://github.com/pandas-dev/pandas/i... | python|pandas|valueerror | 0 |
359,775 | 49,278,571 | Python, Machine Learning: Are there any API that can split dataset and shuffle? | <p>I have a dataset with 10000 samples, and 4 classes (0, 1, 2, 3) label.</p>
<pre><code>>>>data.shape
(10000, 250)
>>>label.shape
(10000,)
</code></pre>
<p>and, I wonder are there any API that could split the data into training and test data and shuffle?</p>
<p>for example:</p>
<pre><code>(traini... | <p>SKLearn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">train_test_split</a> is what you're looking for, using the following:</p>
<pre><code>from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = tr... | python|numpy|tensorflow|machine-learning|deep-learning | 3 |
359,776 | 49,232,243 | Sorting a grouped dataframe | <p>I have a dataframe with columns ['name', 'sex', 'births', 'year']. I then group the dataframe on the basis of name to create 2 new columns "max" and "total".</p>
<pre><code>trendy_names['max'] = trendy_names.groupby(['name'], as_index = False)['births'].transform('max')
trendy_names['total'] = trendy_names.groupby(... | <p>To sort the dataframe on the basis of "trendiness" which is type: DataFrameGroupBy</p>
<pre><code> 1. trendy_names.reset_index()
</code></pre>
<p><code>reset_index()</code> - converting back to a regular index
i.e converting pandas.core.groupby.DataFrameGroupBy to pandas.core.frame.DataFrame</p>
<p... | python|python-3.x|pandas|pandas-groupby | 0 |
359,777 | 58,868,986 | Coding softmax activation using numpy | <p>I am having a neural network for multi-class classification (3 classes) having the following architecture:</p>
<p>Input layer has 2 neurons for 2 input features</p>
<p>There is one hidden layer having 4 neurons</p>
<p>Output layer has 3 neurons corresponding to 3 classes to be predicted</p>
<p>Sigmoid activation... | <p>From what I understand, the equation for the second activation should be:</p>
<pre class="lang-py prettyprint-override"><code>Z2 = np.dot(A1, W2.T) + b2.T # Z2.shape = (m,3)
</code></pre>
<p>A soft-max for Z2 could be performed as:</p>
<pre class="lang-py prettyprint-override"><code>o = np.exp(Z2)/np.sum(np.exp(Z... | python|numpy|neural-network | 1 |
359,778 | 58,723,835 | how to convert series(24 numbers) into datetime like Y/M/D H:M:S | <p>I want to convert 24 numbers series, like <code>20190919120426</code>, into date time, <code>2019-09-19 12:04:26</code></p>
<p>Here are the <code>'Datatime'</code> series</p>
<pre><code>0 20190919093350
1 20190919093350
2 20190919093357
3 20190919093357
4 20190919093517
5 201909... | <p>change format with omit space and <code>:</code>, also loop here is not necessary, because is possible pass column to function:</p>
<pre><code>df['Datatime'] = pd.to_datetime(df['Datatime'], format='%Y%m%d%H%M%S')
print (df)
Datatime
0 2019-09-19 09:33:50
1 2019-09-19 09:33:50
2 2019-09-19 09:33:57
3 2... | python|pandas|datetime|series | 3 |
359,779 | 58,954,764 | How to query between the values of two columns of a data frame | <p>Say I have a data frame with following columns,</p>
<pre><code>df.head()
ref_loc ref_chr REF ALT coverage base
9532728 21 G [A] 1 A
9540473 21 C [G] 2 G
9540473 21 CTATT [C] 2 G
9540794 21 C [T] 1 A
9542965 21 C [A] 1 T
</code></pre>
<p>And I want to compare the ... | <p>Note that since you have the square brackets around the <code>ALT</code> column, it will always be different. You can first extract what is inside the brackets:<br>
<code>df["ALT"] = df.ALT.apply(lambda l: l[0])</code></p>
<p>You need to use <code>axis=1</code> to iterate over the rows. <code>axis=0</code> iterate... | python|pandas|function|lambda | 2 |
359,780 | 58,667,797 | Python pandas sort inter groups, not intra groups (rearrange grouped rows but maintain original row order before groupby | <p>I want to sort groups of rows based on a column (in my example, 'Group' is the column to group and then sort the groups (maintain in-group row order). I can't sort by index because the index is purposefully out of order as a result of previous operations.</p>
<pre><code>df = pd.DataFrame({
'Group':[5,5,5,9,9,77... | <p>You need to use <code>sort_values</code> with option <code>kind='mergesort'</code>. From pandas docs:</p>
<pre><code>kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’
Choice of sorting algorithm. See also ndarray.np.sort for more
information. mergesort is the only stable algorithm. For ... | python|pandas | 2 |
359,781 | 58,870,276 | In python using iloc how would you retrive the last 12 values of a specific column in a data frame? | <p>So the problem I seem to have is that I want to acces the data in a dataframe but only the last twelve numbers in every column so I have a data frame:</p>
<pre><code>index A B C
20 1 2 3
21 2 5 6
22 7 8 9
23 10 1 2
24 3 1 2
25 4 9 0
26 10 11 12
2... | <p>You can get the last n rows of a DataFrame by:</p>
<pre><code>df.tail(n)
</code></pre>
<p>or</p>
<pre><code>df.iloc[-n-1:-1]
</code></pre> | python|pandas|dataframe | 1 |
359,782 | 58,777,355 | How to use a Series to filter a DataFrame | <p>I have a pandas Series with the following content.</p>
<pre><code>$ import pandas as pd
$ s = pd.Series(
data = [True, False, True, True],
index = ['A', 'B', 'C', 'D']
)
$ s.index.name = 'my_id'
$ print(s)
my_id
A True
B False
C True
D True
dtype: bool
</code></pre>
<p>and a DataFrame ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>. ... | python|pandas|dataframe | 3 |
359,783 | 58,656,307 | How to fix "node.decodeJpeg is not a function" (tensorflow.js)? | <p>I use <a href="https://js.tensorflow.org/api_node/1.2.6/#node.decodeImage" rel="nofollow noreferrer">this</a> link to decode an image and get 3d tensor. Code bellow:</p>
<pre><code>const tf = require('@tensorflow/tfjs');
let node = require('@tensorflow/tfjs-node');
const { Image } = require('image-js');
async func... | <p>Oh, my mistake, correct form will be like: node.node.decodeImage(...)</p> | javascript|tensorflow.js | 1 |
359,784 | 58,734,276 | Extracting data from website using Beautifulsoup | <p>I am trying to extract the model name and any other detail about the models. When i try to fetch text then i can't find anything special which i can use to fetch data. </p>
<p>Anyone know how to fetch data from these urls? </p>
<p><a href="https://www.audi.de/de/brand/de.html" rel="nofollow noreferrer">https://www... | <p>If you go to Network Tab you will get The below link which returns value in json format.
You don't need selenium to do that.</p>
<pre><code>https://www.opel.de/apps/atomic/getVehicleTeasers.path=L2NvbnRlbnQvb3BlbC93b3JsZHdpZGUvZ2VybWFueS9kZS9pbmRleC9iYXNlYmFsbC1jYXJkcy9iYmMtY29sbGVjdGlvbnMvdmVoaWNsZXMtb25seS1jb2xsZ... | python|pandas|selenium|beautifulsoup | 3 |
359,785 | 58,941,819 | Django Database Structure for Time Series Data? | <p>I am developing an app that allows users to choose an ocean buoy and then explore its historical time series data via interactive plotly plots. My end goal is that the user can input a location, which then loads a buoy's data, and the user can then choose filters for which data they'd like to have plotted (so basica... | <p>The standard approach here would be to use Django models (translated to tables in the db):</p>
<ul>
<li><code>Buoy</code></li>
<li><code>BuoyData</code></li>
</ul>
<p>The <code>BuoyData</code> class will have a <code>ForeignKey</code> to the <code>Buoy</code> model.</p>
<p>Also look into <a href="https://docs.dja... | python|django|database|pandas|django-models | 2 |
359,786 | 58,796,795 | Get a numpy arrays indices in order of occurrence | <p>I am using train_test_split. My training set, X[], is an array of file paths. Then I have another array y[] that is composed on one hot encoded labels. They are related by the array row index. So if I pass X it looks like this:</p>
<p>Index path</p>
<p>4, data\djip2\DJIP2.5844MHz.10MSPS.fc32.2016-07-01_00000000... | <p>One solution might be:</p>
<pre><code>n = range(numberOfInstances)
</code></pre>
<p>which creates a list of integers like [0,1,2,3,4...numberOfInstances-1]. Then shuffle the list</p>
<pre><code>random.shuffle(n)
</code></pre>
<p>Save this list as a numpy array</p>
<pre><code>n_np = np.array(n)
</code></pre>
<p... | python|numpy | 1 |
359,787 | 59,032,854 | python custom summary table | <p>I have a table which looks like the one below:</p>
<pre><code> A B C D
1 1 2 3
1 1 3 3
2 3 0 1
2 4 2 3
3 1 4 1
3 0 2 4
</code></pre>
<p>And I need to generate a table something like the one below: </p>
<pre><code> A Metric Min Mean M... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame... | python|pandas | 5 |
359,788 | 58,812,201 | Automatically recognize whether data is a tabular text format | <p>I have messages that are text with the following format:</p>
<pre><code> Name Number1 Number2 Number3(ID)
somename1 1234.5678 273.4234 2783
somename2 2384.2 12.54
somename3 234.1 98234.2
</code></pre>
<p>As can be seen, there are some n... | <p>A heuristic approach like this seems to work. It reads the first row to figure out the starting offset of each header, then uses that information for each row to find out the most likely column for each datum.</p>
<p><del>The <code>col_offset</code> parameter is an unfortunate fudge factor required when the column ... | python|python-3.x|pandas|dataframe|tabular | 0 |
359,789 | 58,961,654 | Extract data from cvent via Python | <p>I really need to access data from cvent via python. Specifically, cvent utilizes SOAP. I have created a custom report in the cvent GUI for a specific event. Now, I would like to call the event data and render in a pandas dataframe. developers.cvent.com only provides C# code snips... which you guessed it, I know noth... | <p>I recently did this using the Python zeep package. Here's an example.</p>
<pre><code>from datetime import datetime
from zeep import Client
#set account, user, password...
wsdl = 'https://api.cvent.com/soap/V200611.ASMX?WSDL'
client = Client(wsdl)
login_result = client.service.Login(account, user, password)
client.... | c#|python|pandas|soap | 1 |
359,790 | 58,711,222 | How to set prunable layers for tfmot.sparsity.keras.prune_low_magnitude? | <p>I am applying the pruning function from <code>tensorflow_model_optimization</code>, <code>tfmot.sparsity.keras.prune_low_magnitude()</code> to MobileNetV2.</p>
<p>Is there any way to set only some layers of the model to be prunable? For training, there is a method "<code>set_trainable</code>", but I haven't foun... | <p>In the end I found that you can also apply prune_low_magnitude() per layer.</p>
<p>So the workaround would be to define a list containing the names or types of the layers that shall be pruned, and iterate the layer-wise pruning over all layers in this list.</p> | python|machine-learning|keras|tensorflow2.0|pruning | 0 |
359,791 | 58,981,800 | How to calculate mean by skipping String Value in Numeric Column? | <pre><code>Name Emp_ID Salary Age
0 John Abc 21000 31
1 mark Abn 34000 82
2 samy bbc thirty 78
3 Johny Ajc 21000 34
4 John Ajk 2100.28 twentyone
</code></pre>
<p>How to calculate mean of 'Age' Column without changing string value in that column. Basically i want to loop throug... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>pd.to_numeric</code></a> with the argument <code>errors='coerce'</code>, which turns values to <code>NaN</code> if it can't convert it to numeric. Then use <a href="https://pandas.pydata.or... | python-3.x|pandas|python-2.7|for-loop|functional-programming | 1 |
359,792 | 58,888,362 | Compare a pandas columns with a range of indices of other column | <p>I have a data frame like this,</p>
<pre><code>df
col1 col2 col3
1 A A
2 A A
3 B A
4 A B
5 A A
6 C A
7 A A
8 A C
9 A A
10 A A
11 C C
12 A A
13 ... | <p>Idea is compare both columns with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> for membership and then check if N values above and below has at least one True values - first are created unique groups by index values... | python|pandas|dataframe | 1 |
359,793 | 58,777,114 | how to use tensorflow::ops::NonMaxSuppression in label_image tensorflow cpp example to remove multi rectangle predicted for one object? | <p>i used Tensorflow label_image example <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image</a> to detect and localize 10 class objects from image . now i want remo... | <p>You can use the below function to draw boxes which surpass the threshold, I am taking it from Tensorflow object detection API. </p>
<p><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/utils/visualization_utils.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/bl... | tensorflow|object-detection | 0 |
359,794 | 59,022,138 | A column Genre in movies data set have multiple categories in each row. How can I separate all the categories from each other? | <p>This is the code: </p>
<pre><code>data[['Movies','Genre']
</code></pre>
<p>The output looks like this: </p>
<pre><code> Movies Genre
1 Xyz Drama,Action
2 Abc Horror,Thriller
3 Mnb Action,Thriller
</code></pre>
<p>The desired output is: </p>
<pre><code> Movies Genre
1 Xyz Drama
2 ... | <p>Firstly, you need to convert <code>Genre</code> from <code>str</code> to <code>list</code>; secondly, you transform each element of a list-like to a row using <a href="https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>pandas.DataFrame.expl... | python-3.x|pandas|numpy|jupyter-notebook | 1 |
359,795 | 58,733,019 | how to filter a dataframe if a rows contains two values from a list in a column | <p>i need to filter a HUGE pandas dataframe that contains in the column 'A' two words from a list.
I already filtered it considering only a value from word_list, but i didnt figured it out how to do it for two values.</p>
<pre><code>new_df = df[df["A"].apply(lambda x: any(i in x.split() for i in word_list))]
</code></... | <p>You can do <code>explode</code> then <code>get_dummies</code>, <code>sum</code> by <code>level</code> then <code>sum</code> by columns , if row return value more than 2 , we should pick</p>
<pre><code>df[df["A"].explode().str.get_dummies().\
sum(level=0).gt(0).reindex(columns=word_list).sum(axis=1).ge(2)]
</co... | python|database|pandas|dataframe|dataset | 1 |
359,796 | 58,811,783 | Interactively change a point plot in bokeh using RangeSlider to select columns in a pandas dataframe | <p>I have a pandas dataframe df where the first two columns represent x, y coordinates and the remaining columns represent time slices (t0,...tn) where the presence(1) or absence(0) of each point at each time slice (ti) is recorded.</p>
<p>I would like to use a <code>RangeSlider</code> (not a <code>Slider</code>) so t... | <p>There are a number of issues in the code above:</p>
<ul>
<li>It is <code>cb_obj</code> not <code>cb.obj</code></li>
<li>Use modern <code>js_on_change</code>, not very old ad-hoc <code>callback</code> parameters</li>
<li>You are assigning to a <em>local variable</em> <code>data</code> and then throwing away the resu... | python|pandas|bokeh | 1 |
359,797 | 58,698,393 | Modify a Python object's attribute when using PyCall.jl in Julia | <p>I'm trying to interface with a python library via PyCall.jl where the library returns a python object (PyObject in Julia) with attributes I want to modify in Julia. For example say I have the following dummy python class,</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
class MyNumpy:
de... | <p>PyCall defaults to converting objects to Julia types if they quack appropriately. In this case, it's happening when you access the <code>array</code> field of your <code>MyNumpy</code> class: it returns a numpy array, which PyCall will convert it to a Julian <code>Array</code> at the boundary. If you want to opt o... | python|numpy|julia|pyobject|pycall | 2 |
359,798 | 58,961,916 | Pandas pd.concat() in separate threads shows no speed-up | <p>I am trying to use pandas in a multi-thread environment. I have a few lists of pandas frames (long list, 5000 pandas frames, with dimensions of 300x2500 dimension) which I need to concatenate.
Since I have multiple lists, I want to run the concat for each list in an own thread (or use a threadpool, at least to get s... | <p>Because of the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow noreferrer">Global Interpreter Lock -GIL)</a>, I'm not sure your code is leveraging multi-threading.
Basically, ThreadPoolExecutor is useful when workload is not CPU bounded but IO bounded, like making many Web API call at the ... | python|pandas|multithreading | 1 |
359,799 | 58,942,535 | ObjectDetection inference with a SavedModel on TFRecords | <p>I'm trying to perform inference using a <a href="https://github.com/tensorflow/models/blob/57e075203f8fba8d85e6b74f17f63d0a07da233a/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">SavedModel from the detection model zoo</a>. I was able to get a working example using the <a href="htt... | <p>I know this is an old question, but this came up for me recently, and I found that most of the answers surrounding this issue were unhelpful. I figured I would post what worked for me to potentially help any future troubleshooters.</p>
<p>Via the TF GitHub: <a href="https://github.com/tensorflow/tensorflow/issues/33... | tensorflow|tensorflow-datasets | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.