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 |
|---|---|---|---|---|---|---|
100 | 58,107,632 | Speed up search of array element in second array | <p>I have a pretty simple operation involving two not so large arrays:</p>
<ol>
<li>For every element in the first (larger) array, located in position <code>i</code></li>
<li>Find if it exists in the second (smaller) array</li>
<li>If it does, find its index in the second array: <code>j</code></li>
<li>Store a float t... | <p>In defense of my approach, here is the authoritative implementation:</p>
<pre><code>import itertools as it
def pp():
la,lb = len(ids_a),len(ids_b)
ids = np.fromiter(it.chain(ids_a,ids_b),'<S6',la+lb)
unq,inv = np.unique(ids,return_inverse=True)
vals = np.empty(la,vals_in_a.dtype)
vals[inv[:l... | python|arrays|performance|numpy | 1 |
101 | 34,157,574 | Complex integration in Python | <p>There is a MATLAB function <a href="http://uk.mathworks.com/help/matlab/ref/quadgk.html" rel="nofollow noreferrer"><code>quadgk</code></a> that can compute complex integrals, or at least functions with poles and singularities. In Python, there is a general-purpose <code>scipy.integrate.quad</code> which is handy for... | <p>I don't think SciPy does provide an equivalent of MATLAB's <code>quadgk</code>, but for what it's worth the code you link to in <a href="https://stackoverflow.com/questions/5965583/use-scipy-integrate-quad-to-integrate-complex-numbers">this question</a> can be made to work in Python 3 with only minor changes:</p>
<... | python|matlab|function|numpy|scipy | 1 |
102 | 34,326,939 | OpenCV createCalibrateDebevec.process is giving me "dst is not a numpy array, neither a scalar" | <p>I'm currently trying to do some HDR processing with OpenCV's python wrapper.</p>
<pre><code>import cv2
import numpy as np
img = cv2.imread("1.jpg")
img2 = cv2.imread("2.jpg")
img3 = cv2.imread("3.jpg")
images = [img, img2, img3]
times = [-2, 0, 2]
response = np.zeros(256)
import ipdb; ipdb.set_trace()
calibrate ... | <p>You should use call</p>
<pre><code>calibrate.process(images, times, response)
</code></pre>
<p>or</p>
<pre><code>response = calibrate.process(images, times)
</code></pre>
<p>instead of</p>
<pre><code>calibrate.process(images, response, times)
</code></pre>
<p>because python <code>CalibrateDebevec</code>'s <cod... | python|c++|arrays|opencv|numpy | 1 |
103 | 37,140,223 | How to sort data frame by column values? | <p>I am relatively new to python and pandas data frames so maybe I have missed something very easy here.
So I was having data frame with many rows and columns but at the end finally manage to get only one row with maximum value from each column. I used this code to do that:</p>
<pre><code>import pandas as pd
d = {'A'... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html"><code>max</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html"><code>nlargest</code></a>, because <code>nlargest</code> sorts output:</p>
<pre><code>print df.m... | python-2.7|pandas|dataframe | 6 |
104 | 36,897,366 | pandas to_html using the .style options or custom CSS? | <p>I was following <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="noreferrer">the style guide for pandas</a> and it worked pretty well. </p>
<p>How can I keep these styles using the to_html command through Outlook? The documentation seems a bit lacking for me.</p>
<pre><code>(df.style
.forma... | <p>Once you add <code>style</code> to your chained assignments you are operating on a <code>Styler</code> object. That object has a <code>render</code> method to get the html as a string. So in your example, you could do something like this:</p>
<pre><code>html = (
df.style
.format(percent)
.applymap(col... | python|pandas|pandas-styles | 45 |
105 | 54,962,758 | Rotating a Geoplot polyplot | <p>I currently have the function:</p>
<pre><code>def cross_country(contiguous_usa, full_geo_data):
full_geo_data['Coordinates'] = full_geo_data[['longitude', 'latitude']].values.tolist()
full_geo_data['Coordinates'] = full_geo_data['Coordinates'].apply(Point)
full_geo_data = gpd.GeoDataFrame(full_geo_data... | <p>The easiest answer likely involves the projection or crs you are using. However, if you can't get that to work, you can use shapely to modify individual rows of the geodataframe. </p>
<pre><code>def rotator(row):
row['geometry'] = shapely.affinity.rotate(row['geometry'], -90)
return row
full_geo_data = ful... | python|pandas|geopandas | 0 |
106 | 54,814,133 | Catch numpy ComplexWarning as Exception | <p>Consider the following example:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1.0, 2.1j])
>>> b = np.array(a, dtype=np.float64)
/Users/goerz/anaconda3/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
#!/Users/goerz/anaconda3/bin/python
... | <p>Using <a href="https://docs.python.org/3/library/warnings.html#the-warnings-filter" rel="nofollow noreferrer">stdlib warnings filter</a> causes these to raise instead of print:</p>
<pre><code>>>> warnings.filterwarnings(action="error", category=np.ComplexWarning)
>>> b = np.array(a, dtype=np.float... | python|numpy | 4 |
107 | 73,416,293 | Python Protocol for Building a `pandas.DataFrame` | <p>Hello SO and community!</p>
<p>Guess, my question somewhat resonates with <a href="https://stackoverflow.com/questions/72798903/is-there-a-way-to-specify-a-protocol-for-a-pandas-dataframe">this one</a>.</p>
<p>However, trust the below task is a little bit different from that referenced above, namely to extract, tran... | <p>All the functions of ETLCanadaFixedAssets and ETL classes should return self. This will allow you to call the functions of the class on the return value of the functions, so you can chain them together. You could add one more function that retrieves the encapsulated dataframe but that will always be called last, as ... | python|pandas|dataframe|protocols | 1 |
108 | 35,261,581 | Change format for data imported from file in Python | <p>My data file is Tab separated and looks like this:</p>
<pre><code>196 242 3 881250949
186 302 3 891717742
22 377 1 878887116
244 51 2 880606923
166 346 1 886397596
298 474 4 884182806
115 265 2 881171488
253 465 5 891628467
305 451 3 886324817
... ... .. .........
</code></pre>
<p>I imported t... | <p>I've solved this, turn out I miss the <code>dtype</code> argument , so the script should look like this:</p>
<pre><code>from numpy import loadtxt
np_data = loadtxt('u.data',dtype=int ,delimiter='\t', skiprows=0)
print(np_data)
</code></pre>
<p>and done</p> | python|python-2.7|numpy | 1 |
109 | 34,932,739 | Python: numpy shape confusion | <p>I have a numpy array:</p>
<pre><code>>>> type(myArray1)
Out[14]: numpy.ndarray
>>> myArray1.shape
Out[13]: (500,)
</code></pre>
<p>I have another array:</p>
<pre><code>>>> type(myArray2)
Out[14]: numpy.ndarray
>>> myArray2.shape
Out[13]: (500,1)
</code></pre>
<p>( 1 ) What i... | <p>(1) The difference between (500,) and (500,1) is that the first is the shape of a one-dimensional array, while the second is the shape of a 2-dimensional array whose 2nd dimension has length 1. This may be confusing at first since other languages don't make that distinction.</p>
<p>(2) You can use np.reshape to do ... | python|numpy | 6 |
110 | 35,097,837 | Capture video data from screen in Python | <p>Is there a way with Python (maybe with OpenCV or PIL) to continuously grab frames of all or a portion of the screen, at least at 15 fps or more? I've seen it done in other languages, so in theory it should be possible. </p>
<p>I do not need to save the image data to a file. I actually just want it to output an arra... | <p>With all of the above solutions, I was unable to get a usable frame rate until I modified my code in the following way:</p>
<pre><code>import numpy as np
import cv2
from mss import mss
from PIL import Image
bounding_box = {'top': 100, 'left': 0, 'width': 400, 'height': 300}
sct = mss()
while True:
sct_img = ... | python|opencv|numpy|screenshot | 32 |
111 | 31,072,305 | Replace a value in MultiIndex (pandas) | <p>In the following DataFrame: How can I replace <code>["x2", "Total"]</code> with <code>["x2", "x2"]</code> leaving <code>x1</code> as is?</p>
<pre><code>l1 900 902 912 913 916
l2 ИП ПС ИП ПС ИП ПС ИП ПС ИП ПС
i1 i2
x1 Total 10 ... | <p>Assuming your dataframe is called df the following code will perform your desired substitution by replacing the existing index with a modified index.</p>
<pre><code>index = df.index
names = index.names
index = df.index.tolist()[:1]+[('x2','x2')]
df.index = pd.MultiIndex.from_tuples(index, names = names)
</code></... | python|pandas|dataframe|multi-index | 8 |
112 | 67,217,354 | How to access Artifacts for a Model Endpoint on Unified AI Platform when using Custom Containers for Prediction? | <p>Because of certain VPC restrictions I am forced to use custom containers for predictions for a model trained on Tensorflow. According to the documentation requirements I have created a HTTP server using Tensorflow Serving. The Dockerfile used to build the image is as follows:</p>
<pre><code>FROM tensorflow/serving:2... | <p>In the <a href="https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#artifacts" rel="nofollow noreferrer">documentation</a>, it is explained that Vertex AI creates and manages a copy of the model artifacts that are passed when creating a model. The URI of the model artifact bucket manage... | docker|tensorflow|google-cloud-platform|google-cloud-ml | 1 |
113 | 67,221,457 | How come I get "ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)." with text data? | <p>Using tensorflow, I am trying to convert a dataframe to a tds so that I can do some NLP work with it. It is all text data.</p>
<pre><code>>>> df.dtypes
title object
headline object
byline object
dateline object
text object
copyright category
country category
in... | <p>If you are using <code>tf.data.Dataset.from_tensor_slices</code> you have to first convert your data into a numpy array. Also, since this is using text data, you also need to tokenize your data.</p>
<pre><code># Create new index
train_idx = [i for i in range(len(train.index))]
test_idx = [i for i in range(len(test.i... | python|pandas|numpy|tensorflow | 0 |
114 | 67,442,037 | Subset permutation of one column based on the category of another column in pandas | <p>Here is one simplified case:</p>
<pre><code>df = pd.DataFrame({'col1': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'col2': ['a', 'b', 'c', 'A', 'C', 'B', 'red', 'blue', 'greed']})
</code></pre>
<p>I want to do subset permutation on col2 with reference to col1. For example, only permute 'a', 'b', 'c' in col2 for they belong to cate... | <pre><code>df['col2'] = df.groupby('col1', as_index=False).col2.transform(np.random.permutation)
df
</code></pre>
<p><strong>Output</strong></p>
<pre><code> col1 col2
0 1 c
1 1 b
2 1 a
3 2 B
4 2 A
5 2 C
6 3 red
7 3 greed
8 3 blue
</code></pre> | pandas|subset|permutation | 1 |
115 | 67,282,736 | How to skip rows with wrong data types of an dataset using python | <p>Have been working on the dataset cleaning and processing the data for further analysis, I have used different cleaning scripts.</p>
<p>My script gets aborted whenever there is any unwanted / unexceptional data comes up in between the dataset columns, The script execution gets stuck and rest of the data doesn't gets ... | <p>I don't think I quite understand the problem.</p>
<p>I have always just done it this way never had problems..</p>
<pre><code>import pandas as pd
FileLocation = (r'Test.xlsx')
df = pd.read_excel(FileLocation, sheet_name='sheet1')
print(df.head)
</code></pre>
<p>and then you can use a for each loop to iterate over you... | python|pandas|dataframe | 0 |
116 | 60,189,328 | Arbitrary number of different groupby levels in one go | <p>Is there a way to compute arbitrary number of different groupby levels in one go with some pre-built Pandas function?
Below is a simple example with two columns.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame( {
"name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
"city" : ["Seattle... | <p>Assuming you look for a general way to create all the combinations in the <code>groupby</code>, you can use <a href="https://docs.python.org/3.8/library/itertools.html#itertools.combinations" rel="nofollow noreferrer">itertools.combinations</a>:</p>
<pre><code>from itertools import combinations
col_gr = ['name', '... | python|pandas|pandas-groupby | 1 |
117 | 60,197,294 | Error when using pandas dataframe in R cell, in rpy2, Jupyter Notebook | <p>I want to use <code>ggplot2</code> within <code>Jupyter Notebook</code>. However, when I try to make an R magic cell and introduce a variable, I get an error.</p>
<p>Here is the code (one paragraph indicates one cell):</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sea... | <p>The problem is most likely with one (or more) columns having more than one type - therefore it is impossible to transfer the data into an R vector (which can hold only one data type). The traceback may be overwhelming, but here is the relevant part:</p>
<pre><code>ValueError: Series can only be of one type, or None... | python|r|pandas|jupyter-notebook|rpy2 | 4 |
118 | 60,308,484 | How do I find the mean of summed values across multiple Dataframes? | <p>Edit: I've realized that I did not ask my question in the right way. I'm not going to accept one answer over another, but am going to leave all content here for anyone's future use.</p>
<p>I have a value that I'm looking to compute across on-going DataFrames.</p>
<p>I have df1:</p>
<pre><code>Name | Col1 |... | <p>Probably you can use <code>pd.merge</code>:</p>
<pre><code>df2 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[7,7,4,np.nan], 'Col2':[1,2,np.nan,2]})
df3 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[3,1,np.nan,np.nan], 'Col2':[3,6,9,np.nan]})
dfn = pd.merge(df... | python|pandas|dataframe | 0 |
119 | 65,346,131 | What's the best way of converting a numeric array in a text file to a numpy array? | <p>So I'm trying to create an array from a text file, the text file is laid out as follows. The numbers in the first two columns both go to 165:</p>
<pre><code>0 0 1.0 0.0
1 0 0.0 0.0
1 1 0.0 0.0
2 0 -9.0933087157900000E-5 0.0000000000000000E+00
2 1 -2.7220323615900000E-09 -7.5751829208300000E-1... | <p>Your data appear to be in a COO sparse matrix format already. This means, that you could use your own function, but you could also capitalize on the work done in the <code>scipy.sparse</code> package.</p>
<p>For example this code creates a function that would generate one of your matrices at a time. You could modify... | python-3.x|numpy | 0 |
120 | 65,426,278 | to_sql() method of pandas sends primary key column as NULL even if the column is not present in dataframe | <p>I want to insert a data frame into the <em><strong>Snowflake</strong></em> database table. The database has columns like <code>id</code> which is a <code>primary_key</code> and <code>event_id</code> which is an <code>integer</code> field and it's also <code>nullable</code>.</p>
<p>I have created a <code>declarative_... | <p>Please note that <code>pandas.DataFrame.to_sql()</code> has by default parameter <code>index=True</code> which means that it will add an extra column (df.index) when inserting the data.</p>
<p>Some Databases like PostgreSQL have a data type <code>serial</code> which allows you to sequentially fill the column with in... | python|pandas|snowflake-cloud-data-platform | 1 |
121 | 50,216,866 | simplify a python numpy complex expression to real and imaginary parts | <p>The expression Exp(it) – Exp(6it)/2 + i Exp(-14it)/3 , for t going to 2*pi is for plotting a Mystery curve as explained in <a href="http://www.johndcook.com/blog/2015/06/03/mystery-curve/" rel="nofollow noreferrer">http://www.johndcook.com/blog/2015/06/03/mystery-curve/</a>
there is a listing of python numpy to plot... | <pre><code>In [37]: def f(t):
...: return np.exp(1j*t) - np.exp(6j*t)/2 + 1j*np.exp(-14j*t)/3
In [39]: t = np.linspace(0,2*np.pi, 10)
In [40]: t
Out[40]:
array([0. , 0.6981317 , 1.3962634 , 2.0943951 , 2.7925268 ,
3.4906585 , 4.1887902 , 4.88692191, 5.58505361, 6.28318531])
In [41]: f(t)
Out[41]... | numpy | 1 |
122 | 50,087,883 | tf.while_loop with flexible row numbers per iteration | <p>I am trying to fill a 2d array in a <code>tf.while_loop</code>. The thing is the result of my computation at each iteration returns a variable number of rows. Tensorflow does not seem to allow this.</p>
<p>See this minimal example that reproduce the issue:</p>
<pre class="lang-py prettyprint-override"><code>indice... | <p>Here's a nested <code>while_loop</code> solution which writes to a single <code>TensorArray</code>:</p>
<pre><code>import tensorflow as tf
def make_inner_loop_body(total_size, anchor):
def _inner_loop_body(j, ta):
return j + 1, ta.write(total_size + j, anchor[j])
return _inner_loop_body
def loop_body(i,... | tensorflow|vector|tensor | 1 |
123 | 50,065,295 | Delimit array with different strings | <p>I have a text file that contains 3 columns of useful data that I would like to be able to extract in python using numpy. The file type is a *.nc and is <strong>NOT</strong> a netCDF4 filetype. It is a standard file output type for CNC machines. In my case it is sort of a CMM (coordinate measurement machine). The... | <p>You can use Pandas</p>
<pre><code>import pandas as pd
from io import StringIO
#Create a mock file
ncfile = StringIO("""X0.8523542Y0.0000000Z0.5312869
X0.7523542Y1.0000000Z0.5312869
X0.6523542Y2.0000000Z0.5312869
X0.5523542Y3.0000000Z0.5312869""")
df = pd.read_csv(ncfile,header=None)
#Use regex with split to def... | python-3.x|numpy|csv | 1 |
124 | 63,799,471 | How do I not write the first column to an Excel file using Python? | <p>I use the following code to move data from one Excel file to another.</p>
<pre><code>import pandas as pd
inventory = pd.read_excel('Original_File.xlsx', skiprows=3)
inventory.to_excel('New_File.xlsx')
</code></pre>
<p>How do I NOT write the content in column 1 to the new Excel file? Column 1 contains a blank column ... | <h2>Problem</h2>
<p>By default, <code>to_excel</code> write row names (index) out.</p>
<h2>Solution</h2>
<p>when you call <code>to_excel</code>, you can skip the row name by setting parameter <code>index</code> as <code>False</code>:</p>
<p><code>inventory.to_excel('New_File.xlsx', index=False)</code></p>
<h2>Reference... | python|excel|pandas | 0 |
125 | 64,157,447 | Pandas: Collapse rows in a Multiindex dataframe | <p>Below is my df:</p>
<pre><code>df = pd.DataFrame({'A': [1, 1, 1, 2],
'B': [2, 2, 2, 3],
'C': [3, 3, 3, 4],
'D': ['Cancer A', 'Cancer B', 'Cancer A', 'Cancer B'],
'E': ['Ecog 9', 'Ecog 1', 'Ecog 0', 'Ecog 1'],
... | <p>Do you mean:</p>
<pre><code>df.set_index(list(df.columns[:-1])).T
</code></pre>
<p>Output:</p>
<pre><code>A 1 2
B 2 3
C 3 4
D Cancer A Cancer B Cancer A Cancer B
E Ecog 9 Ecog 1... | python|python-3.x|pandas|dataframe|multi-index | 4 |
126 | 64,160,528 | How to use cross validation in keras classifier | <p>I was practicing the keras classification for imbalanced data. I followed the official example:</p>
<p><a href="https://keras.io/examples/structured_data/imbalanced_classification/" rel="nofollow noreferrer">https://keras.io/examples/structured_data/imbalanced_classification/</a></p>
<p>and used the scikit-learn api... | <p>MilkyWay001,</p>
<p>You have chosen to use <code>sklearn</code> wrappers for your model - they have benefits, but the model training process is hidden. Instead, I trained the model separately with validation dataset added. The code for this would be:</p>
<pre><code>clf_1 = KerasClassifier(build_fn=build_fn,
... | python|pandas|tensorflow|keras|scikit-learn | 1 |
127 | 33,055,070 | "AttributeError: 'matrix' object has no attribute 'strftime'" error in numpy python | <p>I have a matrix with (72000, 1) dimension. This matrix involves timestamps.</p>
<p>I want to use "strftime" as the following; <code>strftime("%d/%m/%y")</code>, in order to get the output something like this: <code>'11/03/02'</code>.</p>
<p>I have such a matrix:</p>
<pre><code>M = np.matrix([timestamps])
</code><... | <p>As the error message shows you, you cannot do something like <code>matrix.strftime</code> . One thing you can do would be to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow"><code>numpy.apply_along_axis</code></a> . Example -</p>
<pre><code>np.apply_along_... | python|numpy|matrix|strftime | 2 |
128 | 38,839,402 | how to use assert_frame_equal in unittest | <p>New to unittest package.
I'm trying to verify the DataFrame returned by a function through the following code. Even though I hardcoded the inputs of <code>assert_frame_equal</code> to be equal (<code>pd.DataFrame([0,0,0,0])</code>), the unittest still fails. Anyone would like to explain why it happens?</p>
<pre><c... | <p>alecxe answer is incomplete, you can indeed use pandas' <code>assert_frame_equal()</code> with <code>unittest.TestCase</code>, using <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.addTypeEqualityFunc" rel="noreferrer"><code>unittest.TestCase.addTypeEqualityFunc</code></a></p>
<pre class=... | python|pandas|unit-testing|python-unittest | 23 |
129 | 63,188,345 | How can I remove the string element in a series in Python? | <p>I got a series name <code>basepay</code> that contains both String and Numeric element. What I wanted to do is to calculate the mean of the numeric part. I've tried <code>basepay.mean()</code> and the kernel return <code>TypeError: unsupported operand type(s) for +: 'float' and 'str'</code> So I tried to drop off th... | <p>it might be easiest to just use a try catch block inside the mask function
like</p>
<hr />
<pre><code>try:
float(basepay)
catch:
do something if it fails
</code></pre> | python|pandas|series | 1 |
130 | 63,310,083 | Dynamic range (bit depth) in PIL's fromarray() function? | <p>I did some image-processing on multi-frame TIFF images from a 12-bit camera and would like to save the output. However, the <a href="https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes" rel="nofollow noreferrer">PIL documentation</a> does not list a 12-bit mode for <code>fromarray()</code>. ... | <p>In my experience, 12-bit images get opened as 16-bit images with the first four MSB as all zeroes. My solution has been to convert the images to numpy arrays using</p>
<pre><code>arr = np.array(img).astype(np.uint16)
</code></pre>
<p>the astype() directive is probably not strictly necessary, but it seems like it's a... | arrays|numpy|save|python-imaging-library|bit-depth | 0 |
131 | 63,138,239 | Convert Matlab struct to python/numpy | <p>I have a small snippet of matlab code I would like to translate the python/numpy</p>
<pre><code>for i = 1:numel(order)
%This puts all output data into one variable, alongside the scan length
%and separation
plotout = [plotout; resout(i).output ...
repmat((i-1)*separation,[length(resout(i).output) 1]) ...
tra... | <p>That last line produces a column vector to be appended along side the other column vectors.</p>
<p>The code</p>
<p><code>(0 : 0.004712 : (length(resout(i).output)*0.004712)) - 0.004712</code></p>
<p>counts from <code>0</code> to <code>(length(resout(i).output)*0.004712)</code> at a step size of <code>0.004712</code>... | python|matlab|numpy | 0 |
132 | 31,732,415 | df.loc filtering doesn't work with None values | <p>Why does this filtering not work when the filter is <code>Project ID</code> == None? I also noticed <code>is None</code> rather than <code>== None</code> returns <code>KeyError: False</code> </p>
<pre><code>import pandas as pd
df = pd.DataFrame(data = [['Project1', 'CT', 800], [None, 3, 1000], ['Project3', 'CA', 2... | <p>You have to use <code>isnull</code> for this:</p>
<pre><code>In [3]:
df[df['Project ID'].isnull()]
Out[3]:
Project ID State Cost
1 None 3 1000
</code></pre>
<p>Or use <code>apply</code>:</p>
<pre><code>In [5]:
df.loc[df['Project ID'].apply(lambda x: x is None)]
Out[5]:
Project ID State Cost
1 ... | python|python-2.7|pandas | 5 |
133 | 41,295,405 | pandas change list of value into column | <p>I have a df like this and I want to change the list of value into column</p>
<p>```</p>
<pre><code> uid device
0 000 [1.0, 3.0]
1 001 [3.0]
2 003 [nan]
3 004 [2.0, 3.0]
4 005 [1.0]
5 006 [1.0]
6 006 [nan]
7 007 [2.0]
```
</code></pre>
<p>should be</p>
<p>```</p>
<pre><code> uid device ... | <p>You can use custom function <code>f</code> with list comprehensions, last cast <code>boolean</code> values to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>astype</code></a>:</p>
<pre><code>df = pd.DataFrame({'uid':['... | python|pandas | 1 |
134 | 41,339,701 | Python - change header color of dataframe and save it to excel file | <p>I have a dataframe <code>df</code> where i want to change the header background color, apply borders and save it excel file in .xlsx extension. </p>
<p>I have tried styleframe, some functionalities in openpyxl and tried to write udf s, But nothing seemed to work.</p> | <p>Here is the solution using <a href="https://github.com/DeepSpace2/StyleFrame" rel="nofollow noreferrer">StyleFrame</a> package that you mentioned.</p>
<pre><code>import pandas as pd
from styleframe import StyleFrame, Styler, utils
df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3]})
sf = StyleFrame(df)
sf.apply_hea... | python|excel|python-2.7|pandas | 3 |
135 | 61,370,341 | Remove a slice of seconds from every minute in pandas | <p>I was wondering how it is possible to remove a slice of time from bigger time unit. Let us say we have a dataset from a day and we want to remove the first 10 seconds of every minute from this day. How can I do this in Pandas or Numpy?</p>
<p>The example shows values in a range of 15 min and the values between 06 a... | <p>The previous solutions were not going to work because you don't have a DateTime column but a DateTimeIndex so the syntax is a bit different.</p>
<p>Your solution works, however, this can be solved by using a pandas function that vectorizes so you don't have to go day by day in a <code>for/while</code> loop</p>
<pr... | python|pandas|algorithm|time-series | 0 |
136 | 61,185,360 | The Tensorflow model can't completely delet and still occupy the CPU memory | <p>I'm working with optimize the the neural network architecture and hyperameters. For this reason, I build a for loop to sent in the hyperameters and build/train/evaluate a new model through each iteration. The example like that:</p>
<pre><code>for k in range(10):
#full_model() function is used to build the new m... | <p>Finally, this problem is resolved by change the OS to Windows. If anyone have wiser way to deal it in Ubuntu, welcome to give some suggestion or comment.</p> | python|tensorflow|keras|tensorflow2.0 | 0 |
137 | 68,792,428 | How can I parallelize np.matmul and np.multiply? | <p>I have a question about matrix calculation using numpy. How can I parallelize these calculation such as <code>np.matmul</code> and <code>np.multiply</code>? I cannot find any references describing how to compute np.matmul using parallelization.</p>
<pre><code>def time_shift_R(V, R_1, I0, t): # V is the potential fun... | <p>You might want to do some time tests to see what exactly is taking most time. For example on a rather modest machine with stock Ubuntu linux:</p>
<p>Make a complex array (you didn't cite any sizes so I'm just guessing as to something reasonable):</p>
<pre><code>In [60]: A = np.ones((1000,1000),complex)
</code></pre... | python|numpy|parallel-processing | 0 |
138 | 36,395,030 | How do I count the frequency against a specific list? | <p>I have a <code>DataFrame</code> that looks like this.</p>
<pre><code> date name
0 2015-06-13 00:21:25 a
1 2015-06-13 01:00:25 b
2 2015-06-13 02:54:48 c
3 2015-06-15 14:38:15 a
4 2015-06-15 15:29:28 b
</code></pre>
<p>I want to count the occurrences of dates against a specific date ran... | <p>I think you can first use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>date</code></a> from column <code>date</code> for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts... | python|pandas|dataframe | 2 |
139 | 36,646,854 | Combining regplot with piecewise linear regression on a Facetgrid with seaborn | <p>I want to plot on a grid my data with associated errorbars and a piecewise linear regression through the mean of each timepoint. I have my data in a pandas dataframe and would like to us seaborn to do the job. </p>
<p>If I use seaborns factorplot I get close.</p>
<pre><code>g = sns.factorplot(x="Time", y='value', ... | <p>After trawling the net and reading many of mwaskom's excellent answers it seems I have found a working solution</p>
<pre><code>def _plotmean(x, *args, **kwargs):
ax = plt.gca()
data = kwargs.pop('data')
data = data.groupby(x).mean()
data.plot(ax=ax, **kwargs)
Conc_norm.sort_values('Time', inplace=T... | python|pandas|seaborn | 2 |
140 | 65,829,670 | AttributeError: 'DataFrame' object has no attribute 'to_CSV' | <p>I'm trying to store my extracted chrome data into a csv format using df.to_CSV</p>
<p>here is my code :</p>
<pre><code>content = driver.page_source
soup = BeautifulSoup(content)
for a in soup.findAll('a',href=True, attrs={'class':'_13oc-S'}):
name=a.find('div', attrs={'class':'_4rR01T'})
price=a.find('div', ... | <p>It's case-sensitive, should be <code>df.to_csv(...)</code></p> | python|pandas|dataframe|selenium|beautifulsoup | 1 |
141 | 65,647,405 | Create a function for a number of lists and correctly group the list elements | <p>I have 3 lists, but sometimes only 2, that each contain 4 multi-index dataframes.</p>
<pre><code>list1=[df1, df2, df3, df4]
list2=[df1_, df2_, df3_, df4_]
list3=[df1__, df2__, df3__, df4__]
</code></pre>
<p>The next step is to create multi-index dataframes:</p>
<pre><code>reportTable1 = list1[0].round(2) #this dataf... | <ul>
<li>The following function will work if there are only two <code>lists</code> of <code>dataframes</code>.
<ul>
<li>The <code>lists</code> of <code>dataframes</code> are passed to the function as <a href="https://realpython.com/python-kwargs-and-args/#using-the-python-args-variable-in-function-definitions" rel="nof... | python|pandas|function|dataframe | 0 |
142 | 2,890,618 | What to beware of reading old Numarray tutorials and examples? | <p>Python currently uses Numpy for heavy duty math and image processing. </p>
<p>The earlier Numeric and Numarray are obsolete, but still today there are many tutorials, notes, sample code and other documentation using them. Some of these cover special topics of interest, some are well written but haven't been updat... | <p>Two good resources:</p>
<ol>
<li><a href="http://www.stsci.edu/resources/software_hardware/numarray/numarray2numpy.pdf" rel="nofollow noreferrer">Numarray to numpy guide</a></li>
<li><a href="http://www.scipy.org/Converting_from_Numeric" rel="nofollow noreferrer">Differences between Numeric and numpy</a></li>
</ol> | numpy | 3 |
143 | 63,708,496 | How to extract document embeddings from HuggingFace Longformer | <p>Looking to do something similar to</p>
<pre class="lang-py prettyprint-override"><code>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outpu... | <p>You wouldn't need to mess with those values (unless you want to optimize the way longformer attends to different tokens). In the example you've listed above it will enforce global attention to just the 1st, 4th and 21st token. They've put random numbers here but sometimes you might want to globally attend for a cert... | huggingface-transformers | 1 |
144 | 63,323,045 | find duplicated csv columns from list [python pandas] | <p>I want to find duplicate columns from a list, so not just any columns.</p>
<p>example of correct csv looks like this:</p>
<pre><code>col1, col2, col3, col4, custom, custom
1,2,3,4,test,test
4,3,2,1,test,test
</code></pre>
<p>list looks like this:</p>
<pre><code>columnNames = ['col1', 'col2', 'col3', 'col4']
</code><... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.duplicated.html" rel="nofollow noreferrer"><code>Index.duplicated</code></a> to crea... | python|python-3.x|pandas|dataframe|csv | 1 |
145 | 24,755,012 | Pandas Dataframe count availability of string in a list | <p>Lets say I have a Pandas <code>DataFrame</code> like following.</p>
<pre><code>In [31]: frame = pd.DataFrame({'a' : ['A/B/C/D', 'A/B/C', 'A/E','D/E/F']})
In [32]: frame
Out[32]:
a
0 A/B/C/D
1 A/B/C
2 A/E
3 D/E/F
</code></pre>
<p>And I have string list like following.</p>
<pre><code>In [33]:... | <p>You can do this way :</p>
<pre><code>In [1]: len(frame[frame.a.isin(mylist)])/float(len(mylist)) * 100
Out[1]: 66.66666666666666
</code></pre>
<p>Or with you method :</p>
<pre><code>In [2]: pattern = '|'.join(mylist)
In [2]: count = frame.a.str.contains(pattern).sum() # will add up True values
In [3]: count/float... | python|list|pandas | 1 |
146 | 24,754,496 | Pandas: Merge hierarchical data | <p>I am looking for a way to merge data that has a complex hierarchy into a pandas <code>DataFrame</code>. This hierarchy comes about by different inter-dependencies within the data. E.g. there are parameters which define how the data was produced, then there are time-dependent observables, spatially dependent observab... | <p>I think you should do something like this, putting <code>df_parms</code> as your index. This way you can easily concat more frames with different parms.</p>
<pre><code>In [67]: pd.set_option('max_rows',10)
In [68]: dfx = df_all_but_parms.copy()
</code></pre>
<p>You need to assign the columns to the frame (you can... | python|pandas|merge|dataframe | 2 |
147 | 53,693,237 | Search column for multiple strings but show faults Python Pandas | <p>I am searching a column in my data frame for a list of values contained in a CSV that I have converted to a list. Searching for those values is not the issue here. </p>
<pre><code>import pandas as pd
df = pd.read_csv('output2.csv')
hos = pd.read_csv('houses.csv')
parcelid_lst = hos['Parcel ID'].tolist()
result = d... | <p>After reconsidering my question and thinking about it a little bit differently, the solution I found is to turn all the values in the data frame in the 'PARID' column into a list. Then compare the 'parcelid_lst' to it. </p>
<p>This resulted in a list of all the values that did not exist in the data frame but did ex... | python|pandas | 0 |
148 | 53,414,818 | Python: How do I change a value in column A if another value in column B repeats itself? | <p>I have many excel files with the same columns in one folder. I need to browse each file and compare which values of the column "User Number" of one file are the same as the other file. And then manipulate another column named "Date" based on that. For exemple:</p>
<pre><code>A2018_02_01 file has:
User_Nu... | <p>My solution is to create a master mapper with all the min dates:</p>
<pre><code>master=pd.concat([df1, df2]).groupby('User_Number').min()
</code></pre>
<p>and then join each dataframe to the master to find the adjusted date:</p>
<pre><code>df1.join(master,rsuffix='_adj',on='User_Number')[['User_Number', 'Date_adj... | python|pandas|dataframe|series|glob | 2 |
149 | 53,563,828 | String processing in Python | <p>I have a text file from which I am trying to create a pandas DF</p>
<pre><code>Name John Doe
Country Wakanda
Month of birth January 1900
social status married
....
</code></pre>
<p>After every 4 lines a new record similar to that is present.
The structure of data frame I am trying to create it</p>
<pre><code> ... | <p>Perhaps an approach could be to have a list of potential matches for each of the entries, and for each entry iterate through this list and strip the key words in the case of a match.</p>
<p>As an example for an individual entry:</p>
<pre><code>text = 'Month of birth January 1900'
keys = ['Month of birth', 'Date of... | python|pandas | 0 |
150 | 53,447,500 | How do I initialise the plot of my function to start at 0? | <p>This is probably a really stupid question, but I just can't seem to work out how to do it for some reason. I've created a function for a random walk here which just uses the numpy binomial function with one trial (ie if it's under 0.5 it's -1, over it's +1. However this obviously makes the first value of the functio... | <p>Little tweak to your code. Hopefully this is what you're looking for.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def random_walk(N,d):
walk = np.concatenate(([0],np.cumsum(2*np.random.binomial(1,.5,N-1)-1)))
return walk
plt.plot(np.arange(0,250),random_walk(250,1))
plt.show()
</code... | python|numpy|matplotlib|random-walk | 0 |
151 | 15,951,488 | plotting dendrograms with scipy in Python | <p>The scipy <code>dendrogram</code> documentation says:</p>
<pre><code>dendrogram(Z, ...)
The dendrogram illustrates how each cluster is
composed by drawing a U-shaped link between a non-singleton
cluster and its children. ...It is expected that the distances in Z[:,2] be
monotonic, otherwise crossing... | <p>Z is supposed to specify merges of clusters (which 2 clusters are merged) and the "time" they happen, where "time" is the y-axis of the dendrogram (this is what they mean by distances). Z is usually constructed so that "time" is in increasing order, which also makes it easy to plot so that U shapes are not on top of... | python|numpy|scipy | 1 |
152 | 16,729,574 | How can I get a value from a cell of a dataframe? | <p>I have constructed a condition that extracts exactly one row from my data frame:</p>
<pre><code>d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
</code></pre>
<p>Now I would like to take a value from a particular column:</p>
<pre><code>val = d2['col_name']
</code></pre>... | <p>If you have a DataFrame with only one row, then access the first (only) row as a Series using <em><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer">iloc</a></em>, and then the value using the column name:</p>
<pre><code>In [3]: sub_df
Out[3]:
A... | python|pandas|dataframe | 731 |
153 | 22,326,882 | Construct single numpy array from smaller arrays of different sizes | <p>I have an array of values, <i>x</i>. Given 'start' and 'stop' indices, I need to construct an array <i>y</i> using sub-arrays of <i>x</i>.</p>
<pre><code>import numpy as np
x = np.arange(20)
start = np.array([2, 8, 15])
stop = np.array([5, 10, 20])
nsubarray = len(start)
</code></pre>
<p>Where I would like <i>y</i... | <p>This is a bit complicated, but quite fast. Basically what we do is create the index list based off vector addition and the use <code>np.take</code> instead of any python loops:</p>
<pre><code>def get_chunks(arr, start, stop):
rng = stop - start
rng = rng[rng!=0] #Need to add this in case of zero size... | python|arrays|optimization|numpy | 3 |
154 | 22,067,325 | What type of object does each column contain: getting more detail than dtypes | <p>I often find myself changing the types of data in columns of my dataframes, converting between datetime and timedelta types, or string and time etc. So I need a way to check which data type each of my columns has. </p>
<p>df.dtypes is fine for numeric object types, but for everything else just shows 'object'. So ho... | <p>You can inspect one of the cells to find the type.</p>
<pre><code>import pandas as pd
#assume some kind of string and int data
records = [["a",1], ["b",2]]
df = pd.DataFrame(records)
df.dtypes
>0 object
>1 int64
>dtype: object
</code></pre>
<p>So pandas knows that column 1 is integer storage but co... | pandas | 1 |
155 | 17,776,075 | Numpy: Is it possible to display numbers in comma-separated form, like 1,000,000? | <p>I have a numpy array like this:</p>
<pre><code>[ 1024 303 392 4847 7628 6303 8898 10546 11290
12489 19262 18710 20735 24553 24577 28010 31608 32196
32500 32809 37077 37647 44153 46045 47562 48642 50134
50030 52700 52628 51720 53844 56640 ... | <p>If you want to apply your printing preference globally; you could use <code>numpy.set_printoptions()</code>:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([338490, 340901, 340224])
>>> a
array([338490, 340901, 340224])
>>> np.set_printoptions(formatter={'int_kind': '{:,}... | python|arrays|numpy|scipy|number-formatting | 5 |
156 | 55,423,683 | Conditionally change year in DOB | <p>I have a 'date' column which I cleaned to change all dates to the same format (date/month/year).</p>
<p>Since originally some dates ended with the year being two digits eg. <code>2/7/95</code>, they got converted to <code>02/07/2095</code>. However, I need to change the year of those dates that are 21st century, to... | <p><code>dt.strftime</code> converts datetime to other formats, but then dtype of column will be object (string). </p>
<pre><code>df['date'] = pd.to_datetime(df['date']).apply(lambda x:
x - pd.DateOffset(years=100) if x.year >= 2000 else x)
</code></pre>
<p>If you want the same datetime formatting ag... | python|pandas|datetime | 0 |
157 | 55,517,960 | How do I find the minimum of a numpy matrix? (In this particular case) | <p>I have a numpy matrix as follows <br></p>
<pre><code>[['- A B C D E']
['A 0 2 3 4 5']
['B 2 0 3 4 5']
['C 3 3 0 4 5']
['D 4 4 4 0 5']
['E 5 5 5 5 0']]
</code></pre>
<p>How do I find the <strong>minimum</strong> in this matrix along with the <strong>index</strong> of this minimum, <strong>excluding</strong> all of ... | <p>You need to go back to the drawing board with your 'numpy' matrix, that is not an matrix, but a list of list of (single) string.</p>
<pre><code>x =['- A B C D E',
'A 0 2 3 4 5',
'B 2 0 3 4 5',
'C 3 3 0 4 5',
'D 4 4 4 0 5',
'E 5 5 5 5 0']
# Preprocess this matrix to make it a matrix
x = [e.split() for e in x]
numbe... | python|numpy|matrix | 2 |
158 | 56,537,706 | I want to sort a dataframe based on the difference of two rows of a single column | <p>I have a dataframe.</p>
<pre><code> Item Type Year_Month Total Cost
Cereal Jul-2017 6000
Cereal Jun-2017 5000
Baby Food Jul-2017 3000
Baby Food Jun-2017 2900
Snacks Jul-2017 4500
... | <p>First you need to calculate the differences for each item type. One of the ways, how to do this with pandas would be to use pivot_tables. Here you tell it which dataframe (df), based on which columns to calculate (values="TotalCost"), what function to use to calculate it (aggfunc=np.diff) and how to group them (inde... | python|pandas|sorting|dataframe | 3 |
159 | 56,769,787 | Find distinct values in a column if the dataframe containts list in columns | <p>lets assume we have the following dataframe:</p>
<pre><code>d = {'col1': [[1,2], [1,2], [2,1]], 'col2': ['A', 'B', 'C']}
df = pd.DataFrame(data=d)
df
col1 col2
[1, 2] A
[1, 2] B
[2, 1] C
</code></pre>
<p>Where I have a list in a column in the dataframe, how can I count the distinct values in each column?
The f... | <p>For the column containing lists, you can map the values to <code>tuples</code>, <em>which are hashable</em>, and then use <code>nunique</code>:</p>
<pre><code>df.col1.map(tuple).nunique()
# 2
</code></pre>
<hr>
<pre><code>df['col1'] = df.col1.map(tuple)
df.nunique()
col1 2
col2 3
dtype: int64
</code></pre>... | python|pandas | 3 |
160 | 56,795,642 | The performance of GPU still slow even by keras fit_generator method | <p>I have a large dataset 5GB that I want to use for training a neural network model designed using Keras. Although I am using Nvidia Tesla P100 GPU, the training is really slow (each epoch takes ~ 60-70s) (I choose the <code>batch size=10000</code>). After reading and searching, I found out that I can improve the trai... | <p>Just try assigning GPUs forcefully,</p>
<pre><code>import os
os.environ["CUDA_VISIBLE_DEVICES"]="0" # or if you want more than 1 GPU set it as "0", "1"
</code></pre>
<p>Hope this helps!</p> | python|tensorflow|keras | 1 |
161 | 56,588,093 | Python, converting int to str, trailing/leading decimal/zeros | <p>I convert my dataframe values to str, but when I concatenate them together the previous ints are including trailing decimals.</p>
<pre><code>df["newcol"] = df['columna'].map(str) + '_' + df['columnb'].map(str) + '_' + df['columnc'].map(str)
</code></pre>
<p>This is giving me output like
<code>500.0</code> how can ... | <p><strong>Edit</strong>:<br>
If your <code>df</code> has more than 3 columns, and you want to join only 3 columns, you may specify those columns in the command using columns slicing. Assume your <code>df</code> has 5 columns named as : <code>AA</code>, <code>BB</code>, <code>CC</code>, <code>DD</code>, <code>EE</code>... | python-3.x|pandas | 1 |
162 | 25,997,532 | swig with openmp and python, does swig -threads need extra GIL handling? | <p>I have my C library interfaced with swig.
I can compile it with my setup.py. Here the extension section:</p>
<pre><code>surf_int_lib = Extension("_surf_int_lib",
["surf_int_lib.i", "surf_int_lib.c"],
include_dirs=[numpy_include],
extra_compile_args=["-fopenmp... | <p>After further investigation, I found that this is an issue between openmp and openblas (at least version 0.2.8).</p>
<p>After recompiling openblas 0.2.11 with option <code>USE_OPENMP=1</code>, both blas routines from numpy as well as my own extensions using openmp make use of all cpus, set by the environment variab... | python|numpy|openmp|openblas | 0 |
163 | 66,777,021 | how to use the models under tensorflow/models/research/object_detection/models | <p>I'm looking into training an object detection network using tensorflow, and i had a look at the TF2 model zoo. I noticed there are noticeably less models there than in the directory /models/research/models/, including the mobiledet with ssdlite developed for the jetson xavier.</p>
<p>to clarify, the readme says that... | <p>If you plan to use the object detection API, you can't use your existing model. You have to choose from a list of models <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">here</a> for v2 and <a href="https://github.com/tensorflow... | tensorflow|object-detection|object-detection-api|tensorflow-model-garden | 0 |
164 | 67,129,554 | ImportError with keras.preprocessing | <p>I am following a <a href="https://www.tensorflow.org/tutorials/images/classification#predict_on_new_data" rel="nofollow noreferrer">image classification tutorial at Tensorflow</a>. On running the following code-</p>
<pre><code>import PIL
import tensorflow as tf
from tensorflow import keras
sunflower_url = "htt... | <p>The error says that you don't have <code>pillow</code> installed on your machine.
If you're using conda, then you have to do</p>
<pre><code>conda install pillow
</code></pre>
<p>If you're not using conda, then I would just try</p>
<pre><code>pip install pillow
</code></pre>
<p><strong>Edit 1</strong>: In case you ha... | python|tensorflow|keras|python-imaging-library | 0 |
165 | 67,099,008 | Matching nearest values in two dataframes of different lengths | <p>If I have two dataframes of different lengths, different labels and different levels of digit precision like so:</p>
<pre><code>df1 = pd.DataFrame({'a':np.array([1.2345,2.2345,3.2345]),'b':np.array([4.123,5.123,6.123])})
df2 = pd.DataFrame({'A':np.array([1.2346,2.2343]),'B':np.array([4.1232,5.1239])})
</code></pre>
... | <p>Using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html" rel="nofollow noreferrer">KDTree</a>, you can find the closest math in <code>df1</code> in <code>m O(log n)</code> which <code>n</code> is the number of elements in <code>df2</code> and <code>m</code> number of elements i... | python|pandas|dataframe|matching | 1 |
166 | 66,929,837 | Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 1) | <p>I am trying to get the prediction of my model</p>
<pre><code>prediction = model.predict(validation_names)
print(prediction)
</code></pre>
<p>but I get the following error:</p>
<pre><code>ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: ... | <p>Conv2D expects <code>4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (rows, cols, channels) if data_format='channels_last'</code></p>
<p><strong>Working sample code:</strong></p>
<pre><code># The inputs are 28x28 RGB images with `cha... | python|tensorflow|keras | 0 |
167 | 66,848,816 | reshape dataframe in the required format | <p>I have the dataframe which looks like this:</p>
<pre><code> b = {'STORE_ID': ['1234','5678','9876','3456','6789'],
'FULFILLMENT_TYPE':
['DELIVERY','DRIVE','DELIVERY','DRIVE','DELIVERY'],
'LAUNCH_DT':['2020-10-01','2020-10-02','2020-10-03','2020-10-04','2020-10-01']}
df_1 = pd.DataFr... | <p>If need add same <code>date_range</code> to each row of <code>df_1</code> use cross join by new DataFrame:</p>
<pre><code>df = (df_1.assign(a=1)
.merge(pd.DataFrame({'date_range':date_range,'a':1}), on='a')
.drop('a', axis=1))
</code></pre> | python-3.x|pandas | 1 |
168 | 66,790,100 | Variable array creation using numpy operations | <p>I wish to create a variable array of numbers in numpy while skipping a chunk of numbers. For instance, If I have the variables:</p>
<pre><code>m = 5
k = 3
num = 50
</code></pre>
<p>I want to create a linearly spaced numpy array starting at <code>num</code> and ending at <code>num - k</code>, skip <code>k</code> nu... | <p>You can try:</p>
<pre><code>import numpy as np
m = 5
k = 3
num = 50
np.hstack([np.arange(num - 2*i*k, num - (2*i+1)*k - 1, -1) for i in range(m)])
</code></pre>
<p>It gives:</p>
<pre><code>array([50, 49, 48, 47, 44, 43, 42, 41, 38, 37, 36, 35, 32, 31, 30, 29, 26,
25, 24, 23])
</code></pre>
<p><strong>Edit:</... | python|arrays|numpy | 4 |
169 | 47,530,736 | correct accessing of slices with duplicate index-values present | <p>I have a dataframe with an index that sometimes contains rows with the same index-value. Now I want to slice that dataframe and set values based on row-indices.</p>
<p>Consider the following example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'index':[1,2,2,3], 'values':[10,20,30,40]})
df.set_index(['i... | <p><code>.loc</code> is not recommended when you have duplicate index. So you have to go for position based selection <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a>. Since we need to pass the positions, we have to use <a href="h... | pandas|indexing | 2 |
170 | 47,189,031 | Initialize empty vector with 3 dimensions | <p>I want to initialize an empty vector with 3 columns that I can add to. I need to perform some l2 norm distance calculations on the rows after I have added to it, and I'm having the following problem. </p>
<p>I start with an initial empty array:</p>
<pre><code>accepted_clusters = np.array([])
</code></pre>
<p>Then... | <p>The most straightforward way is to use <code>np.vstack</code>:</p>
<pre><code>In [9]: arr = np.array([1,2,3])
In [10]: x = np.arange(20, 23)
In [11]: arr = np.vstack([arr, x])
In [12]: arr
Out[12]:
array([[ 1, 2, 3],
[20, 21, 22]])
</code></pre>
<p>Note, your entire approach has major code smell, doing... | python|arrays|numpy | 3 |
171 | 47,317,617 | Pandas iterrows get row string as list | <p>I have a df in pandas which looks like:</p>
<pre><code>id name values
1 a cat dog
2 b bird fly
</code></pre>
<p>I'm currently doing:
</p>
<pre><code>for index, row in df.iterrows():
print row["values"]
</code></pre>
<p>However, that prints the entire cell: <code>"cat dog"</code> or <code>"bir... | <p>You need to split the data</p>
<pre><code>df['values'].str.split()
0 [cat, dog]
1 [bird, fly]
</code></pre>
<p>To get the individual element, </p>
<pre><code>df['values'].str.split().str[0]
</code></pre>
<p>And you get</p>
<pre><code>0 cat
1 bird
</code></pre> | python|pandas | 2 |
172 | 68,306,769 | Pandas: how to transpose part of a dataframe | <p>I have the following dataframe:</p>
<pre><code> A B C param1 param2 param3
0 1 4 NaN val1 val4 val7
1 2 5 NaN val2 val5 val8
2 3 6 NaN val3 val6 val9
</code></pre>
<p>Which I'd like to modify to get:</p>
<pre><code> A B C Values
0 1 4 param1 val1
1 1 4 param2 val4
2 1... | <pre><code>df.melt(id_vars = ['A','B'], value_vars = ['param1','param2', 'param3'])
</code></pre>
<p>You can check melt function and it can change the label for the id_vars and value_vars.</p> | python|pandas|dataframe | 0 |
173 | 59,100,941 | Python Pandas Library Resample By Truncate Date | <p>use python3 library <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a>, i have a data in excel file like this</p>
<pre><code> Id | Date | count
----+-------------------------+-----------
1 | '2019/10/01 10:40' | 1
----+-------------------------------------
2 | ... | <p>I believe you need custom format of datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> and then aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupb... | python|python-3.x|pandas|dataframe|resampling | 2 |
174 | 59,311,945 | Jupyter Notebook - Kernel dies during training - tensorflow-gpu 2.0, Python 3.6.8 | <p>Since I am kind of new in this field I tried following the official tutorial from tensorflow for predicting time series. <a href="https://www.tensorflow.org/tutorials/structured_data/time_series" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/structured_data/time_series</a></p>
<p>Following problem ... | <p>Problem was a too big batch size. Reducing it from 1024 to 256 solved the crashing problem.</p>
<p>Solution taken from the comment of rbwendt on <a href="https://github.com/tensorflow/tensorflow/issues/9829" rel="nofollow noreferrer">this thread on github</a>.</p> | python-3.x|tensorflow|jupyter-notebook | 0 |
175 | 59,155,277 | Looping through list with dataframe elements in python | <p>I want to iterate over a list, which has dataframes as its elements. </p>
<p>Example: ls is my list with below elements (two dataframes)</p>
<pre><code> seq score status
4366 CGAGGCTGCCTGTTTTCTAGTTG 5.15 negative
5837 GGACCTTTTTTACAATATAGCCA 3.48 negative
96 TTTCTAGCCTACCAA... | <p>This should work ok</p>
<pre><code>cut_off = [1,2,3,4]
for df in ls:
for co in cut_off:
print "Negative set : " + "cut off value =", str(
co), number of variants = ", str((df['score'] > co).sum())
</code></pre> | python|pandas | 1 |
176 | 59,343,025 | Adding few columns to data frame calculating a median corresponding with other 3 columns | <p>I have the following dataframe:</p>
<pre><code> Name Number Date Time Temperature RH Height AH
0 Rome 301 01/10/2019 02:00 20.5 89 10 15.830405
1 Rome 301 01/10/2019 05:00 19.4 91 10 15.176020
.. ... ... ... ... ... | <p>I believe you just need to update your groupby to include <code>Date</code>:</p>
<pre><code>my_data['med_AH_[Date]']= my_data.groupby(['Name', 'Date'])['AH'].transform('median')
</code></pre> | python|pandas|dataframe|transform|pandas-groupby | 0 |
177 | 59,400,154 | passing value from panda dataframe to http request | <p>I'm not sure how I should ask this question. I'm looping through a csv file using panda (at least I think so). As I'm looping through rows, I want to pass a value from a specific column to run an http request for each row. </p>
<p>Here is my code so far:</p>
<pre><code>def api_request(request):
fs = gcsfs.GCS... | <p>Actually, forgo the use of the Pandas library and simply iterate through csv</p>
<pre><code>import csv
def api_request(request):
fs = gcsfs.GCSFileSystem(project=PROJECT)
with fs.open('gs://project.appspot.com/file.csv') as f:
reader = csv.reader(f)
next(reader, None) # SKI... | python|python-3.x|pandas|google-cloud-functions | 2 |
178 | 14,160,806 | histogram matching in Python | <p>I am trying to do histogram matching of simulated data to observed precipitation data. The below shows a simple simulated case. I got the CDF of both the simulated and observed data and got stuck theree. I hope a clue would help me to get across..Thanks you in advance</p>
<pre><code>import numpy as np
import matplo... | <p>I tried to reproduce your code, and got the following error:</p>
<pre><code>ValueError: A value in x_new is above the interpolation range.
</code></pre>
<p>If you look at the plot of your two CDFs it is pretty straight forward to figure out what is going on:</p>
<p><img src="https://i.stack.imgur.com/n6KlP.png" a... | python|numpy|histogram|cdf | 4 |
179 | 13,958,129 | How to apply function to date indexed DataFrame | <p>I am having lots of issues working with DataFrames with date indexes.</p>
<pre><code>from pandas import DataFrame, date_range
# Create a dataframe with dates as your index
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
idx = date_range('1/1/2012', periods=10, freq='MS')
df = DataFrame(data, index=idx, columns=['Revenue'])
... | <p>You nearly had it! First create the groupby object:</p>
<pre><code>means = df.groupby('State').mean()
In [5]: means
Out[5]:
Revenue
State
FL 7.5
GA 7.5
NY 2.5
</code></pre>
<p>Then <code>apply</code> this to each state in the DataFrame:</p>
<pre><code>df['mean'] = df['Sta... | indexing|group-by|pandas | 6 |
180 | 45,026,934 | How to perform convolutions individually per feature map | <p>I have data in the format NHWC: <code>100 x 64 x 64 x 3</code>. I want to apply the laplacian filter to each channel separately. I want the output as <code>100 x 64 x 64 x 3</code>. </p>
<pre><code>k = tf.reshape(tf.constant([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], tf.float32), [3, 3, 1, 1])
</code></pre>
<p>I tried... | <p>This is what <code>tf.nn.depthwise_conv2d</code> does. However, it is more general than that and actually let you choose one or more convolution kernels <em>per channel</em>.</p>
<p>If you want to have the same kernel for all channels, you need to duplicate the kernel to match the number of channels. E.g.</p>
<pre... | python|tensorflow | 2 |
181 | 57,202,717 | How to iterate over first element of each nested tensor in tensorflow, python? | <p>I am working with a tensor which looks as follows:</p>
<pre><code>X = tf.constant([['a', 'y', 'b'],
['b', 'y', 'a'],
['a', 'y', 'c'],
['c', 'y', 'a'],
['a', 'y', 'd'],
['c', 'y', 'd'],
['b', 'y', 'c'],
['f', 'y', 'e']]... | <p>You probably have not evaluated the tensor yet. Use <code>tensor.eval()</code> or <code>session.run(tensor)</code> to evaluate the result:</p>
<pre><code>import tensorflow as tf
X = tf.constant([['a', 'y', 'b'],
['b', 'y', 'a'],
['a', 'y', 'c'],
['c', 'y', 'a'],
... | python|tensorflow | 2 |
182 | 57,086,868 | How to append 2 numpy Image Arrays with different dimensions and shapes using numpy | <p>I am making an input dataset which will have couple of thousands of images which all don't have same sizes but have same number of channels. I need to make these different images into one stack.</p>
<pre><code>orders = (channels, size, size)
Image sizes = (3,240,270), (3,100,170), etc
</code></pre>
<p>I have tried a... | <p>If you don't want to resize the image, choose the biggest one and padding all picture become same shape with it, i used to answer how to pad in this question: <a href="https://stackoverflow.com/questions/56420792/can-we-resize-an-image-from-64x64-to-256x256-without-increasing-the-size/56421174#56421174">Can we resiz... | python|arrays|numpy | 0 |
183 | 45,844,805 | C/C++ speed ODE integration from Python | <p>I am numerically integrating some ODE's, e.g.</p>
<pre><code>y'(t) = f(y(t), t)
</code></pre>
<p>This is easily done using for instance scipy's <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html" rel="nofollow noreferrer">integrate.ode</a>. The function <code>f</code> is defined... | <p>There is a scikit devoted to this that extends the capabilities of <code>scipy.integrate</code>.</p>
<p>It is available here: <a href="https://github.com/bmcage/odes" rel="nofollow noreferrer">https://github.com/bmcage/odes</a></p>
<p>The documentation contains an example of ODE integration sped up by implementing... | python|numpy|scipy|cython | 2 |
184 | 23,266,343 | numpy: copying value defaults on integer indexing vs boolean indexing | <p>I have recently started studying McKinney's Python for data analysis. This tripped me up in the book:</p>
<blockquote>
<p>Array slices are views on the original array. This means data is not
copied and any modifications to the view will be reflected in the
source array ... As NumPy has been designed with larg... | <p>Let's assume a 1D array. The data in memory would look something like:</p>
<pre><code>10 | 11 | 12 | 13 | 14 | 15 | 16
</code></pre>
<p>Accessing an element by index is trivial. Just take the position of the first element, and jump <code>n</code> steps. So, for <code>arr[2]</code>:</p>
<pre><code>10 | 11 | 12 | 1... | python|arrays|numpy | 8 |
185 | 35,728,838 | Pandas: Get an if statement/.loc to return the index for that row | <p>I've got a dataframe with 2 columns and I'm adding a 3rd. </p>
<p>I want the 3rd column to be dependant on the value of the 2nd either returning a set answer or the corresponding index for that row. </p>
<p>An example the database is below:</p>
<pre><code>print (df)
Amount Percentage
Country ... | <p>You can try <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df['Country'] = np.where(df['Percentage']>0.25, df.index, 'Other')
print df
Amount Percentage Country
Country
Belgi... | python|if-statement|pandas|dataframe | 2 |
186 | 35,756,601 | Debug for reading JSON file with Python Pandas | <p>I got stuck when I was trying to simply read JSON file with <code>Pandas.read_json</code>. When I try with this sample dataset, it's great. </p>
<pre><code>import pandas as pd
df = pd.read_json('sample.json')
</code></pre>
<p>My sample JSON file looks like below:</p>
<pre><code>[{"field1": "King's Landing", "fiel... | <p>I guess you have misspelled your JSON filename...</p>
<p>the following script gives me exactly the same error message:</p>
<pre><code>import pandas as pd
df = pd.read_json('THERE_IS_NO_SUCH_FILE.json')
</code></pre>
<p>You may also want to validate your JSON file <a href="https://jsonformatter.curiousconcept.com... | python|json|pandas | 2 |
187 | 11,883,072 | Python and numpy - converting multiple values in an array to binary | <p>I have a numpy array that is rather large, about 1mill. The distinct number of numbers is about 8 numbered 1-8.</p>
<p>Lets say I want given the number 2, I would like to recode all 2's to 1 and the rest to 0's.</p>
<pre><code>i.e.
2==>1
1345678==0
Is there a pythonic way to do this with numpy?
[1,2,3,4,5,... | <p>That's the result of <code>a == 2</code> for a NumPy array <code>a</code>:</p>
<pre><code>>>> a = numpy.random.randint(1, 9, size=20)
>>> a
array([4, 5, 1, 2, 5, 7, 2, 5, 8, 2, 4, 6, 6, 1, 8, 7, 1, 7, 8, 7])
>>> a == 2
array([False, False, False, True, False, False, True, False, False,
... | python|numpy | 5 |
188 | 28,767,642 | How to compare two lists in python | <p>Suppose I have two lists (or <code>numpy.array</code>s):</p>
<pre><code>a = [1,2,3]
b = [4,5,6]
</code></pre>
<p>How can I check if each element of <code>a</code> is smaller than corresponding element of <code>b</code> at the same index? (I am assuming indices are starting from 0)
i.e. </p>
<pre><code>at index 0 ... | <p>Answering both parts with <code>zip</code> and <code>all</code></p>
<pre><code>all(i < j for (i, j) in zip(a, b))
</code></pre>
<p><code>zip</code> will pair the values from the beginning of <code>a</code> with values from beginning of <code>b</code>; the iteration ends when the shorter iterable has run out. <c... | python|list|python-3.x|numpy|itertools | 14 |
189 | 51,091,981 | Making a numpy array from bytes packed with struct | <p>The following piece of python code:</p>
<pre><code>import numpy as np
import struct
arr = []
arr.append(struct.pack('ii', 1, 3))
arr.append(struct.pack('ii', 2, 4))
dt = np.dtype([('n','i4'),('m','i4')])
a = np.array(arr,dt)
print(a)
</code></pre>
<p>returns with <code>[(1, 3) (2, 4)]</code> (as I expected) unde... | <p>You can get around this in <strong><code>1.14</code></strong> by using <strong><code>frombuffer</code></strong></p>
<pre><code>>>> np.frombuffer(np.array(arr), dt)
array([(1, 3), (2, 4)], dtype=[('n', '<i4'), ('m', '<i4')])
</code></pre>
<hr>
<p>I <em>believe</em> this has to do with the <a href="h... | python|numpy | 0 |
190 | 50,993,568 | Any easier way to assign values of a DataFrame row to corresponding variables in a custom object? | <p>Let's say I have the following DataFrame with some sample rows:</p>
<pre><code> id first_name last_name age
0 1 John Doe 18
1 2 Joe Shmuck 21
</code></pre>
<p>Let's say I also have a custom Python class called <code>Person</code> which ought to rep... | <p>Do you really need a class for this? You can use <code>df.itertuples</code> to create a list of "Person" <code>namedtuple</code>s:</p>
<pre><code>>>> list(df.itertuples(index=False, name='Person'))
</code></pre>
<p></p>
<pre><code>[Person(id=1, first_name='John', last_name='Doe', age=18),
Person(id=2, f... | python|pandas|dataframe|series | 1 |
191 | 51,010,662 | Getting the adjugate of matrix in python | <p>i having some problems in solving the question finding the adjugate of a matrix by given the formula of cofactor matrix </p>
<pre><code>c[i][j] = (-1)**(i+j)*m[i][j]
</code></pre>
<p>where m stand for determinant of matrix.</p>
<pre><code>x = np.array([[1,3,5],[-2,-4,-5],[3,6,1]] , dtype = 'int')
</code></pre>
... | <p>You can calculate the adjugate matrix by the transposal of the cofactor matrix
with the method below which is suitable for non singular matrices.
First, find the cofactor matrix, as follows:
<a href="https://www.geeksforgeeks.org/how-to-find-cofactor-of-a-matrix-using-numpy/" rel="nofollow noreferrer">https://www.ge... | python|numpy | 0 |
192 | 9,215,174 | concatenate numpy arrays that are class instance attributes in python | <p>I am attempting to use a class that strings together several instances of another class as a numpy array of objects. I want to be able to concatenate attributes of the instances that are contained in the numpy array. I figured out a sloppy way to do it with a bunch of for loops, but I think there must be a more el... | <p>you can use numpy.hstack() to concatenate arrays:</p>
<pre><code>def concatenate_attributes(self):
self.a = np.hstack([o.a for o in self.my_class_inst])
self.arr = np.hstack([o.arr for o in self.my_class_inst])
</code></pre>
<h2>See Also</h2>
<p>vstack : Stack arrays in sequence vertically (row wise).
dst... | python|class|attributes|numpy|string-concatenation | 1 |
193 | 66,371,667 | How to normalize image in tensorflow.js? | <p>I applied transformation during training phase in pytorch then I convert my model to run in tensorflow.js. It is working fine but got wrong predictions as I didn't apply same transformation.</p>
<pre><code>test_transform = torchvision.transforms.Compose([
torchvision.transforms.Resize(size=(224, 224)),
torch... | <ul>
<li><strong>torchvision.transforms.ToTensor()</strong> converts PIL Image or numpy array in the range of 0 to 255 to a float tensor os shape (channels x Height x Width) in the range 0.0 to 1.0 . To convert in the range 0.0 to 1.0 it divide each element of tensor by 255. So, execute same in tensorflowJS I done as f... | javascript|tensorflow|deep-learning|tensorflow.js | 4 |
194 | 66,734,739 | My Dataframe contains 500 columns, but I only want to pick out 27 columns in a new Dataframe. How do I do that? | <p>My Dataframe contains 500 columns, but I only want to pick out 27 columns in a new Dataframe.
How do I do that?</p>
<p>I used query()
but output
TypeError: query() takes from 2 to 3 positional arguments but 27 were given</p> | <p>If you want to select the columns based on their name, you can do the following:</p>
<pre><code>df_new = df[["colA", "colB", "colC", ...]]
</code></pre>
<p>or use the "filter" function:</p>
<pre><code>df_new = df.filter(["colA", "colB", "colC", ..... | pandas | 0 |
195 | 66,696,489 | Python Panda : Count number of occurence of a number | <p>I've searched for long time and I need your help, I'm newbie on python and panda lib. I've a dataframe like that charged from a csv file :</p>
<pre><code>ball_1,ball_2,ball_3,ball_4,ball_5,ball_6,ball_7,extraball_1,extraball_2
10,32,25,5,8,19,21,3,4
43,12,8,19,4,37,12,1,5
12,16,43,19,4,28,40,2,4
</code></pre>
<p>bal... | <h3><code>groupby</code> on <code>columns</code> with <code>value_counts</code></h3>
<pre><code>def get_before_underscore(x):
return x.split('_', 1)[0]
val_counts = {
k: d.stack().value_counts()
for k, d in df.groupby(get_before_underscore, axis=1)
}
print(val_counts['ball'])
12 3
19 3
4 2
8 ... | python|pandas|data-science | 3 |
196 | 66,726,869 | Group a numpy array | <p>I have an one-dimensional array <code>A</code>, such that <code>0 <= A[i] <= 11</code>, and I want to map <code>A</code> to an array <code>B</code> such that</p>
<pre><code>for i in range(len(A)):
if 0 <= A[i] <= 2: B[i] = 0
elif 3 <= A[i] <= 5: B[i] = 1
elif 6 <= A[i] <= 8: B[i] ... | <p>You need to use an int division by <code>//3</code>, and that is the most performant solution</p>
<pre><code>A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
B = A // 3
print(A) # [0 1 2 3 4 5 6 7 8 9 10 11]
print(B) # [0 0 0 1 1 1 2 2 2 3 3 3]
</code></pre> | python|arrays|numpy|matrix | 2 |
197 | 66,609,544 | Obtaining a list of x,y coordinates of a specific RGB value from a screenshot of the screen | <p>I have been trying to take a screenshot of my screen and find every x,y coordinate of a specific color.</p>
<pre><code>from PIL import ImageGrab
import numpy as np
image = ImageGrab.grab()
indices = np.all(image == (209, 219, 221), axis=-1)
print(indices)
print(zip(indices[0], indices[1]))
</code></pre>
<p>When I r... | <p>I believe you're making an error with the following line:</p>
<pre><code>indices = np.all(image == (209, 219, 221), axis=-1)
</code></pre>
<p>You can iterate over the pixels directly and achieve the result you want:</p>
<pre><code>from PIL import ImageGrab
import numpy as np
image = ImageGrab.grab()
color = (43, 4... | python|image|numpy|image-processing|rgb | 0 |
198 | 66,686,745 | When im converting the predicted value this gives me IndexError: invalid index to scalar variable | <pre><code>@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, ... | <p>If <code>make_predict = [[0. 1. 0. 0. 0. 0. 0.]]</code>, than you try to access the first index of the integer <code>0</code> that you get from <code>pred_class[0][0]</code>, so by removing the redundant indexer in <code>result = str(pred_class[0][0][0])</code> and changing it to <code>result = str(pred_class[0][0])... | python|pandas|numpy|tensorflow|keras | 0 |
199 | 66,719,264 | Create a dataframe from multiple list of dictionary values | <p>I have a code as below,</p>
<pre><code>safety_df ={}
for key3,safety in analy_df.items():
safety = pd.DataFrame({"Year":safety['index'],
'{}'.format(key3)+"_CR":safety['CURRENT'],
'{}'.format(key3)+"_ICR":safety['ICR'],
... | <p>Use <code>axis=1</code> to concate along the columns:</p>
<pre><code>import numpy as np
import pandas as pd
years = np.arange(2010, 2021)
n = len(years)
c1 = np.random.rand(n)
c2 = np.random.rand(n)
c3 = np.random.rand(n)
frames = {
'a': pd.DataFrame({'year': years, 'c1': c1}),
'b': pd.DataFrame({'year': y... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.