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 |
|---|---|---|---|---|---|---|
4,800 | 33,137,764 | Dynamically adding dictionary values based on row count from pandas dataframe | <p>I am rewriting some code of mine and feel there must be a better more dynamic way to do the below. Currently as you can see I am creating a condition based directly on the row count and adding values from there. However I don't want to have to make static conditions for multiple values <code>if row_count == 3:</code... | <pre><code>def func1(device_dict):
device_dic[df.iloc[0][1]] = {}
device_dic[df.iloc[0][1]]['item1'] = df.iloc[0][2]
device_dic[df.iloc[0][1]]['item2'] = df.iloc[0][3]
device_dic[df.iloc[1][1]] = {}
device_dic[df.iloc[1][1]]['item1'] = df.iloc[1][2]
device_dic[df.iloc[1][1]]['item2'] = df.iloc... | python|pandas | 0 |
4,801 | 66,366,889 | How to change all values to the left of a particular cell in every row | <p>I have an array which contains 1's and 0's. A very small section of it looks like this:</p>
<pre><code>arr=[[0,0,0,0,1],
[0,0,1,0,0],
[0,1,0,0,0],
[1,0,1,0,0]]
</code></pre>
<p>I want to change the value of every cell to 1, if it is to the left of a cell with a value of 1. I want all other cells to ... | <p>You can flip using it, and use <code>np.cumsum</code>:</p>
<pre><code>>>> arr[:, ::-1].cumsum(axis=1)[:, ::-1]
array([[1, 1, 1, 1, 1],
[1, 1, 1, 0, 0],
[1, 1, 0, 0, 0]], dtype=int32)
</code></pre>
<p>Or the same using <code>np.fliplr</code>,</p>
<pre><code>>>> np.fliplr(np.fliplr(arr)... | python|numpy | 3 |
4,802 | 66,588,756 | Is there a better way to create a Multi Index with columns preceding the multi-index data? | <p><a href="https://i.stack.imgur.com/o3482.png" rel="nofollow noreferrer">This</a> is my current output and what I'd like to improve.</p>
<p>Here is the code:</p>
<pre><code>df = pd.DataFrame(np.random.rand(8, 3),
index=[['Fund Name', 'Jerry Partners','', '', 'Fund Name','Boris LTD','',''],
... | <p>Your data is in a good form to get into a dataframe with the right indices.</p>
<pre><code>import pandas as pd
managers_tickers = {
"AKO Capital": {
"LIN": 0.25,
"BKNG": 0.11,
"EBAY": 0.13,
"OTIS": 0.05,
"PG": ... | python|pandas|dataframe|multi-index | 1 |
4,803 | 66,749,664 | Speeding up numpy | <p>Is there a way to speed up the following code snippet? This is a function that accepts lidar points and converts it to Range View image Any suggestions would be appreciated. I tried using numba but didn't get much improvement.</p>
<pre><code>def lidar_rv_projection(points, proj_H=32, proj_W=2048, proj_fov_up=10, pro... | <p>If you're considering other numerical packages, using <code>torch</code> or <code>tensorflow</code> (especially if you have access to a GPU) may help substantially. Fortunately, most <code>torch</code> and <code>tensorflow</code> functions are implemented in a similar way to <code>numpy</code>, so you probably woul... | python|performance|numpy|time|numba | 0 |
4,804 | 57,516,662 | ValueError: Error when checking input: expected input to have 4 dimensions, but got array with shape (859307, 1) | <p>I'm creating a convolutional autoencoder that takes in 16x16 images but I keep getting the following error: </p>
<pre><code>Traceback (most recent call last):
File "WTApruning.py", line 69, in <module>
validation_data=(x_test, x_test))
File "/PycharmProjects/predictivemodel/venv/lib/python3.6/site-pac... | <p>You input x_train is not a 4d input.
you should reshape it before feeding it into the network.
Best</p> | python|tensorflow|keras|conv-neural-network|dimension | 1 |
4,805 | 43,661,189 | How to get count from groupby operation into new column with Python Pandas? | <p>I am trying to figure out how to count all unique barcodes (2 in this case) in this groupby operation. Then I would like to write the count value into a new column into my dataframe. I am banging my head against the wall, trying all kinds of things without success so far. Any help is greatly appreciated.</p>
<pre>... | <p>You can count unique column values in any pandas dataframe using:</p>
<pre><code>dataframe.column_name.unique()
</code></pre>
<p>In your case, it would be</p>
<pre><code>df.barcode.unique()
</code></pre>
<p>or</p>
<pre><code> df["barcode"].unique()
</code></pre>
<p>where df is the dataframe and barcode is the ... | python|pandas | 0 |
4,806 | 72,863,343 | ValueError: ssd_mobilenet_v2_fpn_keras is not supported for tf version 1. See `model_builder.py` | <p>hi i am facing a problem in Jupyter notebook i use python 3.7.13 and TensorFlow 1.15.5</p>
<pre><code># Load pipeline config and build a detection model
configs = config_util.get_configs_from_pipeline_file(CONFIG_PATH)
detection_model = model_builder.build(model_config=configs['model'], is_training=False)
# Restore... | <p>I see in <a href="https://github.com/tensorflow/models/tree/r1.13.0/research/object_detection/models" rel="nofollow noreferrer">tensorflow model version 1.x</a> don't have ssd_mobilenet_v2_fpn_keras model. It is just supported from version 2.x. So you should install tensorflow object detection api version 2.0 and tr... | python|tensorflow|jupyter-notebook|object-detection|checkpoint | 0 |
4,807 | 72,903,381 | How to find the average of a row in pandas barring one column? | <p>I'm trying to find the average of each row without taking into account the "unnamed column" which is the year.<br />
Currently I have:</p>
<pre><code>print(df.mean(axis=0))
</code></pre>
<p>But this just finds the average WITH the year which obviously is a huge outlier and skews the data.</p>
<p>Below is t... | <p>Try excluding the first column with <code>.loc</code>:</p>
<pre><code>print(df.iloc[:, 1:].mean(axis=0))
</code></pre> | python|pandas|data-science|data-cleaning | 0 |
4,808 | 10,321,036 | python numpy recarray join | <p>Is there no "join" function in numpy recarrays? I see matplotlib has something and there is a concatenate but this is not a solution. I want a fast join in numpy/scipy or understand why it is not there. </p> | <p>After some digging I found this slightly buried library. I think it might be doing what I need ... curious to hear other answers as well. If this is the best solution it is NOT very well documented. I'm not sure how to contribute docs:</p>
<pre><code>import numpy as np
import numpy.lib.recfunctions as rfn
import n... | python|numpy|join|recarray | 0 |
4,809 | 70,490,204 | How to make batch with pictures of different sizes for model in PyTorch? | <p>I want to use GlobalAveragePooling in my PyTorch model and not to resize, crop or pad the image. I can train my model using only one image every iteration (not batch). But it is too slow and I don't know how to use several images of different sizes as one input for Model.
Example of model code:</p>
<pre><code>class ... | <p>One idea is to choose a image of the same size for each stack.
Caution.</p>
<ol>
<li>shuffling: can group indexes/images_id by size and then apply shuffle within the group.</li>
<li>last batch: just do something similar to drop_last if neccessary (see torch dataloader)</li>
<li>maybe there is more work ...</li>
</ol... | python|neural-network|pytorch|conv-neural-network | 0 |
4,810 | 70,731,467 | Function not callable anymore after one try | <p>I'm coding a function right now which has a really weird problem. When I define the function <code>Psi(t)</code> and call it to be plotted, it works fine. But, when you call it again to be plotted, it sends an error <code>'numpy.ndarray' object is not callable</code>. When you click play (on Jupyter notebook) on <co... | <p>On the third-to-last line:</p>
<pre><code>Psi = Psi(2e-16)
</code></pre>
<p>You are updating the reference to <code>Psi</code> from the function to the return value. Upon doing so, <code>Psi</code> can no longer be used as a function. It is advisory to never use variables with the same names as functions or classes ... | python|arrays|numpy|callable | 1 |
4,811 | 70,719,806 | Outlier removal techniques from an array | <p>I know there's a ton resources online for outlier removal, but I haven't yet managed to obtain what I exactly want, so posting here, I have an array (or DF) of <code>4</code> columns. Now I want to remove the rows from the DF based on a column's outlier values. The following is what I have tried, but they are not pe... | <p>You could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html" rel="nofollow noreferrer">scipy's median_filter</a>:</p>
<pre><code>import pandas as pd
from matplotlib import pyplot as plt
from scipy.ndimage import median_filter
b = pd.read_csv("test.csv")
x ... | python|pandas|numpy|scipy|outliers | 2 |
4,812 | 42,788,713 | Pandas mapping to TRUE/FALSE as String, not Boolean | <p>When I try to convert some columns in a pandas dataframe from '0' and '1' to 'TRUE' and 'FALSE', pandas automatically detects dtype as boolean. I want to keep dtype as string, with the strings 'TRUE' and 'FALSE'.</p>
<p>See code below:</p>
<pre><code>booleanColumns = pandasDF.select_dtypes(include=[bool]).columns.... | <p>If need replace <code>boolean</code> values <code>True</code> and <code>False</code>:</p>
<pre><code>booleandf = pandasDF.select_dtypes(include=[bool])
booleanDictionary = {True: 'TRUE', False: 'FALSE'}
for column in booleandf:
pandasDF[column] = pandasDF[column].map(booleanDictionary)
</code></pre>
<p>Sample... | python|pandas|dictionary|replace | 28 |
4,813 | 43,011,713 | Rotate a numpy.array one bit to the right | <p>I have a <code>numpy.array</code> and would like to rotate its content one bit to the right. I want to perform this as efficient (in terms of execution speed) as possible. Also, please note that every element of the array is an 8-bit number (<code>np.uint8</code>). The rotation assumes that the array stores one big ... | <p>You can speed up your "Method #2" by reducing the amount of memory allocation for temporaries:</p>
<pre><code>def method2a(w):
rotW = np.right_shift(w, 1)
lsb = np.bitwise_and(w, 1)
np.left_shift(lsb, 7, lsb)
rotW[0] |= lsb[-1]
rotW[1:] |= lsb[:-1]
return rotW
</code></pre>
<p>On my system,... | python|arrays|numpy|bit-manipulation | 2 |
4,814 | 42,948,719 | TensorFlow HVX Acceleration support | <p>I successfully built and ran the test application from <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/hvx" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/hvx</a>. I'd now like to benchmark HVX against the CPU implementation of <a hr... | <p>Currently, the Android demo app does not support the HVX runtime. But I'm sure that you can use the runtime with Android demo app by replacing .so file with HVX version. If you can wait for the official support, that would be happening soon, but no promise. Let me know if you have any questions :)</p> | tensorflow|hexagon-dsp | 2 |
4,815 | 25,182,421 | Overlay two numpy arrays treating fourth plane as alpha level | <p>I have two numpy arrays of shape (256, 256, 4). I would like to treat the fourth 256 x 256 plane as an alpha level, and export an image where these arrays have been overlayed.</p>
<p>Code example:</p>
<pre><code>import numpy as np
from skimage import io
fg = np.ndarray((256, 256, 4), dtype=np.uint8)
one_plane = n... | <p><a href="http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending" rel="noreferrer">Alpha blending</a> is usually done using the Porter & Duff equations:</p>
<p><img src="https://i.stack.imgur.com/iCSV2.png" alt="enter image description here"></p>
<p>where <em>src</em> and <em>dst</em> would correspond to... | python|image|numpy|alphablending|scikit-image | 10 |
4,816 | 25,087,769 | RuntimeWarning: Divide by Zero error: How to avoid? PYTHON, NUMPY | <p>I am running in to RuntimeWarning: Invalid value encountered in divide</p>
<pre><code> import numpy
a = numpy.random.rand((1000000, 100))
b = numpy.random.rand((1,100))
dots = numpy.dot(b,a.T)/numpy.dot(b,b)
norms = numpy.linalg.norm(a, axis =1)
angles = dots/norms ### Basically I am calculating angle between ... | <p>you can ignore warings with the <code>np.errstate</code> context manager and later replace nans with what you want:</p>
<pre><code>import numpy as np
angle = np.arange(-5., 5.)
norm = np.arange(10.)
with np.errstate(divide='ignore'):
print np.where(norm != 0., angle / norm, -2)
# or:
with np.errstate(divide='i... | python|numpy | 15 |
4,817 | 26,823,556 | Mask array entries when column index is greater than a certain cutoff that is unique to each row | <p>I want to efficiently mask a large array with several hundred thousand rows and ~500 columns wherever column index is greater than <code>cutoff[i]</code>, 0 <= <code>i</code> < number of rows.</p>
<p>Here is an example:</p>
<pre><code>In [2]: x = np.random.randint(0,100,size=24).reshape((6,4)); x
Out[2]:
ar... | <p>You can use broadcast:</p>
<pre><code>cutoff = np.array([10,4,3,2,1,0])
np.arange(4)[None, :] >= cutoff[:, None]
</code></pre>
<p>Here is the result:</p>
<pre><code>array([[False, False, False, False],
[False, False, False, False],
[False, False, False, True],
[False, False, True, True]... | python|numpy|pandas | 2 |
4,818 | 26,572,664 | Set each individual column to have its own datatype | <p>How can I set a particular datatype for every single column?</p>
<p>I opened a <code>.txt</code> file which has 236 columns with Pandas. </p>
<p>For example I have a column with values called "System Time", another one called "Temperature", another one called "Alarm", ...</p>
<p>For "System Time" I want to use <c... | <p>When Pandas reads your file (e.g. using <code>pd.read_csv</code>) to construct the DataFrame it will automatically select the appropriate datatype (<code>dtype</code>) to hold the data on a column by column basis. This means that a column of decimal numbers will have the <code>float64</code> type, and so on.</p>
<p>... | python|python-2.7|pandas|dataframe|types | 0 |
4,819 | 26,518,673 | Format data for survival analysis using pandas | <p>I'm trying to figure out the quickest way to get survival analysis data into a format that will allow for time varying covariates. Basically this would be a python implementation of <code>stsplit</code> in Stata. To give a simple example, with the following set of information:</p>
<pre><code>id start end x1 x2 e... | <p>Assuming:</p>
<pre><code>>>> df1
id start end x1 x2 exit
0 1 0 18 12 11 1
</code></pre>
<p>and:</p>
<pre><code>>>> df2
id t age
0 1 0 30
1 1 7 40
2 1 17 50
</code></pre>
<p>You can do:</p>
<pre><code>df = df2.copy() # start ... | python|pandas|stata|survival-analysis | 1 |
4,820 | 26,563,745 | Python Pandas : how to set 2 colums at the same time? | <p>I posted something simpler because I thought it could be easy to understand, but referring to your comments, I was wrong, so I edit this question :</p>
<p>So here is the code. I want to do it without a loop, should it be done in pandas ?</p>
<pre><code>import pandas as pd
myval = [0.0,1.1, 2.2, 3.3, 4.4, 5.5,6.6,... | <p>I was hoping that something like the following might work (as suggested in the comments), however (suprisingly?) this use of np.where raises a <code>ValueError: shape mismatch: objects cannot be broadcast to a single shape</code> (using a 1D to select from a 2D):</p>
<pre><code>np.where(df.s1 & df.s2,
... | python|pandas | 0 |
4,821 | 39,075,173 | Pandas: create a table using groupby | <p>I have dataframe </p>
<pre><code>ID subdomain search_engine search_term code category term_code
0120bc30e78ba5582617a9f3d6dfd8ca yandex.ru 0 None 1 поисковая машина 1
0120bc30e78ba5582617a9f3d6dfd8ca my-shop.ru 0 None 5 интернет-магазин 1
0120bc30e78ba5582617a9f3d6dfd8ca r... | <p>try this:</p>
<pre><code>df.groupby('ID')['category'].apply(lambda x: ' -> '.join(list(x)))
</code></pre>
<p>Demo:</p>
<pre><code>In [14]: df.groupby('ID')['category'].apply(lambda x: ' -> '.join(list(x)))
Out[14]:
ID
0120bc30e78ba5582617a9f3d6dfd8ca поисковая машина -> интернет-ма... | python|pandas | 1 |
4,822 | 39,030,164 | pandas: Add row from one data frame to another data frame? | <p>I have two dataframes with identical column headers.</p>
<p>I am iterating over the rows in df1, splitting one of the columns, and then using those split columns to create multiple rows to add to the other dataframe.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for... | <p>I figured it out.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for award in curr_awards:
new_line = row
new_line['AWARD'] = award.strip()
df2.loc[len(df2)] = new_line
</code></pre> | python|python-3.x|pandas | 4 |
4,823 | 29,297,033 | Numpy filter 2D array by two masks | <p>I have a 2D array and two masks, one for columns, and one for rows. If I try to simply do <code>data[row_mask,col_mask]</code>, I get an error saying <code>shape mismatch: indexing arrays could not be broadcast together with shapes ...</code>. On the other hand, <code>data[row_mask][:,col_mask]</code> works, but is ... | <p>Use <code>ix_</code> function :</p>
<pre><code>>>> data[np.ix_(row_mask,col_mask)]
array([[ 1, 2],
[ 4, 5],
[10, 11]])
</code></pre>
<blockquote>
<p>Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the <a href="http://docs... | python|numpy|scipy | 3 |
4,824 | 33,851,716 | Installing numpy and pandas for python 3.5 | <p>I've been trying to install numpy and pandas for python 3.5 but it keeps telling me that I have an issue. </p>
<p>Could it be because numpy can't run on python 3.5 yet? </p> | <p>This is as a result of a Numpy distutils bug (which is already fixed in the development branch).</p>
<p>If you have brew:</p>
<pre><code>brew install homebrew/python/numpy --with-python3
</code></pre>
<p>If you don't:</p>
<pre><code>pip3 install git+https://github.com/numpy/numpy.git
</code></pre> | python|numpy | 2 |
4,825 | 23,543,836 | Generating repetitive data in numpy / pandas in a fast vectorized way | <p>Suppose I want to generate a 1D array like this:</p>
<pre><code>1 1 1 1 2 2 2 3 3 4
</code></pre>
<p>In general I am looking for something with this form:</p>
<pre><code>Element N-repetition
1 n-0
2 n-1
3 n-2
4 n-3
. .
. .
. .
n ... | <p>Its very simple with Numpy's <code>repeat</code>:</p>
<pre><code>n = 4
a = np.arange(1,n+1)
</code></pre>
<p>The array <code>a</code> looks like:</p>
<pre><code>array([1, 2, 3, 4])
</code></pre>
<p>And you basically want to repeat it with the reverse of <code>a</code>, so:</p>
<pre><code>np.repeat(a, a[::-1])
<... | python|numpy|pandas | 5 |
4,826 | 29,570,394 | Solving a differential equation in python with odeint | <p>I am trying to solve that differential equation R·(dq/dt)+(q/C)=Vi·sin(w·t), so i have the this code:</p>
<pre><code>import numpy as np
from numpy import *
import matplotlib.pyplot as plt
from math import pi, sin
from scipy.integrate import odeint
C=10e-9
R=1000 #Ohmios
Vi=10 #V
w=2*pi*1000 #Hz
fc=1/(2*pi*R*C)
pri... | <p>There are a few issues here:</p>
<p>Division in python2, as commenters have noted, doesn't cast integers to floats during division. So you'll want to make sure your parameters are floats:</p>
<pre><code> C=10e-9
R=1000.0 #Ohmios
Vi=10.0 #V
w=2*pi*1000.0 #Hz
</code></pre>
<p>Now, you don't really need, for what... | python|numpy|differential-equations|integrate|odeint | 2 |
4,827 | 62,167,953 | How to keep values for nonexistent categories while subtracting dataframes? | <p>I have 12 dataframes with cumulative values, and I want to transform them to non-cumulative one.</p>
<pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({
"ADMIN": [1, 2],
"FIN_SOURCE": ["A", "B"],
"PROG": [150, 155],
"FUNC": [1, 2],
"ECON": [30, 50],
"VALUE": [5, 10]
})
df2 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>DataFrame.sub</code></a> with <code>fill_value=0</code> parameter:</p>
<pre><code>indxs = ["ADMIN", "FIN_SOURCE", "PROG", "FUNC", "ECON"]
df = df2.set_index(indxs).sub(df1.set_index(indx... | python|pandas | 1 |
4,828 | 62,361,162 | Is A PyTorch Dataset Accessed by Multiple DataLoader Workers? | <p>When using more than 1 DataLoader workers in PyTorch, does every worker access the same Dataset instance? Or does each DataLoader worker have their own instance of Dataset?</p>
<pre><code>from torch.utils.data import DataLoader, Dataset
class NumbersDataset(Dataset):
def __init__(self):
self.samples = ... | <p>It seams like they are accessing to the same instance. I have tried adding a static variable inside the dataset class and incrementing it every time a new instance is created. Code can be found below.</p>
<pre><code>from torch.utils.data import DataLoader, Dataset
class NumbersDataset(Dataset):
i = 0
def... | python|python-3.x|deep-learning|neural-network|pytorch | 2 |
4,829 | 62,368,138 | Pandas giving error to read txt data file | <p>This is the code that I am using and it is not working for some reason. Please help me out.</p>
<p>I have created a text file with some data and when I try to use Pandas to read the data it is not working.</p>
<pre><code>dF = pd.read_csv("PandasLongSample.txt", delimiter='/t')
print(dF)
</code></pre>
<p>This is t... | <p>Use a backslash (\) instead of a slash (/) for the tab delimiter.</p>
<pre><code>dF = pd.read_csv("PandasLongSample.txt", delimiter='\t')
print(dF)
</code></pre> | python|pandas | 3 |
4,830 | 62,154,772 | pandas printing maximum value found in a column with an f string | <p>If I have some made up data... How do I print just the index (date & time stamp) of the maximum value found in a column named <code>Temperature</code>?</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(11)
rows,cols = 50000,2
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01... | <p>You f string could be:</p>
<pre><code>f'maximum temperature recoded in the dataset is {maxy} found on {maxDate.name}'
</code></pre>
<p>Or without <code>maxy</code>:</p>
<pre><code>f'maximum temperature recoded in the dataset is {maxDate.Temperature} found on {maxDate.name}'
</code></pre>
<p>Output:</p>
<pre><co... | python|pandas|string-formatting | 0 |
4,831 | 51,241,471 | F tensorflow/core/common_runtime/device_factory.cc:77] Duplicate registration of device factory for type GPU with the same priority 210 | <p>When excute my binary c++ file, this error happened.
I compile my c++ file with tensorflow_cc.so by using make all, and the version of tensorflow is 1.8.
Does anyone have met this problem?</p> | <p>We recently encountered this error. It happened when we inadvertently linked against both libtensorflow.so (<code>-ltensorflow</code>) and libtensorflow_cc.so (<code>-ltensorflow_cc</code>). It went away when we picked one.</p> | c++|tensorflow | 0 |
4,832 | 51,449,242 | Search through a concatenated dataframe for exact match and then pull minimum date | <p>So I am new to pandas and am punching above my weight here. I have two csv files: one is a list of authors I am interested in (data frame 1) and the second file is a total list of authors for the publishing company and their publication date (data frame 2).</p>
<p>I need to use data frame 1 to see if there is an ex... | <pre><code>lis1=[{'FIRST_NAME':'James','Last_Name':'Cameran','City':'NYC'},{'FIRST_NAME':'Samuel','Last_Name':'Smith','City':'London'},{'FIRST_NAME':'Kane','Last_Name':'Win','City':'NYC'}]
lis2=[{'FIRST_NAME':'James','Last_Name':'Cameran','Pub. Year':2011},{'FIRST_NAME':'Kane','Last_Name':'Win','Pub. Year':2010},{'FIRS... | python|pandas|csv|dataframe|data-science | 0 |
4,833 | 48,158,460 | Distributed tensorflow monopolizes GPUs after running server.__init__ | <p>I have two computers with two GPUs each. I am trying to start with distributed tensorflow and very confused about how it all works. On computer A I would like to have one <code>ps</code> tasks (I have the impression this should go on the CPU) and two <code>worker</code> tasks (one per GPU). And I would like to have ... | <p>I found that the following will work when invoking from command line:</p>
<p><code>CUDA_VISIBLE_DEVICES="" python3 test.py --job_name ps --task_idx 0 --dir_name TEST</code></p>
<p>Since I found this in a lot of code examples it seems like this may be the standard way to control an individual server's access to GPU... | python|tensorflow | 0 |
4,834 | 48,417,950 | pandas dataframe - merging rows by substituting values with column value | <p>Apologies for the ambiguous title.</p>
<p>I have a dataset of students and I want to run a clustering algorithm on the students.</p>
<p>The dataset is structured such that there are more than one row per student, each with age, grade (9th, 10th, etc) a single class the student is taking and the final score in that... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> + <a href="h... | python|python-2.7|pandas | 2 |
4,835 | 47,989,741 | Python - Array becomes scalar variable when passed into function | <p>I am trying to create a simple python script that when given a photo, first converts it to greyscale and then will band it into a number of colors. For example if the number of colours passed in is 2, the greyscale image will be changed so that each pixel is either pitch black (0) or bright white (255). </p>
<p>How... | <p>Change:</p>
<pre><code>for i in range(1, bandWidthArray.len):
</code></pre>
<p>to:</p>
<pre><code>for i in range(1, len(bandWidthArray)):
</code></pre>
<p>NumPy arrays don't have a <code>len</code> method.</p>
<p>Furthermore, don't vectorize your function. Remove this line:</p>
<pre><code>getGreyScaleValue = n... | python|numpy | 0 |
4,836 | 48,654,403 | How do I know the maximum number of threads per block in python code with either numba or tensorflow installed? | <p>Is there any code in python with either numba or tensorflow installed?
For example, if I would like to know the GPU memory info, I can simply use:</p>
<pre><code>from numba import cuda
gpus = cuda.gpus.lst
for gpu in gpus:
with gpu:
meminfo = cuda.current_context().get_memory_info()
print("%s, f... | <pre><code>from numba import cuda
gpu = cuda.get_current_device()
print("name = %s" % gpu.name)
print("maxThreadsPerBlock = %s" % str(gpu.MAX_THREADS_PER_BLOCK))
print("maxBlockDimX = %s" % str(gpu.MAX_BLOCK_DIM_X))
print("maxBlockDimY = %s" % str(gpu.MAX_BLOCK_DIM_Y))
print("maxBlockDimZ = %s" % str(gpu.MAX_BLOCK_DIM_... | python|tensorflow|cuda|numba | 7 |
4,837 | 48,497,449 | python pandas check column contains item from a list | <p>I have two data frames like </p>
<pre><code>vid vbull
1125 RHSA:2017:3200
1127 RHSA:2017:3205
1128 RHSA:2017:3208
1129 RHSA:2017:3209
kbid vdesc
2401 This contains details for RHSA:2017:3205
2402 This contains details for RHSA:2017:3206
2403 This contains details fo... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extract</code></a> for values from <code>vbull</code> first:</p>
<pre><code>df2['extracted'] = df2.vdesc.str.extract('(' + '|'.join(df1.vbull) + ')', expand=False)
print (df2)
kbid ... | python|list|pandas|merge|extract | 0 |
4,838 | 48,568,712 | DataFrame: add same data for different column and merge the whole file | <p>I have a DataFrame which looks like this:</p>
<pre><code>Name Year Jan Feb Mar Apr
Bee 1998 26 23 22 19
Cee 1999 43 23 43 23
</code></pre>
<p>I want to change the DataFrame into something like this:</p>
<pre><code>Name Year Mon Val
Bee 1998 1 26
Bee 1998 2 23
Bee 1998 3 22
Bee 1998 4 19
Cee 1... | <p>First, reshape your DataFrame with <code>pd.DataFrame.melt</code>:</p>
<pre><code>df = df.melt(id_vars=['Name', 'Year'], var_name='Mon', value_name='Value')
</code></pre>
<p>...and then convert your <code>Mon</code> values to datetime values, and extract the month number:</p>
<pre><code>df.loc[:, 'Mon'] = pd.to_d... | python|pandas|dataframe | 0 |
4,839 | 48,533,286 | Why does my data change into NaN in Task4? | <p>Why does my data change into NaN in task 4? I also tried using .loc[], but that still doesn't work. I need to be able to use the numbers.</p>
<pre><code>dec6 = pd.read_csv('coinmarketcap_06122017.csv', header=0)
market_cap_raw = dec6[['id', 'market_cap_usd']]
print(market_cap_raw.describe())
#print(market_cap_raw)
... | <p>The re_index() method is causing the data to change to NaN. </p> | python|pandas | 0 |
4,840 | 48,479,571 | While Import python. ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory | <p>I have tried many solutions like installing from different sources official google link <code>Google.api...</code>, <code>pypi</code> and also building from git repo.</p>
<p>But every time I face the same problem <code>ImportError: libcublas.so.9.0:</code></p>
<p>OS: <code>Linux Arch</code> tensorflow: <code>tenso... | <p>Your error message indicates that Tensorflow is looking for CUDA 9.0, while the default download is CUDA 9.1. I suggest down-reviving to CUDA 9.0. I just installed TF prebuilt binaries with CUDA 9.0 and the corresponding cudnn 7.05 and everything ran fine. From <a href="https://github.com/tensorflow/tensorflow/issue... | python|tensorflow|archlinux | 5 |
4,841 | 48,625,687 | replace a chained method with a variable in python | <p>I have a function from the <code>simple_salesforce</code> package,</p>
<pre><code>sf = Salesforce(username, pass, key)
</code></pre>
<p>In order to update an object in the salesforce database, you call sf by:</p>
<pre><code>sf.bulk.object.update(data)
</code></pre>
<p>For example, <code>account</code> is the nat... | <p>You can use builtin function <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow noreferrer"><code>getattr</code></a> to fetch your desired entity:</p>
<pre><code>>>> getattr(sf.bulk, object).update(data)
</code></pre>
<p>To also able to dynamically select operation(insert, up... | python|pandas|dictionary|methods|salesforce | 2 |
4,842 | 70,786,169 | How to measure training time per batches during Deep Learning in Tensorflow? | <p>I want to measure training time per batches during Deep Learning in Tensorflow.
There are several ways to measure training time per epochs, but I cannot find how to measure training time per batches.</p>
<p>I tried Tensorboard, but I don't know how to add some kind of 'execution time' scalars in tensorboard callback... | <p>You can do this by creating a keras custom callback. The code below will print out the time it takes to process each batch, the training accuracy for that batch and the loss for that batch</p>
<pre><code>class batch_timer(keras.callbacks.Callback):
def __init__(self ):
super(batch_timer, self).__init__(... | python|tensorflow|deep-learning | 0 |
4,843 | 70,889,776 | while saving model: list index (0) out of range | <p>this is my face_landmark.py</p>
<pre><code>import cv2
import numpy as np
import tensorflow as tf
from tensorflow import keras
def get_landmark_model(saved_model="models/pose_model"):
model = keras.models.load_model(saved_model)
return model
</code></pre>
<p>and in camera.py, I am importing it and usin... | <p>While loading the model, provide file extension as well.
For example</p>
<pre><code>def get_landmark_model(saved_model="models/pose_model.h5"):
model = keras.models.load_model(saved_model)
return model
</code></pre>
<p>here <strong>h5</strong> is the extension of model.</p> | python|tensorflow|keras | 0 |
4,844 | 70,926,249 | Barplot with twinx and two bars per month | <p>a given df where the index is the month two columns 'Ta' and 'G_Bn'.</p>
<p><a href="https://i.stack.imgur.com/qQiVw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qQiVw.png" alt="df" /></a></p>
<p>Those columns shall be ploted against the month with seaborn to get a barplot with two y-axis. One ... | <p>The following approach creates a dummy categorical variable to serve as <code>hue</code>:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
dataMonthly = pd.DataFrame({'G_Bn': np.random.uniform(30, 40, 5).cumsum(),
... | python|pandas|seaborn|bar-chart | 0 |
4,845 | 51,573,241 | TypeError: while_loop() got an unexpected keyword argument 'maximum_iterations' In Jupyter Azure | <p>I am setting up my recurrent neural network in Azure:</p>
<pre><code>model = Sequential()
model.add(GRU(units=512,
return_sequences=True,
input_shape=(None, x1,)))
model.add(Dense(y1, activation='sigmoid'))
</code></pre>
<p>But I am getting the error:</p>
<pre><code>TypeError:... | <pre><code>!pip uninstall keras
!pip install keras==2.1.2
</code></pre>
<p>And now it works</p> | python|azure|tensorflow|keras|jupyter-notebook | 6 |
4,846 | 51,733,128 | Your kernel may have been built without NUMA support | <p>I have Jetson TX2, python 2.7, Tensorflow 1.5, CUDA 9.0</p>
<p>Tensorflow seems to be working but everytime, I run the program, I get this warning:</p>
<p><code>with tf.Session() as sess:</code></p>
<p><code>print (sess.run(y,feed_dict))</code>
... </p>
<p><code>2018-08-07 18:07:53.200320: E</code></p>
<p><code... | <p>It shouldn't be a problem for you, since you don't need NUMA support for this board (it has only one memory controller, so memory accesses are uniform).</p>
<p>Also, I found <a href="https://devtalk.nvidia.com/default/topic/1027507/jetson-tx2/numa-error-running-tensorflow-on-jetson-tx2/" rel="noreferrer">this post<... | tensorflow|linux-kernel|numa | 5 |
4,847 | 51,702,572 | How to find common elements in several dataframes | <p>I have the following dataframes:</p>
<pre><code>df1 = pd.DataFrame({'col1': ['A','M','C'],
'col2': ['B','N','O'],
# plus many more
})
df2 = pd.DataFrame({'col3': ['A','A','A','B','B','B'],
'col4': ['M','P','Q','J','P','M'],
... | <p>This should achieve what you want, using a combination of <code>merge</code>, <code>groupby</code> and set intersection:</p>
<pre><code># Getting tuple of all col1=col3 values in col4
df3 = pd.merge(df1, df2, left_on='col1', right_on='col3')
df3 = df3.groupby(['col1', 'col2'])['col4'].apply(tuple)
df3 = df3.reset_i... | python|pandas | 1 |
4,848 | 41,843,600 | how to install cudnn5.1 with cuda 8.0 support for tensorflow? | <p>I am unable to find the cudnn-8.0-linux-x64-v5.1.tgz file. The download link has only .deb file and when I install it using
sudo dpkg -i /path/to/deb/file
I get libcudnn.so.5.1.5 file and not the headers (cudnn.h). Where can I get the .tgz file with all the .so and .h files? I am looking for libcudnn.so.5.1</p> | <p>You can download cuDNN from <a href="https://developer.nvidia.com/cudnn" rel="nofollow noreferrer">here</a>, you need to have an NVIDIA developer account which is free of cost. After downloading it, extract the contents and copy the files to appropriate locations:</p>
<pre><code>$ sudo cp -P include/cudnn.h /usr/in... | cuda|tensorflow|cudnn | 1 |
4,849 | 42,065,870 | How can i use my own images to train my CNN neural network in tensorFlow | <p>I am currently working on a program that uses a CNN tensorflow neural network and I want to use my own images to train and test it, please I want some advice because I am new in deep learning </p>
<p>Thanks.</p> | <p>Download the ronnie package from python.[{pythonpath}\scripts\pip3 ronnie]
Construct the training data structure as [label, image pixel] and execute the below code to create the training data.</p>
<p>dataFileLoc = os.path.join(dir,"./data/digitalRec/train.csv")
orgDF = collector.initial(dataFileLoc)</p>
##########... | tensorflow | 0 |
4,850 | 64,454,408 | Performing Calculations From A Pandas Data Frame with Multiple Conditions | <p>Forgive the question as I'm a science major, not computer science and I'm teaching myself Python to help with a class project.</p>
<p>I have a Pandas data frame that I've imported from a .csv that looks like:</p>
<pre><code>Item_ID Event_ID Value
27 83531 2533501.8
28 83531 1616262
31 83531 269829
32 83... | <p>You can use <code>groupby</code> followed by <code>agg</code> methods to do that.</p>
<p>First, define your calculations as functions:</p>
<pre><code># Define calculations
def Calc1(x):
return (x[28]/x[27])*((x[31]*x[32])/x[28])*((x[33]-x[34])/x[33])
def Calc2(x):
return x[36]/x[35]
# Calc3 = lambda x: (x[35... | python-3.x|pandas | 1 |
4,851 | 64,444,993 | How to filter pandas dataframe between a negative and a positive value (-0.2 to 0.2), and removing the rows that meet the condition? | <p>I have a Pandas dataframe with the following columns: Position, Control, Patient, REFGENE, REFGROUP
And very many rows with data (methylation data). I show you the first row of the dataframe here:</p>
<pre><code>Position Controls Patients REFGENE REFGROUP
16:53468112 0.598153 ... | <p>your approach is correct, however, "&" corresponds to "and", so you could use :</p>
<pre><code>df['Results']= (df['diff_methylation'] > float(0.2)) | (df['diff_methylation'] < float(-0.2))
</code></pre> | pandas|filter|range|negative-number | 1 |
4,852 | 64,290,589 | Simple Neural Network numpy error missing "exe" | <p>I am trying to run this code for simple Neural Network in python however an error is prompted saying " module 'numpy' has no attribute 'exe' ". I tried searching online but couldn't figure out where the problem is, here is the code:</p>
<pre><code>import numpy as np
x=np.array([ [0,0,1],
[0,1,1... | <p>In Your <code>sigmoid</code> function you are using <code>np.exe</code> where it should be <code>np.exp</code></p>
<p><code>Numpy</code> doesn't have any function named <code>exe</code> so you are getting <code>AttributeError</code></p> | python|python-3.x|numpy|deep-learning|neural-network | 1 |
4,853 | 47,959,059 | Performing pct_change() that only considers the prior year in a time-series dataframe? | <p>I have a sample dataframe "df":</p>
<pre><code>df = pd.DataFrame({'Year': [2000, 2002, 2003, 2004],
'Name': ['A'] * 4,
'Value': [4, 1, 1, 3]})
</code></pre>
<p>When I perform pct_change() i.e.</p>
<pre><code>df['change'] = df['Value'].pct_change()
</code></pre>
<p>The comp... | <p>Use <code>set_index</code> + <code>reindex</code> + <code>pct_change</code> with <code>fill_method=None</code> - </p>
<ol>
<li>First, set <code>Year</code> as the index</li>
<li>Get a range of years from the minimum to maximum, and use this range to reindex the dataframe. Missing years are now added in as <code>NaN... | python|pandas|dataframe | 2 |
4,854 | 48,896,516 | I want to specify an array's axes and their index values and get the sub array back | <p>So I know how to do this on a case by case basis, but I would like to write a class and method, or have a code snippet to do this in general. For instance, typically to extract a sub-array I would do:</p>
<pre><code>my_array = np.array(range(81)).reshape((3,3,3,3))
sub_array = my_array[0, 1, :, 0]
</code></pre>
<... | <pre><code>my_array[0, 1, :, 0]
</code></pre>
<p>can also be written as</p>
<pre><code>my_array[(0, 1, slice(None), 0)]
</code></pre>
<p>or</p>
<pre><code>idx = (0, 1, slice(None), 0)
my_array[idx]
</code></pre>
<p>So you could construct that <code>idx</code> from your</p>
<pre><code>axis_list = [0, 1, 3]
axis_id... | python|numpy|indexing|slice | 0 |
4,855 | 49,142,561 | Change contrast in Numpy | <p>I want to write a pure Numpy function to change the contrast of an RGB image (that is represented as a Numpy uint8 array), however, the function I wrote doesn't work and I don't understand why.</p>
<p>Here is an example image:</p>
<p><a href="https://i.stack.imgur.com/Ceppy.png" rel="nofollow noreferrer"><img src=... | <p>What you are seeing is underflow of unsigned integers:</p>
<pre><code>>>> a = np.array((64, 128, 192), dtype=np.uint8)
>>> a
array([ 64, 128, 192], dtype=uint8)
>>> a-128
array([192, 0, 64], dtype=uint8) # note the "wrong" value at pos 0
</code></pre>
<p>One way of avoiding this is co... | python|numpy | 5 |
4,856 | 58,930,339 | more efficient way to get proportion of ones using groupby in pandas | <p>I have the following pandas DataFrame:</p>
<pre><code>import pandas as pd
i1 = ["AA", "AA", "AA", "BB", "BB", "BB"]
i2 = ["B1", "B1", "B1", "A1", "A1", "A1"]
col1 = [1, 1, 1, 0, 1, 0]
col2 = [0, 0, 0, 1, 1, 0]
col3 = [1, 1, 0, 0, 0, 0]
df = pd.DataFrame({"I1": i1,
"I2": i2,
"Co... | <p>Use <code>mean</code> if there are only <code>1</code> and <code>0</code> values, because <code>mean</code> by defintion is <code>sum / count</code>:</p>
<pre><code>#mean of all numeric columns (without I1, I2)
df1 = df.groupby(["I1", "I2"]).mean()
#if need specify columns names
#df1 = df.groupby(["I1", "I2"])["Col... | python|pandas | 3 |
4,857 | 59,020,566 | how to concatenate two cells in a pandas column based on some conditions? | <p>Hello I have this pandas dataframe:</p>
<pre><code>
Key Predictions
C10D1 1
C11D1 8
C11D2 2
C12D1 2
C12D2 8
C13D1 3
C13D2 9
C14D1 4
C14D2 9
C15D1 8
C15D2 3
C1D1 5
C2D1 7
C3D1 4
C4D1 1
C4D2 9
C5D1 3
C5D2 2
C6D1 1
C6D2 0
C7D1 8
C7D2 6
C8D1 3
C8D2 3... | <p><strong><em>EDIT:</em></strong> Since OP wants to concatenate values of same index so adding that solution here.</p>
<pre><code>df.groupby(df['Key'].replace(regex=True,to_replace=r'(C[0-9]+).*',value=r'\1'))\
['Predictions'].apply(lambda x: ','.join(map(str,x)))
</code></pre>
<p>Above will concatenate them with <c... | python|pandas|data-science|data-analysis | 1 |
4,858 | 58,754,293 | Convert only rows that list length equals 1 to string | <p>I have a DataFrame in Python where every row from <code>tags</code> column is a list:</p>
<pre><code>df
>>> name tags
>>> alice | [a]
>>> bruce | [a, b, c]
</code></pre>
<p>I want to convert only rows that have list <code>length = 1</code> to string.
Expected resul... | <p>You can use:</p>
<pre><code>c=df['tags'].str.len().eq(1)
df['tags']=np.where(c,df['tags'].str[0],df['tags'])
print(df) #df.to_csv('file.txt',sep='|',index=False)
</code></pre>
<hr>
<pre><code> name tags
0 alice a
1 bruce [a, b, c]
</code></pre> | python|string|pandas|list | 3 |
4,859 | 58,731,643 | Find number of rows in a given week in PySpark | <p>I have a PySpark dataframe, a small portion of which is given below:</p>
<pre><code>+------+-----+-------------------+-----+
| name| type| timestamp|score|
+------+-----+-------------------+-----+
| name1|type1|2012-01-10 00:00:00| 11|
| name1|type1|2012-01-10 00:00:10| 14|
| name1|type1|2012-01-10 00... | <p>Something like this:</p>
<pre><code>from pyspark.sql.functions import weekofyear, count
df = df.withColumn( "week_nr", weekofyear(df.timestamp) ) # create the week number first
result = df.groupBy(["week_nr","name"]).agg(count("score")) # for every week see how many rows there are
</code></pre> | python|pandas|pyspark|pyspark-sql|pyspark-dataframes | 1 |
4,860 | 58,966,448 | Webscraping an entire website pandas word cloud | <p>I'm attempting to create a wordcloud based off the <strong>scraped</strong> text from a specific website. The issue I'm having is with the webscraping portion of this. I've attempted two different ways, and both attempts I get stuck on how to proceed further.</p>
<p>First method:
<strong>Scrape</strong> the data for... | <p>This ended up working for me</p>
<pre><code>lists = soup.find_all(['article','div'])
str = ""
for list in lists:
info= list.text
str+=info
</code></pre> | python|pandas|web-scraping|jupyter-notebook|word-cloud | 0 |
4,861 | 59,016,143 | Why doesn't iLocation based boolean indexing work? | <p>I was trying to filter a Dataframe and thought that if a <code>loc</code> takes a boolean list as an input to filter, it should also work in the case for <code>iloc</code>. Eg. </p>
<pre><code>import pandas as pd
df = pd.read_csv('https://query.data.world/s/jldxidygjltewualzthzkaxtdrkdvq')
df.iloc[[True,False,True... | <p>It is not <a href="https://github.com/pandas-dev/pandas/issues/17454#issuecomment-327645521" rel="noreferrer">bug</a>:</p>
<blockquote>
<p>this is by-definition not allowed. <strong>.iloc</strong> is purely positional, so it doesn't make sense to align with a passed Series (which is what all indexing operations d... | python|pandas | 5 |
4,862 | 58,732,447 | Unable to resize image with cv2 | <p>I'm trying to resize cifar10 image set from 32x32 to 96x96.</p>
<pre><code>(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
train_images_reshaped = np.array((50000, 96, 96, 3,))
for a in range(len(train_images)):
train_images_reshaped[a] = cv2.resize(train_images[a], dsize=(96, 96... | <p>I think you meant to do </p>
<pre><code>train_images_reshaped = np.zeros((50000, 96, 96, 3,))
</code></pre>
<p>instead of </p>
<pre><code>train_images_reshaped = np.array((50000, 96, 96, 3,))
</code></pre> | python|numpy|keras|cv2 | 1 |
4,863 | 58,860,589 | Cloud9 deploy hitting size limit for numpy, pandas | <p>I'm building in Cloud9 to deploy to Lambda. My function works fine in Cloud9 but when I go to deploy I get the error</p>
<blockquote>
<p>Unzipped size must be smaller than 262144000 bytes</p>
</blockquote>
<p>Running <code>du -h | sort -h</code> shows that my biggest offenders are:</p>
<ul>
<li><code>/debug</c... | <p><strong>A brief background to understand the problem root-cause</strong></p>
<p>The problem is not with your function but with the size of the zipped packages. As per AWS <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html" rel="nofollow noreferrer">documentatio... | pandas|aws-lambda|aws-cloud9 | 3 |
4,864 | 58,792,218 | How to ensure no singleton expansion in numpy is made | <p>Coming from MATLAB to NumPy, the distinction between 2 dimensional array where one of the dimensions equalsl 1 to 1D array is annoying.</p>
<p>For example:</p>
<pre><code>>>>import numpy as np
>>>x1 = np.array([[1],[2],[3]])
>>>x2 = np.array([1,2,3])
>>>x1.shape
(3, 1)
>>&... | <p>What you are getting is the result of broadcasting, which <code>numpy</code> implemented long before MATLAB. Even Octave had it before MATLAB.</p>
<p>You have a (3,1) and a (3,). A leading dimension is added to the lower dim, producing (1,3). Together those broadcast to (3,3), and do the math.</p>
<p>If you cou... | python|numpy | 1 |
4,865 | 58,922,742 | JupyterLab notebook on Google AI Platform superslow when making predictions | <p>I have uploaded a trained tensorflow v2 model onto the Google AI Platform to make predictions on unseen data.
This data is stored in Google Cloud Storage in shards, each c 300 MB large.</p>
<p>I am using a notebook to preprocess the data, which works fine.
When making predictions on the preprocessed data, it works ... | <p>When trying to optimize the a model for serving the most impotant considerations are</p>
<p>1: Model size</p>
<p>2: Prediction speed</p>
<p>3: Prediction throughput</p>
<p>Several techniques exist in TensorFlow that will allow you to shrink the size of a model and improve prediction latency.As per offical docume... | python-3.x|google-cloud-platform|tensorflow2.0|jupyter-lab|gcp-ai-platform-notebook | 0 |
4,866 | 58,853,889 | Creating two shifted columns in grouped pandas data-frame | <p>I have looked all over and I still can't find an example of how to create two shifted columns in a Pandas Dataframe within its groups. </p>
<p>I have done it with one column as follows:</p>
<pre><code>data_frame['previous_category'] = data_frame.groupby('id')['category'].shift()
</code></pre>
<p>But I have to do ... | <p>It is possible by custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a>, because one column need shift down and second shift up:</p>
<pre><code>df = pd.DataFrame({
'B':[4,5,4,5... | python|pandas|dataframe | 2 |
4,867 | 70,105,227 | Numpy: How to find the ratio between multiple channels and assign index of a particular channel if it's ratio is higher than a threshold value | <p>I have numpy array(Dimension : N * X * Y) of N channels. I need to find the ratio for each X,Y between the N channels. Create a new array (Dimension : X * Y) and assign the index of a particular channel (say N =1) if its ratio is greater than a threshold value else assign the maximum value index. Say there are 2 cha... | <p><code>channel1 = arr[0, :, :]</code> will get the values in channel 1 as an X by Y array.
<code>channel2 = arr[1, :, :]</code> will get the values in channel 2. Then <code>channel1 / channel2 > 0.4</code> will give you an X by Y array with True in any spot where the ratio is more than 0.4. You can convert this to... | numpy | 0 |
4,868 | 56,181,198 | following line take lot of time to update since it has nearly 2.5l records are present | <p>In one dataframe i took group count which is more than one,need to update those index sepcific column value since its 2.5l it is failing with memory error is there any fast solution for it?</p>
<pre><code>gl_no=primary.groupby('GL Account').filter(lambda x:len(x)>1)
primary_index=primary[primary['GL Account'].... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferr... | pandas | 0 |
4,869 | 56,154,199 | How can I simplify adding columns with certain values to my dataframe? | <p>I have a big dataframe (more than 900000 rows) and want to add some columns depending on the first column (Timestamp with date and time). My code works, but I guess it's far too complicated and slow. I'm a beginner so help would be appreciated! Thanks!</p>
<pre><code>df['seconds_midnight'] = 0
df['weekday'] = 0
df[... | <p>If the column is a datetime64/Timestamp column you can use the <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#dt-accessor" rel="nofollow noreferrer">.dt accessor</a>:</p>
<pre><code>In [11]: df = pd.DataFrame(pd.date_range('2019-01-23', periods=3), columns=['date'])
In [12]: df
O... | python|pandas | 0 |
4,870 | 56,345,215 | How to convert stacked columns with duplicate indices into multiple unique columns with pandas? | <p>I'm working with a cryptocurrency time-series data-set which has all of the different currencies vertically stacked. It has 3 columns for the date, currency and price. There date ranges are also different for each currency.</p>
<p>i.e.</p>
<pre><code>>>> df
Currency Date Price
0 0x ... | <p>Pandas <code>pivot_table</code> could help here. I would use:</p>
<pre><code>resul = df.pivot_table(index=['Date'], columns=['Currency'], values=['Price']).fillna(0)
</code></pre>
<p>With your example data, it gives:</p>
<pre class="lang-none prettyprint-override"><code> Price
Currency ... | python|pandas | 2 |
4,871 | 56,302,920 | Reverse Binary Encoding with Pandas | <p>I have a Pandas Dataframe and wish to reverse the binary encoding (i.e. <code>get_dummies()</code>) of three columns. The encoding is left-to-right: </p>
<pre><code> a b c
0 0 1 1
1 0 0 1
2 1 1 1
3 1 0 0
</code></pre>
<p>would result in a new categories column <code>C</code> taking ... | <p>Use numpy if performance is important - first convert DataFrame to numpy array and then use <a href="https://stackoverflow.com/a/15506055/2901002">bitwise shift</a>:</p>
<pre><code>a = df.values
#pandas 0.24+
#a = df.to_numpy()
df['C'] = a.dot(1 << np.arange(a.shape[-1]))
print (df)
a b c C
0 0 1 1 ... | python|pandas | 2 |
4,872 | 56,014,057 | Error while trying to load tensorflowJS model from local, Fetch API cannot load downloads://model. URL scheme must be"https" for CORS request error | <p>I am trying to load a tensorflow js model that is saved in downloads directory as mentioned in the tutorials of tensorflowjs. But I am facing cors error please find the image below.</p>
<p>Code:</p>
<pre><code><html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.... | <p>The protocol you specified looks invalid. You can specify <code>file://</code> or just omitting it should work. And also you need to specify the path to <code>model.json</code> file created by <a href="https://github.com/tensorflow/tfjs-converter" rel="nofollow noreferrer">tfjs-converter</a>. So overall, the code to... | google-chrome|tensorflow.js | 0 |
4,873 | 55,705,361 | Filter multiindex df based on std | <pre><code>df.groupby(['name','cat'])['valtocount'].agg('count')
</code></pre>
<p>through the above I get the following multindex df:</p>
<pre><code>name cat count
abc a 1
b 1
def a 1
c 2
</code></pre>
<p>I want to keep only the names where the std of count is >0
do you guys have any suggestion?<... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <code>std</code> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.nunique.html" r... | python|pandas|multi-index | 1 |
4,874 | 55,926,313 | Duplicating rows in a DataFrame based on column value | <p>Below is a set of sample data I am working with:</p>
<pre><code>sample_dat = pd.DataFrame(
np.array([[1,0,1,1,1,5],
[0,0,0,0,1,3],
[1,0,0,0,1,1],
[1,0,0,1,1,1],
[1,0,0,0,1,1],
[1,1,0,0,1,1]]),
columns=['var1','var2','var3','var4','var5','... | <p>Create an empty dataframe then iterate over your data, appending each row to the new dataframe x amount of times where x is the number in the 'cnt' column.</p>
<pre><code>df =pd.DataFrame()
for index, row in sample_dat.iterrows():
for x in range(row['cnt']):
df = df.append(row, ignore_index=True)
</cod... | python|pandas|numpy | 0 |
4,875 | 55,972,556 | ValueError: Cannot feed value of shape 'x' for Tensor 'y', which has shape 'z | <p>A complete rookie here, trying to run the code. The problem is that my shapes' dimensions do not coincide. Does anyone know which variables' dimensions should be changed?</p>
<p>I tried changing x or y dimensions right after assigning values to x and y but I still keep getting the error</p>
<pre class="lang-py pre... | <p>It seems like it is complaining about feeding <code>X</code> which has shape (100,) into <code>x</code> which is required to have shape (anything, 20, 44). This variable has the name “input” noted in the error.</p>
<p><code>x</code> and <code>y</code> are tensorflow placeholders rather than numpy arrays, and their ... | python|numpy|tensorflow|neural-network|reshape | 1 |
4,876 | 55,772,649 | bazel build tensorflow/tools/graph_transforms:transform_graph ERROR | <p>i have some problem when i want to transfer my model using bazel to convert it.<br>
i try this cmd: </p>
<pre><code>$ bazel build tensorflow/tools/graph_transforms:transform_graph
</code></pre>
<p>here are the error:</p>
<blockquote>
<p>ERROR: Skipping 'tensorflow/tools/graph_transforms:transform_graph': no su... | <p>In order to run that first command (<code>bazel build</code>) you must have a BUILD file at the specified directory, which in this case is <strong><em>tensorflow/tools/graph_transforms</em></strong>. Based on only the info you've provided, chances are you haven't actually cloned or downloaded the Tensorflow reposito... | python|tensorflow|model|bazel | 1 |
4,877 | 55,999,420 | Merge small pandas dataframe into larger, copying values by rule | <p>There are two dataframes, both with datetime objects in either 5 min, <code>df_05min</code>, or 15 min, <code>df_15min</code>, increments.</p>
<pre><code>df_05min = pd.DataFrame({'dt':['2008-10-2404:12:30',
'2008-10-2404:12:35',
'2008-10-2404:12:40',
... | <p>Here need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a> with outer join, what is not implemented, so possible solution is <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" ... | python|pandas | 1 |
4,878 | 64,668,703 | Iterate over list (2 dataframes in 1 list) | <p>I am importing 2 data frames at the same time:</p>
<pre><code>import pandas as pd
import numpy as np
import time
import glob
import os
msci_folder = 'C:/Users/Mike/Desktop/docs'
mscifile = glob.glob(msci_folder + "/*.csv")
dfs = []
for file in mscifile:
df = pd.read_csv(file)
dfs.append(df)
</cod... | <p>In your second <code>for</code> loop:</p>
<pre><code>for i, df in enumerate(dfs):
dfs = dfs.loc[dfs['URI'] == '/ID']
dfs.TIMESTAMP = dfs.TIMESTAMP.apply(lambda x: '%.3f' % x)
dfs.insert(0, 'Date', 0)
dfs['Date'] = [x[:8] for x in dfs['TIMESTAMP']]
dfs.to_csv('C:/Users/Mike/Desktop/docs/test.csv',... | python|pandas|list|iteration | 2 |
4,879 | 64,787,228 | read excel with password in python without column number | <p>Hi I would like to read an Excel file with Password in Python, I found the solution here:</p>
<p><a href="https://davidhamann.de/2018/02/21/read-password-protected-excel-files-into-pandas-dataframe/" rel="nofollow noreferrer">https://davidhamann.de/2018/02/21/read-password-protected-excel-files-into-pandas-dataframe... | <p>I think the best way to do this is to determine which is the last non-empty row and the last non-empty column. You could do this this way:</p>
<p>In my example I use a chart df from Spotify</p>
<pre><code>import xlwings as xw
filename_read = 'C:/Users/k_sego/spotifymall.xlsx'
wb = xw.Book(filename_read)
ws = wb.she... | python|excel|pandas|csv | 1 |
4,880 | 64,716,913 | Change column values in pandas df under different conditions / invert answers on 4-point likert-scale | <p>In a df I have some columns with answers on a 4-point Likert scale which I need to invert meaning I need to flip the values in each row of this column: 4->1, 2->3, 3->2, 4->1</p>
<p>I've tried this:</p>
<pre><code>questDay1Df.loc[questDay1Df['STAI_State_01'] == 4] = 1
questDay1Df.loc[questDay1Df['STAI_St... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">.replace()</a>, but I think this solution is more fun :)</p>
<pre><code>questDay1Df['STAI_State_01'] = np.abs(questDay1Df['STAI_State_01'] - 5)
</code></pre>
<br>
<p>The <code>.r... | python|pandas|dataframe | 1 |
4,881 | 64,708,946 | Pivoting a repeating Time Series Data | <p><a href="https://i.stack.imgur.com/ygdhh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ygdhh.png" alt="enter image description here" /></a>I am trying to pivot this data in such a way that I get columns like eg: AK_positive AK_probableCases, AK_negative, AL_positive.. and so on.</p>
<p>You can g... | <p>Just flatten the original MultiIndex column into tuples using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.to_flat_index.html" rel="nofollow noreferrer">.to_flat_index()</a>, and rearrange tuple elements into a new column name.</p>
<pre><code>df_pivoted.columns = [f"{i[1... | python-3.x|pandas|pivot|pandas-groupby|data-manipulation | 0 |
4,882 | 40,020,270 | Pandas groupby countif with dynamic columns | <p>I have a dataframe with this structure:</p>
<pre><code>time,10.0.0.103,10.0.0.24
2016-10-12 13:40:00,157,172
2016-10-12 14:00:00,0,203
2016-10-12 14:20:00,0,0
2016-10-12 14:40:00,0,200
2016-10-12 15:00:00,185,208
</code></pre>
<p>It details the number of events per IP address for a given 20 minute period. I need a... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a> of boolean mask by condition <code>df == 0</cod... | python|pandas|sum|multiple-columns|mean | 3 |
4,883 | 44,222,313 | pandas more efficient way to create dictionary object from csv to send as a post request | <p>Sample data:</p>
<pre><code>data = {'account': {0: 'ted',
1: 'ned',
2: 'bed',
3: 'fred',
4: 'med'},
'account_type': {0: 'Enterprise',
1: 'Enterprise',
2: 'Enterprise',
3: '',
4: 'Mid-Market'},
'rep': {0: 'bob', 1: 'sam', 2: 'sam', 3: 'bob', 4: 'tim'},
'id': {0: 5542, 1: 7118, 2: 5510, 3: 5872, 4: 5766},
'industry... | <p>A bit more succinct solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pandas.DataFrame.apply()</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow noreferrer"><... | python|pandas | 1 |
4,884 | 69,394,979 | translate docker run command (tensorflow-serving) into docker-compose | <p>Here is the docker run command:</p>
<pre><code>docker run -p 8501:8501 \
--name tfserving_classifier \
-e MODEL_NAME=img_classifier \
-t tensorflow/serving
</code></pre>
<p>Here is what I tried but I am not able to get the MODEL_NAME to work</p>
<pre><code> tensorflow-servings:
container_name: tfserving_classif... | <pre><code> tensorflow-servings:
container_name: tfserving_classifier
image: tensorflow/serving
environment:
- MODEL_NAME=img_classifier
ports:
- 8501:8501
</code></pre> | docker|tensorflow|tensorflow-serving | 1 |
4,885 | 69,336,227 | How to convert string representation list with mixed values to a list? | <p>How do can I convert a string that contains values that are both strings and numeric, given that the string within the list is not in quotes?</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col_1': ['[2, A]', '[5, BC]']})
print(df)
col_1
0 [2, A]
1 [5, BC]
col_1 [2, A]
Name: 0, dtype: object
</... | <p>You can first use a regex to add quotes around the potential strings (here I used letters + underscore), then use <code>literal_eval</code> (for some reason I have an error with <code>pd.eval</code>)</p>
<pre><code>from ast import literal_eval
df['col_1'].str.replace(r'([a-zA-Z_]+)', r'"\1"', regex=True).a... | python|pandas | 1 |
4,886 | 54,014,341 | unable to change dtype pandas python | <p>I'm working with a dataframe in <code>pandas</code> and I have a column with an <code>int64</code> data type. I need to convert this data type to a string so that I can slice the characters, taking the first 3 chars of the 5 character column. The code is as follows: </p>
<pre><code>trainer_pairs[:, 'zip5'] = trai... | <p>Here you should using <code>astype(str)</code></p>
<pre><code>trainer_pairs['zip5'] = trainer_pairs.zip5.astype(str)
</code></pre>
<hr>
<p>About your errors </p>
<pre><code>df=pd.DataFrame({'zip':[1,2,3,4,5]})
df.zip.astype(object)
Out[4]:
0 1
1 2
2 3
3 4
4 5
Name: zip, dtype: object
</code></pre... | string|pandas|slice | 1 |
4,887 | 66,277,350 | pandas: I need to slice single column into two column separated by commas | <p>I have a pandas data frame which includes a column with two values in it. That looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Co-Ordinates</th>
</tr>
</thead>
<tbody>
<tr>
<td>23.821352807207695, 90.40975987926335</td>
</tr>
<tr>
<td>23.812076990866696, 90.4308790732571... | <p>Use this code:
<a href="https://www.w3resource.com/pandas/series/series-str-split.php" rel="nofollow noreferrer">Str.split()</a></p>
<pre><code>df = pd.DataFrame(data = ['23.821352807207695, 90.40975987926335','23.812076990866696, 90.43087907325717'], columns = ['Coordinates'])
df[['Lat','Long']] = df['Coordinates']... | python|pandas|dataframe | 1 |
4,888 | 66,160,791 | Merging excel sheets using pandas | <p>I have a quick script using python and pandas thats supposed to compare two excel sheets, grab the information that i need and create a new file. However when it creates the new file or if i just print it for testing one of the columns is coming back empty depending on where i merge (left of right)</p>
<pre><code> ... | <p>I haven't double checked your merge, but rather than sending your merged data to a string, you should use
pd.to_excel()</p>
<p>something like:</p>
<pre><code>merge_data.to_excel('merged_data.xlsx', sheet_name='merged')
</code></pre>
<p>If you need to save multiple sheets, looks the documentation - there are directio... | python|excel|pandas | 1 |
4,889 | 66,030,470 | Plotly: How to show other values than counts for marginal histogram? | <p>I am trying to create a linked marginal plot above the original plot, with the same x axis but with a different y axis.</p>
<p>I've seen that in <code>plotly.express</code> package there are 4 options in which you can create marginal_x plot on a scatter fig, but they are all based on the same columns as x and y.</p>... | <p>I'm understanding your statement</p>
<blockquote>
<p>[...] and rate of something on my y-axis</p>
</blockquote>
<p>... to mean that you'd like to display a value on your histogram that is <em>not</em> count.</p>
<p><code>marginal_x='histogram'</code> in <code>px.scatter()</code> seems to be defaulted to show counts ... | python|pandas|plotly|plotly-python|plotly.graph-objects | 4 |
4,890 | 52,784,378 | Pandas reading a specific line in python with a csv file | <p>I want to read a specific line in a csv file in pandas on python.Here on this image I want to read the 19010101 date <a href="https://i.stack.imgur.com/lBuTQ.png" rel="nofollow noreferrer">enter image description here</a></p> | <p>You can specify the column you want to use</p>
<pre><code>df=read_csv(yourcsv.csv)
dates = df['DATE'].values.tolist()
print(dates[0])
</code></pre>
<p>Bunch of ways to do this, just depends on your requirements.
<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofol... | python|pandas | 1 |
4,891 | 52,698,072 | Dynamically building indexes to classify records in pandas | <p>I am trying to write a simple record classifier. I want to add a column whose value classifies a record. I want to codify my classification rules in a yaml, or similar file for maintenance purposes.</p>
<p>I am using Pandas as that seems to be the best way to do this with csv records in python. I am open to other s... | <p>Some points to note:</p>
<ol>
<li>Quotation marks denote strings in Python. Don't use them to surround calculation of Boolean masks.</li>
<li>Don't use chained indexing. It's <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow noreferrer">explicitly discourag... | python|string|pandas|indexing|series | 2 |
4,892 | 52,476,573 | selenium pandas dataframe constructor not properly called | <p>The purpose of this code is to scrape a web page and extract data from a table then convert it to pandas data frame.</p>
<p>The scraping and data extracting went well.</p>
<p>The output is like this:</p>
<p>Release Date</p>
<p>Time</p>
<p>Actual</p>
<p>Forecast</p>
<p>Previous</p>
<p>Sep 09, 2018 (Aug)</p>
... | <p>Just make changes to the last part</p>
<pre><code>df = pd.DataFrame(columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous'])
pos = 0
for table in wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//*[contains(@id,"eventHistoryTable")]//tr'))):
data = [item.text for item in table.find_eleme... | python|pandas|selenium | 1 |
4,893 | 46,348,826 | Using SQL commands in Python | <p>I used the following code in iPython in order to get some information from a database's table in the form of a pandas dataframe.</p>
<pre><code>import sqlite3
con = sqlite3.connect('-----.db')
a = pd.read_sql('SELECT * FROM table1, con)
c= con.cursor
</code></pre>
<p>I have table 1 as a dataframe named a. Howeve... | <p>You just write the full sql command directly using read_sql.</p>
<pre><code>sql = """
select col1 from
tablea inner join tableb
on tablea.col2 = tableb.col2
where tablea.col3 < 10
limit 10
"""
a = pd.read_sql(sql, con)
</code></pre> | sqlite|pandas | 0 |
4,894 | 46,269,491 | Tensorflow Serving of Saved Model ssd_mobilenet_v1_coco | <p>I have looked on several posts on stackoverflow and have been at it for a few days now, but alas, I'm not able to properly serve an object detection model through tensorflow serving. </p>
<p>I have visited to the following links:
<a href="https://stackoverflow.com/questions/45362726/how-to-properly-serve-an-object-... | <p>You need to change the export signature somewhat from what the original post did. This script does the necessary changes for you:</p>
<pre><code> $OBJECT_DETECTION_CONFIG=object_detection/samples/configs/ssd_mobilenet_v1_pets.config
$ python object_detection/export_inference_graph.py \ --input_type encoded_image_... | tensorflow|object-detection|tensorflow-serving|google-cloud-ml | 4 |
4,895 | 58,555,782 | Using generators on networks ending with tensorflow probability layer | <p>I have a network which ends with probability layer something like this: </p>
<pre class="lang-py prettyprint-override"><code>model = tfk.Sequential([
tfkl.InputLayer(10),
tfkl.Dense(tfpl.MultivariateNormalTriL.params_size(2)),
tfpl.MultivariateNormalTriL(2)])
</code></pre>
<p>An... | <p>Maybe you could add one more layer:</p>
<pre><code>model = tfk.Sequential([
tfkl.InputLayer(10),
tfkl.Dense(tfpl.MultivariateNormalTriL.params_size(2)),
tfpl.MultivariateNormalTriL(2),
tfkl.Lambda(lambda x: tf.transpose(x.sample(100), perm=[1,0,2]))])
</code></pre>
<p>and then use </p>
<pre><code>... | python|tensorflow|tensorflow-datasets|tf.keras|tensorflow-probability | 0 |
4,896 | 58,398,772 | numpy array: efficient way to compute argmax within a fixed window at a set of rows and columns given as input | <p>Lets assume we have a 2D array <code>arr</code>, a set of positions defined by <code>rows</code> and <code>cols</code>, and a window of shape <code>(5, 1)</code>. For <code>(i, j)</code>, we need the index of the max value within <code>arr[i-2:i+2, j]</code>. We want to repeat for all input <code>(i, j)</code> pairs... | <p>We can leverage <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> based <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow noreferrer"><code>sciki... | python|arrays|numpy | 1 |
4,897 | 58,547,216 | Trouble importing Excel fields into Python via Pandas - index out of bounds error | <p>I'm not sure what happened, but my code has worked today, however not it won't. I have an Excel spreadsheet of projects I want to individually import and put into lists. However, I'm getting a "IndexError: index 8 is out of bounds for axis 0 with size 8" error and Google searches have not resolved this for me. An... | <blockquote>
<p>"IndexError: index 8 is out of bounds for axis 0 with size 8" </p>
</blockquote>
<pre><code>cols = [0,1,2,3,4,5,6,7,8]
</code></pre>
<p>should be <code>cols = [0,1,2,3,4,5,6,7]</code>.</p>
<p>I think you have 8 columns but your col has 9 col index.</p> | python|excel|pandas|numpy|text | 3 |
4,898 | 69,072,900 | How to create a dictionary from a xls file with multiple rows/columns | <p>I'm trying to create a dictionary of dictionaries from a file with multiple columns.
Basically what I want is to have the first column as the key and the remaining columns as values.
I am stuck on the following:</p>
<pre><code>import pandas as pd
from openpyxl import load_workbook
from pandas import DataFrame
epito... | <p>There is a method that does exactly that, <em>DataFrame.to_dict</em>.</p>
<p>Check this: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html</a></p>
<pre><... | python|pandas|dictionary|openpyxl | 0 |
4,899 | 69,073,297 | Pandas: Compare rows within groups in a dataframe and create summary rows to mark / highlight different entries in group | <p>I have a pandas dataframe with approx. 1200 rows, where some of the rows are duplicated multiple times. The df looks like this:</p>
<pre><code>ID Serial Age Grade Chem Bio Math Phy
M001 2 52 37 1 1 1 1
M001 2 55 37 2 1 0 1
M001 3 51 36,5 1 1 ... | <p>You can create a comparison marking table by grouping on <code>ID</code> and <code>Serial</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> and get the number of unique entries for each column by <a hr... | python|pandas|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.