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 |
|---|---|---|---|---|---|---|
18,100 | 55,343,893 | How to do parallel processing in pytorch | <p>I am working on a deep learning problem. I am solving it using pytorch. I have two GPU's which are on the same machine (16273MiB,12193MiB). I want to use both the GPU's for my training (video dataset).</p>
<p>I get a warning:</p>
<p>There is an imbalance between your GPUs. You may want to exclude GPU 1 which
h... | <p>As mentioned in this link, you have to do model.cuda() before passing it to nn.DataParallel.</p>
<pre><code>net = nn.DataParallel(model.cuda(), device_ids=[0,1])
</code></pre>
<p><a href="https://github.com/pytorch/pytorch/issues/17065" rel="nofollow noreferrer">https://github.com/pytorch/pytorch/issues/17065</a><... | parallel-processing|pytorch|torch|gpu|torchvision | 2 |
18,101 | 55,562,121 | How to fix "TypeError: object of type 'CategoricalDtype' has no len()" problem in the fit() method? | <p>I am trying out Titanic dataset on Kaggle. I used dropna() to keep it simple and also dropped a couple of columns. However, I get the "TypeError: object of type 'CategoricalDtype' has no len()" message when I call the fit() method.</p>
<p>I have tried to use different classifiers, but I get the same error. I guess ... | <p>try to make X and y np.arrays, id est X = np.array(X) and y = np.array(y), just before train_test_split()</p> | python|python-3.x|scikit-learn|sklearn-pandas | 1 |
18,102 | 55,239,883 | Can't perform calculations on DataFrame values | <p>I am trying to apply a formula to each value in a Pandas DataFrame, however, I am getting an error.</p>
<pre><code>def transform_x(x):
return x/0.65
transformed = input_df.applymap(transform_x)
</code></pre>
<p>This returns the following error:</p>
<pre><code>----------------------------------------------------... | <p>You may try something like:</p>
<pre><code>input_df = input_df.apply(lambda x: pd.to_neumeric(x,errors='coerce')).applymap(transform_x)
</code></pre>
<p>the <code>input_df</code> is a 2D array but <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer">... | pandas|python-applymap | 0 |
18,103 | 10,158,269 | install numpy and matplotlib to locally installed python2.7 in linux | <p>I installed python2.7 linux locally through </p>
<pre><code>./configure --prefix=$HOME
make
make install
</code></pre>
<p>then how can I install modules numpy & matplotlib to it? </p>
<p>The system of server is Fedora x86_64. Thanks</p> | <p>Install distribute:</p>
<pre><code> curl -O http://python-distribute.org/distribute_setup.py
~/bin/python distribute_setup.py
</code></pre>
<p>Install pip (not necessary, but helpful):</p>
<pre><code> ~/bin/easy_install pip
</code></pre>
<p>Install packages:</p>
<pre><code> ~/bin/pip install numpy
~/bin/pip i... | python|numpy|matplotlib | 2 |
18,104 | 56,730,036 | Value direction change in a pandas column | <p>I have a column in a dataframe like below</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Difference
0
0
0.067
0
0
0
0
0.062
0
0
0
0
0.018
0
0
0
0
-0.085
0
0
0
0
0.033
... | <p>Use:</p>
<pre><code>m = df['Difference'].ne(0)
posneg = df['Difference'].where(m).ffill().gt(0)
g = posneg.ne(posneg.shift()).cumsum()
g = g.mask(df['Difference'].eq(0).groupby(g).transform('all')).bfill()
df['Switch'] = np.where(~g.duplicated(), df['Difference'].groupby(g).transform('sum').shift(), np.nan)
df['S... | pandas | 1 |
18,105 | 56,755,188 | Where do I get Visual Studio 15.4 that I need for pyTorch 0.4.1 | <p>I have a problem with the following dependency chain:</p>
<ul>
<li>MedicalDetectionToolkit (MDT) needs pyTorch 0.4.1 since in pyTorch 1.0 torch.utils.ffi is depricated</li>
<li>pyTorch 0.4.1 needs CUDA 9.0 (does not work with 10.0)</li>
<li>CUDA 9.0 does not work with Visual Studio > 15.4</li>
<li>Visual Studio 15.... | <p>There are the "Build Tools for Visual Studio 2017 (version 15.0)" available on
<a href="https://my.visualstudio.com/Downloads?q=Visual%20Studio%202017" rel="nofollow noreferrer">https://my.visualstudio.com/Downloads?q=Visual%20Studio%202017</a></p>
<p>You may first have to join the "Essentials" program. After join... | visual-studio|pytorch|ffi|cffi | 0 |
18,106 | 67,182,821 | Python - valuecounts() method - display all results | <p>I am a complete novice when it comes to Python so this might be badly explained.</p>
<p>I have a pandas dataframe with 2485 entries for years from 1960-2020. I want to know how many entries there are for each year, which I can easily get with the <code>.value_counts()</code> method. My issue is that when I print thi... | <p>Use <code>pd.set_options</code> and set <code>display.max_rows</code> to <code>None</code>:</p>
<pre><code>>>> pd.set_option("display.max_rows", None)
</code></pre>
<p>Now you can display all rows of your dataframe.</p>
<ul>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/opti... | python|pandas|dataframe | 7 |
18,107 | 67,121,904 | pandas dataframe multiple condition error with "The truth value of a Series is ambiguous" | <p>pandas version: <code>'1.2.3'</code>, python version: 3.7.9</p>
<p>code:</p>
<pre><code> x = pd.DataFrame({'a':[1,2], 'b':[2,3]})
x['a']>1 & x['b'] <= 2
</code></pre>
<p>it shows <code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</code></p>... | <p>If check linked answer difference is missing parentheses, because priority of operators, so add them:</p>
<pre><code>mask = (x['a']>1) & (x['b'] <= 2)
df = x[mask]
</code></pre> | pandas|dataframe | 2 |
18,108 | 67,020,692 | How would I plot this as a line graph? | <p>I have this data below. I was wondering how I would plot it. This is a dataframe and the first column is the index and the second column holds a timestamp(left number) and then the price. This is only showing the first 5 rows but the dataframe is actually (366, 1). I am not sure how to split the data up so I can mak... | <p>You can convert the column <code>prices</code> to a list by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tolist.html" rel="nofollow noreferrer"><code>tolist()</code></a> and store the result in another <code>DataFrame</code>. The result can be plotted with the <a href="https://pa... | python|pandas|dataframe|matplotlib | 4 |
18,109 | 67,029,800 | fillna() after .reset_index was used to create DataFrame | <p>I have 3 dfs with call, message and internet data for some users. I used groupby to find the number of calls (or messages, or GB) used per user per month, and then used <code>.reset_index</code> to convert the MultiIndexes to DataFrames. Through further analysis, I noticed that for some user ids, there were NaN valu... | <p>you can try some actions:</p>
<p>use the df.replace(' ','') probably is a empty space and is not recognized for the fillna() as a 'Nan' value
or check that the Nan values are not actually 'Nan' string, if so, then you can do df.replace('Nan', '')</p>
<p>hope you can solve it</p> | python|pandas|dataframe|missing-data | 0 |
18,110 | 67,120,911 | Pandas - sorting dataframe by two columns that one of them uses key | <p>This is my dataframe:</p>
<pre><code>df = pd.read_csv('https://raw.githubusercontent.com/AmirForooghi/stocks_example/main/xxx.csv')
</code></pre>
<p>I want to sort df by two columns: rsi and sector. For rsi I want <code>ascending=False</code> and for sector I want to use the <code>key</code> argument. The key is:</p... | <p>You need to use a stable sorting algorithm to preserve the order of the first sort. You can do this by setting <code>kind='mergesort'</code></p>
<pre><code>sorted_df = df.sort_values(by='rsi', ascending=False).sort_values(by='sector', key=lambda x:x.map(order_dic), kind='mergesort')
</code></pre> | python|pandas | 1 |
18,111 | 67,024,709 | Pandas - Count total quantity of item and remove unique values that have a total quantity less than 5 | <p>Here is a simplified table that resembles my df below. A clothing item such as, blue_shirt, could appear more than once in the column with a different value under Quantity_ordered each time it appears (1st time it appears there is only 1 unit under Quantity_ordered, 2nd time there are 3 units).</p>
<pre><code> It... | <p>You simply get the size of each group by doing the following:</p>
<pre><code>grouped = df.groupby('Item').agg(np.size)
</code></pre>
<p>You can refer to this example below:</p>
<pre><code>df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Spee... | python|pandas | 2 |
18,112 | 67,147,295 | Cloud Function strange behaviour when downloading from storage bucket | <p>I download my image from my cloud bucket with (python):</p>
<pre><code>storage_client = storage.Client()
bucket = storage_client.get_bucket('mybucket')
blob = bucket.blob('myimage.png')
img = blob.download_as_bytes(raw_download=True)
</code></pre>
<p>Then using tensorflow, I convert the image to a tensor, and return... | <p>From comments</p>
<blockquote>
<p>Eager execution seems to be disabled by default in this cloud
environment. So calling <code>tf.compat.v1.enable_eager_execution()</code> before
solves the problem (paraphrased from waltwhite)</p>
</blockquote>
<pre><code>import tensorflow as tf
tf.compat.v1.enable_eager_execution()
... | tensorflow|google-cloud-platform|google-cloud-functions|google-cloud-storage|google-ai-platform | 1 |
18,113 | 47,197,007 | Pandas DataFrame: resampling along integer index / grouping by groups of n elements | <p>I know about pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.resample.html" rel="nofollow noreferrer">resampling</a> functions using a DateTimeIndex.</p>
<p>But how can I easily resample/group along an integer index?</p>
<p>The following code illustrates the problem and works:<... | <p>You can floor divide index and aggregate some function:</p>
<pre><code>df1 = df.groupby(df.index // n).sum()
</code></pre>
<p>If index is not default (integer, unique) aggregate by floor divided <code>numpy.arange</code> created by <code>len</code> of <code>DataFrame</code>:</p>
<pre><code>df1 = df.groupby(np.ara... | python|pandas | 2 |
18,114 | 11,124,578 | Automatically import modules when entering the python or ipython interpreter | <p>I find myself typing <code>import numpy as np</code> almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?</p> | <p>For ipython, there are two ways to achieve this. Both involve ipython's configuration directory which is located in <code>~/.ipython</code>.</p>
<ol>
<li>Create a custom ipython profile.</li>
<li>Or you can add a startup file to <code>~/.ipython/profile_default/startup/</code></li>
</ol>
<p>For simplicity, I'd use... | python|numpy|ipython | 88 |
18,115 | 59,458,312 | How to parse the value to csv with column name | <p>I would like to update specific columns in a csv file. I want to update the first column in the function <code>func1</code> and the second column in function <code>func2</code>:</p>
<pre><code>def func1(x):
data = 'test1'
file = open("test.csv","a+")
file.write(data)
file.close()
return data
de... | <p>You can use the <code>pandas</code> package to update specific columns (If you don't have it, you can install it by running <code>pip install pandas</code> in your terminal): </p>
<pre><code>import pandas as pd
def func1(file):
column = 'col1'
data = 'new_test1'
file[column] = data
return d... | python|pandas | 5 |
18,116 | 59,424,429 | How to join two TIFF files populated using memory-mapped IO | <p>I'm trying to write a python function which will output a single TIFF file after combining multiple TIFF files. I have a folder with a large amount of TIFF files and I'm trying to join each of the TIFF files into a single file. I have to load the data as numpy array and should also be populating using memory-mapped ... | <p>Untested example, that should give you an idea:</p>
<pre><code>from pathlib import Path
import numpy as np
import tifffile
my_path = Path(r'path/to/tiffs')
output = Path('output.tiff')
tiffs = list(my_path.glob('*.tiff'))
x,y = (512,512) # either hardcode or read from first tiff
output = np.zeros((len(tiffs), x... | python|numpy|tiff|numpy-ndarray|memory-mapped-files | 0 |
18,117 | 45,027,829 | Keeping the dimensionality of image data stack in rgb2gray transformation | <p>I have 4D RGB image_data[image, height, width, channel], in my case the dimensions are (x, 32, 32, 3) and I would like to convert these images to grayscale so that I have still 4D so that my dimensions are (x, 32, 32, 1).</p>
<p>I found a very simple rgb2gray transformation:</p>
<pre><code>def rgb2gray(rgb):
r... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code></a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow noreferrer"><code>np.tensordot</code></a> or <a href="https://docs.scipy.org... | python|arrays|numpy|dimension | 1 |
18,118 | 45,256,703 | Pandas Dataframe With Conditional Rules | <p>I have the following data frame</p>
<pre><code>import pandas as pd
df= pd.DataFrame({'Name':['Tam','John','Tom','Mark','Tim'],'Surname':['Jones','James','James','Perez','Desouza'],'ID':['-','-','-','-','-'],'ID1':['-','-','-','-','-']})
df.loc[df.Name.str.startswith('T'),'ID']="Rule 1"
df.loc[df.Surname.str.starts... | <p>I think you can chain new condition with <code>&</code> (bitwise and), dont forget for <code>()</code>:</p>
<pre><code>df.loc[df.Name.str.startswith('T'),'ID']="Rule 1"
df.loc[df.Surname.str.startswith('J') & (df.ID != '-'),'ID1']="Rule 2"
print (df)
ID ID1 Name Surname
0 Rule 1 Rule 2 Tam ... | python|pandas|dataframe | 1 |
18,119 | 45,021,268 | Strange behavior of numpy.round | <p>Python's <code>round()</code> seems to always round up when faced with x.5 numbers:</p>
<pre><code>print round(1.5),round(2.5),round(3.5),round(4.5)
>>> 2.0 3.0 4.0 5.0
</code></pre>
<p>But <code>numpy.round()</code> seems to be inconsistent: </p>
<pre><code>import numpy as np
print np.round(1.5),np.roun... | <p>numpy rounds to the nearest even value:</p>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html#numpy.around" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html#numpy.around</a></p>
<blockquote>
<p>For values exactly halfway between rou... | python|python-2.7|numpy|rounding | 6 |
18,120 | 57,288,519 | Time complexity between appending to a Dict vs a Dataframe | <p>My program currently creates a bunch of Dataframes with a specific structure. The total number of DataFrames is, for now, 88 (with up to 10k rows) ; however, this is just the testing phase with a small amount of data. </p>
<p>This number might increase to several hundreds of Dfs, with up to few 100k rows.</p>
<p>I... | <p><strong>Approach2 is absolutely faster.</strong> Pandas is quite a heavy lib I think. Maybe you should consider using <code>MySQL</code> to insert data into the database rather than <code>pandas</code> if the data is large and consumes much memory. In MySQL, you could save the data in the database rather than save t... | python|pandas|time-complexity | 2 |
18,121 | 57,157,290 | Is there a way to change the margins "All" column location for a pandas pivot table? | <p>I was not able to find a proper solution so decided to ask here. I just wanted to change the "All" column and put it at the start of the "values" column (Before CPU). Is there a way to do this?</p>
<p>Reproducible code:</p>
<pre><code>df = pd.DataFrame({'Rep': ['Wendy Yule','Wendy Yule','Wendy Yule','Wendy Yule','... | <p>You can add a <code>margin_name</code> argument while creating pivot table to do this. For example</p>
<pre class="lang-py prettyprint-override"><code>table = pd.pivot_table(df, values=['A'], index=['B'],
columns=['C'], aggfunc=sum, margins=True, margins_name='Grand Total')
</code></pre>
<p>The m... | python|pandas | 1 |
18,122 | 57,278,214 | Does TensorFlow's `sample_from_datasets` still sample from a Dataset when getting a `DirectedInterleave selected an exhausted input` warning? | <p>When using TensorFlow's <a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/sample_from_datasets" rel="noreferrer"><code>tf.data.experimental.sample_from_datasets</code></a> to equally sample from two very unbalanced Datasets, I end up getting a <code>DirectedInterleave selected an exhausted inp... | <p>The smaller dataset does NOT repeat - once it is exhausted the remainder will just come from the larger dataset that still has examples.</p>
<p>You can verify this behaviour by doing something like this:</p>
<pre class="lang-py prettyprint-override"><code>def data1():
for i in range(5):
yield "data1-{}".form... | python|tensorflow|tensorflow-datasets|tensorflow2.0 | 6 |
18,123 | 57,021,397 | TensorFlow JS - Load A Model Generated Using Python | <p>I followed the steps in <a href="https://www.tensorflow.org/js/tutorials/conversion/import_keras" rel="nofollow noreferrer">this tutorial</a> to convert a trained <code>TensorFlow</code> model generated using <code>Python</code>. Now I want to use that to re-create the model in <code>TensorFlow JS</code>. I passed t... | <p>1 - You're using the wrong function <code>modelFromJSON</code> to import the model. According to the tutorial, here is the function to use: <code>loadLayersModel</code>.</p>
<p>2- </p>
<blockquote>
<p>The first layer in a Sequential model must get an <code>inputShape</code> or <code>batchInputShape</code> argume... | javascript|python|json|tensorflow|tensorflow.js | 1 |
18,124 | 56,917,581 | What means the Error: "float() argument must be a string or a number, not 'builtin_function_or_method'" | <p>I have a Variable, in the Form:</p>
<pre><code>X = array([<built-in function array>, 66.0, 98.0, ..., 244.0, 254.0, 255.0], dtype=object)
</code></pre>
<p>If I want to fit them in a SVC classifier, the Error:</p>
<pre><code>float() argument must be a string or a number, not 'builtin_function_or_method'... | <blockquote>
<p>What means the Error: “float() argument must be a string or a number, not 'builtin_function_or_method'”</p>
</blockquote>
<p>The error means you are trying to convert an array to a floating point number. You have data that isn't a number and doesn't look like a number, and are trying to convert it to... | python|numpy|keras | 0 |
18,125 | 22,990,470 | Python openCV: I get an unchanged image when I use cvtColor | <p>I have an image as a numpy array with the shape (480,640) in grayscale.</p>
<p>I want to lay a colored mask over the image and need to get the image in the same shape to do it, which is (480,640,3).</p>
<p>Here is what I tried:</p>
<pre><code>print str(img.shape) +' '+ str(type(img)) +' '+ str(img.dtype)
# prints... | <p>The main thing is that you need to assign the converted image to a new name.</p>
<p>I'm not sure if using the c++ format of providing the target image as an argument works. I would just do it the usual python (cv2) way of assigning to a name (same name is fine).</p>
<p>Also, you don't need to assign the number of ch... | python|opencv|numpy | 1 |
18,126 | 35,580,136 | pandas map dataframes columns | <p>I have two dataframes, the first as pairwise connections among values:</p>
<pre><code>df1 = pd.DataFrame({'n1': [5,1,1,3,4,3,2,2],
'n2': [1,6,3,4,3,2,3,7]})
n1 n2
0 5 1
1 1 6
2 1 3
3 3 4
4 4 3
5 3 2
6 2 3
7 2 7
</code></pre>
<p>and the second as a representa... | <p>drop the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">duplicates</a> in <code>df2</code> and you can then call <code>map</code>:</p>
<pre><code>In [58]:
df2 = df2.drop_duplicates()
df2
Out[58]:
g n
0 a 1
1 a 5
2 a 6
3 b 2
4 b 3
5... | python|pandas | 1 |
18,127 | 51,085,853 | Keras model.predict error for categorical labels | <p>I am trying to see prediction results and print them with model.predict function but I am having an error:</p>
<pre><code>ValueError: Error when checking model : the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following ... | <p>The model expects two arrays and you are passing one single numpy array.</p>
<pre><code> prediction_result = model.predict([test_text.values[i].reshape(-1,100), test_posts.values[i].reshape(-1,1)])
</code></pre>
<p>remove calling the numpy.array method and you the Error will go away.</p>
<p>Update:<br>
There is n... | python|numpy|keras|label|prediction | 0 |
18,128 | 51,024,561 | Pandas Pivot table with multi index | <p>Input Dataframe: </p>
<p><a href="https://i.stack.imgur.com/rEbzj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rEbzj.png" alt="enter image description here"></a></p>
<p>I am trying to pivot my df by sorting Time Column in column wise<br>
my output df:<br>
<a href="https://i.stack.imgur.co... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow noreferrer"><code>unique</code></a> values of column <co... | pandas | 1 |
18,129 | 50,779,346 | Iterate over a numpy Matrix rows | <p>First, I tried to find an answer to my question ( which I think is pretty basic) searching in google and in the site, but nothing came up.</p>
<p>I'm trying to get the rows from a numpy matrix, but I can't. For example if I use this: </p>
<pre><code>result = numpy.matrix([[11, 12, 13],
[21, ... | <p>The problem is you are using <code>np.matrix</code>. Use <code>np.array</code> instead and simply iterate without indexing:</p>
<pre><code>result = np.array([[11, 12, 13],
[21, 22, 23],
[31, 32, 33]])
for p in result:
print(p)
[11 12 13]
[21 22 23]
[31 32 33]
</code></pre... | python|arrays|python-3.x|numpy|matrix | 14 |
18,130 | 51,023,113 | How to add two numpy arrays together? | <p>Having a little trouble on something that seems pretty simple. I want to join these two arrays to meet output:</p>
<pre><code>array([['category_1', '4500', '5000'], ['category_2', '3200', '5000'], ['category_3', '3000', '5000'], ['category_4', '2000', '5000']], dtype='<U8')
</code></pre>
<p>I have some data</p>... | <pre><code>data = np.array([['category_1', '4500', '5000'], ['category_2', '3200', '5000']])
other_data = np.array([['category_3', '3000', '5000'], ['category_4', '2000', '5000']])
np.concatenate((data, other_data), axis=0)
</code></pre> | python|arrays|numpy|multidimensional-array|concat | 1 |
18,131 | 20,413,264 | join two CSVs by IDs | <p>I have two CSV files like:</p>
<p>first.csv:</p>
<pre><code>1,A B C
2,A D
3,T Q
</code></pre>
<p>second.csv:</p>
<pre><code>1,
2,P A
3,
4,A O
</code></pre>
<p>Is is possible to join these two CSVs to make a CSV in similar format using pandas?</p>
<p>The output CSV should be like:</p>
<pre><code>1,A B C
2,A D ... | <p>Try:</p>
<pre><code>import pandas as pd
first = pd.DataFrame('first.csv')
second = pd.DataFrame('second.csv')
third = pd.merge(first,second, how='inner')
</code></pre>
<p><a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> is king for loading csv data in and manipulating it later. </p> | python|csv|pandas | 1 |
18,132 | 20,402,109 | calculating percentage error by comparing two arrays | <p>I have some data in two numpy arrays.</p>
<pre><code>a = [1, 2, 3, 4, 5, 6, 7]
b = [1, 2, 3, 5, 5, 6, 7]
</code></pre>
<p>I say array <code>a</code> is my calculated result and array <code>b</code> are the true result values. I want to calculate the error percentage in my result.
Now I can loop through the two arr... | <p>First calculate the positions where <code>a</code> and <code>b</code> differ using <code>a != b</code>, then find the mean of those values:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7])
>>> b = np.array([1, 2, 3, 5, 5, 6, 7])
>>> error = np.mean( a... | python|arrays|numpy | 25 |
18,133 | 33,353,633 | How to avoiding skipped months in Python pivot table when all entires in table are 0 | <p>I have a pivot table which I sort index by year then month from a pandas dataframe column with timestamp objects. This works great for what I need except for one detail. If there are no entries for a particular month/year that particular row in the pivot table is not populated. </p>
<p>I need it to show as 0 for al... | <p>Is this meet your expectation? Use <code>.fillna</code> if you want padding.</p>
<pre><code>pv = pd.pivot_table(data2,index=pd.Grouper(key='DateBuild', freq='M'),
values='Quantity',
columns=pd.Grouper(key='DateOpen', freq='M'))
pv.reindex(index=pd.date_range(pv.index.min(), p... | python|python-2.7|sorting|pandas|pivot-table | 2 |
18,134 | 66,572,404 | python chunksize difference | <p>I have a question regarding reading large csv file with chunksize.<br />
My question is: what is the difference between these two below?</p>
<pre><code>import pandas as pd
chunks = pd.read_csv("large_data.csv", chunksize=1000000)
chunk_list = []
# Each chunk is in dataframe format
for data_chunk in chun... | <p>When you have doubts regarding efficiency, as @Patrick Artner suggested, just test it :</p>
<pre class="lang-py prettyprint-override"><code>start = time.perf_counter()
final = pd.read_csv("large_data.csv")
print(time.perf_counter() - start)
</code></pre>
<pre class="lang-py prettyprint-override"><code>star... | python|pandas|chunks | 1 |
18,135 | 66,352,574 | Error when trying to run code with a higher integer value (n > 20) | <p>I'm a beginner programmer that's trying to write a program that requests an integer n within some defined limits and then computes certain mathematical functions and displays them in a formatted table.</p>
<p>At the moment I have the limits set so that (0 <= n <= 10000) but this might be the issue for now.</p>... | <p>Factorial gets very big, very fast. After 20 (20! ~= 2e18), <code>numpy</code> switches to a different integer formulation that doesn't have a <code>log</code> method.</p>
<p>You can either use higher precision, or you can take advantage of the fact that multiplying <code>log</code> is the same as adding outside of... | python|numpy|for-loop | 1 |
18,136 | 57,626,307 | How to groupby and then write the result to csv (and more) | <p>My data looks like this:</p>
<pre><code>BOL,StopSequence,TimeArrived
5076223,1,12:52:56 PM
5076223,1,12:52:56 PM
5076223,2,9:50:58 AM
5076223,3,11:00:32 AM
5076223,4,11:00:52 AM
5077138,1,5:00:45 AM
5077138,2,1:43:13 PM
5077138,3,12:29:39 PM
5077138,4,1:02:31 PM
5077138,4,1:02:31 PM
5077138,5,1:02:50 PM
5077138,5,1... | <p>Here is problem output of <code>.groupby('BOL')</code> is <code>'DataFrameGroupBy' object</code>, so necessary add functions - here for new column <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></... | python|python-3.x|pandas|pandas-groupby | 1 |
18,137 | 57,451,767 | Tensorflow: how to concat tensor with specific index | <p>I have tensors like these:</p>
<pre><code>tensor_a = [[[[255,255,255]]], [[[100,100,100]]]]
tensor_b = [[[[0.1,0.2]]], [[[0.3,0.4]]]]
tensor_c = [[[[1]]], [[[2]]]]
</code></pre>
<p>Today I try to concat these tensors above to tensor_d like:</p>
<pre><code>tensor_d = [[[[255,255,255,0.1,1]]], [[[100,100,100, 0.3, ... | <p>You can use tensor manipulation such as <code>tf.split</code> and <code>tf.concat</code>. </p>
<pre><code>import tensorflow as tf
# tensors
tensor_a = [[[[255, 255, 255]]], [[[100, 100, 100]]]]
tensor_b = [[[[0.1, 0.2]]], [[[0.3, 0.4]]]]
tensor_c = [[[[1]]], [[[2]]]]
# casting becuase date type should match in t... | python|tensorflow|deep-learning | 1 |
18,138 | 57,573,453 | How can I find the actual implementation of np.partition()? | <p>To understand <a href="https://stackoverflow.com/q/57564644/11566345">how <code>numpy.partition()</code> works</a> I am trying to read the <a href="https://github.com/numpy/numpy/blob/e1c42bb77fa727f0b214f3433207e20261acb57f/numpy/core/fromnumeric.py#L659" rel="nofollow noreferrer">source code</a>.</p>
<pre><code>i... | <p>As you pointed out, <code>np.partition</code> uses the method <code>partition</code> of <code>ndarray</code>, which itself is written in C, under the name <code>array_partition</code>. <a href="https://github.com/numpy/numpy/blob/deea4983aedfa96905bbaee64e3d1de84144303f/numpy/core/src/multiarray/methods.c#L1289" re... | python|numpy | 5 |
18,139 | 57,328,545 | Efficient Sampling | <p>I'm a beginner and need some guidance on what probably is a very basic problem, yet unsolvable to me :</p>
<p>I'm working on a Kaggle dataset with over 10M rows and would like to sample it to go into proper EDA. I've seen a couple people putting simply an <em>nrows</em> argument to the <em>.read_csv</em> method, bu... | <p>If this is supervised learning (i.e you have data label ) you can use </p>
<pre><code>train_X, test_X, train_Y, test_Y = train_test_split(data, label, test_size = 0.2, random_state = 138,shuffle=True,stratify=label)
</code></pre>
<p>stratify will allow you to keep same proportion of each class in the final data ... | python|pandas|scikit-learn|sampling|eda | 0 |
18,140 | 57,471,655 | Problem in creating pandas data frame in Python3 | <p>I am new to Python. I got trouble in creating a pandas data frame.</p>
<pre><code>dataDict = {}
dataDict['grant_id'] = grant_ids
dataDict['patent_title'] = patent_title
dataDict['kind'] = kinds
df=pd.DataFrame(dataDict)
</code></pre>
<p>The code above works in python2, but when I change to python3, I got error me... | <p>The issue is with Python 2 and 3 <code>map</code> function returns differences. In Python 2, the <code>map</code> returns a list while in 3, it returns a generator. Generators have no length(as they yield result on evaluating, namely do not store all values on memory). You can turn generator to list with <code>list(... | python|pandas | 1 |
18,141 | 57,492,007 | Copy and convert all values in pandas dataframe | <p>In a dataframe, I have a column "UnixTime" and want to convert it to a new column containing the UTC time.</p>
<pre><code>import pandas as pd
from datetime import datetime
df = pd.DataFrame([1565691196, 1565691297, 1565691398], columns = ["UnixTime"])
unix_list = df["UnixTime"].tolist()
utc_list = []
for i in un... | <p>Could you try this:</p>
<pre><code>df["UTC"] = pd.to_datetime(df['UnixTime'], unit='s')
</code></pre> | python|pandas | 4 |
18,142 | 57,725,608 | PyTorch: RuntimeError: Function MulBackward0 returned an invalid gradient at index 0 - expected type torch.cuda.FloatTensor but got torch.FloatTensor | <p>I don't understand what this error is telling me. In <a href="https://github.com/NVIDIA/flownet2-pytorch/issues/139" rel="nofollow noreferrer">a different post</a> the same problem was also addressed but there was no useful solution for this.</p>
<pre><code>Traceback (most recent call last):
File "train.py", line... | <p>try changing
<code>loss = criterion(predicted, target.type(torch.FloatTensor).to(device))</code>
to
<code>loss = criterion(predicted, target.to(device).float())</code></p> | python|pytorch|backpropagation | 0 |
18,143 | 24,032,332 | canopy matplotlib windows 64 bit | <p>I've tried to run matplotlib in canopy on windows 7 64bit. After updating the packages in canopy it does not work the matplotbib. My numpy version installed showed in package manager is 1.8.0-2. Help needed with this problem. matplotlib version installed 1.3.1.-3
I've run an example code of an animation from website... | <p>Please update to Canopy 1.4.0, then quit Canopy, delete
<code>C:Users\HOT-GAZ\AppData\Local\Enthought\Canopy\User</code>
and restart Canopy.</p> | python|numpy|matplotlib|canopy | 0 |
18,144 | 43,923,944 | AttributeError - But Dataframe has the attribute | <p>I have the following DataFrame and it won't recognize the column with the following error message: <code>AttributeError: 'DataFrame' object has no attribute 'B_N'</code></p>
<p>df1</p>
<pre><code>Type B_N
A AT74
A BQT1
C 0
</code></pre>
<p>The line of code that errors is:</p>
<pre><code>df1.B_N[... | <p>The key you think is 'B_N' may not be 'B_N'. There might be spaces around it.</p>
<p>Can you do a df.columns and check if it's exactly 'B_N'?</p> | python|python-3.x|pandas|numpy|dataframe | 1 |
18,145 | 43,839,154 | Backfill values in Pandas series when value matches another column | <p>I have a DataFrame like this:</p>
<pre><code>import numpy as np
raw_data = {'surface': [np.nan, np.nan, 'round', 'square'],
'city': ['San Francisco', 'Miami', 'San Francisco', 'Miami']}
df = pd.DataFrame(raw_data, columns = ['surface', 'city'])
</code></pre>
<p>This looks like this:</p>
<pre><code> ... | <p>You can use <code>groupby.bfill</code>; group data frame by <em>city</em> column and then use <code>bfill</code>:</p>
<pre><code>df.groupby('city').bfill()
# surface city
#0 round San Francisco
#1 square Miami
#2 round San Francisco
#3 square Miami
</code></pre> | python|pandas | 1 |
18,146 | 43,918,578 | Extend a matrix by interpolating zeros | <p>I am trying to implement a python code to extend a matrix in such a way as given below:</p>
<p>Given Matrix:</p>
<pre><code>1 2
3 4
</code></pre>
<p>Now I want to convert it to the following:</p>
<pre><code>1 0 0 2 0 0
0 0 0 0 0 0
0 0 0 0 0 0
3 0 0 4 0 0
0 0 0 0 0 0
0 0 0 0 0 0
</code></pre>
<p>I am trying the ... | <p>You can use the <code>step</code> part of the slice to achieve this, if you preallocate yourself a result</p>
<pre><code>repeat = 3
result = np.zeros((arr.shape[0]*repeat, arr.shape[1]*repeat))
result[::repeat,::repeat] = arr
</code></pre> | python|numpy | 3 |
18,147 | 43,617,400 | Python update multiple columns with where condition. Error cannot be broadcast together | <p>I need to update several columns in DB based on conditions. I am using numpy.where and would prefer to do not change that.</p>
<p>Here is what I could do:</p>
<pre><code>DB['Start'] = np.where(((DB['Start Date']<=time_delta) | (DB['Start Date'].isnull()) | (DB['Start Date'] == "")),DB['Start'],DB['Start Date'])... | <p>not sure if this is acceptable to you, since you mentioned computational efficiency and this takes the same computer time as listing the update steps manually. but in case it's helpful...</p>
<pre><code>columns_to_filter = ['Start', 'End']
for c in columns_to_filter:
DB[c] = np.where(((DB['Start Date']<=tim... | python|pandas|numpy|where | 0 |
18,148 | 43,482,426 | How can I create a function that combines list/array rows/columns/elements in arbitrary sized array/list? | <p>Afternoon. I'm currently trying to create a function(s) that, when given an array or list and a specified selection of columns/rows/elements, the specified columns/rows/etc are removed and concatenated into a array/list-much in this fashion (but for arbitrary sized objects that may or may not be pretty big)</p>
<... | <p>How is this different from advanced indexing</p>
<pre><code>In [324]: A = np.arange(12).reshape(2,6)
In [325]: A
Out[325]:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
In [326]: A[:,[1,2,4]]
Out[326]:
array([[ 1, 2, 4],
[ 7, 8, 10]])
</code></pre>
<p>To select both rows and column... | arrays|list|python-3.x|numpy|iteration | 1 |
18,149 | 73,035,156 | Exporting distance matrix pairs into columns in .xlsx/.csv in python | <p>Probably a pretty basic export but I didn't manage to extract the values for every combination in the distance matrix.</p>
<p>The code to create the distance matrix is very basic and looks as follows:</p>
<pre><code>dist = DistanceMetric.get_metric('haversine')
output = pd.DataFrame(dist.pairwise(df[['latitude', 'lo... | <p>You should start by unstacking your dataframe: <code>result = df.unstack()</code>.</p>
<p>Now you have a DataFrame with this shape :</p>
<pre><code>1 1 0.0000
2 1.4072
3 0.5405
2 1 1.4072
2 0.0000
3 1.8499
...
</code></pre>
<p>Now, if you want to save it in a csv file, just call <code... | python|pandas|distance-matrix | 0 |
18,150 | 73,157,407 | Why is repeated numpy array access faster using a single-element view? | <p>I saw in <a href="https://stackoverflow.com/a/23654229/2808520">another SO thread</a> that it's possible to create a single-element view of an array <code>arr</code> with <code>arr[index:index+1]</code>. This is useful to me since I need to set several values of a (possibly large ~100k entries) array repeatedly. But... | <p>Since <code>num_indices</code> have not significant impact on the observed performance, we can simplify the problem by discarding this parameter (ie. set to 1). Since only large <code>accesses</code> matters, we can also simplify the problem by considering only a large value like 10946 for example. The use of <code>... | python|python-3.x|numpy|numpy-ndarray | 2 |
18,151 | 70,458,029 | Python: Splitting a Column into concatenated rows based on specific Values | <p>I am sure someone has asked a question like this before but my current attempts to search have not yielded a solution.</p>
<p>I have a column of text values, for example:</p>
<pre><code>import pandas as pd
df2 = pd.DataFrame({'text':['a','bb','cc','4','m','...']})
print(df2)
text
0 a
1 bb
2 cc
3 4
4 ... | <p>You can convert columns to numeric and test non missing values, so get <code>True</code>s for numeric rows, then filter only non numeric in inverted mask by <code>~</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</c... | python|python-3.x|pandas|dataframe | 3 |
18,152 | 70,593,981 | Create a list of N random numbers with max and min value and total sum | <p>I'm trying to create a list (call it: weights) of N random numbers between 0.005 and 0.045 with a total sum equal to 1. N can be any integer between 22 and 200. So the following restrictions:</p>
<ul>
<li>Number of numbers in weights = N</li>
<li>For every n in weights: 0.005 < n < 0.045</li>
<li>sum of all n'... | <p>This might do the trick. The strategy is to uniformly partition the available space then iterate over the partitions and for each iteration take a random bit from the current one and add it to a second one.</p>
<p>You might find that you need to use the <code>decimal</code> package to get a little more precision. Yo... | python|list|numpy|random|sum | 1 |
18,153 | 42,829,463 | What's the fastest way of reading data from a text file and allocating it to a data frame? | <p>I want to create a multi-index <code>DataFrame</code> by reading a textfile. Is it faster to create the multi-index and then allocate data to it from the text file using <code>df.loc[[],[]]</code>, or concatenate rows to the <code>DataFrame</code> and set the index of the <code>DataFrame</code> at the end? Or, is it... | <p>Element by element lookups in pandas is an expensive operation, so is aligning by index. I would read everything into arrays, create a DataFrame of values, and then set the hierarchical index directly. Usually much faster if you can avoid append or lookups.</p>
<p>Here is a sample result assuming you have a dataset... | python|performance|pandas|dataframe | 8 |
18,154 | 27,276,816 | Pandas read_csv not recognizing ISO8601 as datetime dtype | <p>Currently I am using pandas to read a csv file into a <code>DataFrame</code>, using the first column as the index. The first column is in ISO 8601 format, so according to the documentation for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html" rel="noreferrer">read_csv</a... | <p>I just added column name for first column in csv file.</p>
<pre><code> Date U V Z Ubar Udir
0 2014-11-01 00:00:00 0.73 -0.81 0.46 1.0904 317.97
1 2014-11-01 01:00:00 1.26 -1.50 0.32 1.9590 319.97
2 2014-11-01 02:00:00 1.50 -1.80 0.13 2.3431 320.19
3 2014-11-01 03:00... | python|datetime|pandas | 4 |
18,155 | 25,344,799 | Apply function to pandas dataframe that returns multiple rows | <p>I would like to apply a function to a pandas DataFrame that splits some of the rows into two. So for example, I may have this as input:</p>
<pre><code>df = pd.DataFrame([{'one': 3, 'two': 'a'}, {'one': 5, 'two': 'b,c'}], index=['i1', 'i2'])
one two
i1 3 a
i2 5 b,c
</code></pre>
<p>And I want somethi... | <p>You have a messed up database (comma separated string where you should have separate columns). We first fix this: </p>
<pre><code>df2 = pd.concat([df['one'], pd.DataFrame(df.two.str.split(',').tolist(), index=df.index)], axis=1)
</code></pre>
<p>Which gives us something more neat as </p>
<pre><code>In[126]: df2
O... | python|pandas|dataframe | 2 |
18,156 | 30,610,061 | Python: Eliminating rows in Pandas DataFrame based on boolean condition | <p>Suppose I have a DataFrame in Pandas like</p>
<pre><code> c1 c2
0 'ab' 1
1 'ac' 0
2 'bd' 0
3 'fa' 1
4 'de' 0
</code></pre>
<p>and I want it to show all rows such that c1 doesn't contain 'a'. My desired output would be:</p>
<pre><code> c1 c2
2 'bd' 0
4 'de' 0
</code></pre>
<p>My first attemp... | <p>Use <code>~</code> to flip your Series of booleans:</p>
<pre><code>df.loc[~df['c1'].str.contains('a')]
</code></pre> | python|pandas|boolean|dataframe | 3 |
18,157 | 30,449,421 | How can I make my plot smoother in Python? | <p>I have a function called calculate_cost which calculates the performance of supplier for different S_range (stocking level). The function works but the plots are not smooth, is there a way to smooth it in Python?</p>
<pre><code>import numpy
import scipy.stats
import scipy.integrate
import scipy.misc
import matplotl... | <p>One solution would be to use the scipy.iterp1D function with a 'cubic' type :</p>
<pre><code>from scipy import interpolate
....
s_range = numpy.arange(0,21,1)
for graph in graphs:
cost = []
for s in s_range:
cost.append(calculate_cost(s, graph.h, graph.d, graph.r, graph.k, graph.alphaR))
f = ... | python|numpy|plot|scipy|smoothing | 2 |
18,158 | 30,555,816 | Get values from a DataFrame in pandas | <p>I have a DataFrame with only 1 row in pandas.</p>
<p>The row has a index/name as a date.</p>
<p>I want to retrieve this date and the value in the 4th column.</p>
<p>I can get the value of the 4th column in this single row by using</p>
<pre><code>first_row = data.iloc[0]
value = row[3]
</code></pre>
<p>but how c... | <p>You have 2 choices, if you are performing integer indexing into the df, then using the same integer to index into the index will return that value.</p>
<p>If you have selected a specific row then you can access the index value by using the <code>.name</code> attribute.</p>
<p>Example:</p>
<pre><code>In [3]:
impor... | python|pandas | 2 |
18,159 | 30,513,632 | Calculations within pandas aggregate | <p>I am trying to perform a calculation within <code>pandas</code> aggregations. I want the calculations to be included in the aggregations. The code on what I am attempting is below. I am also using the pandas package for the df.</p>
<pre><code>data = data.groupby(['type', 'name']).agg({'values': [np.min, np.max, 100... | <p>Passing df.agg a dictionary is used to specify the name of the output columns, here you're essentially writing an aggregation function which is attempting to use three formulas for one named column, and that column is already in your dataframe so its going to fail.</p>
<p>What you should be doing should look more l... | python|numpy|pandas | 2 |
18,160 | 39,319,556 | DataFrame Groupby while maintaining original DataFrame | <p>I have a DataFrame that has 9 columns which are encoded values for Day of the week(1-7), Week of the Year(1-52), Month of the Year (1-12), Time bin (every 3 hours), Salary Day(0,1) and Holiday(0,1) and Amount(real number). The time is placed in a time bin e.g. 15:00 is placed in 6th time bin and 7:34 is placed in t... | <p>You can use <code>transform</code> to return a column of the same size of the original data frame, from <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>The transform method returns an object that is indexed the same (same
size) as the one being... | python|pandas|dataframe|group-by | 2 |
18,161 | 39,002,125 | Matplotlib - Legend of a specific contour at different instants | <p>I m trying to plot a figure with a specific contour line (level = 320) at different times that is why a loop is used.
I would like plot a legend with labels to specify the time during the loop as here :</p>
<p><a href="https://i.stack.imgur.com/cfSMK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c... | <p>I used: <a href="http://matplotlib.org/examples/pylab_examples/contour_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/contour_demo.html</a></p>
<pre><code>cmap = plt.cm.hot
lines = []
labels = []
i = 0
instant = 0
for instant in range(0,Sigma_stockMAX.shape[2]):
name = 'test'
VM_M... | python|numpy|matplotlib|contour | 1 |
18,162 | 39,156,545 | interactive conditional histogram bucket slicing data visualization | <p>I have a df that looks like: </p>
<pre><code>df.head()
Out[1]:
A B C
city0 40 12 73
city1 65 56 10
city2 77 58 71
city3 89 53 49
city4 33 98 90
</code></pre>
<p>An example df can be created by the following code:</p>
<pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,... | <p>In order to get the interaction effect you're looking for, you must bin all the columns you care about, together.</p>
<p>The cleanest way I can think of doing this is to <code>stack</code> into a single <code>series</code> then use <code>pd.cut</code></p>
<p>Considering your sample <code>df</code></p>
<p><a href=... | python|pandas|data-visualization|seaborn|bokeh | 6 |
18,163 | 39,333,881 | Python: Pandas: making a dictionary from dataframe | <p>I am trying to convert a dataframe to dictionary:</p>
<pre><code>xtest_cat = xtest_cat.T.to_dict().values()
</code></pre>
<p>but it gives a warning :</p>
<blockquote>
<p>Warning: DataFrame columns are not unique, some columns will be omitted python</p>
</blockquote>
<p>I checked the columns names of the datafr... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a> for create <code>unique</code> index:</p>
<pre><code>xtest_cat = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C'... | python|pandas|dictionary|dataframe|multiple-columns | 7 |
18,164 | 12,926,898 | numpy unique without sort | <p>How can I use numpy unique without sorting the result but just in the order they appear in the sequence? Something like this?</p>
<p><code>a = [4,2,1,3,1,2,3,4]</code></p>
<p><code>np.unique(a) = [4,2,1,3]</code></p>
<p>rather than</p>
<p><code>np.unique(a) = [1,2,3,4]</code></p>
<p>Use naive solution should be... | <p>You can do this with the <code>return_index</code> parameter:</p>
<pre>
>>> import numpy as np
>>> a = [4,2,1,3,1,2,3,4]
>>> np.unique(a)
array([1, 2, 3, 4])
>>> indexes = np.unique(a, return_index=True)[1]
>>> [a[index] for index in sorted(indexes)]
[4, 2, 1, 3]
</pre> | python|numpy | 65 |
18,165 | 29,287,847 | String wildcard in pandas on replace function | <p>I'm sure this problem has an easy answer but I'm having trouble figuring out the correct string to use. I basically want to replace any email address in a data frame with the new domain. For a specific column, replace the substring '@*' where * is any set of characters with '@newcompany.com'. I want to keep whatever... | <p>You can use the vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#string-handling" rel="nofollow"><code>str</code></a> method to split on <code>'@'</code> character and then join the left side with the new domain name:</p>
<pre><code>In [42]:
df = pd.DataFrame({'email':['asdsad@old.com', 'as... | python|pandas | 4 |
18,166 | 29,092,770 | Machine Learning clustering with n-dimensional data in Python | <p>I'm trying to figure out a procedure to perform clustering on a set of data with 52 dimensions. This is purely for my own learning so I have a data set of known fields. The data is from <a href="http://www.retrosheet.org/gamelogs/" rel="nofollow">retrosheet.org Gamelogs</a> using the World Series data set. I'm attem... | <p>Scikit learn is the way to go for clustering in Python. See <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_digits.html#example-cluster-plot-kmeans-digits-py" rel="nofollow">http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_digits.html#example-cluster-plot-kmeans-digits-py</a... | python|numpy|machine-learning | 1 |
18,167 | 29,311,659 | How can Pandas DataFrames appear identical but fail equals()? | <p>To confirm that I understand what Pandas <code>df.groupby()</code> and <code>df.reset_index()</code> do, I attempted to do a round-trip from a dataframe to a grouped version of the same data and back. After the round-trip the columns and rows had to be sorted again, because <code>groupby()</code> affects row order a... | <p>This feels like a bug to me, but could be simply that I'm misunderstanding something. The blocks are listed in a different order:</p>
<pre><code>>>> df1._data
BlockManager
Items: Index(['title', 'year', 'director'], dtype='object')
Axis 1: Int64Index([0, 1, 2, 3, 4], dtype='int64')
IntBlock: slice(1, 2, 1... | python|pandas | 6 |
18,168 | 28,949,249 | efficiently generate "shifted" gaussian kernel in python | <p>I have a (very large) number of data points, each consisting of an x and y coordinate and a sigma-uncertainty (sigma is the same in both x and y directions; all three variables are floats). For each data-point I want to generate a 2d array on a standard grid, with probabilities that the the actual value is in that l... | <p>A reasonably fast approach is to note that the Gaussian is separable, so you can calculate the 1D gaussian for <code>x</code> and <code>y</code> and then take the outer product:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x0, y0, sigma = 5.5, 4.2, 1.4
x, y = np.arange(9), np.arange(9)
gx = ... | python|numpy|scipy | 7 |
18,169 | 22,866,406 | How to remove efficiently all duplicates in dataframe or csv file in python? | <p>I have the table below contained in mytest.csv as below :</p>
<pre><code>timestamp val1 val2 user_id val3 val4 val5 val6
01/01/2011 1 100 3 5 100 3 5
01/02/2013 20 8 6 12 15 3
01/07/2012 19 57 10 9 6 6
01/11/2014 3100 49 ... | <p>If you want to drop duplicates based on specific columns, you can use the <code>subset</code> argument (older pandas versions: <code>cols</code>) in <code>drop_duplicates</code>:</p>
<pre><code>df_clean = df.drop_duplicates(subset=['timestamp', 'user_id'])
</code></pre> | python|pandas | 8 |
18,170 | 13,629,245 | Anomalous decimal places in python after list-to-numpy-to-list | <p>Executing the following code in a fresh Python 2.7.3 interpreter on my ubuntu linux machine gives the output shown after the code.</p>
<pre><code>import numpy as np
p = [1/3., 1/2., 23/25., 1]
q = np.array(p)
r = list(q)
print p; print q; print r
</code></pre>
<p>Output:</p>
<pre><code>[0.3333333333333333, 0.5, 0... | <p>They print differently because <code>p</code> is a list of <code>float</code> and <code>int</code>, whereas <code>r</code> is a list of <code>numpy.float64</code>:</p>
<pre><code>In [23]: map(type, p)
Out[23]: [float, float, float, int]
In [24]: map(type, r)
Out[24]: [numpy.float64, numpy.float64, numpy.float64, n... | python|numpy|floating-point|python-2.7 | 3 |
18,171 | 29,410,291 | Numpy Concatenate to empty array | <p>I am trying to concatenate a set of numpy arrays loaded from disk. All arrays have varying number of columns.</p>
<p>This is my code</p>
<pre><code>import numpy as np
FILE_LIST = ["matrix a", "matrix b"]
result=np.array([[0,0],[0,0]]) # I need to avoid this zero matrix
for fileName in FILE_LIST:
matrix = mat... | <p>I would recommend to first load all the data in an array and then apply numpys <code>hstack</code> in order to horizontally stack the arrays</p>
<pre><code>result = np.hstack([np.genfromtxt(fileName,delimiter=" ") for fileName in FILE_LIST])
</code></pre> | python|numpy | 2 |
18,172 | 29,445,052 | Operation by indexing only last axis | <p>I have an array of 3 dimensional vectors. The dimension of the array is arbitrary: it could be a single (N×3), double (M×N×3), triple (K×M×N×3) etc. I need to operate on two components of the vector while preserving the other dimensions. </p>
<p>For example, if I know it is three dimensionsional, I could do the fol... | <p>I found an even nicer way. This here works for me</p>
<pre><code>R = numpy.arctan2(A[...,1],A[...,0])
</code></pre> | python|numpy | 5 |
18,173 | 62,260,478 | tensorflow boosted tree classifier multi class | <p>In the current version of TF (2.2.0) there is an option
to do multi class classification (i.e., more than two classes, by changing
n_classes to the relevant number in the estimator params).
However, all previous examples that I saw, for example the formal one here:
<a href="https://www.tensorflow.org/tutorials/esti... | <p>Indeed when I've changed the TF code manually everything worked.
Then, I found out there is a bug report on the issue here:
<a href="https://github.com/tensorflow/tensorflow/issues/40063" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/40063</a></p> | python|tensorflow|boosting | 1 |
18,174 | 62,278,785 | given percentiles find distribution function python | <p>From <a href="https://stackoverflow.com/a/30460089/2202107">https://stackoverflow.com/a/30460089/2202107</a>, we can generate CDF of a normal distribution:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 100
Z = np.random.normal(size = N)
# method 1
H,X1 = np.histogram( Z, bins = 10, normed =... | <p>My first thought was <code>plt.plot(x,np.gradient(y))</code>, but gradient of y was all zero (data points are evenly spaced in y, but not in x) These kind of data is often met in percentile calculations. The key is to get the data evenly space in x and not in y, using interpolation:</p>
<pre><code>x=X2
y=F2
num_poi... | python|numpy|statistics | 0 |
18,175 | 62,166,396 | How to scale histogram y-axis in million in matplotlib | <p>I am plotting a histogram using <code>matplotlib</code> but my <code>y-axis</code> range is in the millions. How can I scale the y-axis so that instead of printing <code>5000000</code> it will print <code>5</code></p>
<p>Here is my code</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import panda... | <p>An elegant solution is to apply a <em>FuncFormatter</em> to format <em>y</em> labels.</p>
<p>Instead of your source data, I used the following <em>DataFrame</em>:</p>
<pre><code> Val
0 800000
1 2600000
2 6700000
3 1400000
4 1700000
5 1600000
</code></pre>
<p>and made a <strong>bar</strong> plot. "Ord... | python|numpy|matplotlib|histogram | 3 |
18,176 | 62,060,920 | How to detect straight lines in absolutely grayscale image, but not throught binary image? | <p>Rencently I'm trying to search for some ways to detect lines in CT scans.I found that all the Hough Transform family and some other algorithms are required to deal with contours born after edge detector.I found the contours are not what I want and a lot of short lines created by these 2 steps.I get perplexed by this... | <p>You have pretty consistent background so I would:</p>
<ol>
<li><p><strong>detect contours</strong></p>
<p>as any pixel with not background color that is neighboring background color.</p></li>
<li><p><strong>Segmentate/label the contour points to form ordered "polylines"</strong></p>
<ol>
<li>create ID buffer and ... | algorithm|numpy|opencv|computer-vision|detect | 0 |
18,177 | 62,078,878 | Stop pandas from grouping the data when reading csv | <p>I have a problem, when I read a csv file with pandas and assign it the header to be row 0 with the following:</p>
<pre><code>df = pd.read_csv(fileName, header = [0])
</code></pre>
<p>The first x columns on each row is being grouped and surrounded by parenthesis.
For example, if I have the following:</p>
<pre><cod... | <p>The firsr important discrepancy in your data sample is that it:</p>
<ul>
<li>contains only <strong>8</strong> column names,</li>
<li>but there are <strong>9</strong> data columns.</li>
</ul>
<p>Another disorder is that column names should be separated <strong>only</strong> with
commas, but your input contains also... | python|pandas|dataframe | 0 |
18,178 | 62,365,562 | Replacing for loops with function call inside with broadcasting/vectorized solution | <h2>Problem:</h2>
<p>When using broadcasting, rather than broadcasting scalars to match the arrays, the vectorized function is instead, for some reason, shrinking the arrays to scalars.</p>
<h2>MWE:</h2>
<p>Below is a MWE. It contains a double for loop. I am having trouble writing faster code that does not use the f... | <p>In your loops, <code>n0</code> and <code>n1</code> are elements of the nested <code>M_</code> lists, each 3 elements.</p>
<pre><code>In [78]: ThreeD(np.arange(3),np.arange(3),3)
Out[78]: 46.577468547527005
</code></pre>
<p><code>OneD</code> works ... | python-3.x|performance|numpy|vectorization|array-broadcasting | 1 |
18,179 | 62,395,588 | Sort 2D list in ascending order | <p>I've created random points and drawn a graphic with the plot and data. Then I'm saving this figure as a image. </p>
<p>How am I able to do the following?</p>
<ul>
<li><p>Sort this random point list , lower coordinates to upper coordinates. </p>
<p>Example list: <code>[[1,3], [1,2], [1,1]]</code></p>
<p>Target: ... | <p>Their is this function in python called sorted. It is an amazing thing you know, we all love it. It basically sorts any list you give it. It truly is a wonderfull tool and I use it a lot when coding. All you have to do is simple:</p>
<p><strong>Input</strong></p>
<pre><code>MyList = [13,7,4,4]
sortedList = sorted(My... | python|list|algorithm|numpy|matplotlib | 0 |
18,180 | 51,214,374 | How do I subtract an odd row value from even row vlaue? | <p>I have dataframe below.<br>
I want to even row value substract from odd row value.
and make new dataframe.<br></p>
<p>How can I do it?</p>
<pre><code>import pandas as pd
import numpy as np
raw_data = {'Time': [281.54385, 436.55295, 441.74910, 528.36445,
974.48405, 980.67895, 986.65435, 1026.... | <p>You can use NumPy indexing:</p>
<pre><code>res = pd.DataFrame(data.values[1::2] - data.values[::2], columns=['Time'])
print(res)
Time
0 155.00910
1 86.61535
2 6.19490
3 39.37050
</code></pre> | python|pandas|dataframe | 4 |
18,181 | 51,227,172 | Add key values pair inside list into pandas dataframe column | <p>I have listA as </p>
<pre><code>[{'index': 0,
'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
{'index': 1,
'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']},
{'index': 2,
'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}]
</cod... | <p>The thing is... you got a series. Do this instead:</p>
<pre><code>df = pd.Series(listA).to_frame('Column_new')
</code></pre>
<p>Full example:</p>
<pre><code>import pandas as pd
listA = [{'index': 0,
'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
{'index': 1,
'keywords': ['paki... | python|python-3.x|list|pandas|dictionary | 2 |
18,182 | 51,463,286 | Jetson TX2 tensorflow per_process_gpu_memory_fraction variable cannot set to 1.0 | <p>When I set per_process_gpu_memory from 0.5 to 1.0, there is not enough memory and it will crashed. </p>
<p>1) So, any ideas or suggestions to make it work? </p>
<p>2) Does convert tensorflow code to tensorRT will improve the performance (not for training, only for prediction)? </p> | <ol>
<li>Don't set memory usage to 1.0. Remember, the TX2 is a SoC and the CPU cores and GPU all share a common pool of memory. If the GPU is using 100% of that memory, there is no memory left for the CPU and if I recall correctly, the default OS is not setup for any swap space.</li>
<li>There are a few benchmarks that... | tensorflow|tensorrt|nvidia-jetson | 1 |
18,183 | 51,425,921 | python segregating lines based on the hostname from a composite logfile | <p>I'm looking forward a way to read a log file and read the hostname based on column 5 and hold the hostname with all iteration until new come, or say Just mark a double space when new name found but it needs to print the entire line.</p>
<p><strong>Just reading the file:</strong></p>
<pre><code>$ cat test.py
with o... | <p>You can get through itertools and operator function, i'm alos learner and i borrowed the code from one of my POST's ans, However i collected the Few detaild about both the function which may useful i hope.</p>
<p><strong>itertools.groupby(iterable, key=None or some func)</strong> takes a list of iterables and group... | python-3.x|pandas | 0 |
18,184 | 51,524,671 | Subsetting based on dates pandas dataframe | <p>I have a date column which after converting to datetime it looks like this:</p>
<pre><code> data['date']=pd.to_datetime(data[date])
2018-07-20 00:00:00
</code></pre>
<p>When I am trying to subset using this:</p>
<pre><code> beg = datetime.datetime.strptime('2018-07-20', '%Y-%m-%d')
end = datetime.datetime.strpt... | <p>One solution would be to use <a href="https://pandas.pydata.org/pandas-docs/stable/timeseries.html#partial-string-indexing" rel="nofollow noreferrer">partial string indexing</a> by moving that date into the dataframe index.</p>
<p>MCVE:</p>
<pre><code>df = pd.DataFrame(np.arange(100),index=pd.date_range('2010-01-0... | pandas|date|subset | 1 |
18,185 | 48,186,624 | Pandas Rolling window Spearman correlation | <p>I want to calculate the Spearman and/or Pearson Correlation between two columns of a DataFrame, using a rolling window.</p>
<p>I have tried <code>df['corr'] = df['col1'].rolling(P).corr(df['col2'])</code><br>
(P is the window size)</p>
<p>but i don't seem to be able to define the method. (Adding <code>method='spea... | <p><code>rolling.corr</code> does Pearson, so you can use it for that. For Spearman, use something like this:</p>
<pre><code>import pandas as pd
from numpy.lib.stride_tricks import as_strided
from numpy.lib import pad
import numpy as np
def rolling_spearman(seqa, seqb, window):
stridea = seqa.strides[0]
ssa = ... | python|pandas|correlation|rolling-computation | 11 |
18,186 | 48,007,472 | Numpy arrays from tuples of arrays for matrix based neural networks | <p>To implement learning in a neural network I'm using stochastic gradient descent in which the mini batches are represented via the following list comprehension:</p>
<pre><code>mini_batches = [training_data[j:j+mini_batch_size] for j in range(0,len(training_data),mini_batch_size)]
</code></pre>
<p>Inside the list co... | <p>Here's a solution, providing an array for the input data, as well as the target data: </p>
<pre><code>input_data_array = np.asarray([input_data.ravel() for input_data, target_data in mini_batch]).T
target_data_array = np.asarray([target_data.ravel() for input_data, target_data in mini_batch]).T
</code></pre>
<p>Th... | python|arrays|python-3.x|numpy|neural-network | 0 |
18,187 | 48,684,774 | How to delete words from a dataframe column that are present in dictionary in Pandas | <p>An extension to :
<a href="https://stackoverflow.com/questions/25346058/removing-list-of-words-from-a-string">Removing list of words from a string</a></p>
<p>I have following dataframe and I want to delete frequently occuring words from df.name column:</p>
<p>df :</p>
<pre><code>name
Bill Hayden
Rock Clinton
Bi... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace</code></a> by regex created by joined all values of column <code>word</code>, last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="n... | python-2.7|pandas|dataframe | 2 |
18,188 | 48,545,397 | ValueError in scipy t test_ind | <p>I have following csv file: </p>
<pre><code>SRA ID ERR169499 ERR169498 ERR169497
Label 1 0 1
TaxID PRJEB3251_ERR169499 PRJEB3251_ERR169499 PRJEB3251_ERR169499
333046 0.05 0.99 99.61
1049 0.03 2.34 ... | <p>Apparently the objects created by the <code>xs</code> method of the Pandas DataFrame look like two-dimensional arrays. These must be flattened to look like one-dimensional arrays when passed to <code>ttest_ind</code>.</p>
<p>Try this:</p>
<pre><code>ttest_ind(case.values.ravel(), ctrl.values.ravel(), equal_var=Fa... | python-3.x|numpy|scipy|array-broadcasting | 1 |
18,189 | 48,620,969 | Python pandas: multiple columns to multiple rows efficiently? | <p>How can I convert multiple columns of a pandas df to multiple rows like below?
I would like to do this for a very large df, so I'm looking for a relatively fast method.</p>
<pre><code> current df:
LOG_TIME QP_HCP IP_HCP QP_PRP IP_PRP
0 68444.0 4.9 0.6 4.8 3.8
df I want... | <p>Firstly, reshape your DataFrame so you have the following format.</p>
<pre><code> LOG_TIME ORIENTATION value result
0 68444.0 PRP 4.8 QP
1 68444.0 HCP 4.9 QP
2 68444.0 PRP 3.8 IP
3 68444.0 HCP 0.6 IP
</code></pre>
<p>You can do this wi... | python|pandas | 4 |
18,190 | 48,685,997 | 'float' object is not callable | <p>I m stuck at the error : </p>
<pre><code> Traceback (most recent call last):
File "neural_network.py", line 239, in <module>
demo()
File "neural_network.py", line 227, in demo
NN.train(X)
File "neural_network.py", line 168, in train
error += self.backPropagate(targets)
File "neural_networ... | <p>If <code>self.ah</code> is a floating point number or numpy array maybe you are trying to call it with an argument <code>int</code> here:</p>
<pre><code>change = output_deltas * np.reshape(self.ah(int), (self.ah.shape[0],1),dtype=int)
</code></pre>
<p>Since <code>self.ah</code> is not an object that you can call l... | python|numpy|machine-learning|neural-network | 0 |
18,191 | 71,058,102 | Manage the missing value in a dataframe with string and number | <p>I have a dataframe with some string columns and number columns. I want to manage the missing values.
I want to change the "nan" values with mean <strong>of each row</strong>.
I saw the different question in this website, however, they are different from my question. Like this link: <a href="https://stackov... | <p>First, you can select only float columns types. Second, for these columns drop rows with all nan values. Finally, you can transpose dataframe (only float columns), calculate average value and later transpose again.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame()
df['id'] = ['a', 'b', 'c', '... | python|pandas|dataframe | 0 |
18,192 | 71,018,718 | Average between values with unevenly distributed time in Pandas DataFrame | <p>I have a compact DataFrame with unevenly distributed timestamps that I want to expand to a one second interval between each time stamp and in the (NaN) expanded rows, I want to fill the average between the preceding and succeeding value from the compact dataframe. The compact df looks like this:</p>
<pre class="lang... | <p>I think your solution is pythonic, you can use <code>ffill</code> and <code>bfill</code> instead <code>fillna</code>:</p>
<pre><code>df1s = df.asfreq('1S')
dfmeans = (df1s.bfill()+df1s.ffill())/2
</code></pre>
<p>Or:</p>
<pre><code>df1s = df.asfreq('1S')
dfmeans = df1s.bfill().add(df1s.ffill()).div(2)
</code></pre> | python|pandas|dataframe|numpy | 1 |
18,193 | 70,900,745 | Pandas read_csv fails to separate tab-delimited data | <p>I have some input files that look something like this:</p>
<pre><code>GENE CHR START STOP NSNPS NPARAM N ZSTAT P
2541473 1 1109286 1133315 2 1 15000 3.8023 7.1694e-05
512150 1 1152288 1167447 1 1 15000 3.2101 0... | <p>Try using <code>\s+</code> (which reads as "one or more whitespace characters") as your delimiter:</p>
<pre><code>df = pd.read_csv('myfile.out', sep='\s+')
</code></pre> | python|pandas | 2 |
18,194 | 71,021,725 | How to use 'same' padding for maxpool1d | <p>Tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool1D" rel="nofollow noreferrer"><code>tf.keras.layers.MaxPool1D</code></a> has the option to set <code>padding='same'</code> to make the input shape the same as the output shape. Is there something equivalent for <a href="https://pyt... | <p>Note that the output of the keras version is only really the same shape as the input whenever you use it with stride and dilation set to 1, so I'll assume the same parameters in this answer.</p>
<p>For any uneven kernel size, this is quite easily achievable in PyTorch by setting the padding to (kernel_size - 1)/2.</... | pytorch | 0 |
18,195 | 51,969,234 | Python: How to vstack all the arrays of a column in a dataframe quickly? | <p>How Can I vstack all the arrays of a column into a big array quickly?</p>
<p>For example:</p>
<p><code>Dataframe['Binary_feature'][0] = array([[1,0,0,0,1]])
Dataframe['Binary_feature'][1] = array([[0,1,0,1,0]])
......
Dataframe['Binary_feature'][i] = array([[0,1,0,1,0]])</code></p>
<p>How can I stack all the ar... | <p>You can <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.squeeze.html" rel="nofollow noreferrer"><code>squeeze</code></a> an array to remove dimensions of size 1:</p>
<pre><code>s = pd.Series([np.array([[1,0,0,0,1]]),
np.array([[0,1,0,1,0]]),
np.array([[0,1,0,... | python|arrays|pandas|numpy|series | 2 |
18,196 | 41,726,646 | Overlapping axis label with length distribution | <p>I'm a newbie in python plot, I want to plot the lists with this code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
alphab = [172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,2... | <p><strong><em>option 1</em></strong><br>
Let <code>plt</code> figure it out</p>
<pre><code>plt.bar(pos, frequencies)
# plt.xticks(pos, alphab, rotation=90)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/kBdBh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kBdBh.png" alt="enter ima... | numpy|plot|label|overlapping | 0 |
18,197 | 42,079,770 | How to get the following column in a dataframe? | <p>Hello I am working with a dataframe that has some dates and times, particularly I am working with the following two columns:</p>
<pre><code>print(df[['service_window_start','delivery_window_start']])
service_window_start delivery_window_start
0 1900-01-01 09:00:00 NaT
1 1900-01... | <h3>Getting the delay_class</h3>
<p>Compute the time delay as you have done.</p>
<p>Then, <code>delay_class</code> can be computed from function like this. The difference of two <code>pandas.Timestamp</code> objects yields a <code>pandas.Timedelta</code> object:</p>
<pre><code>from pandas import Timedelta, NaT
def ... | python-3.x|pandas | 1 |
18,198 | 42,128,462 | In Python how to do Correlation between Multiple Columns more than 2 variables? | <p>I have a Pandas Dataframe like so:</p>
<pre><code>id cat1 cat2 cat3 num1 num2
1 0 WN 29 2003 98
2 1 TX 12 755 76
3 0 WY 11 845 32
4 1 IL 19 935 46
</code></pre>
<p>I want to find out the correlation between ... | <p>I tried the following and it worked :</p>
<pre><code>features1=list(['cat1','cat2','cat3'])
features2=list(['Cat1', 'Cat2','num1','num2'])
df[features1].corr()
df[features2].corr()
</code></pre>
<p>Good way to select the columns based on the need when you have a very high number of variables in your dataset.</p> | python|python-3.x|pandas|correlation | 7 |
18,199 | 64,358,445 | How to create a HTML table from a DataFrame | <p>I would like to create a HTML table from a DataFrame. Column number of table is fixed (it doesn't change). But row number of table always changes. I simplified my code so that any csv file will enough to reproduce the problem. My code is come from <a href="https://stackoverflow.com/questions/24620442/creating-a-html... | <p>See <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html#pandas-dataframe-to-html" rel="nofollow noreferrer">DataFrame.to_html</a></p>
<blockquote>
<p>Render a DataFrame as an HTML table.</p>
</blockquote>
<pre><code>from io import StringIO
import pandas as pd
styles = '... | python|html|python-3.x|pandas|dataframe | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.