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 |
|---|---|---|---|---|---|---|
358,500 | 55,460,481 | Ignore NaN values when searching for a minimum datetime | <p>I have the following piece of code:</p>
<pre><code>if isinstance(df["col1"][0], datetime.datetime):
min_dt = min(df["col1"].values)
</code></pre>
<p>It searches for a minimum date value in a column <code>col1</code>. However, it checks the data type of the first rows, while there might be empty values in the re... | <p>Using the builtin DataFrame <code>min</code> method you can automatically ignore NaNs (there's even a <code>skipna</code> argument just for that). Much better than python <code>min</code></p>
<pre><code>min_dt = df["col1"].min()
</code></pre>
<p>EDIT:</p>
<p>If you have some dates in string format, try converting... | python|pandas | 1 |
358,501 | 55,162,148 | How to load a converted pre-trained keras model to Tensorflow.js using Node.js? | <p>I have pre-trained keras models that I have conveter using TensorflowJs Converter. I'm trying to load them in this following script</p>
<p>(index.js)</p>
<pre><code>const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
global.fetch = require('node-fetch')
const model = tf.loadLayersModel(
... | <p>Replace </p>
<pre><code>const tf = require('@tensorflow/tfjs');
</code></pre>
<p>With</p>
<pre><code>const tf = require('@tensorflow/tfjs-node');
</code></pre>
<p>And remove the line</p>
<pre><code>require('@tensorflow/tfjs-node');
</code></pre>
<p>Then, if you are loading a model from the local file system, ... | node.js|tensorflow|tensorflowjs-converter | 2 |
358,502 | 55,302,897 | Using Pandas to average data across excel sheets with matching column data | <p><a href="https://i.stack.imgur.com/3ySMd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3ySMd.png" alt="Data Snippet"></a></p>
<p>See data snippet. I have similar data across multiple sheets in Excel with each sheet being a different year. For each month, day, and time (12 and 00), I would like ... | <p>Without having your data I made two example <code>DataFrames</code></p>
<p>First of all you need to import the data from excel into <code>pandas</code> with:</p>
<pre><code>df1 = pd.read_excel('name_file.xlsx', sheet_name='year2018')
</code></pre>
<p>And do this for each year.</p>
<p>After that you can use my ex... | python|excel|pandas|average | 0 |
358,503 | 55,185,365 | if record ouputting as NaT in pandas, skip record | <p>I have a few records outputting in my pandas data frame as <code>NaT</code>.</p>
<p><em>i.e.</em> <code>Date_Refused_Final_Something_of_ICP=NaT,</code> </p>
<p>And it seems to disrupt my script. I would simply like to skip these few records found as Nat, and continue with the rest of the records/script.</p>
<p>B... | <p>I'm not sure where you're encountering this, but you can simply put <code>continue</code> when it finds this:</p>
<pre><code>if mrn in ("", " ", "N/A", None) or math.isnan(mrn):
print(f"Invalid record: {row}")
continue # <--- if it encounters any of the conditions above, it skips and goe... | python|excel|pandas|selenium | 1 |
358,504 | 55,155,417 | Concatenating/Appending Multiple Vertical Arrays of Different Sizes | <p>I have a function that returns a numpy array. I loop this function with different data files but will end up with every loops giving out a different sized array (which is the desired output) but I cannot figure out how to properly append these arrays. Example arrays and the method I use for arranging them after I gr... | <p>First, <code>vstack</code> on an array treats the array as a list on the first dimension. It then makes each 'row/element' into a 2d array, and concatenates them.</p>
<p>These all do the same thing:</p>
<pre><code>In [94]: np.vstack(np.array([1,2,3]))
Out[94]:
array([[1... | python|arrays|python-3.x|numpy|concatenation | 2 |
358,505 | 55,282,709 | Replace pyspark column based on other columns | <p>In my "data" dataframe, I have 2 columns, 'time_stamp' and 'hour'. I want to insert 'hour' column values where 'time_stamp' values is missing. I do not want to create a new column, instead fill missing values in 'time_stamp'</p>
<p>What I'm trying to do is replace this pandas code to pyspark code:</p>
<pre><code>d... | <p>Something like this should work</p>
<pre><code>from pyspark.sql import functions as f
df = (df.withColumn('time_stamp',
f.expr('case when time_stamp is null then hour else timestamp'))) #added ) which you mistyped
</code></pre>
<p>Alternatively, if you don't like sql:</p>
<pre><code>df = df.withColumn('time_sta... | pandas|pyspark|apache-spark-sql | 1 |
358,506 | 55,283,746 | ground_truth = np.squeeze(np.asarray(true_labels)) | <p>Please help me understand this line of code? </p>
<p>What do the <code>squeeze</code> and <code>asarray</code> function do? </p>
<p>In this approach k-means clustering with k=5, and random initialization has been fitted.</p>
<pre><code>ground_truth = np.squeeze(np.asarray(true_labels))
</code></pre>
<p>Many Than... | <p>In future if you could, please include more example code specific to the issue to make it clearer what you want to achieve from your question. K-means clustering and random initalization don't explicitly tell us what the value of <code>true_labels</code>, but I'm guessing it a 1d array of category labels so I'll ans... | python|pandas|numpy | 3 |
358,507 | 55,294,130 | How to get the rows based on unique column values of their first occurrence | <p>I have a data frame like this:</p>
<pre><code>df
col1 col2 col3
1 A B
1 D R
2 R P
2 D F
3 T G
1 R S
3 R S
</code></pre>
<p>I want to get the data frame with first 3 unique value of col1. If some col1 value comes... | <p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html#pandas.DataFrame.duplicated" rel="nofollow noreferrer"><code>duplicated</code></a> method in pandas:</p>
<pre><code>mask1 = df.duplicated(keep = "first") # this line is to get the first occ.... | python|pandas|dataframe | 1 |
358,508 | 55,495,760 | Transforming DataFrame to get the count of records for a given hours | <p>I have a DataFrame which looks like this:</p>
<p><a href="https://i.stack.imgur.com/ckejs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ckejs.png" alt="enter image description here"></a></p>
<p>Where <code>Time request submitted</code> is a timestamp. <code>date</code> and <code>hour</code>
a... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a>:</p>
<pre><code>df1 = pd.crosstab(df['date'], df['hour'])
</code></pre>
<p>Alternatives:</p>
<pre><code>df1 = df.pivot_table(index='date', columns='hour',... | python|pandas | 3 |
358,509 | 55,288,248 | Turn str fractions to floats in pandas df | <p>I have a really awkward pandas DataFrame that looks kind of like this:</p>
<pre><code>identifier per_1 per_2 per_3 per_4 per_5
'something' 124/127 100/100 24/39 14/20 10/10
'camel' 121/122 150/206 300/307 11/12 0/2
... ... ..... | <p>Try the below code:</p>
<pre><code>df[['identifier']].join(df.filter(like='per').apply(pd.eval))
identifier per_1 per_2 per_3 per_4 per_5
0 'something' 0.976378 1 0.615385 0.7 1
1 'camel' 0.991803 0.728155 0.977199 0.916667 0
</code></pre> | python|pandas | 3 |
358,510 | 55,318,273 | Tensorflow._api.v2.train has no attribute 'AdamOptimizer' | <p>When using </p>
<pre><code>model.compile(optimizer = tf.train.AdamOptimizer(),
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
</code></pre>
<p>in my Jupyter Notebook the following Error pops up:</p>
<p><strong>module 'tensorflow._api.v2.train' has no attribute 'AdamOpt... | <pre class="lang-py prettyprint-override"><code>tf.train.AdamOptimizer() => tf.optimizers.Adam()
</code></pre>
<p>From <a href="https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/optimizers" rel="noreferrer">https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/optimizers</a></p> | python|tensorflow | 80 |
358,511 | 55,321,537 | df.apply( ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series | <p>I am trying to create a pd.DataFrame with 2 columns 'JV', 'Tags' basis a dictionary self.tags but getting following exception</p>
<pre><code>tgs = {'JV':list(self.tags.keys())}
tagsData = pd.DataFrame.from_dict(tgs)
tagsData['Tags'] = tagsData.apply(lambda row: self.tags[row['JV']], axis = 1)
</code></pre>
<p>dict... | <p>received this error when the dictionary was empty and so could not create a dataframe from empty dictionary.</p>
<p>So the solution is to check for empty dictionary and act accordingly</p> | python|pandas|python-2.7 | 8 |
358,512 | 55,237,899 | How to open pretrained models in python | <p>Hi I'm trying to load some pretrained models from <code>.sav</code> files and so far nothing is working. The models were originally made in pytorch and when I open the raw file in vs-code I can see that all the appropiate information was stored correctly.</p>
<p>I've tried the following libraries:</p>
<p><code>skl... | <p>You need to use PyTorch to load the models. On top of this, you also need the original model definition, so you need to need the clone the authors repository. In your example this repo:</p>
<pre><code>git clone https://github.com/tbepler/protein-sequence-embedding-iclr2019.git
</code></pre>
<p>Then you can open th... | python-3.x|pytorch|spss|pre-trained-model | 2 |
358,513 | 55,147,057 | Train an Object Detection Classifier How to Make Money with Tensorflow | <pre><code>from object_detection.protos import calibration_pb2 as object__detection_dot_protos_dot_calibration__pb2
</code></pre>
<blockquote>
<p>ImportError: cannot import name 'calibration_pb2' from
'object_detection.protos'
(C:\ProgramData\Anaconda3\envs\tensorflow1\lib\site-packages\object_detection-0.1-py3.... | <p>After 7 hours of complete reinstallations and changing versions and updating pilotes and and and ... I had to look closely where is the import of calibration_pb2. And after 10 minutes of investigations, I noticed that the <strong>protoc cmd does not generate the file calibration_pb2.py</strong> !!!!</p>
<p>To gener... | tensorflow | 0 |
358,514 | 55,255,669 | Identifying none value from column | <p>I am reading csv using pandas to perform some analysis on it. Where I am getting this error</p>
<pre><code>ValueError: could not convert string to float: 'none'
</code></pre>
<p>I checked, I am getting this error due to <code>shift_zip</code> parameter. I manually went to csv file and openoffce and converted this ... | <p>If finding the Na or null value is the objective then simply use </p>
<pre><code>df.info()
</code></pre>
<p>and you will be able to see the datatype of the column as well as the None value count also.</p>
<p>But I think, in your dataset the value which making noise is not in null format.
You can give a try to bel... | python|pandas | 2 |
358,515 | 55,575,031 | Iterate through a dataframe to populate API requests | <p>I have a dataframe <code>complete</code> and I would like to iterate through each row and build an API request from the contents of the columns, each row being a new request.</p>
<p>My request body must look like:</p>
<pre><code>body=
{
'conversion' : [{
'clickId' : complete['click_id'],
'conve... | <p>You need to replace <code>complete</code> with your <code>row</code> and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer">iterrows()</a>:</p>
<pre><code>for row in complete.iterrows():
request = service.conversion().update(
b... | python|pandas | 2 |
358,516 | 55,384,802 | How to reduce image portion with numpy.compress method ? (numpy+scikit-image) | <p>Hi using the sample image phantom.png I'm following some operations with numpy + skimage libraries and after some modifications the last one exercise ask for:</p>
<blockquote>
<p>Compress the size of center spots by 50% and plot the final image.</p>
</blockquote>
<p>These are the steps I do before.</p>
<p>I rea... | <p>You seem ok with cropping and extracting, but just stuck on the <em>compress</em> aspect. So, crop out the middle and save that as <code>im</code> and we will compress that in the next step. Fill the area you cropped from with white.</p>
<p>Now, compress the part you cropped out. In order to reduce by 50%, you need... | python-3.x|numpy|scikit-image | 1 |
358,517 | 55,438,910 | Understanding the differences between similar numpy flattening techniques | <p>I'm working through the homework assignment for week 2 of the first course in the deeplearning.ai certificate on Coursera. </p>
<p>One of the first tasks is to flatten an image (209, 64, 64, 3). You can do this in three ways (or so I think):</p>
<ol>
<li>X.reshape(X.shape[0],-1).T</li>
<li>X.flatten().reshape(1228... | <p>First, we note that we can think of <code>reshape</code> as "pulling" an array out into a long line of elements, and then "restacking" them by filling axes in a certain order. Consider the following array:</p>
<pre><code>array = np.arange(48).reshape(6, 4, 2)
</code></pre>
<p>This array will contain elements from ... | python|image|numpy|reshape | 2 |
358,518 | 55,526,633 | Loop through and rename files | <p>I'm trying to loop through a folder that contains a bunch of other folders with titles Spec01, Spec02, Speco03,...,Spec14. Each of the Spec folders has a handful of files but the one I need is called specimen.dat in each folder. I want to loop through each folder, convert it to an Excel file, and save it with the na... | <p>So, I came up with this. I'm still a novice to Python so I'm not sure if this is the most efficient answer but it seems to do the trick:</p>
<pre><code>import os
your_path = 'C:/Users/abh85/Desktop/AAA/'
file_names = []
i = 0
for root, dirs, files in os.walk(your_path):
for name in dirs:
file_names.a... | python|pandas|for-loop | 0 |
358,519 | 55,248,631 | Tensorflow can't assign a device for operation | <p>I am trying to run <a href="https://github.com/tkarras/progressive_growing_of_gans" rel="noreferrer">NVidia's face generating demo</a> on my computer. I am using Windows 10. I have downloaded the source, and am trying to follow the steps further down the page. I have installed the latest NVidia drivers for my GTX106... | <blockquote>
<p>Cannot assign a device for operation
G_paper_1/Run/G_paper_1/latents_in: {{node
G_paper_1/Run/G_paper_1/latents_in}}was explicitly assigned to
/device:GPU:0 but available devices are [
/job:localhost/replica:0/task:0/device:CPU:0 ]</p>
</blockquote>
<p>have you installed <code>tensorflow</cod... | python|tensorflow | 7 |
358,520 | 55,149,795 | What's the difference between .loc[index, col] and .loc[index][col]? | <p>Suppose I have a dataframe like this, with a "dense" first column and a "sparse" second column:</p>
<pre class="lang-py prettyprint-override"><code># python 3.7.1, pandas 0.23.4.
import pandas as pd
df = pd.DataFrame({'col1':range(1,5), 'col2': [5, '', 7, '']})
missing_values_index = df[df['col2'] == ''].index
</... | <p>The second method you mentioned "works ok", so let's talk about why the first method doesn't work!</p>
<p>I think the <em>core</em> of the problem is when we try to assign a value to a <strong>copy of an object</strong>, instead of the object itself. I can rewrite your first method like this: </p>
<pre><code>somet... | python|pandas|dataframe | 0 |
358,521 | 55,229,836 | Failed to load the native TensorFlow runtime - Symbol not found: _clock_gettime | <p>Been having a ton of issues loading Tensorflow. I've uninstalled and reinstalled numpy (now it's up to date, that was another initial error), uninstalled and reinstalled Tensorflow, and uninstalled and reinstalled Nextgenrnn (the package I plan to use it in combination with).</p>
<p>Launching python and calling "im... | <p>In the macOS SDK <code>clock_gettime</code> is declared like this: <code>__CLOCK_AVAILABILITY
int clock_gettime(clockid_t __clock_id, struct timespec *__tp);</code></p>
<p>and if we look at the definition of the <code>__CLOCK_AVAILABILITY</code> macro: <code>#define __CLOCK_AVAILABILITY __OSX_AVAILABLE(10.12) __IOS... | python|macos|tensorflow | 1 |
358,522 | 55,367,194 | Change the axis name seaborn plot from value/variable | <p><a href="https://i.stack.imgur.com/F7WxH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F7WxH.png" alt="enter image description here"></a>I am working on a dataframe that consists of multiple of columns that corresponds to different part of the drive (e.g. right turn, left turn, etc.) and rows th... | <p>To change the labels you can do by:</p>
<p><b> Setting direct to the plot </b> </p>
<pre><code>plt.xlabel('Average speed (mph)')
plt.ylabel('Parts')
</code></pre> | pandas|seaborn|axis|names | -2 |
358,523 | 55,468,413 | Python - Error when saving output of Dataframe to excel | <p>I am trying to print out shape of a Dataframe to a excel file.</p>
<p>Given below is what I have achieved thus far:</p>
<pre><code>file_shape = df.shape[0] <<-- This saves the count of rows to a variable
writer = pd.ExcelWriter(output, engine='xlsxwriter')
file_shape.to_excel(writer, startrow=0, merge_cells=... | <p>Try the following:</p>
<pre><code>file_shape = df.shape[0] # <<-- This saves the count of rows to a variable
df['file_shape'] = file_shape
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, startrow=0, merge_cells=False, sheet_name="Summary", index=False)
</code></pre> | python|pandas | 0 |
358,524 | 55,394,262 | Group by unique Name and Status with the last Date | <p>I would like to analyze statistics per cars which were repairs and which are new. Data sample is:</p>
<pre><code>Name IsItNew ControlDate
Car1 True 31/01/2018
Car2 True 28/02/2018
Car1 False 15/03/2018
Car2 True 16/04/2018
Car3 True 30/04/2018
Car2 False 25/05/2018... | <p>One way to do it would be to <code>GroupBy</code> the <code>Name</code>, and aggregate on <code>IsItNew</code> with two functions. A custom one using <code>any</code> to check if there are any <code>False</code> values, and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.h... | python|pandas|dataframe|group-by|crosstab | 2 |
358,525 | 55,464,277 | How to smooth and plot x vs weighted average of y, weighted by x? | <p>I have a dataframe with a column of weights and one of values. I'd need:</p>
<ul>
<li>to <strong>discretise weights and, for each interval of weights, plot the
weighted average of values</strong>, then</li>
<li>to extend the same logic to another
variable: discretise z, and for each interval, plot the weighted
aver... | <p>The first part of your question is rather easy to do.</p>
<p>I'm not sure what you mean with the second part. Do you want a (simplified) reproduction of your code or a new approach that better fits your need?</p>
<p>Anyway i had to look at your code to understand what you mean by weighting the values. I think peop... | python|pandas|matplotlib|pandas-groupby|weighted-average | 1 |
358,526 | 10,081,048 | Pysparse installation ubuntu | <p>I am having trouble installing pysparse on ubuntu. I installed the package python-sparse, but when running the example code found in the documentation</p>
<pre><code>from pysparse.sparse import spmatrix
from pysparse.direct import superlu
import numpy
n = 100
A = poisson2d_sym_blk(n)
b = numpy.ones(n*n)
x = numpy.e... | <p>I replicated the error you are having on Ubuntu v11.10 and your code looks just like the example code from the pysparse website ( <a href="http://pysparse.sourceforge.net/fact.html" rel="nofollow">http://pysparse.sourceforge.net/fact.html</a> ).</p>
<p>Possible reasons:</p>
<ul>
<li>The example is old and the pysp... | python|ubuntu|numpy|scientific-computing|sparse-matrix | 1 |
358,527 | 7,543,250 | How to select elements row-wise from a NumPy array? | <p>I have an array like this numpy array</p>
<pre><code>dd= [[foo 0.567 0.611]
[bar 0.469 0.479]
[noo 0.220 0.269]
[tar 0.480 0.508]
[boo 0.324 0.324]]
</code></pre>
<p>How would one loop through array
selecting foo and getting 0.567 0.611 as floats as a singleton.
Then select bar and getting ... | <p>You have put the <em>NumPy</em> tag on your Question, so i'll assume you want NumPy syntax, which the answer before mine doesn't use. </p>
<p>If in fact you wish to use NumPy, then you likely don't want the strings in your array, otherwise you will also have to represent your floats as strings.</p>
<p>What you are... | python|multidimensional-array|numpy|scipy | 29 |
358,528 | 7,100,995 | Testing if all values in a numpy array are equal | <p>I have a numpy one dimensional array <code>c</code> that is supposed to be filled with the contents of
<code>a + b</code>. I'm first executing <code>a + b</code> on a device using <code>PyOpenCL</code>.</p>
<p>I want to quickly determine the correctness of the result array <code>c</code> in python using <code>numpy... | <p>Why not just use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html"><code>numpy.array_equal(a1, a2)</code><em><sup>[docs]</sup></em></a> from NumPy's functions?</p> | python|numpy | 53 |
358,529 | 56,864,481 | Find change in a column with date column in Pandas | <p>I have a pandas dataframe that I got after melting and filtering based on some criteria, it looks like this</p>
<pre><code> P D
A 2018-01-01
A 2018-01-02
A 2018-01-03
B 2018-01-03
A 2018-01-04
B 2018-01-04
A 2018-01-05
A 2018-01-06
A 2018-01-07
B 2018-01-07
</code></pre>
<p>From... | <p>You could try something like the below:</p>
<pre><code>import pandas as pd
import datetime as dt
#generate dataframe
letters = ['A', 'A', 'A', 'B', 'A', 'B', 'A', 'A', 'A', 'B']
dates = [dt.date(2018,1,1), dt.date(2018,1,2), dt.date(2018,1,3), dt.date(2018,1,3), dt.date(2018,1,4), dt.date(2018,1,4), dt.date(2018,1... | python|pandas | 3 |
358,530 | 56,826,104 | Identify variable ordinalities | <p>Suppose I have a Pandas Series named <code>fruit</code> that looks like this:</p>
<pre><code>mango, kiwi, pear, kiwi, pear, mango, mango.
</code></pre>
<p>and I know the price relationship between among these fruits is such that:</p>
<p><code>mango = 1.2 * pear</code> and <code>kiwi = 0.8 * pear</code></p>
<p>Ho... | <p>If you have a self-consistent set of equalities you could do something like:</p>
<pre><code>>>> eq=S('[mango = 1.2 * pear, kiwi = 0.8 * pear]'.replace('=','-'))
>>> v = solve(eq)
>>> S('Tuple(mango, kiwi, pear)').subs(v)
(1.2*pear, 0.8*pear, pear)
</code></pre>
<p>(In this case, not enou... | python-3.x|pandas|sympy | 0 |
358,531 | 56,695,339 | Pandas: for groups of rows where 2 or more particular columns values are exactly the same, how to assign a unique integer as a new column | <p>In a Pandas dataframe, I have groups of rows where the values for 2 particular columns are exactly the same. How do I add a new column for those rows, that assigns a unique integer, starting at integer 1 (not integer 0)? Any completely unique rows also get an int. </p>
<p>This is a sample dataframe where the 2nd an... | <p>Using <code>groupby</code> with <code>sort=False</code> and <code>ngroup</code></p>
<pre><code>df[3] = df.groupby([1,2], sort=False).ngroup()+1
Out[1261]:
0 1 2 3
0 plane1 az 1
1 plane2 az 1
2 plane3 az 2
3 plane4 az 2
4 plane5 ny 3
5 plane6 ny 3... | python|pandas | 2 |
358,532 | 56,801,575 | How to use if condition in pandas using logical operators | <p>I have data frame </p>
<pre><code>Software Product Case Number Created date End date CS date
MDM9607.LE.1.0 2774904 2/3/2017 3/4/2019
MDM9607.LE.1.0 2774203 8/7/2017 3/9/2018 7/8/2016
MDM9607.LE.1.0 2768088 9/3/2018 1/2/2019
MDM9... | <p>You can do something like this</p>
<p>Store the result of your comparison in a variable like:</p>
<pre><code>data=f9["Created Date"]>f9["End Date"]
</code></pre>
<p>This will return a list of booleans.Using this you can get the relevent rows which satisfy this condition and proceed further.</p>
<pre><code>new... | python-3.x|pandas|numpy | 0 |
358,533 | 56,550,413 | Conditional replacement within dataframe | <p>I am using a considerably big dataframe <code>histdf</code> (20M, 3). The fields are <code>Visitor_ID</code>, <code>content</code> and <code>time</code>. The dataframe will be used for an URL recommendation system, where <code>Visitor_ID</code> is a unique visitor identification, content is a visited URL and time is... | <p>Your first instinct to extract the Visitor ID's of heavy users was good, but you don't need to iterate over your dataframe once you have them. </p>
<p>Here is how you could do it :</p>
<pre><code>histdf = pd.DataFrame({'Visitor_ID':[1, 1, 2, 2, 2, 3],
'content ': ["url" + str(x) for x in range(... | python|pandas|bigdata | 2 |
358,534 | 56,829,623 | getting list index out of range when extracting dataframe rows conditionally | <p>Extracting part of the tokens data frame throws up list index out of range error. </p>
<p><strong>Edited to show full code</strong></p>
<pre><code>tokens['len'] = tokens['token_raw'].apply(lambda x: len(x))
txt = "this is a sample text"
input_df = pd.DataFrame(txt.lower().split(), columns=['input_text'])
input_df ... | <p>Or two <code>iloc</code>s:</p>
<pre><code>def flag_nonword(w):
input_len = len(w)+3
tokens_ext = tokens.loc[tokens['len'] < input_len]
return list(tokens.iloc[:,0].iloc[:6])
</code></pre> | python|pandas | 2 |
358,535 | 56,627,639 | How to automatically generate a matrix by given values in 1-d-matrix | <p>I've tried using a for-loop to generate each column in an list-array, which worked. But unfortunantly I cant use this list in the np.append(matrix_name, values(=list), axis=0) comand to add those values as a column to a defined matrix X with the size of 10x10.</p>
<p>Approximately it should look like this: <a href=... | <p>This should do</p>
<pre><code>np.tile(np.arange(1, 11), (10, 1)).cumprod(axis=0)
</code></pre>
<p>Let's see what we're doing in detail.</p>
<p>Generate first row</p>
<pre><code>np.arange(1, 11)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
</code></pre>
<p>Repeat it ten times</p>
<pre><code>np.tile(np.arange... | numpy|matrix | 0 |
358,536 | 56,519,823 | Drop row based on two columns conditions | <p>I have <code>dataframe</code> looks like this:</p>
<pre><code>df
Data1 Data2 Data3
A XX AA
A YY AA
B XX BB
B YY CC
C XX DD
C YY DD
D XX EE
D YY FF
</code></pre>
<p>I want to delete all the row (column data3) based on two co... | <p>Using <code>groupby</code> + <code>transform</code> with <code>nunique</code></p>
<pre><code>yd=df[df.groupby(['Data1']).Data3.transform('nunique').gt(1)].copy()
Out[506]:
Data1 Data2 Data3
2 B XX BB
3 B YY CC
6 D XX EE
7 D YY FF
</code></pre> | python|pandas|row|multiple-columns | 2 |
358,537 | 56,849,920 | GroupBy Count using Pandas Dataframe in python | <p>I know how to do this Scala Spark - I wonder why it's so painful in Anaconda -Python</p>
<p>I want to do an identical operation in Python</p>
<pre><code>val dfs = df.groupBy($"col1").count.orderBy(desc("count"))
</code></pre>
<p>This is giving error</p>
<pre><code>dfs = df[['col1']].groupby(['col1]).count.sort([... | <p>you can use <code>.size()</code> and <code>.sort_values()</code>.</p>
<p>try this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
df = pd.DataFrame.from_dict({"col1": np.random.randint(11, 20, size=100, dtype=int)})
dfs = df.groupby('col1').size().sort_values()
print(df... | python|pandas|scala|apache-spark|anaconda | 1 |
358,538 | 56,465,794 | Re-write TensorFlow into Keras with tf.keras | <p>I wan to re-write TensorFlow code into Keras. I just wonder if you can use for this purpose the <code>tf.keras.layers</code> to just replace the <code>tf.layers</code>?</p>
<p>Like</p>
<pre><code>tf.layers.max_pooling2d()
</code></pre>
<p>to:</p>
<pre><code>tf.keras.layers.max_pooling2d()
</code></pre>
<p>Can... | <p>First of all, I think you meant <code>tf.keras.layers.MaxPool2D</code>, which is a class, not a function. If I got your point, it shouldn't be an issue. There are some minor difference in syntax, but nothing serious. Besides, <code>tf.keras.layers</code> is a direct substitute for <code>tf.layers</code>. As per offi... | python|tensorflow|keras | 0 |
358,539 | 56,490,995 | How to continuously update the value of a tensor in a loop | <p>So I am trying to continuously update a tensor in my code in a loop by assigning it with a new value in each iteration. genRandMat function assigns the variable <strong>a1</strong> with a random <strong>MxN matrix</strong> comprising 0 and 1 with <strong>frequency of 1 being decided with probability pt</strong>.</p>... | <p>You have generated the random value ones, and you keep assigning the same value again. To assign different value each time you need to generate random values using TensorFlow API, not numpy.</p>
<p>Alternatively, you could assign a new value without creating graph operations by using <code>tf.Variable.load()</code>... | python|numpy|tensorflow|random|random-seed | 1 |
358,540 | 56,624,172 | Pandas: How to return rows where a column has a line breaks/new line ( \n ) with one of several case-sensitive words coming directly after? | <p>This is a follow up to this stackoverflow questions</p>
<p><a href="https://stackoverflow.com/questions/56624067/pandas-how-to-return-rows-where-a-column-has-a-line-breaks-new-line-n-in-i/56624112#56624112">Pandas: How to return rows where a column has a line breaks/new line ( \n ) in its cell?</a></p>
<p>Which sh... | <p>Try the below code:</p>
<pre><code>>>> testdf[testdf['A'].str.contains('\nRESULTS|\nMETHODS|\nBACKGROUND')]
A
0 generates the final summary. \nRESULTS We eva...
1 the cat and bat \n\n\nRESULTS\n teamed up to f...
4 the cat and bat \n\n\nMETHODS\n teame... | python|pandas | 1 |
358,541 | 56,513,831 | object detection inference for high resolution images is taking huge time on cpu | <p>I have trained the ML model on pascal dataset with the image size of 224 but when inferencing on new images (some are of high resolution and some are of slightly higher resolution than the pascal images), I get the error in <code>pil2tensor()</code></p>
<pre><code>@app.route('/analyze', methods=['POST'])
async def ... | <p>fixed the issue, here is the correct code:</p>
<pre><code>@app.route('/analyze', methods=['POST'])
async def analyze(request):
data = await request.form()
img_bytes = await (data['file'].read())
img = open_image(BytesIO(img_bytes))
localtime = _utc_to_local(datetime.utcnow())
current_dir = os.p... | pytorch|fast-ai | 0 |
358,542 | 56,510,282 | Finding rows in numpy array with specific condition efficiently | <p>I have two numpy array 2D. What I want to do is to find specific rows of <code>np_weight</code> in the <code>np_sentence</code>.</p>
<p>For example:</p>
<pre><code>#rows are features, columns are clusters or whatever
np_weight = np.random.uniform(1.0,10.0,size=(7,4))
print(np_weight)
[[9.96859395 8.65543961 6.074... | <p>Here is one approach: The function <code>f</code> below creates a mask the same shape as <code>weight</code> (plus one dummy row of <code>False</code>s) marking the top five entries in each column with <code>True</code>.</p>
<p>It then uses <code>np_sentence</code> to index into the mask and counts the <code>True</... | python|arrays|performance|numpy|numpy-ndarray | 1 |
358,543 | 56,574,048 | Pandas one-hot encoding with multiple like columns | <p>I have several 'condition' columns in a dataset. These columns are all eligible to receive the same coded input. This is only to allow multiple conditions to be associated with a single record - which column the code winds up in carries no meaning. </p>
<p>In the sample below there are only 5 unique values acros... | <p>Get <code>max</code> values if need <code>1</code> and <code>0</code> data in output:</p>
<pre><code>dfDummies = dummies.max(axis=1, level=0)
</code></pre>
<p>Or use <code>sum</code> if need count <code>1</code> values:</p>
<pre><code>dfDummies = dummies.sum(axis=1, level=0)
</code></pre> | python|pandas | 2 |
358,544 | 56,562,741 | Does corr function in DataFrame object return restricted matrix with size 190X190? | <p>I have been trying to produce corr matrix based spearman using pandas DataFrame. all the results grant me matrix 190X190 although i inserted 200+ nd.array into the DataFrame object. </p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
vectors # list of 200 nd.array with the same size
df = pd.D... | <p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html" rel="nofollow noreferrer"><code>pandas.DataFrame.corr</code></a> method computes the correlations on columns, perhaps your vectors are of length 190 and this is why you are seeing the result.</p>
<p>For example:</p>
... | python|pandas|scipy|correlation | 0 |
358,545 | 56,593,324 | Cannot open a csv file | <p>I have a csv file on which i need to work in my jupyter notebook ,even though i am able to view the contents in the file using the code in the picture</p>
<p>When i am trying to convert the data into a data frame i get a "no columns to parse from file error"</p>
<p>i have no headers. My csv file looks like this a... | <p>Try to use pandas to read the csv file:</p>
<pre><code>df = pd.read_csv("BON3_NC_CUISINES.csv)
print(df)
</code></pre> | pandas|data-science | 2 |
358,546 | 56,727,199 | How does the input output tensors work for tensorflowjs layers api | <p>I have a classification problem with 8 inputs and 1 output. I create the below model:</p>
<pre><code>const hidden = tf.layers.dense({
units: 8,
inputShape: [58, 8, 8],
activation: 'sigmoid'
});
const output = tf.layers.dense({
units: 1,
activation: 'softmax'
});
var model = tf.sequential({
layers: [
... | <p>The <code>input.shape</code> [1, 58, 8, 8], corresponds to the following:</p>
<ul>
<li>1 is the batch size. <a href="https://stats.stackexchange.com/questions/153531/what-is-batch-size-in-neural-network">More</a> on batchsize</li>
<li>58, 8, 8 is the inputShape specified in the entry of the network</li>
</ul>
<p>... | javascript|tensorflow|machine-learning|tensorflow.js | 0 |
358,547 | 56,573,515 | Calling "fit_generator()" multiple times in Keras | <p>I have a generator function which generates tuples of (inputs, targets) on which my model is trained using the <code>fit_generator()</code> method in Keras.</p>
<p>My dataset is divided into 9 equal parts. I wish to perform a leave-one-out cross validation on the dataset using the <code>fit_generator()</code> metho... | <p><code>fit</code> and <code>fit_generator</code> behave the same in that regard, calling them again will resume training from the previously trained weights.</p>
<p>Also note that what you are trying to do is not cross-validation, as to do real cross-validation, you train one model for each fold, and the models are ... | python|tensorflow|keras|deep-learning|computer-vision | 4 |
358,548 | 56,827,206 | Python 3 throws name 'InputLayer' is not defined when trying to add tensorflow input layer | <p>I've been trying to implement a simple network which takes images of varying sizes and colorizes them. I've been trying to use an input layer with this model, but it seems that python has "changed its mind" since I last worked on this project, and no longer recognises InputLayer</p>
<p>I've checked my imports for m... | <p>Add this in your <code>import</code>: </p>
<pre class="lang-py prettyprint-override"><code>from tensorflow.keras.layers import InputLayer
</code></pre> | python|python-3.x|tensorflow|keras | 3 |
358,549 | 56,673,720 | How can I create a macro to loop through all columns in Pandas Dataframe? | <p>I'm analyzing a data set with information from soccer players. I have the soccer player name, his club and all skills. I want to get the mean value of all players from a club and check the skill in which the club is better. For instance, what club has the faster players, the tallest players, etc.</p>
<p>This is wha... | <p>You want a combination of <code>groupby().mean()</code> to get all the mean stats by clubs and <code>idxmax()</code> to identify the clubs with maximum mean:</p>
<pre><code>df.groupby('Club').mean().idxmax()
</code></pre>
<p>Output:</p>
<pre><code>Balance Corinthians
Speed Palmeiras
Aggression ... | python|pandas|pandas-groupby | 3 |
358,550 | 56,819,030 | How to implement Lineplot using seaborn with x-axis as "Date" | <p>I have tried to implement seaborn lineplot</p>
<ol>
<li>Data frame has list of Date value as index trying to make it as x-axis.
Dataframe.info shows "Date" field as object</li>
<li>I need lineplot for the 4 types of column values with date as x-axis</li>
<li>when I tried to execute the below code it shows the error... | <p>Sorry in advance if I misunderstood the question. </p>
<p>The way I see it is that you need to plot integer values for given categories as y-axis, using dates as the x-axis. </p>
<p>I created this sample dataframe: </p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'Avila Adobe': [11, 22, 33, 44, 55],
... | python|pandas|matplotlib|seaborn|data-science | 5 |
358,551 | 56,798,051 | Pandas vectorized way to get counts using conditional statement between two dataframes | <p>I have two dataframes (with unequal rows, but the same columns) such as the following.</p>
<p>DataFrame A:</p>
<pre><code>dummy | probability
-------------------
0 | .1
-------------------
0 | .2
</code></pre>
<p>DataFrame B:</p>
<pre><code>dummy | probability
-------------------
1 | .05
-... | <p>Here is an iteration-less function that (hopefully) does what you need:</p>
<pre><code>def compare_probabilities(A, B):
df = pd.concat([A] * B.shape[0], axis=0).reset_index(drop=True)
df['Ap'] = df.probability
df['Bp'] = B.probability.repeat(A.shape[0]).values
AgtB = (df.Ap > df.Bp).sum()
Bgt... | python|pandas|numpy | 1 |
358,552 | 56,701,041 | Tensor contraction in tensorflow | <p>I have a tensor <code>weights</code> of shape <code>(?,4)</code> and a tensor <code>embeddings</code> of shape <code>(?,4,1024)</code>.</p>
<p>I would like to contract the tensor by taking a weighted mean of the 4 tensors in each row of <code>embeddings</code> according to the corresponding <code>weights</code>, fi... | <p>You can do that like this:</p>
<pre><code>import tensorflow as tf
weights = tf.placeholder(tf.float32, [None, 4])
embeddings = tf.placeholder(tf.float32, [None, 4, 1024])
output = tf.einsum('ij,ijk->ik', weights, embeddings)
</code></pre>
<p>You can express the same thing through matrix product, not sure if th... | python|tensorflow|tensor | 3 |
358,553 | 56,700,175 | Why can't I see all the columns in Jupyter notebook? | <p>I am displaying a pandas df in <strong>Jupyter lab 0.35.5</strong> with,</p>
<pre><code>pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)`
</code></pre>
<p>but I cannot see the righthand columns, there is no scrollbar (see image). How can I get them to display?</p>
<p>TIA!</p>
<p><a... | <p>Try this </p>
<pre><code>import pandas as pd
from IPython.display import display
pd.options.display.max_columns = None
display(data)
</code></pre>
<p>To enable scrolling :</p>
<pre><code>You can try Cell -> Current Outputs -> Toggle Scrolling in the Jupyter UI to enable the scrolling for the output of one ... | python-3.x|pandas|jupyter-notebook|jupyter-lab | 0 |
358,554 | 56,491,909 | How to do conditional aggregation with pandas | <p>I want to do a conditional aggregation with pandas but with two conditionals, I have seen this <a href="https://stackoverflow.com/questions/17266129/python-pandas-conditional-sum-with-groupby">Python Pandas Conditional Sum with Groupby</a> and I have found really useful but if I added another condition for example:<... | <p>if number of rows of <code>x</code> is N1, number of rows of <code>x[x['key2'] == 'one']</code> will be N2 <= N1 and also number of rows of <code>x[x['key2'] == 'one']['data2']<0.4</code> will be N2 too. Now, in the final <code>x[...]</code> stage, <code>x</code> has N1 rows and the mask inside <code>[...]</co... | python|pandas | 1 |
358,555 | 56,818,779 | How to access Pandas pivot-table data | <p>I have this pivot table:</p>
<pre><code>d = c.pivot_table(index=[ 'Material'], columns = ['MvT'], values=['Quantity'], aggfunc=[np.sum],fill_value=0, margins = True)
sum
Quantity
MvT 601 631 641 All
Material
Type_A 9 2 5 16
Type_B 6 4 10 20
Type_C 3 ... | <p>Change <code>[np.sum]</code> to <code>np.sum</code> , you create a multiple index </p>
<pre><code>d = c.pivot_table(index='Material', columns = 'MvT', values='Quantity', aggfunc=np.sum,fill_value=0, margins = True)
</code></pre>
<p>then </p>
<pre><code>d.loc[:,'All']
</code></pre> | python|pandas | 0 |
358,556 | 56,459,244 | Python - Parsing JSON Data through user defined function | <p>I have a <a href="https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json" rel="nofollow noreferrer">JSON Text File</a></p>
<p>Inside the JSON text file, there are columns like id, title, context, question, is_impossible, answer_start and text.</p>
<p>I am trying to read this into a Pandas DataFrame. I am... | <p>The reason why you don't get the "True"-s back is because they are under a different json-tag - they are under "<strong>plausible_answers</strong>" instead of <strong>answers</strong> I think. In your code the answers_dict is only pulled from the "answers" tag from the json - so you never actually loop over the plau... | python|json|pandas | 2 |
358,557 | 56,850,502 | How to remove outliers in a text dataframe? | <p>I'm writing a program that reads a text file and sorts the data into name, job, company and location fields in the form of a pandas dataframe. The location field is the same for all of the rows except for one or two outliers. I want to remove these rows from the df and put them in a separate list.
Example: </p>
<pr... | <p>I would extract the two groups into separate DFS</p>
<pre><code>same_df = df.query('location == "<onethatisthesame>"')
</code></pre>
<p>Then I would repeat this but using != To get the others</p>
<pre><code>other_df = df.query('location =! "<onethatisthesame>"')
</code></pre> | python|pandas | 0 |
358,558 | 56,691,456 | Modify the orientation of default xtick labels in matplotlib | <p>I have created a graph in matplotlib from a dataframe. My dataframe has automatically populated the graph with the index name as the xlabel and has set the xtick labels as the value of each index (0-16).</p>
<p>But, the labels overlap each other and I can't seem to figure out how to grab them to rotate them so the... | <p>Try passing the value of rotation angle as a parameter <code>rot=30</code> to your second plot. This will rotate the x-axis ticks with the specified angle. Use a negative value for rotating them clockwise</p>
<hr>
<p><strong>Sample complete answer</strong></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'l... | python|pandas|matplotlib | 1 |
358,559 | 56,484,875 | How do I search a csv file for keywords stored in another csv file? | <p>I'm trying to search a csv file having 150K+ row using keywords stored in a csv file with several dozen row. What's the best way to go about this? I've tried a few things but nothing has gotten me very far.</p>
<p>Current Code:</p>
<pre><code>import csv
import pandas as pd
data = pd.read_csv('mycsv.csv')
for line ... | <p>Supposing that your keywords are stored in a file named <code>keys.csv</code> and in each row of that file, there's only one keyword, like this:</p>
<pre><code>Orange
Apple
...
</code></pre>
<p>then try this:</p>
<pre><code>with open('mycsv.csv') as mycsv, open('keys.csv') as keys:
keys = keys.readlines()
... | python|pandas|csv | 0 |
358,560 | 56,647,535 | Pandas iterating over multiple rows at once with overlap | <p>I have a pandas DataFrame that need to be fed in chunks of n-rows into downstream functions (<code>print</code> in the example). The chunks may have overlapping rows.</p>
<p>Let's start from a dummy DataFrame:</p>
<pre><code>d = {'A':list(range(1000)), 'B':list(range(1000))}
df=pd.DataFrame(d)
</code></pre>
<p>In... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="noreferrer"><code>DataFrame.groupby</code></a> with integer division with helper 1d array created with same length like <code>df</code> - index values are not overlapped:</p>
<pre><code>d = {'A':list(range(5))... | python|pandas|iteration | 8 |
358,561 | 56,865,946 | Occurrence of list in ndarray | <p>I have an RGB image -ndarray- and I want to count the occurrence of some colors like [255,0,0] or [0,0,255] in this image.</p>
<p>example of image data</p>
<pre><code>np.ones((3, 3, 3)) * 255
array([[[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.]],
[[255., 255., 255.],
[... | <p>One solution could be the <code>Counter</code> function:</p>
<pre><code>from collections import Counter
import numpy as np
# Generate some data
data = np.ones((10, 20, 3)) * 255
# Convert to tuple list
data_tuple = [ tuple(x) for x in data.reshape(-1,3)]
Counter(data_tuple)
</code></pre>
<p>Returns:</p>
<pre><c... | python|numpy|image-processing|numpy-ndarray | 4 |
358,562 | 56,715,112 | How to add a pandas Series to a DataFrame ignoring indices? | <p>I have a DataFrame with random, unsorted row indices, which is a result of removing some 'noise' from the original DataFrame.</p>
<pre><code>row_index col1 col2
2 1 2
19 3 4
432 4 1
</code></pre>
<p>I would like to add some pd.Series to this Dataframe. The Series has its i... | <p>convert the series into a data frame.</p>
<pre><code>code
df=pd.DataFrame(df)
result=pd.concat([df1,df],axis=1,ignore_index=True)
</code></pre>
<p>df1 is the data frame you want to add .</p>
<p>df is the data frame i.e series you converted to data frame</p> | python|pandas|dataframe | 6 |
358,563 | 56,861,676 | How to iterate over a tf.dataset, without deprecated functions? | <p>I'm using tensorflow 1.14 and have a problem with dataset.</p>
<p>my code:</p>
<pre><code>my_data = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
]
slices = tf.data.Dataset.from_tensor_slices(my_data) # get dataset
it = slices.make_one_shot_iterator() # get iterator from dataset (deprecated)
next_item = it.get... | <p>From the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#as_numpy_iterator" rel="nofollow noreferrer">tf.data.Dataset</a> you can do a simple loop with:</p>
<pre><code>for element in my_dataset:
print(element)
</code></pre>
<p>As you can see in the image, this returns a <co... | python|tensorflow | 2 |
358,564 | 56,548,107 | Why does python's lambda function not resample from a distribution? | <p>Python's lambda function does not resample from a distribution when applied on an array; e.g. when using: </p>
<pre><code>f1 = lambda x: -3 + 0.75*x + numpy.random.randn()
</code></pre>
<p>The proper way would be to use a map() and thereby 'map' the lambda function on the array.</p>
<p>However, one can easily app... | <p>The issue is with how you have defined the lambda function <code>f1</code>:</p>
<pre><code>f1 = lambda x: -3 + 0.75*x + numpy.random.randn()
</code></pre>
<p>Here <code>numpy.random.rand()</code> returns a scalar. So you have <code>-3 + 0.75 * x</code> (a vector) + <code>numpy.random.randn()</code> (a scalar) - th... | python|numpy | 2 |
358,565 | 56,808,425 | SQLAlchemy (psycopg2.ProgrammingError) can't adapt type 'dict' | <p>Couldn't find a solution on the web for my problem.
I am trying to insert this pandas df to a Postgresql table using SQLAlchemy </p>
<ul>
<li>Pandas 0.24.2 </li>
<li>sqlalchemy 1.3.3</li>
<li>python 3.7</li>
</ul>
<p>Relevant part of my code is below:</p>
<pre><code>engine = create_engine('postgresql://user:pass@... | <p>Just use dataframe apply</p>
<pre><code>df['bets'] = df['bets'].apply(json.dumps)
</code></pre> | json|python-3.x|pandas|postgresql|sqlalchemy | 13 |
358,566 | 56,441,409 | Applying weights to a Pandas Dataframe to identify recurring terms | <p>I have a very large Pandas Dataframe with a list of terms found in a large library of text. The columns are the term and the amount of times that term appears in the text:</p>
<pre><code>Term Hits
volvo car handbrake 300
kelly blue book 20000
mcdonals health 1
dog show cambridge 5... | <p>I had written these functions earlier for generating <code>ngrams</code> and finding there frequency:</p>
<pre><code>import nltk
def generate_ngrams(text, n_gram=2):
token = [token for token in text.strip().lower().split(" ")]
ngrams = zip(*[token[i:] for i in range(n_gram)])
return [" ".join(ngram) fo... | python|pandas|scikit-learn|n-gram|weighted-average | 1 |
358,567 | 56,801,700 | replace function in python give wrong result | <p>dfF:</p>
<pre><code> Sample AlmostFinal
1 KOPLA234
1 KOPLA234
2 RWPLB253
3 MMPLA415
3 MMPLA415
</code></pre>
<p>I need to replace <code>KOPL</code> and <code>RWP</code> and <code>MM</code> to KOLPOL and last char a/b should stay. So re... | <p>You should execute one assignment, not three. Otherwise, each next assignment overwrites the results of the previous assignment.</p>
<pre><code>dfF['Final'] = dfF['AlmostFinal']\
.replace({'KOP|RWP|MMP': 'KOLPO'}, regex = True)
</code></pre> | python|pandas|dataframe | 1 |
358,568 | 56,570,282 | How can I mask a pandas dataframe column in logging output? | <p>I am having to log some pandas dataframe outputs that contain sensitive information. I would rather not have this info in the logs or print in the terminal. </p>
<p>I normally write a little function that can take a string and mask it with a regex, but I am having trouble doing that with a dataframe. Is there anywa... | <p>Make sure to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html" rel="nofollow noreferrer">df.copy</a> the dataframe if you want to leave the original df as is:</p>
<pre><code>def hide_by_pd_df_columns(dataframe,columns,replacement=None):
'''hides/replaces a pandas da... | python|pandas|security|logging | 1 |
358,569 | 56,573,317 | Decode a column in a dataframe and remove "b'\xc2\xa" n "\xc2\xa0" | <p>I have two problems. </p>
<ol>
<li>All my columns begin with the letter 'b'. I want to get rid of this character and convert all the values to float. (I've attached an image of the entire data frame). </li>
</ol>
<p><a href="https://i.stack.imgur.com/I3vge.png" rel="nofollow noreferrer"><img src="https://i.stack.i... | <p>I changed your code according to the comments from @cs95 and @eyllanesc. I can execute the code without errors and it yields a dataframe without byte encoding.</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
Base_url = ("https://www.nseindia.com/live_market/dynaContent/live_watch/f... | python|python-3.x|pandas | 1 |
358,570 | 56,512,931 | Does making DataFrame smaller makes it faster? | <p>I read an article (<a href="https://www.ritchieng.com/pandas-making-dataframe-smaller-faster/" rel="nofollow noreferrer">https://www.ritchieng.com/pandas-making-dataframe-smaller-faster/</a>) which mentions that it makes the DataFrame faster by making it smaller (by converting data type).</p>
<p>Is there any associ... | <p>why not to test it?</p>
<h1>int64 dtype</h1>
<pre><code>In [29]: df = pd.DataFrame(np.random.randint(100, size=(10**7, 10), dtype="int64"))
In [30]: df.dtypes
Out[30]:
0 int64
1 int64
2 int64
3 int64
4 int64
5 int64
6 int64
7 int64
8 int64
9 int64
dtype: object
</code></pre>
... | python|pandas|dataframe | 2 |
358,571 | 56,721,644 | How to run TensorBoard in Docker container without root privileges? | <p>I am running tensorflow-gpu in a Docker container.
At the moment I am only able to run and access TensorBoard when I access the running Docker container using root privileges. I would like to accomplish this without using root privileges. How can this be accomplished?</p>
<p><strong>Here some information on what I... | <p>The steps I followed and I could visualise the results with tensorboard:</p>
<ul>
<li>when creating a the container, open/map an external port for tensorboard:</li>
</ul>
<blockquote>
<pre><code>> nvidia-docker run -d --name tkra_tensorb --ipc=host -it -p 8513:8090
> -p 3014:6006 -v /data:/data tkra_tb
</code>... | docker|tensorflow|tensorboard|tensorflow-datasets | 0 |
358,572 | 25,586,783 | pandas: vectorize counting rows in time interval | <p>My situation is as follows. I've got one Series (<code>a_series</code>) of events of type A, indexed by PersonID and another ID irrelevant to the question:</p>
<pre><code>PersonID AnotherID
19 768 2013-02-03 13:39:00
767 2013-02-03 14:03:00
766 ... | <p>Depending on the size of frame and number of matches it <em>may</em> be more efficient to use join operations:</p>
<p>First, give the series names and change them to data-frames:</p>
<pre><code>>>> a.name, b.name = 'a', 'b'
>>> xb = b.reset_index(level=-1).filter('b')
>>> xa = a.reset_in... | python|pandas | 1 |
358,573 | 25,888,207 | Pandas: join DataFrames on field with different names? | <p>According to <a href="http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html#left-outer-join" rel="noreferrer">this documentation</a> I can only make a join between fields having the same name.</p>
<p>Do you know if it's possible to join two DataFrames on a field having different names?</p>
<p>The eq... | <p>I think what you want is possible using <code>merge</code>. Pass in the keyword arguments for <code>left_on</code> and <code>right_on</code> to tell Pandas which column(s) from each DataFrame to use as keys:</p>
<pre><code>pandas.merge(df1, df2, how='left', left_on=['id_key'], right_on=['fk_key'])
</code></pre>
<p... | python|pandas|join|dataframe|field | 122 |
358,574 | 25,875,253 | Numpy or SciPy Derivative function for non-uniform spacing? | <p>I was wondering if numpy or scipy had a method in their libraries to find the numerical derivative of a list of values with non-uniform spacing. The idea is to feed in the timestamps that correspond to the values and then for it to use the timestamps to find the numerical derivative.</p> | <p>You can create your own functions using numpy. For the derivatives using forward differences (edit thanks to @EOL, but note that <strong>NumPy's <code>diff()</code> is not a differentiate function</strong>):</p>
<pre><code>def diff_fwd(x, y):
return np.diff(y)/np.diff(x)
</code></pre>
<p>"central" differences... | python|numpy|scipy|derivative | 7 |
358,575 | 25,670,760 | Copying a row screws up pandas column data types, how to avoid? | <p>If after generating a Pandas data frame with some boolean columns, I get the appropriate data types for columns.</p>
<pre><code>>>> individuals = pandas.DataFrame([[True, 1],[False, 1]],
... columns = ["female","fitness"])
...
>>> print(individuals["female"])
0 True
1 False
Name: female,... | <p>You should use <code>.append</code>. The <code>.loc</code> syntax for extending on purpose will not preserve the dtypes in a multi-dtype case. This will be fixed for 0.15.0</p>
<pre><code>In [18]: individuals.append(individuals.loc[1])
Out[18]:
female fitness
0 True 1
1 False 1
1 False ... | python|types|pandas | 4 |
358,576 | 25,717,397 | Using np.where but maintaining exisitng values if condition is False | <p>I like np.where, but have never fully got to grip with it. </p>
<p>I have a dataframe lets say it looks like this:</p>
<pre><code>import pandas as pd
import numpy as np
from numpy import nan as NA
DF = pd.DataFrame({'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0... | <p>There is a <code>pandas.Series</code> method (<code>where</code> incidentally) for exactly this kind of task. It seems a little backward at first, but from the documentation. </p>
<blockquote>
<p>Series.where(cond, other=nan, inplace=False, axis=None, level=None,
try_cast=False, raise_on_error=True) </p>
... | numpy|pandas|where | 17 |
358,577 | 25,497,889 | Rounding errors with floats in Python using Numpy | <p>I'm having an issue that I believe has to do with working with floats and precision but I'm not very well versed in the various intricacies involved. I'm a math person and in my mind I might as well still be just working with decimals on a chalkboard. I'll begin studying up on this, but in the mean time, I'm wonde... | <p>Rather than using <code>==</code> to select subsets of data, try using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow noreferrer">numpy.isclose()</a>. This allows you to specify a relative/absolute tolerance for your comparison <code>(absolute(a - b) <= (atol + rto... | python|numpy|rounding-error | 4 |
358,578 | 26,030,945 | Performing math.sqrt on numpy structured array column | <p>I have a numpy structured array. The final column needs to contain the result of a simple math equation based on the other values in the row. Problem is I get the following error when trying to calculate the square root portion of the equation:</p>
<p><code>TypeError: only length-1 arrays can be converted to Python... | <p>You simply need to use <code>np.sqrt</code> instead of <code>math.sqrt</code> (the latter only works on single values).</p> | python|arrays|numpy|math.sqrt | 6 |
358,579 | 26,066,126 | groupby common values in two columns | <p>I need to extract a common max value from pairs of rows that have common values in two columns.</p>
<p>The commonality is between values in columns A and B. Rows 0 and 1 are common, 2 and 3, and 4 is on its own.</p>
<pre><code>f = DataFrame([[1, 2, 30], [2, 1, 20], [2, 6, 15], [6, 2, 70], [7, 10, 35]], columns=['A... | <p>You could sort the values in columns <code>A</code> and <code>B</code> so that for each row the value in <code>A</code> is less than or equal to the value in <code>B</code>. Once the values are ordered, then you could apply <code>groupby-transform-max</code> as usual:</p>
<pre><code>import pandas as pd
df = pd.Data... | python|pandas | 2 |
358,580 | 26,108,879 | Append rows from a Pandas DataFrame to a new DataFrame | <p>I have a Pandas dataframe for which the first 6 lines look like below:</p>
<pre><code> Timestamp u1 u2 u3
0 0 0.00000 23.02712 30.46594
1 2 0.00000 22.31358 30.10915 ... | <p>You could collect the data frames that have the max u3 values, and use <code>pd.concat</code> to put them back together - </p>
<pre><code>counter = df.Timestamp.max()/90000
collected_dfs = []
for i in range(counter):
df_temp = df[(df.Timestamp >= i*90000) & (df.Timestamp < (i+1)*90000)]
try:
... | python|pandas|dataframe | 1 |
358,581 | 26,130,442 | rolling_mean instability in pandas | <p>I'm performing an upgrade from our current environment (Python 2.7.3 64-bit, pandas 0.9) to a new one (Python 2.7.6, pandas 0.14.1) and some of my regression tests are failing. I tracked it down to the behavior of <code>pandas.stats.moments.rolling_mean</code></p>
<p>Here is a sample to reproduce the error:</p>
<... | <p>The reason for the difference in the outcome of the different approaches is an accumulated rounding error that is greater during the <em>sum divide</em> computation. In the past, the <em>rolling mean</em> computation suffered from a similar issue, but it seems that internal improvements in its algorithm over the pas... | python|numpy|pandas | 4 |
358,582 | 26,051,079 | Plotting image Red channel by intensity | <p>Okay, So i'm trying to take the red channel of an image, and plot it (preferably 3d) to an image. The image is 480x640 (or thereabouts), and is taken from a webcam. I'm currently using scipy, numpy, and python to get the image, extract he red channel, and process it. That all works.</p>
<p>However, when i try to... | <p>Try using <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow"><code>pyplot.imshow</code></a>:</p>
<pre><code>plt.cmap('Reds')
plt.imshow(self.R)
plt.show()
</code></pre> | python|numpy|matplotlib|scipy | 0 |
358,583 | 26,334,151 | getting Killed message in Python -- Is memory the issue? | <p>I have a <strong><code>list</code></strong> which I <strong><code>.append()</code></strong> to in a <strong><code>for</code></strong>-loop, finally the length of the <code>list</code> is around 180,000. Each item in the <code>list</code> is a <strong><code>numpy</code></strong> array of 7680 <strong><code>float32</c... | <h2>Yes, memory is the problem</h2>
<p>Your estimate also needs to take into account a memory-allocation already done for the <strong><code>list</code></strong>-representation of the <code>180000 x 7680 x float32</code>, so without other details on dynamic memory-releases / garbage-collections, the <strong><code>numpy... | python|numpy | 1 |
358,584 | 26,157,092 | Python - Combine 2 masks arrays with same dimensions | <p>I would like to combine two masked arrays of same dimensions. I work on a grid and i do calculation on two parts of the array defined with the grid.
When i have obtained the 2 masked arrays I want to combine it (sum the 2 results) in a same dimension array...but the masks "annihilate" the results of the other part a... | <p>Use <code>numpy.ma.filled</code>:</p>
<pre><code>>>> import numpy as np
>>> data = np.arange(10, 20)
>>> data = np.ma.array(data, mask=np.zeros(data.shape))
>>> data.mask[[3,5,6]] = True
>>> data
masked_array(data = [10 11 12 -- 14 -- -- 17 18 19],
mask = [F... | arrays|numpy|combinations|mask | 2 |
358,585 | 67,019,403 | Retrieve all columns from one label in the top level alongside only a subset of another label | <p>I have a dataframe similar to this:</p>
<pre><code>df1 = pd.DataFrame(np.arange(12).reshape(4, 3),
columns=list('abc'))
df1.columns = pd.MultiIndex.from_product((["df1"], df1.columns))
df2 = pd.DataFrame(np.arange(100, 112).reshape(4, 3),
columns=list('def'))
df2.colum... | <p>I think <code>concat</code> is simpliest way here, but it is possible e.g. if some way create masks and join them by <code>|</code> for bitwise <code>OR</code>:</p>
<pre><code>m1 = df.columns.isin([('df2','d'), ('df2','e')])
m2 = df.columns.get_level_values(0) == 'df1'
df = df.loc[:, m1 | m2]
print (df)
df1 ... | python|pandas|indexing|multi-index | 2 |
358,586 | 66,926,443 | Arbitrary separator in pandas csv | <p>I am trying to use an arbitrary separator for reading a very long csv file with six columns. The column separator is '%$%$%', but when I read the dataframe with
<code>df = pd.read_csv(filename, sep='%$%$%', engine='python')</code> the code gives me a single column
<code>Out[1]: Index(['Col1%$%$%Col2%$%$%Col3%$%$%Col... | <p>Escape the <code>$</code> in separator:</p>
<pre><code>df = pd.read_csv("your filename", sep=r"%\$%\$%", engine="python")
print(df)
</code></pre>
<p>Prints:</p>
<pre><code>Empty DataFrame
Columns: [Col1, Col2, Col3, Col4, Col5, Col6]
Index: []
</code></pre>
<hr />
<p>Why? From <a href="... | python|pandas | 0 |
358,587 | 66,920,055 | Keep the value corresponding to the maximum of another column in a dataframe | <p>I have a DataFrame</p>
<pre><code> day type price
0 10900 2 300
1 10900 1 500
2 10900 3 200
3 10901 5 100
4 10901 2 400
5 10901 1 300
6 10902 2 100
7 10902 3 300
8 10902 1 200
9 10902 4 400
</code></pre>
<p>and i want for each day t... | <pre><code>df["price"] = df.groupby("day", as_index=False)["price"].transform(
lambda x: df.loc[df.loc[x.index, "type"].idxmax(), "price"]
)
print(df)
</code></pre>
<p>Prints:</p>
<pre><code> day type price
0 10900 2 200
1 10900 1 200
2 10900 ... | python|pandas|dataframe|group-by | 1 |
358,588 | 66,916,869 | How to combine rows of list of string based on another column's value in pandas? | <p>I have a table like this:</p>
<pre><code>|Name |Txt |
| --- |-----------------|
|Mike |[I like pie] |
|Jason| [Good morning] |
|Mike | [good afternoon]|
|Jason| [One two three]|
</code></pre>
<p>I want to turn it into something like this:</p>
<pre><code>|Name |Txt |
| --- | --... | <p>Use <code>groupby</code>, <code>str.cat()</code></p>
<pre><code>df.groupby('Name')['Text'].apply(lambda x:x.str.cat(sep=" "))
</code></pre> | python|pandas|dataframe | 2 |
358,589 | 66,806,753 | minus between 2 dataframe based on column | <p>I have 2 dataframe pandas df1, df2:</p>
<pre><code>df1 = pd.DataFrame({'col1': ['A', 'B', 'C', 'D'],
'col2': ["D1","D2","D3","D4"],
'col3': ["C1","C2","C3","C4"],
'col4': ["... | <h3><code>isin</code></h3>
<pre><code>df1[~df1.col1.isin(df2.col_ID)]
</code></pre> | python|pandas|dataframe | 5 |
358,590 | 66,972,473 | how to insert array in numpy using two variables | <p>if I have array:
a=[1,2,3]
b=[7,8,9]
I want to get new array c=[1,7,2,8,3,9], which is alternating arrangement between a and b. How to use np.insert on that case?</p> | <pre><code># solution 1
import numpy as np
a=[1, 2, 3]
b=[7, 8, 9]
list(np.transpose((a,b)).flatten())
# output [1, 7, 2, 8, 3, 9]
# solution 2
import operator
a=[1, 2, 3]
b=[7, 8, 9]
reduce(operator.concat, map(lambda x, y : [x, y], a, b))
# output [1, 7, 2, 8, 3, 9]
</code></pre> | python|numpy-ndarray | 1 |
358,591 | 67,028,236 | after a groupby create a new column with a list of unique values for another column of the groupes values | <p>So i have a dataframe with two columns: artistID and genre:</p>
<pre><code> artistID genre
0 52 rock
1 63 pop
2 73 salsa
3 94 reggaeton
4 6177 rock
5 64 salsa
6 862 metal
7 52 pop
8 63 hiphop
9 64 jazz
10 52 metal
11 63 electro
12 73 latino
13 94 ... | <p>I think what you need is:</p>
<pre><code>df.groupby('artistID').agg(list).reset_index()
artistID genre
0 52 [rock, pop, metal]
1 63 [pop, hiphop, electro]
2 64 [salsa, jazz, latino]
3 73 [salsa, latino]
4 94 [reggaeton, trap]
5 456 ... | python|pandas | 1 |
358,592 | 66,961,748 | Removing min, max and calculating average | <p>I have columns of numbers and I would need to remove only one min. and one max. and then calculate the average of the numbers that remain.
The hitch is that the min/max could be anywhere in the column and some rows may be blank (null) or have a zero, or the column might have only 3 values.
All numbers will be betwee... | <p>If the objective is to calculate the average without one min and one max, you can just do</p>
<pre><code>(df['Value'].sum() - df['Value'].min() - df['Value'].max())/(len(df)-2)
</code></pre>
<p>which outputs <code>52.54</code> for your data. Note that this will ignore NaNs etc. This will not modify your df which, if... | python|pandas | 2 |
358,593 | 66,846,578 | Joining DataFrame and calculating distance from Date | <p>Given</p>
<pre><code>import pandas as pd
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_date
start = parse_date("Jan 1 2021")
records = []
for i in range(15):
records.append(dict(date=start+timedelta(days=i), t=i))
df = pd.DataFrame(records).set_index('date')... | <p>tdy's Answer is definitely a good solution if the data is exactly as in the sample, so if there is a row for each day...</p>
<p>Personally, I would prefer to do it like this:</p>
<pre><code>df = DF(dict(date= [to_datetime("20210101") + to_timedelta(i, unit= "D") for i in range(15)]))
df["eve... | python|pandas | 1 |
358,594 | 67,087,980 | Multiplying multidimensional multiindex dataframe with single index dataframe over time | <p>I am new to Python and looking for help to multiply 2 dataframes over time. Any help to understand the error would be highly appreciated.</p>
<p>First DataFrame (cov)</p>
<pre><code>Date NoDur Durbl Manuf
2018-12-27 NoDur 0.000109 0.000112 ... | <p>I think you can use <code>groupby</code> on the <code>'Date'</code> level and then multiply the weights in <code>w</code> corresponding to the date in the group:</p>
<pre><code>cov.groupby(level='Date').apply(lambda g: w.loc[g.name].dot(g.values@(w.loc[g.name])))
</code></pre>
<p>As your data really is better repres... | python|pandas|dataframe|numpy | 2 |
358,595 | 66,770,663 | Python Pandas Add DataRow Revision Number | <p>I have a Data Frame looking like below. I need to use a combination of ID and Serial and calculate revision numbers.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Serial</th>
<th>Time</th>
<th>Revision</th>
</tr>
</thead>
<tbody>
<tr>
<td>48ff35eb-70ad-4dcd-a441-8c7c9966a23... | <p>I think you are looking for dense <code>rank</code>:</p>
<pre><code># `rank` only works with numerical
df['Time'] = pd.to_datetime(df['Time'])
df['Revision'] = df.groupby(columns_of_interest)['Time'].rank(method='dense')
</code></pre>
<p>Output:</p>
<pre><code> ID Serial ... | python|python-3.x|pandas|python-3.8 | 4 |
358,596 | 67,063,904 | Combining Pandas DataFrames With Multiple Reference Columns | <p>I'm trying to combine two pandas DataFrames to update the first one based on criteria from the second. Here is a sample of the two dataframes:
df1</p>
<pre><code>year
2016 CALIFORNIA CLINTON, HILLARY
2016 CALIFORNIA ... | <p>An alternate way to write -</p>
<pre><code>merged_df = df1.merge(df2, on=['year', 'state'], how='left')
</code></pre>
<p>If you want to use only 3 columns from df1 -</p>
<pre><code>df1 = pd.read_csv('<name_of_the_CSV_file>', usecols=['year', 'state', 'candidate'])
</code></pre> | python|pandas|dataframe | 1 |
358,597 | 66,949,584 | How to sum a row from two dataframe that has the row with certain same value in Pandas Dataframe | <p>Expected output is a dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Dates</th>
<th>Total Revenue</th>
</tr>
</thead>
<tbody>
<tr>
<td>2019-11-01</td>
<td>59946202</td>
</tr>
<tr>
<td>2019-11-02</td>
<td>95429717</td>
</tr>
<tr>
<td>2019-11-03</td>
<td>89662309</td>
</tr>
<tr>... | <p>Change the Dates as the "Index" of the DataFrame, it will then automatically perform data alignment in arithmetic calculation.</p> | python|pandas|dataframe | 0 |
358,598 | 66,880,548 | Array to columns in dataframe | <p>I've built a functioning classification model following <a href="https://kavita-ganesan.com/news-classifier-with-logistic-regression-in-python/#Saving-Logistic-Regression-Model" rel="nofollow noreferrer">this tutorial</a>.
I bring in a csv and then pass each row's text value into a function which calls on the classi... | <p>You function returns a list that contains a list of tuples? Why the double-nested list? One way I can think of:</p>
<pre class="lang-py prettyprint-override"><code>tmp = {}
for index, row in df.iterrows():
predictions = get_top_k_predictions(...)
tmp[index] = {
key: value for key, value in prediction... | python|arrays|pandas|machine-learning|logistic-regression | 0 |
358,599 | 67,146,595 | Pytorch GAN model doesn't train: matrix multiplication error | <p>I'm trying to build a basic GAN to familiarise myself with Pytorch. I have some (limited) experience with Keras, but since I'm bound to do a larger project in Pytorch, I wanted to explore first using 'basic' networks.</p>
<p>I'm using Pytorch Lightning. I think I've added all necessary components. I tried passing so... | <p>This multiplication problem comes from the <code>DoppelDiscriminator</code>. There is a linear layer</p>
<pre class="lang-py prettyprint-override"><code> nn.Linear(25, 1),
</code></pre>
<p>that should be</p>
<pre class="lang-py prettyprint-override"><code> nn.Linear(9, 1),
</code></pre>
<p>based on the error m... | python-3.x|neural-network|pytorch|generative-adversarial-network|pytorch-lightning | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.