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 |
|---|---|---|---|---|---|---|
365,700 | 63,346,690 | Image array from ImageDataGenerator does not match image read by CV2 | <p>I use the Image Data Generator with flow from directory to read in
a single 224 X 224 X 3 image titled 1.jpg. The result should be
and identical to the initial image since image size is set to
224 X 244 in flow from directory. I then read in the same image using
cv2. I then compare the array provided by the image da... | <p>The issue here was that openCV's standard method for reading images is to read them as BGR, so that blue is the first channel and red is the last. However, most other standard libraries will use RGB (keras's ImageGenerator and PIL.Image, as examples), and so you cannot directly compare cv2 objects with these objects... | python|tensorflow|keras | 1 |
365,701 | 63,344,321 | pandas read_json in chunks but still has memory error | <p>I'm trying to read and process a large json file(~16G) but it keeps having memory error even if I read in small chunks by specifying chunksize=500. My code:</p>
<pre><code>i=0
header = True
for chunk in pd.read_json('filename.json.tsv', lines=True, chunksize=500):
print("Processing chunk ", i)
... | <p>I had the same strange problem in one of my project's virtual env with pandas v1.1.2.
Downgrading pandas to v1.0.5 seems to solve the problem.</p> | pandas|large-files | 3 |
365,702 | 63,526,001 | How to get the maximum 2D Tensor from a 3D tensor using TensorFlow 1.14? | <p>I am looking for the best and optimized way (without loops) to get a 2D max Tensor from a 3D Tensor based on the maximum one value using TensorFlow 1.14. let's say we have this Tensor and this function(for understanding-it's not working-):</p>
<pre><code>def get_Max(inputs):
max_indices = [0,0,0]
for i in ra... | <pre><code>inp = tf.random.uniform(shape=[4, 6, 2], maxval=20, dtype=tf.int32)
print(inp)
array([[[14, 8],
[18, 10],
[ 6, 14],
[ 8, 9],
[11, 11],
[14, 13]],
[[ 7, 18],
[ 4, 10],
[15, 6],
[ 6, 2],
[19, 11],
[10, 4]],
[[ 8, 1],
[ 1, 3],
[ 4, 17],
[15, 7... | python|tensorflow|tensorflow2.0|tensorflow-serving | 1 |
365,703 | 63,351,334 | Unable to import BigQuery data into GCP AI Notebook | <p>I had previously used the code below to import data from bigquery to an AI notebook instance in GCP. For unknown reasons it stopped working and gives me the following error: "ImportError: cannot import name 'bigquery_storage_v1beta1' from 'google.cloud' (unknown location)". It may have started after I bega... | <p>The solution was updating the packages with the following commands:</p>
<p>First:</p>
<pre><code>!sudo /opt/conda/bin/conda install -c conda-forge google-cloud-bigquery google-cloud-bigquery-storage pandas pyarrow --yes
</code></pre>
<p>Then:</p>
<pre><code>%pip install google-cloud-bigquery
</code></pre> | python|pandas|google-cloud-platform|google-bigquery | 1 |
365,704 | 63,633,360 | why numpy max function(np.max) return wrong output? | <p>I have <code>pandas DataFrame</code> and I turn it to <code>numpy ndarray</code>.I use <code>max</code> function for one column in my DataFrame like this:</p>
<pre><code>print('column: ',df[:,3])
print('max: ',np.max(df[:,3]))
</code></pre>
<p>And the output was:</p>
<pre><code>column: [0.6559999999999999 0.48200000... | <h2>There are two problems here</h2>
<hr />
<br>
<ol>
<li><p>It looks like <strong>column you are trying to find maximum for has the data type <code>object</code></strong>. It's not recommended if you are sure that your column should contain numerical data since it may cause unpredictable behaviour not only in this par... | python|pandas|numpy | 3 |
365,705 | 21,643,407 | Define a pandas.tseries.index.DatetimeIndex using 2 datetimes (dt_start and dt_stop) and a timedelta | <p>With Pandas we can define a <code>pandas.tseries.index.DatetimeIndex</code> using the following syntax:</p>
<pre><code>rng = pd.date_range(dt_start, dt_stop, freq='5Min')
</code></pre>
<p><code>freq</code> is a string.</p>
<p>I would like to define the same kind of DatetimeIndex using a timedelta as freq</p>
<pr... | <p>A more robust way to get this is to use a DateOffset (which you can pass as freq to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow"><code>date_range</code></a>).</p>
<p>Since <a href="http://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollo... | python|datetime|pandas|timedelta | 2 |
365,706 | 21,910,580 | Using polyval and polyfit to plot linear regression on semi-log charts | <p>I'm using matplotlib + numpy to generate linear regressions using the polyfit and polyval functions</p>
<pre><code>lateReg = np.polyfit(x=xm,y=mcherryp,deg=1)
ax1.plot(xm, np.polyval(lateReg,xm), 'r-')
earlyReg = np.polyfit(xv,venusp,deg=1)
ax1.plot(xv, np.polyval(earlyReg,xv), 'g-')
</code></pre>
<p>However, sinc... | <p>Assuming that your data looks like a straight line on the semilog plot, you want</p>
<pre><code>p = np.polyfit(np.log(xm), mcherryp, 1)
ax1.semilogx(xm, p[0] * np.log(xm) + p[1], 'r-')
</code></pre>
<p>In this case, and the loglog case, I usually think that <code>polyval</code> is not useful.</p> | python|numpy|matplotlib | 3 |
365,707 | 21,614,065 | Why does shifting a numpy uint8 create negative values? | <p>I'm using python 2.7, numpy 1.6.1, 32-bit on windows. I'm writing a function to pack some data into 32-bit integers and generating C source declarations from the constant values. In doing so, I found some strange behavior in numpy's uint8 type.</p>
<p>No one is surprised, I'm sure, to see this:</p>
<pre><code>&g... | <p><code>numpy</code> appears to treat the right-hand argument (<code>24</code>) as a signed integer of the native width (<code>int32</code> in your case, <code>int64</code> in mine).</p>
<p>It looks like the <code>uint8</code> gets promoted to the same type, and the result of the shift is also of the same type:</p>
... | python|numpy | 5 |
365,708 | 21,747,499 | How to save object according to a key which is hash created from tuple or list which numpy.ndarray | <p>My work takes a lot of computational time.</p>
<p>So I want to save each calculated result according to key, for example, a hashed key which generated by parameter which consist of a tuple include numeric, numpy.ndarray, etc.</p>
<p>To solve this assignment, I try to save result(for example, model of machine learn... | <p>Numpy's ndarray object doesn't have a hash method, but you can use md5 or something similar:</p>
<pre><code>import md5
m = md5.new()
m.update(iris.data)
m.update(iris.target)
key_m = m.hexdigest()
</code></pre> | python|numpy|hash | 1 |
365,709 | 21,597,299 | Eigenvalues NaN and inf | <p>Suppose I have a system AX = nBX where A and B are known martrices, X is the coefficient matrix. </p>
<p>I am solving this using Chebyshev polynomials. </p>
<p>BC's are u(-1)=0=u(1)</p>
<p>I am imposing the bc's for the first and last rows of matrices A and B.</p>
<pre><code>e=solve(A,B)
e[1]=0
e[-1]=0
x=sol... | <p>The question you seem to be asking: how come a generalized eigenvalue problem has eigenvalues inf and nan?</p>
<p>Your generalized eigenvalue problem is singular and has eigenvalues lambda=alpha/beta such that (alpha=0, beta=0) and (alpha!=0, beta=0). Since eigvals reports the eigenvalues, they are 0/0=nan or x/0=i... | python|numpy|linear-algebra | 2 |
365,710 | 21,882,799 | Pandas, large file with varying number columns, in memory append | <p>I would like to maintain a large PyTable in a hdf5 file.
Normally as new data comes I would append to the existing table: </p>
<pre><code> store = pd.HDFStore(path_to_dataset, 'a')
store.append("data", newdata)
store.close()
</code></pre>
<p>However, if the columns of old stored data and those of the in... | <p><code>HDFStore</code> stores row-oriented, so this is currently not possible. </p>
<p>You could need to read it in, append, and write it out. Possibly you could use: <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#multiple-table-queries" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/io.htm... | database|pandas|hdf5|pytables | 1 |
365,711 | 21,447,595 | How to mask clouds from Python numpy array for a linear regression model? | <p>I intend to build a linear regression model between two images, but I need to mask clouds first. </p>
<p>Based on some discussions, a masked array may be helpful (<a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#the-numpy-ma-module" rel="nofollow">http://docs.scipy.org/doc/numpy/reference... | <p>I found the solution from Scipy API for Masked array operations. Here is the page: <a href="http://docs.scipy.org/doc/numpy/reference/routines.ma.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/routines.ma.html</a></p>
<p>Either ma.compressed(x) or ma.MaskedArray.compressed() can eliminate those miss... | python|numpy | 0 |
365,712 | 21,919,223 | filtering array with conditional control variables in python to create numpy matrix | <pre><code>import numpy as np
def get_positions(values, mintreshold=0.1):
maxindex = 0
result_row = np.zeros(np.shape((0, 0)), dtype=int)
result = np.matrix(result_row)
result_index = 0
for index in xrange(len(values)):
diff = values[maxindex] - values[index]
... | <p>I am not sure if this is exactly what you are looking for, but <code>reduce</code> from <code>functools</code> can be used here to accumulate a state that depends on the "past" values of your input list. Once you calculate a list of states that correspond to each input, you can use <code>filter</code> to get rid of ... | python|arrays|numpy|filter|functional-programming | 2 |
365,713 | 21,792,590 | Numpy way of appending the data retrieved from for loop | <p>I am looking for the numpy way of appending the data retrieved from for loop as in the example below:</p>
<pre><code>import glob, gdal, numpy as np
tiff_files = glob.glob('*.tif')
all_data = [] #LOOKING FOR ALTERNATIVE HERE
for f in tiff_files:
data_open = gdal.Open(f)
data_array = data_open.ReadAsArray... | <p>If you want to make it a one-liner:</p>
<pre><code>np.array([gdal.Open(f).ReadAsArray().astype(np.float32) for f in glob.glob('*.tif')])
</code></pre>
<p>but making data in a <code>ndarray</code> is not faster than the builtin <code>list</code>. E.g:</p>
<pre><code>In [391]: timeit a=[0]*1000
100000 loops, best o... | python|numpy | 1 |
365,714 | 24,635,721 | How to compare frequencies/sampling rates in pandas? | <p>is there a way to say that '13Min' is > '59S' and <'2H' using the frequency notation in pandas? </p> | <pre><code>In [4]: from pandas.tseries.frequencies import to_offset
In [5]: to_offset('59s') < to_offset('1T')
Out[5]: True
In [6]: to_offset('13T') > to_offset('59s')
Out[6]: True
In [7]: to_offset('13T') < to_offset('59s')
Out[7]: False
In [8]: to_offset('13T') > to_offset('2H')
Out[8]: False
In [10]... | python|pandas|sample-data | 6 |
365,715 | 24,853,762 | pandas - merging multiple DataFrames | <p>This is a multi-part question. I just can't seem to combine everything together. The goal is to to create one DataFrame (guessing using MultiIndex) that I can access as follows: </p>
<pre><code>ticker = 'GOLD'
date = pd.to_datetime('1978/03/31')
current_bar = df.ix[ticker].ix[date]
</code></pre>
<p>Can I then j... | <p>You can use <code>pd.concat</code> to <em>concatenate</em> DataFrames. (<em>Concatenating</em> smushes DataFrames together, while <em>merging</em> joins DataFrames based on common indices or columns). When you supply the <code>keys</code> parameter, you get a hierarchical index:</p>
<pre><code>import pandas as pd
d... | python|pandas | 4 |
365,716 | 24,702,868 | Python3 Pillow Get all pixels on a line | <p>I need to get the pixel values along a line, I'm using Python3 and Pillow. In opencv there is such a thing as a <a href="http://docs.opencv.org/modules/core/doc/drawing_functions.html#lineiterator" rel="nofollow noreferrer">LineIterator</a> which will return all of the appropriate pixels between two points, but I ha... | <p>I tried the code suggested by @Rick but it did not work. Then I went to <a href="https://github.com/sachinruk/xiaolinwu/blob/master/xiaolinwu.m" rel="noreferrer">Xiaolin's code</a> written in Matlab and translated it into Python:</p>
<pre><code>def xiaoline(x0, y0, x1, y1):
x=[]
y=[]
dx = ... | python|opencv|python-3.x|numpy|pillow | 5 |
365,717 | 24,585,706 | SciPy medfilt wrong result | <p>Hi python enthusiasts!</p>
<p>I'm currently working with signal filtering for research purposes and decided to use SciPy. Nothing special, just automation of routine work.</p>
<p>So, here is the code</p>
<pre><code>from scipy.signal import medfilt
print(medfilt([2,6,5,4,0,3,5,7,9,2,0,1], 5))
</code></pre>
<p>But... | <p>I believe that both you and SciPy have correct results. The difference is in what happens at the boundaries, but I believe that both you and SciPy have made valid choices.</p>
<p>The question is <strong>what should happen when your sliding window is at the edges, and there is no valid data to use to fill in your sl... | python|numpy|scipy|median | 18 |
365,718 | 24,527,279 | Mixed length object type in pandas dataframe | <p>I want to use the pandas library to store mixed length objects.</p>
<p>Let's say for instance that I want to have a dataframe with two columns: the first one storing a float and the second one storing a list of float.
What is the best way to do this in pandas, bearing in mind that I want to be able to sort the dat... | <pre><code>import pandas as pd
data = {
'a': [.1,.2,.3],
'b': [ [.1,.2], [.3,.4,.5,.6,.7], [.8,.9,1.] ],
}
df = pd.DataFrame(data)
print df
</code></pre>
<p>result:</p>
<pre><code> a b
0 0.1 [0.1, 0.2]
1 0.2 [0.3, 0.4, 0.5, 0.6, 0.7]
2 0.3 [0.8, 0... | python|numpy|pandas | 2 |
365,719 | 24,472,905 | Python testing whether a string has "%" and not have it break | <p>I've look at this answer: <a href="https://stackoverflow.com/questions/10678229/selectively-escape-percent-in-python">How can I selectively escape percent (%) in Python strings?</a> and I believe my problem is different.</p>
<p>I'm trying to convert a percentage to decimal, but first I need to test if a percentage ... | <p>It seems you need <code>else</code> in <code>lambda</code> like this</p>
<pre><code>lambda x: float(x.strip('%'))/100 if '%' in x else x
</code></pre> | python|pandas|dataframe | 2 |
365,720 | 24,484,774 | Pandas DateTimeIndex | <p>I need to have a DateTimeIndex for my dataframe. Problem is my source file. The Date header is Date(dd-mm-yy), but the actual date data has the format dd:mm:yy (24:06:1970) etc. I have lots of source files so manually changing the header would be tedious and not good programing practice. How would one go about addre... | <p>I think the main problem is that the header line <code>Date(dd-mm-yy), Time(hh:mm:ss), Julian_Day</code> only appears to specify some of the column names. <code>Pandas</code> cannot infer what to do with the other data.</p>
<p>Try skipping the file's column name line and passing <code>pandas</code> a list of column... | python|datetime|pandas | 2 |
365,721 | 24,644,656 | How to print pandas DataFrame without index | <p>I want to print the whole dataframe, but I don't want to print the index</p>
<p>Besides, one column is datetime type, I just want to print time, not date.</p>
<p>The dataframe looks like:</p>
<pre><code> User ID Enter Time Activity Number
0 123 2014-07-08 00:09:00 1411
1 123 ... | <h2>python 2.7</h2>
<pre class="lang-py prettyprint-override"><code>print df.to_string(index=False)
</code></pre>
<h2>python 3</h2>
<pre class="lang-py prettyprint-override"><code>print(df.to_string(index=False))
</code></pre> | python|datetime|pandas|dataframe | 356 |
365,722 | 24,709,342 | Segmentation fault 11 in Python when importing pandas.rpy.common | <p>I'm running Mountain Lion which has Python 2.7.2 installed by default. I've set up a new virtual Python environment using this version of Python. I install a few packages using pip install such as numpy, matplotlib, ipython, and a few others. I've been trying to develop a script to load data from R and so I also ins... | <p>On machines where a system R is installed (e.g with RStudio) together with rpy2 installed in an environment (e.g conda), the system one is used, and that might not be compatible with the one rpy2 was built with, causing seg faults.
To diagnose if you have different R version which rpy2 is bundeled with, run:</p>
<p... | python|r|pandas|rpy2|robjects | 0 |
365,723 | 30,139,598 | ipython forcing pandas to plot | <p>I have a loop to generate plots for each column of a DF in pandas. I use Ipython, but the plots are all displayed at the end of the loop, rather than at the place where I would like to see them displayed according to my code.</p>
<p>How could I force ipython/pandas to display the cols at the precise point on which ... | <p>Be sure to call <code>plt.show()</code> every time you plot a new graph. If you don't, iPython will automatically buffer each plot and display them once you reach the end of the cell. I think you forget to do this at the end of your loop.</p>
<p>Here is an example of some code which will correctly plot a graph with... | python|pandas|plot | 0 |
365,724 | 30,265,723 | Python: create a new column from existing columns | <p>I am trying to create a new column based on both columns. Say I want to create a new column z, and it should be the value of y when it is not missing and be the value of x when y is indeed missing. So in this case, I expect z to be <code>[1, 8, 10, 8]</code>.</p>
<pre><code> x y
0 1 NaN
1 2 8
2 4 10
3 8 ... | <p>You can use <code>apply</code> with option <code>axis=1</code>. Then your solution is pretty concise.</p>
<pre><code>df[z] = df.apply(lambda row: row.y if pd.notnull(row.y) else row.x, axis=1)
</code></pre> | python|pandas|missing-data|calculated-columns | 20 |
365,725 | 30,121,729 | Polynomial Curve fittings with GNU Scientific Library (GSL) | <p>I'm going to use GNU Scientific Library (GSL) for solving Polynomial Curve fittings. Here is my function for polyFit - see <strong>"C++ code"</strong>. If I use below example data, then I got the result below - see <strong>"Output"</strong>. I've tried to verification if it is OK or not with python - see <strong>"Py... | <p>Using an orthogonal least square fit algorightm, I get:</p>
<p>-1.9386e-015 X^6 + 1.3095e-013 X^5 + 3.9775e-009 X^4 + -2.3274e-007 X^3 + -2.6963e-003 X^2 + 7.3943e-002 X + 5.9382e+003</p>
<p>which matches the python output. Link to .rtf document for the algorithm I use, including example c code:</p>
<p><a h... | python|c++|numpy|polynomial-math|gsl | 0 |
365,726 | 30,279,750 | Finding 2 largest eigenvalues of large-sparse matrix in Python | <p><br>
I want to find the 1st and 2nd largest eigenvalues of a big, sparse and symmetric matrix (in python). scipy.sparse.linalg.eigsh with k=2 gives the second largest eigenvalue with respect to the absolute value - so it's not a good solution. In addition, I can't use numpy methods because my matrix is too big and n... | <p><strong>tl;dr: You can use the <code>which='LA'</code> flag as described in the <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.sparse.linalg.eigsh.html" rel="nofollow">documentation</a>.</strong></p>
<p>I quote:</p>
<blockquote>
<p>scipy.sparse.linalg.eigsh(A, k=6, M=None, sigma=None, ... | python|numpy|scipy|sparse-matrix|eigenvalue | 2 |
365,727 | 29,974,672 | Writing pandas DataFrame to Excel with different formats for different columns | <p>I am trying to write a pandas <code>DataFrame</code> to an <code>.xlsx</code> file where different numerical columns would have different formats. For example, some would show only two decimal places, some would show none, some would be formatted as percents with a "%" symbol, etc. </p>
<p>I noticed that <code>Data... | <p>You can do this with Pandas 0.16 and the XlsxWriter engine by accessing the underlying workbook and worksheet objects:</p>
<pre><code>import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame(zip(
[1010, 2020, 3030, 2020, 1515, 3030, 4545],
[.1, .2, .33, .25, .5, .75, .45],
[.1,... | python|excel|pandas|openpyxl | 13 |
365,728 | 30,031,920 | Make numpy.sum() return a sum of matrices instead of a single number | <p>I am doing a fairly complicated summation using a matrix with numpy.
The shape of the matrix is <code>matrix.shape = (500, 500)</code> and the shape of the array is <code>arr.shape = (25,)</code>. The operation is as follows:</p>
<pre><code>totalsum = np.sum([i * matrix for i in arr])
</code></pre>
<p>Here is wha... | <p>You must call np.sum with the optional axis parameter set to 0 (summation over the axis 0, i.e the one created by your list comprehension)</p>
<pre><code>totalsum = np.sum([i * matrix for i in arr], 0)
</code></pre>
<p>Alternatively, you can omit the brackets so np.sum evaluate a generator.</p>
<pre><code>totalsu... | python|arrays|numpy|matrix|sum | 7 |
365,729 | 30,097,549 | How to realize the probability marginalize function using DataFrame in pandas? | <p>I have a probability table like this:<br></p>
<pre><code> BC_array =[np.array(['B=n','B=m','B=s','B=n','B=m','B=s']),np.array(['C=F', 'C=F', 'C=F', 'C=T', 'C=T', 'C=T'])]
pD_BC_array=np.array([[0.9,0.8,0.1,0.3,0.4,0.01],[0.08,0.17,0.01,0.05,0.05,0.01],[0.01,0.01,0.87,0.05,0.15,0.97],[0.01,0.02,0.02,0... | <p>You can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html#pandas.DataFrame.sum" rel="nofollow"><code>sum</code></a> on the df and pass params <code>axis=1</code> for row-wise and <code>level=0</code> to sum along that level:</p>
<pre><code>In [259]:
pD_BC.sum(axis=1, lev... | python|pandas | 1 |
365,730 | 29,884,046 | Build pandas dataframe in for loop | <p>I have a for loop that iterates over a dataframe and calculates two pieces of information:</p>
<pre><code>for id in members['id']
x = random_number_function()
y = random_number_function()
</code></pre>
<p>I'd like to store id, x and y in a dataframe that is built one row at a time, for each pass through th... | <p>Here's an example of using a dict to build a dataframe:</p>
<pre><code>dict_for_df = {}
for i in ('a','b','c','d'): # Don't use "id" as a counter; it's a python function
x = random.random() # first value
y = random.random() # second value
dict_for_df[i] = [x,y] # store in a dict
df ... | for-loop|pandas|dataframe | 4 |
365,731 | 53,601,657 | Combine multiple dictionaries into one pandas dataframe in long format | <p>I have several dictionaries set up as follows:</p>
<pre><code>Dict1 = {'Orange': ['1', '2', '3', '4']}
Dict2 = {'Red': ['3', '4', '5']}
</code></pre>
<p>And I'd like the output to be one combined dataframe:</p>
<pre><code>| Type | Value |
|--------------|
|Orange| 1 |
|Orange| 2 |
|Orange| 3 |
|Orange... | <p>One option is using <code>pd.concat</code>:</p>
<pre><code>pd.concat(map(pd.DataFrame, mydicts), axis=1).melt().dropna()
variable value
0 Orange 1
1 Orange 2
2 Orange 3
3 Orange 4
4 Red 3
5 Red 4
6 Red 5
</code></pre>
<hr>
<p>If performance matters, you can in... | python|pandas|dictionary|dataframe | 6 |
365,732 | 53,392,451 | get string slices in a groupby statement python | <p>I have a dataframe where I want to group by the ID field and get last letters in GG field. For example, say I have the following:</p>
<pre><code>df1 = pd.DataFrame({
'ID':['Q'] * 3,
'GG':['L3S_0097A','L3S_0097B','L3S_0097C']
})
print (df1)
ID GG
0 Q L3S_0097A
1 Q L3S_0097B
2 Q L3... | <p>Use syntactic sugar - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by - 2 <code>Series</code> - <code>GG</code> Series with last value and <code>df1['ID']</code>:</p>
<pre><code>mm = df1['GG'].str[-1].groupby(df1['ID'])... | python-3.x|pandas | 1 |
365,733 | 53,654,940 | Convert for loop which calls different functions to a generator | <p>I am reading a list of csv's, performing computations, and writing the output to drive. The dataset is large (2 gb csv on 16gb RAM), the calculation is expensive and output is also large. Therefore I want to use a generator; so that I can write my output file one at a time. The functions I have used are big, hence n... | <p>I am appending list of exceptions. So I set the program to run after every 5mins using <code>time</code> module. Because it's not going to be easy to define all the exceptions inside the generator. </p>
<pre><code>exceptions_list = []
def gen_out(paths):
for i in paths:
try:
yield csv_to_ou... | python-3.x|pandas|generator | 0 |
365,734 | 53,463,798 | Concatenating select columns of a panda, while ignoring blanks in columns | <p>I have a data frame which looks like this.</p>
<pre><code>key A1 A2 A3 BX CX DX
1 X1 Y1 B1 C1 D1
2 X2 Z2 B2 C2 D2
3 X3 B3 C3 D3
4 X4 B4 C4 D4
5 B5 C5 D5
</code></pre>
<p>I am trying to form a new col 'NC' which is concatenated from columns A1,A2 and A3. If there is no entry in ... | <p>You can use <code>filter</code> to filter your columns, and <code>agg</code> to join:</p>
<pre><code># Extract columns
v = df.filter(like='A')
# Convert blanks to NaNs so we can call Series.dropna later.
df['NC'] = v[v.astype(bool)].agg(lambda x: '_'.join(x.dropna()), axis=1)
# Or,
# df['NC'] = v[v.astype(bool)].ag... | python|pandas | 2 |
365,735 | 53,569,363 | RETURNN Custom Layer Search Mode Assertion Error | <p>I've implemented a custom RETURNN layer (<a href="https://github.com/nikita68/returnn/blob/master/TFNetworkHMMFactorization.py" rel="nofollow noreferrer">HMM Factorization</a>), which works as intended during training, but throws an assertion error when used in search mode. The output of the layer is identical to th... | <p>This is actually a bug in RETURNN. I created a pull request <a href="https://github.com/rwth-i6/returnn/pull/90" rel="nofollow noreferrer">here</a> which should fix that, and merged that in now.</p>
<p>The problem was not with your custom layer, but rather with a layer inside your RecLayer, which was actually total... | tensorflow|returnn | 0 |
365,736 | 53,360,508 | Python data error: ValueError: invalid literal for int() | <p>I have the below dataframe</p>
<pre><code>customerid birthdate
8a1edbf14734127f0147356fdb1b1eb2 45
8a2ac4745091002b0150a144bcbe58b7 24
</code></pre>
<p>customerid is the unique identifier of type <code>non-null object</code> . Howerever I want to convert it into an integer for me ... | <p>It looks like need convert hex values to integers:</p>
<pre><code>df['customerid'] = df['customerid'].apply(lambda x: int(x, 16))
print (df)
customerid birthdate
0 183593693287801188128470244383876914866 45
1 183655524454060116426046384483461912759 24
</code></pre>
... | python|python-3.x|pandas | 0 |
365,737 | 53,653,303 | Where is the tensorflow session in Keras | <p>I'm new to keras and tensorflow.
When I write programs with tensorflow, I must bulid a session to run the graph. However, when I use keras, although the backend is obviously tensorflow, I don't see session in the keras code. It seems all thing is done after the model.compile and model.fit.</p>
<p>So, how does Kera... | <p>Keras doesn't directly have a session because it supports multiple backends. Assuming you use TF as backend, you can get the global session as:</p>
<pre><code>from keras import backend as K
sess = K.get_session()
</code></pre>
<p>If, on the other hand, yo already have an open <code>Session</code> and want to set i... | python|tensorflow|keras|deep-learning|keras-layer | 18 |
365,738 | 53,700,965 | Pandas to Excel (Merged Header Column) | <p>I want to convert my df to an excel sheet, but also want to add a header column to categorize all the columns. <a href="https://i.stack.imgur.com/GqGW6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GqGW6.png" alt="Here is a screenshot without the merged column header"></a></p>
<p><a href="https://i.stac... | <p>You can create <code>MultiIndex</code>:</p>
<pre><code>df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
</code></pre>
<p>Specified new name of level with start and end colum... | python|excel|pandas | 9 |
365,739 | 53,660,736 | numpy.random Seed in multiprocessing | <p>I have a distributed process of a random process. Therefor I use the <code>numpy.random.RandomState</code> to seed the numbers.
The problem is that I have to use another <code>numpy.random</code> function inside my wrapper. Now I am losing the reproducibility of the seed because I cant control the order of the funct... | <p>Setting the seed differently isn't going to solve your reproducibility problem. (It'd solve another problem we'll get to later, but it won't solve the reproducibility problem.) Your reproducibility issue comes from the nondeterministic assignment of tasks to workers, which is not controlled by any random seed.</p>
... | python|numpy | 1 |
365,740 | 53,620,023 | Python Pandas read_html get rid of nested span element in table | <p>I try to grab some stock data from a website. The german website onvista.de have all the information I need. Now I tried to get the stock data into a pandas dataframe.</p>
<p>Like this:
<code>
url = '<a href="https://www.onvista.de/aktien/fundamental/ADLER-REAL-ESTATE-AG-Aktie-DE0005008007" rel="nofollow noreferrer... | <p>Once you have each table into a list of lists you can add to a new data frame. Example data:</p>
<pre><code>raw_data = [
['Gewinn', '2020e', '2019e', '2018e', '2017', '2016', '2015', '2014'],
['Gewinn pro Aktie in EUR', '-', '1,20', '0,89', '1,91', '2,11', '1,83', '4,65'],
['KGV', '-', '12,52', '16,79',... | python|html|pandas|dataframe|beautifulsoup | 0 |
365,741 | 53,660,125 | How to add a Hodrick-Prescott filtered trend on a pandas groupby? | <p>I'm currently stuck trying to get the <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.filters.hp_filter.hpfilter.html" rel="nofollow noreferrer">Hodrick-Prescott</a> trend from different groups within a monthly dataset. Here's a replica of the dataset:</p>
<pre><code>import pandas as pd
import nu... | <pre><code>groups = final_df.groupby('id')
group_keys = list(groups.groups.keys())
bs = pd.DataFrame()
for key in group_keys:
g = groups.get_group(key).copy()
target = g['target']
cycle, trend = sm.tsa.filters.hpfilter(target, lamb=129600)
g['hp_trend'] = trend
bs = bs.append(g)
bs
</code></p... | python-3.x|pandas|pandas-groupby | 1 |
365,742 | 53,625,978 | I am trying to convert .pb file to .mlmodel file. I am getting an error "Tensorflow graph does not contain a tensor with this name" | <p>I tried using tfcoreml and the error is :</p>
<p>Loading the TF graph...</p>
<p>2018-12-05 11:16:50.591360: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA</p>
<p>Graph Loaded.
Collecting all the 'Const' ops from the... | <p>When you call <code>tfcoreml.convert()</code> you need to supply the name of the tensor with the model's output. You supplied <code>"softmax:0"</code>, probably because you saw that in a tutorial somewhere. But apparently this is not the name of the output from your own TensorFlow graph. </p>
<p>You can use a tool ... | python-3.x|tensorflow|coreml|mlmodel | 1 |
365,743 | 53,599,329 | Python: replace string in the dataframe/column if only 1 word in the row | <p>I have pretty messy data I am trying to replace rows that might contain only 1 word or string with '' or empty string. </p>
<p>Here is the original data: </p>
<pre><code>df = pd.DataFrame({'some_text': [
'I enjoy read Mark Twain\'s Books',
'Library is very useful',
'/',
'\\',
... | <p>With the implementation you made, instead of drop the rows, asign a new value like this:</p>
<pre><code>count = df['some_text'].str.split().str.len()
df[count == 1] = ""
</code></pre> | python|python-3.x|pandas | 2 |
365,744 | 53,538,847 | Inserting blank row pandas dataframe | <p>i have a columns called 'factor' and each time a name in that column changes, i would like to insert a blank row, is this possible?</p>
<pre><code>for i in range(0, end):
if df2.at[i + 1, 'factor'] != df2.at[i, 'factor']:
</code></pre> | <p>It's inefficient to manually insert rows sequentially in a <code>for</code> loop. As an alternative, you can find the indices where changes occur, construct a new dataframe, concatenate, then sort by index:</p>
<pre><code>df = pd.DataFrame([[1, 1], [2, 1], [3, 2], [4, 2],
[5, 2], [6, 3]], columns... | python|python-3.x|pandas|dataframe | 7 |
365,745 | 53,557,806 | Matching if value of a column in a df is one of the values of another column in the same dataframe(going row by row) | <p>df</p>
<pre><code>col1 col2
A a|x|y
B a|x|y
C c|x|z
D e|j|y
</code></pre>
<p>My objective is to make a new column named 'status' to see if entry in col1 is one of the entry in col2 (separated by pipe).
output should be like this</p>
<pre><code>col1 col2 status
A a|x|y True
B ... | <h3><code>get_dummies</code></h3>
<pre><code>df.col2.str.get_dummies().mul(pd.get_dummies(df.col1.str.lower())).sum(1).astype(bool)
0 True
1 False
2 True
3 False
dtype: bool
</code></pre>
<hr>
<pre><code>a = pd.get_dummies(df.col1.str.lower())
b = df.col2.str.get_dummies()
status = b.mul(a).sum(1).ast... | python|string|pandas|matching | 3 |
365,746 | 53,713,311 | I'm try to count each occurence from sublists in a main list and make a graph | <p>This is the list:</p>
<pre><code>for i in programming_skills_list:
print i
output: ['SQL', 'C', 'Excel']
['R', 'SQL', 'C']
['SQL', 'C']
['R', 'SQL', 'C']
['SQL', 'C']
['R', 'C']
['R', 'C']
['R', 'C', 'Excel']
['R', 'SQL', 'C', 'Excel']
['R', 'Tableau', 'SQL', 'C']
['R', 'Tableau', 'SQL', 'C', 'Excel']
['R', 'C... | <p>We can use pandas to get value counts and plot:</p>
<pre><code>import pandas as pd
programming_skills_list = #however you defined that list of list above#
s = pd.Series(sum(programming_skills_list, []))
s.value_counts().plot.bar()
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/p4DJd.png" rel="... | python|pandas|list|data-visualization | 1 |
365,747 | 53,450,520 | Numpy: adding n-dimensional vector to m-dimensional vector to get (n, m) matrix | <p>Suppose I have the array [1,2,3,4,5].
I want to "add" the array [2,4,6,8] to it so I get</p>
<pre><code>[[3,5,7,9],
[4,6,8,10],
[5,7,9,11],
[6,8,10,12],
[7,9,11,13]]
</code></pre>
<p>(or its transpose).</p>
<p>There is probably a function for this but I can't seem to find it because I'm not sure what to searc... | <p>As suggested by @Divakar, the best way is to use <code>add.outer</code>:</p>
<pre><code>a1 = np.array([1,2,3,4,5])
a2 = np.array([2,4,6,8])
np.add.outer(a1,a2)
</code></pre>
<p>But you can also explicitely <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html" rel="nofollow noreferrer">br... | numpy|array-broadcasting|numpy-ndarray | 0 |
365,748 | 53,432,089 | Invert matrix without Numpy in Python | <p>i try this for matrix 2x2 and matrix 3x3 but i would like to use some loops like <strong>for</strong> or <strong>while</strong>.</p>
<pre><code>from libmatrice import det2, det3, comatrice, transposee, inverse
reponse = input('Quelle est la dimension de la matrice à inverser (2 ou 3) ?\n')
determinant = 0
if rep... | <p>you can work with <code>for</code> loops of you represent your matrices as lists (of lists):</p>
<pre><code>A = [[1, 2], [3, 4]]
def det2(A):
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
def inv2(A):
d = det2(A)
return [[A[1][1]/d, -A[0][1]/d], [-A[1][0]/d, A[0][0]/d]]
print(det2(A)) # 2
print(inv2(A))... | python|numpy | 0 |
365,749 | 53,367,059 | How to zero pad dense layer in Keras? | <p>I can see there is <code>ZeroPadding1D</code> in Keras <a href="https://keras.io/layers/convolutional/#zeropadding1d" rel="nofollow noreferrer">[doc]</a>, but it require <code>3D tensor with shape (batch, axis_to_pad, features)</code>, but how to zero pad dense layer output on the right side with shape <code>(batch,... | <p>You can do it with <a href="https://www.tensorflow.org/api_docs/python/tf/reshape" rel="nofollow noreferrer">tensorflow.reshape()</a>:</p>
<pre><code>x = Dense(64, activation='linear')(x)
x = Reshape([-1, 1])(x)
x = ZeroPadding1D(padding=(0,64))(x)
</code></pre>
<p><strong>A simple example:</strong></p>
<pre><cod... | python|tensorflow|keras|deep-learning | 1 |
365,750 | 53,421,179 | Forming conditional distributions in TensorFlow probability | <p>I am using Tensorflow Probability to build a VAE which includes image pixels as well as some other variables. The output of the VAE:</p>
<pre><code>tfp.distributions.Independent(tfp.distributions.Bernoulli(logits), 2, name="decoder-dist")
</code></pre>
<p>I am trying to understand how to form other conditional dis... | <p>The answer to your question depends very much on the nature of the joint model within which you'd like to do the conditioning. Much has been written about the topic, and in short it's a very hard problem in general :). Without knowing a bit more about the particulars of your problem, it's near impossible to recommen... | tensorflow|machine-learning|autoencoder|tensorflow-probability | 3 |
365,751 | 53,794,856 | Loop iteration through character instead of word when trying to remove stop words from a Pandas Dataframe | <p>I'm trying to remove stop words from strings stored in a pandas DataFrame, but for some reason instead of iterating through the words of the strings I'm iterating through every character, which gives me an unwanted result. I was not able to find any solution to this problem. </p>
<p>Can someone please explain why a... | <p>At first it seemed that I couldn't reproduce... Copying raw data from your example:</p>
<pre><code>>>> trainData = pd.DataFrame([(['o', 'que', 'causa'], ['causadorDe']), (['o', 'que', 'leva', 'á', 'existência', 'de'], ['causadorDe'])], columns=['text', 'response'])
>>> trainData
... | python|pandas|nlp | 2 |
365,752 | 53,392,177 | How to interpolate 2D array from a coarser resolution to finer resolution | <p>Suppose that I have an emission data with shape <code>(21600,43200)</code>,
which corresponds to the <code>lat</code> and <code>lon</code>,i.e, </p>
<pre><code>lat = np.arange(21600)*(-0.008333333)+90
lon = np.arange(43200)*0.00833333-180
</code></pre>
<p>And I also have a scaling factor with shape of <code>(720,1... | <p>Here's a complete example of the kind of interpolation you're trying to do. For example purposes I used <code>emission</code> data with shape <code>(10, 20)</code> and <code>scale</code> data with shape <code>(5, 10)</code>. It uses <code>scipy.interpolate.RectBivariateSpline</code>, which is the recommended method ... | numpy|scipy|netcdf|python-xarray | 5 |
365,753 | 53,492,524 | Using groupby function properly | <p>I have a dataframe called df1 which looks like this:</p>
<pre><code>details endFrame id indexID object startFrame
List of dictionaries 1 1111 78 0 Motorbike 1
List of dictionaries 2 3647 78 0 Motorbike 1112
List of dictionaries 3 3678 78 0 Motorbike 3649
List ... | <pre><code>_newdf2 = df1.groupby('indexID')['detail'].sum().reset_index()
for index,row in _newdf2.iterrows():
x = _newdf.loc[df1['indexID'] == row['indexID'], 'object']
_newdf2['object'] = x.to_string().lstrip('0123456789.- ')
</code></pre> | pandas|python-2.7|dataframe|group-by | 1 |
365,754 | 53,652,185 | Modifying values of a sub-array in python | <p>I want to modify the values of a sub-array in Python but it does not work the way I would like to. Here is an example, first let us consider the numpy arrays :</p>
<pre><code>A = np.reshape(np.arange(25),(5,5))
</code></pre>
<p>and </p>
<pre><code>B = np.ones((2,3))
</code></pre>
<p>If we check the values of A w... | <p>This is a confusing case. What's happening is</p>
<pre><code>A[:, [1,3,4]]
</code></pre>
<p>indexes into <code>A</code>, creating a new array containing columns 1, 3, and 4 of <code>A</code>. The next expression, <code>[[1, 3], :]</code> indexes the rows of that temporary array and sets it's values.</p>
<p>To ... | python|numpy|sub-array | 1 |
365,755 | 53,592,206 | Printing mutiple columns in Pandas (Python) | <p>I'm new to Python and the Pandas module, but I can't seem to get this to work.</p>
<p>This is my code. I'm using a csv file containing the month and rainfall for Singapore.</p>
<p>Below is my code: 0</p>
<pre><code>df = pd.read_csv('rainfall-monthly-total.csv')
print ((df['total_rainfall'])[df.total_rainfall == df[... | <p>Try this:</p>
<pre><code>print ((df[['total_rainfall', 'month']])[df.total_rainfall == df['total_rainfall'].max()]
</code></pre>
<p>You need to convert single square brackets to double:</p>
<pre><code>['total_rainfall', 'month']
</code></pre>
<p>TO</p>
<pre><code>[['total_rainfall', 'month']]
</code></pre> | python|pandas | 3 |
365,756 | 53,476,874 | Using GPU error when use TensorFlow to train image | <p>When I am runing a tensorflow image train job in the container tensorflow/tensorflow:latest-gpu, it doesn't work.</p>
<p>Error message:</p>
<pre><code>Cannot assign a device for operation InceptionV3/InceptionV3/Conv2d_1a_3x3/Conv2D: Operation was explicitly assigned to /device:GPU:0 but available devices are [ /j... | <p>It seems that you Tensorflow is not detecting any gpu as available but maps the operations to GPU:0. First try this: </p>
<pre><code>from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
</code></pre>
<p>And you'll get the available devices. Is there <code>/device:GPU:0</code> ?</p... | tensorflow|gpu | 0 |
365,757 | 53,492,199 | How to concat a scalar to a 1D vector in Keras? | <p>I have a Keras layer of Shape (None, 8) and I would like to append a single scalar (value = 1) to the end of the Tensor. However I haven't been successful.</p>
<p>Here is my code (simplified):</p>
<pre><code>print(layers)
# Tensor("feature_layer_2_89/Relu:0", shape=(?, 8), dtype=float32)
pad_tensor = tf.constant([... | <p>You could create the <code>pad_tensor</code> such that it has the rank 2 as @Psidom suggested. So first we need to get the <code>batch_size</code> as follows:</p>
<pre><code>batch_size = tf.shape(layers)[0]
padding_tensor = tf.ones([batch_size, 1])
</code></pre>
<p>Now we can use <code>concatenate</code> function ... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
365,758 | 53,608,633 | Way to remove keys that have array of zeros as value | <p>I have nested dict as follows:</p>
<pre><code> u'dvlRaw':{
u'diagnosticInfoUDP': {
u'clientConnected': array([0, 0, 0, 0, 0, 0, 0,0, 0,0], dtype=uint8),
u'channel': array([1, 1, 1, ..., 1, 1, 1], dtype=uint32)
}
}
</code></pre>
<p>How to remove the key, value pairs for which values that have ... | <p>Use <code>numpy.any</code> to check if each array contains any non-zero value or not:</p>
<pre><code>import numpy as np
diagnosticInfoUDP = dictionary['dvlRaw']['diagnosticInfoUDP']
for key in list(diagnosticInfoUDP):
if not np.any(diagnosticInfoUDP[key]):
del diagnosticInfoUDP[key]
</code></pre>
<p><... | python|numpy|dictionary | 1 |
365,759 | 53,521,066 | How to find the intersection of a pair of columns in multiple pandas dataframes with pairs in any order? | <p>I have multiple pandas dataframes, to keep it simple, let's say I have three.</p>
<pre><code> >> df1=
col1 col2
id1 A B
id2 C D
id3 B A
id4 E F
>> df2=
col1 col2
id1 B A
id2 D C
id3 M N
id4 F E
&... | <p>You can create list of <code>DataFrame</code>s and in list comprehension sorting per rows with removing duplicates:</p>
<pre><code>dfs = [df1,df2,df3]
L = [pd.DataFrame(np.sort(x.values, axis=1), columns=x.columns).drop_duplicates()
for x in dfs]
print (L)
[ col1 col2
0 A B
1 C D
3 E F, ... | python|python-3.x|pandas|dataframe | 5 |
365,760 | 53,484,051 | Python plotting dictionary | <p>I am VERY new to the world of python/pandas/matplotlib, but I have been using it recently to create box and whisker plots. I was curious how to create a box and whisker plot for each sheet using a specific column of data, i.e. I have 17 sheets, and I have column called HMB and DV on each sheet. I want to plot 17 dat... | <p>I agree with @Alex that forming your columns into a new DataFrame and then plotting from that would be a good approach, however, if you're going to use the dict, then it should look something like this. Depending on the version of Python you're using, the dictionary may be unordered, so if the ordering on the plot i... | python|pandas|matplotlib | 2 |
365,761 | 53,501,704 | Python - pandas different size of cartesian product every run | <p>I have two dataframes in python, and I want to do a cartesian product of them.
For that I have used the merge with the same key command as follow:</p>
<pre><code>print("dna", df_genes.size)
print("names",df_citations.size)
df_genes['key'] = 0
df_citations['key'] = 0
df = pd.merge(df_genes, df_citations, on='key').... | <p>Don't use .size, which shows the number of rows times columns. To check if your cartesian product worked, you expect that when df1 has 5 rows and df2 has 3 rows, the cartesian product would result in 15 rows. This you can check by replacing .size by .shape or .shape[0]</p>
<p>In your case:</p>
<pre><code>print("dn... | python|python-3.x|pandas|dataframe|cartesian-product | 2 |
365,762 | 53,588,170 | How to replace row with float values with in a nested numpy array with a row of `NaN`s? | <p>Say i have a numpy array:</p>
<pre><code>a=np.array([[7,2,4],[1.2,7.4,3],[1.5,3.6,3.4]])
</code></pre>
<p>And my goal is to replace rows that which contain floats with a row of <code>NaN</code>s, and so far this is my attempt:</p>
<pre><code>a[a.dtype==float]=np.nan
</code></pre>
<p>Which works, but only the fir... | <p>Try rounding:</p>
<pre><code>a[np.round(a)!=a] = np.nan
#array([[ 7., 2., 4.],
# [nan, nan, 3.],
# [nan, nan, nan]])
</code></pre> | python|arrays|numpy|replace|nan | 3 |
365,763 | 53,492,970 | Python - Keras Model doesnt converge | <p>I have a network with <code>32</code> input nodes, <code>20</code> hidden nodes and <code>65</code> output nodes. My network input actually is a hash code of length <code>32</code> and the output is the word.
The input is the ascii value of each character of the Hash code. The output of the network is a binary repre... | <p>There are some hyper parameters that i would suggest to change first. </p>
<p>Try <code>'relu'</code> or <code>LeakyReLU()</code> as the activation function for the non-output layers. Basically <code>relu</code> is the standard activation function for baseline models. </p>
<p>The standard optimizer (for most cas... | python|tensorflow|machine-learning|keras|neural-network | 1 |
365,764 | 53,671,437 | How does the validation accuracy decide which class is correct in a binary classification with Keras? | <p>I've been using Keras for binary classification with Tensorflow backend in Python. My model is created like this : </p>
<pre><code>model = Sequential()
model.add(Dense(1000, input_dim=168319))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(loss="binary_crossentropy",
optimizer="adam",
... | <p>Since you are using <code>binary_crossentropy</code>, in this case each of your six classes is evaluated separately. For each a value above 0.5 is set to 1. Below 0.5 is set to 0. If you were using <code>categorical_crossentropy</code> then only one of the classes can be 1. Whichever has the highest probability will... | python|tensorflow|machine-learning|keras | 0 |
365,765 | 53,675,183 | Error in concat1D: rank of tensors[23] must be the same as the rank of the rest | <p>Tensorflow 1.12.0</p>
<p>I traned SSD_Mobilenet_V1_pnp model (pre-trained with COCO) with my dataset.</p>
<p>On phyton works - detect objects good</p>
<p>Convert to js.</p>
<p>In Browser Run with error:</p>
<pre><code>tfjs@latest:2 Uncaught (in promise) Error: Error in concat1D: rank of tensors[23] must be the ... | <p>I faced the same kind of issue in <code>tfjs-node</code> and this error might need you to follow <a href="https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd#technical-details-for-advanced-users" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd#technical-details-for... | javascript|tensorflow|tensor | 1 |
365,766 | 53,720,059 | Dictionary not handling multiple values | <p>I am trying to create a dataframe of states and cities.</p>
<p>Each state name in the table I am reading from ends with the letters [edit],city on the other hand either end with (<em>text</em>)[<em>number</em>]</p>
<p>I have used regex to remove the text within the parentheses and square brackets, saved states in ... | <p>Note that:</p>
<pre><code>city_st = dict(zip(state,city))
</code></pre>
<p>this operation could lead to reduce number of your result because of multi value.</p>
<p>you can just use </p>
<pre><code>aa = pd.dataframe({'state': state,'city': city})
aa['State' ] = range(aa.shape[0])
</code></pre>
<p>then use the pi... | python|python-3.x|pandas|data-analysis|data-cleaning | 0 |
365,767 | 53,734,646 | Group Dataframe Column Graph Based on Common x Axis Values | <p>I have a dataframe that looks at local maximums of Mass from 2001 to 2015. A section of it looks like:</p>
<p><a href="https://i.stack.imgur.com/yqUT1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yqUT1.png" alt="enter image description here"></a></p>
<p>I'm using the below to plot the datafra... | <p>I believe this should fix the problem...assuming that each group of year has the same length. IF not then you may need to subplot each group.</p>
<pre><code># sample df
df = pd.DataFrame({'year':[2001,2001,2001,2001,2002,2002,2002,2002], 'mass':[1,2,3,4,1,3,2,4]})
# create a multiindex from the cumcount of each ye... | python|pandas|matplotlib | 1 |
365,768 | 53,384,990 | Strange output error following example of matirx vector operation in python | <p>I want to do this in python, here is a small example:</p>
<pre><code>number_of_payments = [
[0, 1, 0, 1, 1, 1, 0, 5, 1, 0, 2, 1],
[0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0],
[1, 3, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]
]
NDD_month = [8, 7, 11]
dates = []
for i in range(len(number_of_payments)):
dates.append([NDD_... | <p>In your "small example", <code>number_of_payments</code> is a <code>list</code> of <code>list</code> of <code>int</code>s:</p>
<pre><code>number_of_payments = [
[0, 1, 0, 1, 1, 1, 0, 5, 1, 0, 2, 1],
[0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0],
[1, 3, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]
]
</code></pre>
<p>In your re... | python|list|numpy|matrix | 1 |
365,769 | 53,647,206 | Apply custom function to 2 or more rows (or columns) in numpy | <p>I am fairly new to <code>numpy.</code> I want to apply a custom function to 1, 2 or more rows (or columns). How can I do this? Before this is marked as duplicate, I want to point out that the only thread I found that does this is <a href="https://stackoverflow.com/questions/44239498/how-to-apply-a-generic-function-o... | <p>You can simply roll your axis along the <code>0</code>th axis</p>
<pre><code>np.roll(M, -1, axis=0)
# array([[6, 1, 2],
# [1, 2, 4],
# [8, 3, 2]])
</code></pre>
<p>And multiply the result with your original array</p>
<pre><code>M * np.roll(M, -1, axis=0)
# array([[48, 3, 4],
# [ 6, 2, 8],... | python|arrays|numpy|scipy | 1 |
365,770 | 53,555,215 | How to read a csv file, which has double quotes next to commas | <p>I have a csv file that its rows look like this</p>
<p><code>q4_1,"blabla,bla",new_label
q4_2,alb,new_label2</code></p>
<p>and I would like to read it in a <code>pandas</code> <code>data.frame</code> that will look like this</p>
<pre><code>import pandas as pd
pd.DataFrame({'col1' : ['q4_1','q4_2'],
... | <p>With <strong>python 3.7</strong> and <strong>pandas 0.23.4</strong>, worked this:</p>
<pre><code>import pandas as pd
df0 = pd.read_csv('data.csv', names=["col1", "col2", "col3"], squeeze=True)
</code></pre>
<p>the result is a DataFrame with the structure described in the question:</p>
<pre><code> col1 ... | python|python-3.x|pandas|csv | 0 |
365,771 | 17,131,083 | why dividing by a scalar in numpy (pylab) return zero (within a script)? | <p>When I run the following inside a script:</p>
<pre><code>from pylab import *
N_rec = 1000
pt = 0.1
bitstrm = rand(N_rec,1)
bitstrm = (bitstrm<=pt)
hist_strm = histogram(bitstrm, 2)
p_strm = (hist_strm[0])/sum(hist_strm[0])
print p_strm
</code></pre>
<p>I get <code>[0 0]</code></p>
<p>However, doing it on the... | <p>That's because you are dividing a integer array, you have to previously converted it to float:</p>
<pre><code>>>> from pylab import *
>>> import numpy as np
>>> N_rec = 1000
>>> pt = 0.1
>>> bitstrm = rand(N_rec,1)
>>> bitstrm = (bitstrm<=pt)
>>> his... | numpy|matplotlib | 1 |
365,772 | 17,400,963 | Slicing numpy recarray at "empty" rows | <p>I created a <code>numpy.recarray</code> from a .csv-Inputfile using the <code>csv2rec()</code>-Method. The Inputfile and consequently the recarray have empty rows with no data (resp. <code>nan</code>-values). I want to slice this recarray at the <code>nan</code>-rows into multiple sub-arrays, excluding the <code>nan... | <p>For a <code>2D-array</code>:</p>
<pre><code>a[~np.all(np.isnan(a),axis=1)]
</code></pre>
<p>For a structured array (recarray) you can do this:</p>
<pre><code>def remove_nan(a, split=True):
cols = [i[0] for i in eval(str(a.dtype))]
col = cols[0]
test = ~np.isnan(a[col])
if not split:
new_le... | python|numpy|slice|recarray | 1 |
365,773 | 17,148,787 | Are there functions to retrieve the histogram counts of a Series in pandas? | <p>There is a method to <strong>plot</strong> Series histograms, but is there a function to retrieve the histogram counts to do further calculations on top of it? </p>
<p>I keep using numpy's functions to do this and converting the result to a DataFrame or Series when I need this. It would be nice to stay with pandas ... | <p>If your Series was discrete you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>value_counts</code></a>:</p>
<pre><code>In [11]: s = pd.Series([1, 1, 2, 1, 2, 2, 3])
In [12]: s.value_counts()
Out[12]:
2 3
1 3
3 1
dtype: int64... | pandas|histogram|series | 17 |
365,774 | 20,338,663 | Efficiently sample all arrays in ndarray using scipy.ndimage.map_coordinates | <p>I have a 3D stack of masked arrays. I'd like to sample all arrays in the stack at the same fixed locations. </p>
<pre><code>stack.ma_stack.shape
</code></pre>
<p>(1461, 390, 327)</p>
<pre><code>#Indices to be sampled
x = np.array([ 117.38670304, 119.1220485 ])
y = np.array([ 209.98120554, 210.37202372])
</cod... | <p>There must be a way to get it to broadcast automatically... in the meantime, you can force the broadcasting with <code>np.arange(...)</code> to get one point from each 2d array in the stack:</p>
<pre><code>map_coords = np.broadcast_arrays(np.arange(stack.ma_stack.shape[0])[:, None], y, x)
samp = ndimage.map_coordin... | python|numpy|scipy|multidimensional-array | 1 |
365,775 | 20,012,507 | Pandas: create dataframe from list of namedtuple | <p>I'm new to pandas, therefore perhaps I'm asking a very stupid question. Normally initialization of data frame in pandas would be column-wise, where I put in dict with key of column names and values of list-like object with same length.</p>
<p>But I would love to initialize row-wise without dynamically concat-ing row... | <p>In a similar vein to <a href="https://stackoverflow.com/a/17005204/1240268">creating a Series from a namedtuple</a>, you can use the <a href="http://docs.python.org/2/library/collections.html#collections.somenamedtuple._fields" rel="noreferrer"><code>_fields</code></a> attribute:</p>
<pre><code>In [11]: Point = nam... | python|pandas|dataframe | 42 |
365,776 | 20,165,369 | query a pandas dataframe based in index and datacolumns | <p>I have a Datset that looks like :</p>
<pre><code>data="""cruiseid year station month day date lat lon depth_w taxon count
AA8704 1987 1 04 13 13-APR-87 35.85 -75.48 18 Centropages_typicus 75343
AA8704 ... | <p>You can refer to <code>datetime</code>'s <code>month</code> attribute:</p>
<pre><code>>>> df.index.month
array([4, 4, 4, 7, 7, 8, 8, 8], dtype=int32)
>>> df[((df.taxon == 'Calanus_finmarchicus') | (df.taxon == 'Gastropoda'))
... & (df.index.month == 4)]
cruiseid station ... | python|numpy|pandas | 5 |
365,777 | 20,140,788 | Pandas colormap with groupby | <p>Pretty new to pandas and matplotlib and having trouble getting colormaps to work when using groupby.</p>
<p>Here is my test;</p>
<pre><code>x=[]
for i in range(5):
for j in range(9):
x.append({'time':datetime(2013,1,1+i), 'col1':chr(ord('A')+j), 'col2':chr(ord('Z')-j), 'value':100+i*j})
df=pd.DataFrame(... | <p>It sort of does work, but because you're plotting from a <code>GroupBy</code>, each group (containing 1 column) gets plotted after each other, but on the same axes. This single column gets the first color from the selected <code>colormap</code>.</p>
<p>To get the colormap to work, you need multiple columns, then eac... | python|pandas | 4 |
365,778 | 20,069,009 | Pandas get topmost n records within each group | <p>Suppose I have pandas DataFrame like this:</p>
<pre><code>df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4],'value':[1,2,3,1,2,3,4,1,1]})
</code></pre>
<p>which looks like:</p>
<pre><code> id value
0 1 1
1 1 2
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
7 3 1
8 4 1
</cod... | <p>Did you try</p>
<pre><code>df.groupby('id').head(2)
</code></pre>
<p>Output generated:</p>
<pre><code> id value
id
1 0 1 1
1 1 2
2 3 2 1
4 2 2
3 7 3 1
4 8 4 1
</code></pre>
<p>(Keep in mind that you might need to order/sort before, depending on... | python|pandas|greatest-n-per-group|window-functions|top-n | 279 |
365,779 | 6,629,546 | Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) to get ndarray of shape (...)? | <p>I have an function that maps an ndarray of shape (3) to a float, and I have an ndarray of shape (...,3). What's the best way to map that function over that array to get an array of shape (...)?</p>
<p>Thanks.</p> | <p>You want <code>numpy.apply_along_axis</code>.</p>
<pre><code>def f(a):
return a[0] + a[1] + a[2]
mm = numpy.random.randn(5, 3)
numpy.apply_along_axis(f, 1, mm)
</code></pre>
<p>output: <code>array([-1.75875289, -0.34689792, 0.66092486, -0.21626001, -0.14125476])</code></p> | python|functional-programming|numpy | 4 |
365,780 | 15,864,710 | How can I check if the values in a series are contained in any of the intervals defined the rows of a DataFrame? | <p>I realize my title is a bit confusing, but I think I can make it clearer if we proceed by example. What I want to do is a vectorized test to check if any of the values in a given series is contained in any of the intervals defined by a DataFrame object with a <code>start</code> and <code>stop</code> column.</p>
<p... | <p>Your blink data </p>
<pre><code>In [27]: blink = pd.DataFrame(dict(tstart = [0,10], tstop = [5,15]))
In [28]: blink_s = blink.stack()
In [29]: blink_s.index = [ "%s_%s" % (v,i) for i, v in blink_s.index ]
</code></pre>
<p>Construct a series of of the blink (kind of like pivoting), but we need new names</p>
<pre... | pandas|vectorization | 1 |
365,781 | 16,028,224 | optimizing indexing and retrieval of elements in numpy arrays in Python? | <p>I'm trying to optimize the following code, potentially by rewriting it in Cython: it simply takes a low dimensional but relatively long numpy arrays, looks into of its columns for 0 values, and marks those as -1 in an array. The code is:</p>
<pre><code>import numpy as np
def get_data():
data = np.array([[1,5,1... | <pre><code>cols = np.array([2] * K)
</code></pre>
<p>That's going to be really slow. That's create a very large python list and then converts it into a numpy array. Instead, do something like:</p>
<pre><code>cols = np.ones(K, int)*2
</code></pre>
<p>That'll be way faster</p>
<pre><code>result = np.array([1] * K)
</... | python|optimization|numpy|scipy|cython | 2 |
365,782 | 15,901,910 | Most appropriate conversion of .mat file for database purposes | <p>I am trying to create a database of my experimental results that with a very flexible structure (as different experiments require different experimental conditions). For now, I am thinking about going with JSON as the most appropriate format due to its "dictionary-like" nature. </p>
<p>My raw data files come in as ... | <p>JSON is plain text so the files will be bigger than in binary formats. I'd also suggest that you use HDF5.</p>
<p>From <a href="http://www.hdfgroup.org/HDF5/" rel="nofollow">http://www.hdfgroup.org/HDF5/</a>:</p>
<p>"HDF5 is a data model, library, and file format for storing and managing data. It supports an unlim... | python|json|matlab|numpy|pickle | 1 |
365,783 | 15,626,215 | Drop rows of pandas dataframe that don't have finite values in certain variable(s) | <p>I cannot see what the built-in function is for the following simple but seemingly common/useful task: Drop rows which have no value for any of my key columns.</p>
<pre><code>def keepIfPopulated(adf,interestingVars):
good=0
for vv in interestingVars:
good+=adf[vv].notnull()
return... | <pre><code>adf = adf.dropna(subset=interestingVars, how='all')
</code></pre> | pandas|notnull | 3 |
365,784 | 15,792,018 | how to access timestamp in DataFrame pandas? | <p>Having downloaded data from yahoo for a stock using the <code>get_data_yahoo</code> I then want to access the time for each row... How do I do that?</p>
<p>One way I've kind of figured out to do this is:</p>
<pre><code>it = stock.iterrows()
st0 = it.next()
resultIWant = st0[0].value # this gives what I want (almos... | <p>Timestamps have a <code>time</code> method:</p>
<pre><code>In [1]: t = pd.Timestamp('200101011300')
In [2]: t
Out[2]: <Timestamp: 2001-01-01 13:00:00>
In [3]: t.time()
Out[3]: datetime.time(13, 0)
</code></pre>
<p>The <code>value</code> is <strong>nanoseconds</strong> since midnight 1 January 1970 i.e. <a ... | python|pandas | 3 |
365,785 | 15,488,809 | How to trouble-shoot HDFStore Exception: cannot find the correct atom type | <p>I am looking for some general guidance on what kinds of data scenarios can cause this exception. I have tried massaging my data in various ways to no avail.</p>
<p>I have googled this exception for days now, gone through several google group discussions and come up with no solution to the debugging <code>HDFStore ... | <p>The link you provided worked just fine to store the frame. Column by column just means specifiy data_columns=True. It will process the columns individually and raise on the offending one.</p>
<p>To diagnose</p>
<pre><code>store = pd.HDFStore('test0.h5','w')
In [31]: for chunk in pd.read_csv('Train.csv', chunksize=... | python|pandas|hdf5 | 5 |
365,786 | 12,085,393 | Problems converting a large file to a panel using read_csv into python pandas | <p>I have been trying to load in a large-ish file <code>(~480MB, 5,250,000 records, stock price daily data -dt, o, h, l, c, v, val , adj, fv, sym, code - for about 4,500 instruments)</code> into pandas using <code>read_csv</code>. It runs fine, and creates the DataFrame. However, on conversion to a Panel, the values fo... | <p>Some bugs have been fixed in the DataFrame to Panel code. Please try with the latest pandas version (preferably upcoming 0.10) and let us know if you're still having issues.</p> | python|large-files|pandas | 1 |
365,787 | 12,428,226 | Error while plotting f(x) in python when x is an array of numbers | <p>I am just starting to try and learn python. I am having trouble plotting functions. I follow examples from the web and it seems to work fine. However, when I try it on my own stuff I get an error that the function can only take length 1 arrays to be used as scalars but I don't see the difference in my own attempts t... | <p>Are you using the functions in the correct module? Python's built-in <code>math.cos</code> only takes a single scalar value, whereas <code>numpy.cos</code> takes arrays as well:</p>
<pre><code>>>> import numpy
>>> import math
>>> math.cos([1, 2, 3])
Traceback (most recent call last):
Fi... | python|numpy | 1 |
365,788 | 12,502,122 | Python/numpy floating-point text precision | <p>Let's say I have some 32-bit and 64-bit floating point values:</p>
<pre><code>>>> import numpy as np
>>> v32 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635],
dtype=np.float32)
>>> v64 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635], ... | <p>Python 2.7 and later already have a smart <code>repr</code> implementation for floats that prints 0.1 as <code>0.1</code>. The brief output is chosen in preference to other candidates such as <code>0.10000000000000001</code> because it is the shortest representation of <em>that particular number</em> that roundtrips... | python|numpy|floating-point|precision | 7 |
365,789 | 12,321,899 | How to determine regions of pixels with a shared value using PIL | <p>I need to divide an image to regions of pixels whose RGB value pass a certain test.<br>
I'm OK with scanning the image and checking each pixel's value however the part of clustering them into regions and then getting those regions coordinates (x, y, width, height) leaves me in total dark :)<br>
here's the code I hav... | <p>[EDIT]</p>
<p>While the solution below works, it can be made better. Here is a version with better names and better performance:</p>
<pre><code>from itertools import product
from PIL import Image, ImageDraw
def closed_regions(image, test):
"""
Return all closed regions in image who's pixels satisfy test.... | python|numpy|scipy|python-imaging-library|cluster-analysis | 5 |
365,790 | 12,230,527 | Randomly shuffle a sparse matrix in python | <p>is there an easy way to shuffle a sparse matrix in python?</p>
<p>This is how I shuffle a non-sparse matrix:</p>
<pre><code> index = np.arange(np.shape(matrix)[0])
np.random.shuffle(index)
return matrix[index]
</code></pre>
<p>How can I do it with numpy sparse?</p> | <p>Ok, found it. The sparse format looks a bit confusing in the print-out.</p>
<pre><code> index = np.arange(np.shape(matrix)[0])
print index
np.random.shuffle(index)
return matrix[index, :]
</code></pre> | python|numpy|sparse-matrix|shuffle | 16 |
365,791 | 12,122,639 | Find indices of a list of values in a numpy array | <p>I have a numpy master array. Given another array of search values, with repeating elements, I want to produce the indices of these search values in the master array.</p>
<p>E.g.: master array is [1,2,3,4,5], search array is [4,2,2,3]</p>
<p>Solution: [3,1,1,2]</p>
<p>Is there a "native" numpy function that do... | <p>Would <code>np.searchsorted</code> work for you ?</p>
<pre><code>>>> master = np.array([1,2,3,4,5])
>>> search = np.array([4,2,2,3])
>>> np.searchsorted(master, search)
array([3, 1, 1, 2])
</code></pre> | numpy | 28 |
365,792 | 12,133,075 | Sorting a pandas series | <p>I am trying to figure out how to sort the Series generated as a result of a groupby aggregation in a smart way.</p>
<p>I generate an aggregation of my DataFrame like this:</p>
<pre><code>means = df.testColumn.groupby(df.testCategory).mean()
</code></pre>
<p>This results in a Series. I now try to sort this by valu... | <p>Use <code>sort_values</code>, i.e. <code>means = means.sort_values()</code>. [<strong><em>Pandas v0.17+</em></strong>]</p>
<hr>
<h3>(Very old answer, pre-v0.17 / 2015)</h3>
<p>pandas used to use <code>order()</code> method: <code>means = means.order()</code>.</p> | python|pandas|sorting|series | 34 |
365,793 | 12,525,722 | Normalize data in pandas | <p>Suppose I have a pandas data frame <code>df</code>: </p>
<p>I want to calculate the column wise mean of a data frame.</p>
<p>This is easy: </p>
<pre><code>df.apply(average)
</code></pre>
<p>then the column wise range max(col) - min(col). This is easy again: </p>
<pre><code>df.apply(max) - df.apply(min)
</code>... | <pre><code>In [92]: df
Out[92]:
a b c d
A -0.488816 0.863769 4.325608 -4.721202
B -11.937097 2.993993 -12.916784 -1.086236
C -5.569493 4.672679 -2.168464 -9.315900
D 8.892368 0.932785 4.535396 0.598124
In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())
In [94... | python|pandas|numpy | 232 |
365,794 | 72,027,922 | Pandas how to convert time in string to integer? | <p>I have pandas Series (column) of time in string. I am interested in time but I need it in to convert to integer or float.</p>
<p>here is my dataframe:</p>
<pre><code> df = pd.DataFrame({'time': ['00:04:01.2540000', '00:02:17.6700000', '00:03:31.6830000',
'00:03:28.5670000', '00:01:50.6770000', '00:02:26.01700... | <p>Use <code>pd.to_timedelta(df['time']).dt.total_seconds()</code>.</p>
<p>Demo:</p>
<pre><code>>>> df = pd.DataFrame({'time': ['00:04:01.2540000', '00:02:17.6700000']})
>>> df
time
0 00:04:01.2540000
1 00:02:17.6700000
>>> pd.to_timedelta(df['time']).dt.total_seconds()
0 ... | python|pandas|datetime | 4 |
365,795 | 71,955,311 | Why does inputting a tensor into a neural network fail to get an output? | <p>I'm new to deep learning and trying to reproduce a neural renderer program.</p>
<p>FCN() is a neural renderer network that renders a 10-dimensional stroke parameter into a stroke on a 128x128 canvas.
renderer.pkl is the network parameter trained by the author, the size of the input is batchsize x 10, here I assume b... | <p>I suspect the issue may be caused by the <code>np.uint8</code> line. Most neural networks are parameterized such that their outputs fall in the range [0,1]. In this case, yours is (sigmoid activation function range is [0,1]). Casting any float in this range as an int will truncate it to 0. Try multiplying by 255 fir... | python|neural-network|pytorch|renderer | 0 |
365,796 | 71,998,978 | early stopping in PyTorch | <p>I tried to implement an early stopping function to avoid my neural network model overfit. I'm pretty sure that the logic is fine, but for some reason, it doesn't work.
I want that when the validation loss is greater than the training loss over some epochs, the early stopping function returns True. But it returns Fal... | <p>The problem with your implementation is that whenever you call <code>early_stopping()</code> the counter is re-initialized with <code>0</code>.</p>
<p>Here is working solution using an oo-oriented approch with <code>__call__()</code> and <code>__init__()</code> instead:</p>
<pre><code>class EarlyStopping():
def ... | python|deep-learning|neural-network|pytorch|early-stopping | 3 |
365,797 | 71,922,229 | How can i filter on column names part of which contain a value in a given list? | <p>Not sure if this has been asked else where but i couldn't find the relevant question if there was. I have a list of values e.g.:</p>
<pre><code>codes = [6757,1234, 5674, 9990,1110,5678,4532,1123,3456,7865]
</code></pre>
<p>i then have colnames such as:</p>
<p><code>col1_6757, col_1234, col1_5432, col1_1110, amount_1... | <p>Convert values to strings and join by <code>|</code> for regex <code>OR</code>:</p>
<pre><code>data.loc[:, data.columns.str.contains('|'.join(map(str, codes)))]
</code></pre>
<p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>Dat... | python|pandas | 1 |
365,798 | 71,813,784 | two conditions multiplication in pandas | <p>I have the following dataframe, and I am trying to get revenue column by a multiplication between columnA or columnB and columnC.</p>
<p>The condition is:</p>
<ul>
<li>if columnB is NaN, then the revenue column = columnA * columnC</li>
<li>if columnB is not NaN, then the revenue column = columnB * columnC</li>
</ul>... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
df['revenue'] = np.where(df['columnB'].isna(), df['columnA'] * df['columnC'], df['columnB'] * df['columnC'])
</c... | python|pandas|multiplication | 1 |
365,799 | 72,007,047 | pandas multi-level index series: index value convert to dataframe columns name | <p>Pandas question: I have a multi-level index series as following</p>
<pre><code>index1 index2
A 2022-01-01 1.0
2022-01-02 2.0
2022-01-03 3.0
2022-01-04 4.0
B 2022-01-01 5.0
2022-01-02 6.0
2022-01-03 7.0
2022-01-04 8... | <p>You can use <code>Series.unstack</code> with <code>level=0</code>:</p>
<pre><code>new_df = s.unstack(level=0)
</code></pre>
<p>Output:</p>
<pre><code>>>> new_df
index1 A B
index2
2022-01-01 1.0 5.0
2022-01-02 2.0 6.0
2022-01-03 3.0 7.0
2022-01-04 4.0 8.0
</code></pre> | python|pandas | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.