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 |
|---|---|---|---|---|---|---|
360,600 | 72,319,119 | Assigning numeric values to column in Python | <p>I'm a beginner so sorry in advance if I'm unclear :)</p>
<p>I have a .csv with 2 columns, doc_number and text. However, sometimes the rows start with the doc number (as they should) and sometimes it just starts with text from the previous row. All input is the type 'object'. There are also many empty rows between th... | <p>Here's what I can think of when looking at the dataset. It looks like a <code>CSV</code> file which translates to an unnamed column (representing <code>_doc</code>) with mixed <code>integers</code> and <code>strings</code> and another unnamed column with strings (representing <code>_text</code>)</p>
<p>Since, it has... | python|pandas|data-cleaning|read.csv|data-preprocessing | 0 |
360,601 | 72,222,059 | Difference between cupy.asnumpy() and get() | <p>Given a CuPy array <code>a</code>, there are two ways to get a numpy array from it: <code>a.get()</code> and <code>cupy.asnumpy(a)</code>. Is there any practical difference between them?</p>
<pre><code>import cupy as cp
a = cp.random.randint(10, size=(4,5,6,7))
b = a.get()
c = cp.asnumpy(a)
assert type(b) == typ... | <p><code>cp.asnumpy</code> is a wrapper calling <code>ndarray.get</code>. You can see that in the code of <code>cp.asnumpy</code>:</p>
<pre class="lang-py prettyprint-override"><code>def asnumpy(a, stream=None, order='C', out=None):
"""Returns an array on the host memory from an arbitrary source arra... | python|numpy|cupy | 2 |
360,602 | 72,463,818 | Concatenate N pytorch tensors (of the same shape) generated from within loop | <p>Tensors of the same shape are being returned from within a loop and I want to concatenate them succinctly and as pythonically / pytorchly as possible.</p>
<h3>Current solution:</h3>
<pre><code>import torch
for object_id in object_ids:
dataset = Dataset(object_id)
image_tensor = dataset.get_random_imag... | <p>A good approach is to first append to a python <em>list</em>, then concatenate at the end the whole <em>list</em>. Otherwise you'll end up moving data around in memory each time the <a href="https://pytorch.org/docs/stable/generated/torch.cat.html" rel="nofollow noreferrer"><code>torch.cat</code></a> is called.</p>
... | python|loops|pytorch|scope|tensor | 2 |
360,603 | 72,222,646 | Python plotly Scattermapbox define colors by category | <p>I want to draw some <a href="https://plotly.com/python/filled-area-on-mapbox/" rel="nofollow noreferrer">colored areas</a> on a map. The coordinates are defined in a dataframe and I want each area to have a different color depending on the <code>test_type</code> value.</p>
<p>How can I do this? (Question is similar ... | <p>First, the color setting is not simply a color specification, but a marker attribute, which is set by the marker specification in the <code>scattermapbox</code>. Then the color value must be an rgb value, hex color value, or color name. For this purpose, a column of colors to be referenced is added to the original d... | python|pandas|plotly|plotly-dash | 0 |
360,604 | 72,178,001 | How to swap many columns into rows with rows by being grouped in pandas? | <p>Let's say that these are my data</p>
<pre><code>day region cars motorcycles bikes buses
1 A 0 1 1 2
2 A 4 0 6 8
3 A 2 9 8 0
1 B 6 12 34 82
2 B 13 92 76 1
3 B 23 87 98 9
... | <p>Use <code>stack</code> and <code>unstack</code>:</p>
<pre class="lang-py prettyprint-override"><code>(
df.set_index(["day", "region"])
.rename_axis(columns="vehicle_type")
.stack()
.unstack(level=1)
.rename_axis(columns=None)
.reset_index()
)
</code></pre> | python|pandas|dataframe|numpy | 0 |
360,605 | 72,437,861 | Compare multiple columns within same row and highlight differences in pandas | <p>I have a dataframe similar to:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">NAME</th>
<th style="text-align: center;">DB1</th>
<th style="text-align: center;">DB2</th>
<th style="text-align: center;">DB3</th>
<th style="text-align: center;">DB4</th>
</tr>
</t... | <p>The simplest (and naïve) approach is to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer">Series.eq</a> to test each row against the first value. Setting an appropriate <code>subset</code> is very important here, as we only want to compare against other simila... | python|python-3.x|pandas|dataframe|pandas-styles | 0 |
360,606 | 72,372,216 | Process string in Pandas Dataframe rows to comma-delimitered chars | <p>I have a dataframe, with data in each row as such.</p>
<pre><code>MKEYGEDLK
</code></pre>
<p>How can I process the sequence strings in each row, such that the format will be as such?</p>
<pre><code>[M, K, E, Y, G, E, D, L, K]
</code></pre>
<p>I tried</p>
<pre><code>get_seq_str = ','.join(test_df.loc[0]['seq_1'])
arr... | <p>IIUC, you can try <code>apply</code> <code>list</code> to string value</p>
<pre class="lang-py prettyprint-override"><code>df['col_list'] = df['col'].apply(list)
</code></pre>
<pre><code>print(df)
col col_list
0 MKEYGEDLK [M, K, E, Y, G, E, D, L, K]
</code></pre> | python|python-3.x|pandas | 0 |
360,607 | 72,356,358 | What's the difference between the print inside and outside | <p>I am learning the tensorflow which version is 2.8.0 on my MacBook M1.
For debugging the code in the map function of dataset, I want to print tensor value in my function.</p>
<pre><code>def function(i):
print("in: ", i)
if i < 2:
i = i - 1
return i
dataset = tf.data.Dataset.range(1,... | <p>I believe it is because tensorflow datasets have <em>lazy loading</em>, which means they aren't evaluated until you actually try to iterate over the result.</p>
<p>When you removed the for loop, you were no longer iterating over the result, so it was never evaluated.</p>
<p>See <a href="https://stackoverflow.com/a/5... | python|macos|numpy|tensorflow|keras | 1 |
360,608 | 72,455,027 | Using astropy to convert pandas columns | <p>I have a <code>pandas</code> dataframe that includes the columns <code>_RA2000</code> and <code>_DEJ2000</code>, thus:</p>
<pre><code>_RAJ2000,_DEJ2000,RA_ICRS,DE_ICRS,mode,q_mode,class,SDSS12,m_SDSS12,ObsDate,Q,umag,e_umag,gmag,e_gmag,rmag,e_rmag,imag,e_imag,zmag,e_zmag,zsp,zph,e_zph,<zph>
02 59 43.85208,+00 ... | <p>You need to do the conversion for both coords simultaneously and supply the frame as a keyword argument:</p>
<pre><code>import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord
df = pd.DataFrame({'_RAJ2000': ['23 58 36.30073 ', '23 58 19.66200 ', '23 58 17.43747 ', '23 58 10.18... | python|pandas|dataframe|astropy | 0 |
360,609 | 72,330,515 | How to compute the gradient of a multidimensional array using numpy's fast Fourier transform | <p>I wrote this short and simple python method the other day</p>
<pre><code>def dFFT_1D(f):
k = 2*np.pi * np.fft.fftfreq(f.shape[0])
return np.fft.ifft(1j*k * np.fft.fft(f)).real
</code></pre>
<p>which takes a one-dimensional array containing samples of a scalar function (step size is taken as unity) as input a... | <p>You should be able to do</p>
<pre><code>1j * k[:, None] * np.fft.fftn(f)
</code></pre>
<p>to line up dimensions.</p> | python|numpy|fft|derivative | 1 |
360,610 | 72,368,551 | Replace values of 2-D array by indices of corresponding to another 2-D array | <p>I am a newbie in numpy. I have an array A of size 6 x 2 of values and an array B of size 4 x 2. I want as result an array C filled with indices i of B.</p>
<p>Here is an example of inputs and outputs:</p>
<pre><code>A = [[ 240. 240.][ 0. 480.][ 0. 960.][ 0. 480.][ 0. 720. ][ 0. 480.]]
B = [[ 0. 48... | <p>Assuming there is necessarily a match, you can use:</p>
<pre><code>np.isclose(abs(B-A[:, None]), 0).all(2).argmax(1)
</code></pre>
<p>Output:</p>
<pre><code>array([3, 0, 2, 0, 1, 0])
</code></pre>
<h4>How it works</h4>
<p>This computes element-wise the absolute difference between A and B, then converts to boolean to... | python|numpy|matrix|multidimensional-array | 0 |
360,611 | 72,352,585 | Removing rows with weekends from dataframe in Pandas | <p>I have a Pandas dataframe that looks like this:</p>
<pre><code>df.head()
Date Abscount Year Quarter Month Week Number
0 2022-01-03 7.0 2022 1 1 1
1 2022-01-04 17.0 2022 1 1 1
2 2022-01-05 16.0 2022 1 1 1
3 2022-01-06 18.0 2022 1 1 1
4 2022-01... | <p>What you want to do is simply:</p>
<pre><code>df['new_col_name'] = df['Date'].dt.day_name()
</code></pre>
<p>However, if you only need the column for a condition, you don't need to add it to the DataFrame. You can use it to filter it directly:</p>
<pre><code># Example: remove weekends.
df = df[~df['Date'].dt.day_nam... | python|pandas|dataframe | 2 |
360,612 | 72,410,579 | Python pandas.cut() | <p>I have the following array:</p>
<pre><code>array.unique()
array(['10','8', '15','20','21','22 '27','28' nan, '30', '32', '33', 'Values']
</code></pre>
<p>I' am trying to assign the following category labels and put them in the respective bin: 'not_number', '10 and below', '11'- '32', '33 and up' using pd.cut() where... | <p>The cut method raise a TypeError if you pass a non-int array datatype. The solution I suggest is to pass from an array to a list to manage different datatypes. In this case you can replace the <code>nan</code> and <code>'Values'</code> with a negative number using a list comprehension. With this set you can use pd.c... | python|pandas | 1 |
360,613 | 72,182,308 | how to read data from multiple folder from adls to databricks dataframe | <p>file path format is data/year/weeknumber/no of day/data_hour.parquet</p>
<p>data/2022/05/01/00/data_00.parquet</p>
<p>data/2022/05/01/01/data_01.parquet</p>
<p>data/2022/05/01/02/data_02.parquet</p>
<p>data/2022/05/01/03/data_03.parquet</p>
<p>data/2022/05/01/04/data_04.parquet</p>
<p>data/2022/05/01/05/data_05.parq... | <p>The last line of your code cannot load data incrementally. In contrast, it refreshes df variable with the data from each path for each time it ran.</p>
<p>Removing the for loop and trying the code below would give you an idea how file masking with asterisks works. Note that the path should be a full path. (I'm not s... | dataframe|pyspark|databricks|pyspark-pandas | 0 |
360,614 | 72,180,001 | Python code works when running normally but not in the debugger - groupby().max().unstack() | <p>I am currently using pycharm Community Edition 2022.1
When I run the following code it works with the run command, but not when I try to use the debugger.</p>
<pre><code>Logical = all_sites.groupby(["parcel_id","TypologySize"])[['NetProfitPct']].max().unstack()
</code></pre>
<p>With the Error mes... | <p>I found using reset_index() instead of unstack worked. i.e.</p>
<p><code>Logical = all_sites.groupby(["parcel_id","TypologySize"])[['NetProfitPct']].max().reset_index() #.unstack()</code></p> | python|python-3.x|pandas | 0 |
360,615 | 72,189,887 | Comparing values in different datasets with pandas | <p>I have 4 different csv files in this format: <a href="https://i.stack.imgur.com/cqJSL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqJSL.png" alt="first file" /></a> <a href="https://i.stack.imgur.com/weuL0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/weuL0.png" alt="secon... | <ol>
<li><p>import every csv into a dataframe:</p>
<p>import pandas as pd</p>
<p>df1=pd.read_csv('path to csv1')</p>
<ul>
<li>the same until csv4</li>
</ul>
<p>df4=pd.read_csv('path to csv4')</p>
</li>
<li><p>Join 4 df in only 1 df:</p>
<p>df = pd.concat([df1,df2,df3,df4])</p>
</li>
<li><p>Put the same date all togethe... | python|pandas|csv | 0 |
360,616 | 72,173,756 | expanding() function very slow, any alternatives? | <p>I am trying to compute cumulative standard deviation. I am using the following code</p>
<pre><code>df['cum_std'] = df[df['growth'].notnull()].groupby('id')['growth'].expanding(2).std(ddof=0)
</code></pre>
<p>BUT, I have more than 90M rows of observation and it is taking forever. I am wondering if there are any other... | <p>It's likely that <code>expanding</code> is computing the std over each window independently rather than using a cumulative operation that builds on prior steps. You can bypass that by implementing your own running standard deviation.</p>
<p>One way to define standard deviation of array <code>x</code> with <code>ddof... | python|pandas|dataframe | 0 |
360,617 | 72,394,950 | How to fix date time format in Pandas Python | <p><strong>I have a data Frame df</strong>
<a href="https://i.stack.imgur.com/BmrCf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BmrCf.png" alt="enter image description here" /></a>
so i converted it to date time using pandas,
<code>stock_data['Date'] = pd.to_datetime(stock_data['Date'],unit='s')<... | <p>In my opinion, there are two solutions.</p>
<p>1.I downloaded the data from yfinance and specifically reset the indexes to turn the 'Datetime' indexes into a column. And I draw a scatter, specifying a list of indexes. Possible that you have these indexes and have buy?</p>
<pre><code>import matplotlib.pyplot as plt
i... | python|pandas|dataframe | 1 |
360,618 | 72,159,311 | Find pattern in pandas column names and change such columns using pipe | <p>Let say I have below calculation,</p>
<pre><code>import pandas as pd
dat = pd.DataFrame({'xx1' : [1,2,3], 'aa2' : ['qq', '4', 'd'], 'xx3' : [4,5,6]})
dat2 = (dat
.assign(xx1 = lambda x : [str(i) for i in x['xx1'].values])
.assign(xx3 = lambda x : [str(i) for i in x['xx3'].values])
)
</code></pre>... | <p>You could do:</p>
<pre><code># Matches all columns starting with 'xx' with a sequence of numbers afterwards.
cols_to_transform = dat.columns[dat.columns.str.match('^xx[0-9]+$')]
# Transform to apply (column-wise).
transform_function = lambda c: c.astype(str)
# If you want a new DataFrame and not modify the other ... | python|python-3.x|pandas|pipe | 2 |
360,619 | 72,380,023 | Having problem displaying dataframe with streamlit | <pre><code>data_to_graph = combined_summary_df.unstack(level=1, fill_value=0)
with st.expander("Where to test everything related to graph"):
st.write(data_to_graph)
</code></pre>
<p>"I am new to Streamlit. I would like to impress my superior with it. Any help, Please!!!</p>
<p>The error below has be... | <p>Here is a sample multi-indexed frame, streamlit is ok. Can you try that?</p>
<h3>Code</h3>
<pre><code>import pandas as pd
import numpy as np
import streamlit as st
index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
('two', 'a'), ('two', 'b')])
df = pd.DataFrame(np.r... | javascript|python|pandas|streamlit | 0 |
360,620 | 72,240,965 | Conversion between binary vector and 128 bit number | <p>Is there a way to convert back and forth between a binary vector and a 128-bit number? I have the following binary vector:</p>
<pre><code>import numpy as np
bits = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0,... | <p>As commented above, numpy only goes up to 64bits, but python has variable length ints, so we can do 128bits int no problem.</p>
<p>The following will go from binary in np.array to python int back to binary in np.array.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
bits = np.array(
[
... | python|numpy|scikit-learn | 0 |
360,621 | 72,217,485 | How to count the same rows between multiple CSV files in Pandas? | <p>I merged 3 different CSV(D1,D2,D3) Netflow datasets and created one big dataset(df), and applied KMeans clustering to this dataset.
To merge them I did not use pd.concat because of memory error and solved with Linux terminal.</p>
<pre><code>df = pd.read_csv('D.csv')
#D is already created in a Linux machine from term... | <pre><code>cluster0_D1 = pd.merge(D1, cluster_0, how ='inner')
number_of_rows_D1 = len(cluster0_D1)
cluster0_D2 = pd.merge(D2, cluster_0, how ='inner')
number_of_rows_D2 = len(cluster0_D2)
cluster0_D3 = pd.merge(D3, cluster_0, how ='inner')
number_of_rows_D3 = len(cluster0_D3)
print("How many samples belong to ... | python|pandas|data-science|cluster-analysis|netflow | 1 |
360,622 | 50,275,306 | Pandas XLSWriter - return instead of write | <p>I want to return an Excel file from my Flask (Python) server. This code:</p>
<pre><code>writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
</code></pre>
<p>will write the Excel file to the file system. How can I <code>return</code> the file instead of writing it? </p> | <p>You can write the excel data to memory using a <code>StringIO</code> or <code>BytesIO</code> object.</p>
<p>This code is copied from the pandas documentation <a href="https://pandas.pydata.org/pandas-docs/stable/io.html?highlight=excelwriter#writing-excel-files-to-memory" rel="nofollow noreferrer">here</a>:</p>
<p... | python|excel|pandas | 3 |
360,623 | 50,650,971 | Pandas: How to build a column based on another column which is indexed by another one? | <p>I have this dataframe presented below. I tried a solution below, but I am not sure if this is a good solution.</p>
<pre><code>import pandas as pd
def creatingDataFrame():
raw_data = {'code': [1, 2, 3, 2 , 3, 3],
'Region': ['A', 'A', 'C', 'B' , 'A', 'B'],
'var-A'... | <p>You can try with <code>lookup</code></p>
<pre><code>df.columns=df.columns.str.split('-').str[-1]
df
Out[255]:
code Region A B C
0 1 A 2 20 3
1 2 A 4 30 4
2 3 C 6 40 5
3 2 B 4 50 1
4 3 A 6 10 2
5 3 B 6 20 3
df.lookup(df.index,df.Region)
... | python-3.x|pandas|select | 1 |
360,624 | 50,463,625 | Differences in one column based on differences in another, pandas | <p>How can I perform the below manipulation with <code>pandas</code>?</p>
<p>I have this dataframe :</p>
<pre><code>weight | Date | dateDay
43 | 09/03/2018 08:48:48 | 09/03/2018
30 | 10/03/2018 23:28:48 | 10/03/2018
45 | 12/03/2018 04:21:44 | 12/03/2018
25 | 17... | <pre><code>#import pandas as pd
#from datetime import datetime
#to_datetime = lambda d: datetime.strptime(d, '%d/%m/%Y')
#df = pd.read_csv('d.csv', converters={'dateDay': to_datetime})
</code></pre>
<p>Above part only if you reading from the file, else its just .shift() what u need</p>
<pre><code>a = df
b = df.shift(... | python|pandas|series|pandas-groupby|timedelta | 1 |
360,625 | 50,439,523 | How to "group" data in a column in a dataframe | <p>I have a dataframe, these are the first lines:</p>
<pre><code>(idx1) AMAZONAS 15
(idx2) AMAZONAS 2
(idx3) ANTIOQUIA 881
(idx4) ANTIOQUIA 696
(idx5) ANTIOQUIA 632
(idx6) ANTIOQUIA 702
</code></pre>
<p>as you can see, there are some names that repeat, and I need to group all that names that are repeated ... | <p>If the dataframe <strong>df</strong> has columns like <strong>name</strong> and <strong>count</strong>, for, respectively, values <em>AMAZONAS</em> and <em>15</em>, for example, you cand do:</p>
<pre class="lang-py prettyprint-override"><code>df.groupby('name')['count'].sum()
</code></pre> | python|pandas|numpy|dataframe | 1 |
360,626 | 50,271,546 | Copy part of data to another column | <p>I have a populated pandas Dataframe and I'm trying to create another column and fill it with some characters from another column. </p>
<p>Example:</p>
<p>This is my dataframe <strong>df1</strong> </p>
<pre><code> a b c
1234 4567 7890
0987 7654 4321
0708 7080 9080
</code></pre>
<p>Now I want to create ... | <p>Try using the <a href="https://pandas.pydata.org/pandas-docs/stable/text.html" rel="nofollow noreferrer"><code>str</code> subscript slice method</a>: </p>
<pre><code>df1['d'] = df1.a.str[: 2]
>>> df1.d
0 12
1 98
2 07
Name: d, dtype: object
</code></pre>
<p>Also, as a rule of thumb, try to avoid ... | python|python-3.x|pandas|dataframe|split | 1 |
360,627 | 50,519,820 | np.all() does not get executed | <p>I wrote a script:</p>
<pre><code>import numpy as np
a=[0,0,0]
if np.all(a==0):
print('All are zeros!')
</code></pre>
<p>but nothing gets printed out. Shouldn't <code>np.all(a==0)</code> evaluate to be True since all elements in <code>a[]</code> are <code>0</code>'s? </p> | <p>In order to avoid explicitly converting list <code>a</code> to a <code>numpy.ndarray</code>, you can call <code>numpy</code>'s comparison operators directly:</p>
<pre><code>np.all(np.equals(a, 0))
</code></pre>
<p>However, if your data are already a Python list, simply use Python's <code>all()</code> to get the sa... | python|numpy | 3 |
360,628 | 50,590,023 | pandas DataFrame float column gets converted to object after values in a different column are renamed | <p>I have a dataframe that I was doing some clean up on and for some reason the column I didn't touch at all got switch from type float to object. The column has no Nan values just numbers and has not been messed with at all.</p>
<pre><code>data = pd.read_csv(path, encoding="ISO-8859-1", names=['c_id', 'c_name', 'org_... | <p>You are changing the entire row to the string <code>product</code> using your <code>loc</code> statement, so in fact, <code>amount</code> does get modified. Instead, just change the value in the column <code>'product_type'</code>:</p>
<pre><code>data.loc[data['product_type'] == 'product', 'product_type'] = 'Product... | python|python-3.x|pandas | 1 |
360,629 | 50,581,956 | Lorentzian fit two ways of writing a code | <p>I am struggling right now with Lorentzian curve fit. I'll try to explain my problem. I need to write my own code for Lorentzian curve fit so I can add some stuff to the equations. I've implemented Lorentzian fit with <code>model</code> and <code>def</code>, I've written similary, but it doesn't work. Check out my co... | <p>Look like a parenthesis problem. This:</p>
<pre><code>(amp/np.pi) * (sig/(x-cen)**2 + sig**2)
</code></pre>
<p>is not a Lorentzian. This:</p>
<pre><code>(amp/np.pi) * (sig/((x-cen)**2 + sig**2))
</code></pre>
<p>is. In addition you may have a slight integer problem in the rare event <code>cen,x,sig</code> are al... | python|numpy|curve-fitting|lmfit | 2 |
360,630 | 50,471,703 | Match pandas value on all and row specific values | <p>I have two large data frames, and I want to match the first against two criteria in the second. </p>
<p>However, I want the first criteria to match against all values in the relevant column of the second, whilst I want the second criteria to be pulled from the specific row of the second and matched to the specific ... | <p>Try using np.select</p>
<pre><code>conditions = [
((df1['criteria1'] in df2['criteria1'].values) & (df2['criteria2'] == 'y'))
]
choices = [
'hit',
]
df1['output'] = np.select(conditions, choices, default = df1['output'])
</code></pre>
<p>output:</p>
<pre><code> criteria1 output
0 0.126479 hit
1 ... | python|pandas|apply | 1 |
360,631 | 50,395,464 | Pandas Replace All Substrings in DataFrame | <p>Given the following dataframe:</p>
<pre><code>import pandas as pd
d = pd.DataFrame({'A':['^|^^|^','abc'],'B':['def','^|^']})
d
A B
0 ^|^^|^ def
1 abc ^|^
</code></pre>
<p>I need to replace all instances of "^|^" with blank spaces (" ").</p>
<p>The desired result is:</p>
<pre><code> A ... | <p>you need to escape special RegEx symbols:</p>
<pre><code>import re
In [191]: d.replace(re.escape('^|^'),' ', regex=True)
Out[191]:
A B
0 def
1 abc
</code></pre> | python-3.x|pandas|replace | 4 |
360,632 | 50,362,185 | Tensorflow Object Detection Training Error | <p>I am following tutorial for Tensorflow Object Detection
<a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">link</a></p>
<p>and getting the following command when i try this command</p>
<pre><code>python train.py --logtos... | <p>I is definitely related to something being off in your setup.py. Here is a thread that may help: <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/issues/146" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/cloudml-samples/issues/146</a>. You may need to specify the version of the pack... | python-3.x|tensorflow | 1 |
360,633 | 50,347,805 | Explanation of the two percentage numbers in tensorflow's profiler? | <p>I am using <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler" rel="nofollow noreferrer">the profiler tool</a> provided by tensorflow. Here is one snapshot of the profiling results:
<a href="https://i.stack.imgur.com/Q5Up8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.i... | <p>The first number is the percentage of the total memory used/time spent in the function while the second one is the percentage of the memory used/time spent in the function that is <strong>not</strong> allocated/spent in the <strong>inner</strong> functions. Often these are called inclusive (including the functions i... | tensorflow|profiling | 2 |
360,634 | 50,294,331 | Load two differents folders on the same port | <p>I would like to know if there is some way to do <code>tensorboard --logdir dir1</code> and <code>tensorboard --logdir dir2</code> without using two different ports?</p> | <p>Yes. Run <code>tensorboard --helpfull</code> and checkout the description of <code>logdir</code> argument:</p>
<blockquote>
<p>You may also pass a comma separated list of log directories, and TensorBoard
will watch each directory. You can also assign names to individual log
directories by putting a co... | tensorflow|tensorboard | 0 |
360,635 | 50,319,614 | count plot with stacked bars per hue | <p>I am looking for an efficient way of drawing a count plot with stacked bars according to "hue".
Standard hue behavior is to split a count into parallel bars according to the value of a second column, what I am looking for is an efficient way to have the hue bars stacked in order to quickly compare totals.</p>
<p>L... | <p>You were basically there with your last part, using <code>DataFrame.plot()</code> with <code>bar</code> and <code>stacked=True</code>. </p>
<p>Instead of your <code>aggregate</code> function, you can accomplish what you want with a <code>groupby</code> + <code>pivot</code>. </p>
<pre><code>df_plot = df.groupby(['c... | python|pandas|bar-chart|seaborn|stacked-chart | 26 |
360,636 | 50,243,230 | Unable to understand tf.nn.raw_rnn | <p>In the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/raw_rnn" rel="nofollow noreferrer">official documentation</a> of <code>tf.nn.raw_rnn</code> we have emit structure as the third output of <code>loop_fn</code> when the <code>loop_fn</code> is run for the first time.</p>
<p>Later on the emit_structure ... | <p>Yep, the doc is rather confusing in this place. If you look at the internals of <code>tf.nn.raw_rnn</code>, the key term there is <strong>"in pseudo-code"</strong>, so the example in the doc isn't accurate.</p>
<p>The exact source code looks like this (may differ depending on your tensorflow version):</p>
<pre c... | python-3.x|tensorflow|recurrent-neural-network|rnn|tensorflow-slim | 1 |
360,637 | 50,526,842 | How to create a parallel linear computation in one layer with TensorFlow? | <p>I have inputs with size [batch_size, height, width]. Here I want to do several different parallel linear transformation in one layer, i.e.,</p>
<pre><code>x = tensor([batch_size, height, width])
y = [W1*x, W2*x, W3*x,...,Wn*x]
</code></pre>
<p>I noticed that there are <code>fully_connected</code> and <code>layer.d... | <p>Taking advantage of broadcasting:</p>
<pre class="lang-python prettyprint-override"><code>import tensorflow as tf
batch_size, height, width = 5, 4, 3
n = 2
x = tf.random_uniform((batch_size, height, width))
W = tf.random_uniform((n,))
y = tf.multiply(tf.reshape(W, (n, 1, 1, 1)), tf.expand_dims(x, 0))
with tf.Se... | tensorflow | 0 |
360,638 | 50,259,463 | Groupby on pandas dataframe and concatenate strings with comma based on the frequency of values in a column | <p>This is an update to the structure of my DataFrame, I formulated the structure in haste, I was inspecting a single user and mocked up that structure. @liliscent's remark: "data accidentally satisfies this condition" is also true and value_counts and cum_sum() solves it. But then user_id's also change, and different ... | <h2><code>value_counts</code> and <code>cumsum</code></h2>
<p><code>value_counts</code> sorts by descending count</p>
<pre><code>cols = ['meet_id', 'user_id']
s = mytable.groupby(cols).label.value_counts().groupby(cols).apply(
lambda d: d.index.to_series().str[-1].cumsum().str.join(', ')
)
mytable.assign(label=[... | python|pandas|dataframe|pandas-groupby | 9 |
360,639 | 50,391,562 | Trying to generate a Keras model with my own data instead of cifar10 | <p>I have followed this example:
<a href="https://www.pyimagesearch.com/2017/10/30/how-to-multi-gpu-training-with-keras-python-and-deep-learning/" rel="nofollow noreferrer">https://www.pyimagesearch.com/2017/10/30/how-to-multi-gpu-training-with-keras-python-and-deep-learning/</a></p>
<p>and had an issue with the follo... | <p>Assume you have your images as .jpg format, and your labels as csv format called <code>label.csv</code>, and separated them into 2 folders, <code>train folder</code> and <code>test folder</code>.</p>
<p>Then you can do the following to get the <code>x_train</code></p>
<pre><code>import cv2 #library for reading ima... | python-3.x|tensorflow|keras | 2 |
360,640 | 50,586,501 | Pandas - Create a column based on values from 2 other columns | <p>I am trying to tackle something on Pandas but I am not sure where to start.</p>
<p>I have a dataframe with multiple columns, but the ones of interest for this question look like this:</p>
<pre><code>df = pd.DataFrame(data = {'subject': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'val': [np.nan, 2, np.nan, np.nan, np.nan, 7, np.n... | <p>try this,</p>
<pre><code>df['total'] =df.groupby('subject')['val'].transform('sum')
</code></pre>
<p>or </p>
<pre><code>df['total2'] =df.groupby('subject')['val'].transform(lambda x:x[x.notnull()].unique()) #this will remove NaN records and give you unique element in each group
</code></pre>
<p>Output:</p>
<pre... | python|pandas | 1 |
360,641 | 50,347,027 | convert each row of a pandas table to list and add to table | <p>I would like to convert each row into a list and insert as a new column.
For example, I start with the following table: </p>
<pre><code> 0 1 2 3 4
0 0 8 3 2 5
1 1 1 2 2 4
2 0 8 9 6 4
3 2 7 6 1 9
4 8 9 1 5 6
</code></pre>
<p>and would like to get:</p>
<pre><code> 0 1 2 3 4 t... | <p>You can use:</p>
<pre><code>In [127]: df['test'] = df.values.tolist()
In [128]: df
Out[128]:
0 1 2 3 4 test
0 0 8 3 2 5 [0, 8, 3, 2, 5]
1 1 1 2 2 4 [1, 1, 2, 2, 4]
2 0 8 9 6 4 [0, 8, 9, 6, 4]
3 2 7 6 1 9 [2, 7, 6, 1, 9]
4 8 9 1 5 6 [8, 9, 1, 5, 6]
</code></pre> | python|list|pandas|dataframe | 7 |
360,642 | 50,460,319 | How to use " iloc " and " loc " method in place of .ix method for index slicing let's just say to get the data between a particular time frame? | <pre><code>sns.distplot(returns.ix['2015-01-01':'2015-12-31']['MS Return'],color='green',bins=100)
</code></pre>
<p>while running this code I am getting an error so how to replace it with '<code>iloc</code>' and '<code>loc</code>' method.</p>
<p>The data head is as below:</p>
<pre><code>BAC Return C Return GS Re... | <p>Just as you did with .ix,
start, end - datetime format, not a string</p>
<p>dataframe.loc[start:end]</p>
<p>And check first if dataframe.index returns you datetime instead of integers
Otherwise use dataframe.set_index() method</p> | python|pandas | 0 |
360,643 | 50,472,337 | How to feed tfrecords to the networks in tensorflow | <p>I want to feed my custom data deep network using "tfrecords" in tensorflow. There are several ways to do this; using coordinator or iterator. I was mixed up with this and tried several times using book's and blog's guide. But unfortunately, none of them did work for me.
Roughly speaking assume that I have tfrecords ... | <p>You read TFRecord files with a tensorflow Dataset object or a TFRecordReader. I think <a href="https://www.skcript.com/svr/why-every-tensorflow-developer-should-know-about-tfrecord/" rel="nofollow noreferrer">this article</a> explains it well (both writing and reading TFRecord files), using TFRecordReader (I prefer ... | tensorflow|machine-learning|deep-learning | 0 |
360,644 | 50,376,282 | Python 3.6: Speed up regex replace in Pandas dataframe | <p>I'm using the following code to read 1 million rows of SQL data and replace any control characters which might appear in the data, the only problem is that is slow and it is definitely the 'replace' which is slowing it down. Anyone have any suggestion about taking a different approach or tweaking to might make the c... | <p>You don't need regex for this to begin with - you're just replacing 'special' characters with an empty space in an one-to-one replacement - but apart from that you hardly need to parse and turn your data into a DataFrame to begin with.</p>
<p>You can work directly with a DB connection and export the columns using t... | python|pandas|replace | 1 |
360,645 | 50,236,820 | Can I use Tensorflow in reactjs? (not react-native) | <p>I want to use deep learning or machine learning to do some calculations on my front-end.</p>
<p>But there are no react examples.</p>
<p>My original idea was use python with react. Tensorflow would run in back-end in Python, while the front-end would be using React and get the results from the Python back-end.</p>
... | <p>Yes you can install it NPM, it is at their documentation: <a href="https://js.tensorflow.org/setup/" rel="noreferrer">https://js.tensorflow.org/setup/</a></p>
<p><code>yarn add @tensorflow/tfjs</code> or <code>npm install @tensorflow/tfjs</code></p>
<p>Then <code>import * as tf from '@tensorflow/tfjs';</code></p>
... | reactjs|tensorflow|tensorflow.js | 8 |
360,646 | 50,432,927 | TypeError: must be str, not int couldn't be solved | <p>The original time data is like this:</p>
<pre><code>df['time'][0:4]
2015-07-08
05-11
05-12
2008-07-26
</code></pre>
<p>I want all these data contains year value.
And I applied this:</p>
<p>con_time = []</p>
<pre><code>i=0
for i in df['time']:
if len(df['time'])==5:
time = '2018... | <p>Since you have asked about an alternative approach. instead of an explicit loop in python and filling a list, one should rather use DataFrame methods directly. In your case this would be</p>
<pre><code>df['time'].apply(lambda x: x if len(x) != 5 else '2018-'+x)
</code></pre>
<p>This might run faster for some datas... | python|pandas|numpy|dataframe | 3 |
360,647 | 50,452,855 | Extract substring from all rows in pandas data frame | <p>I have a pd.DataFrame like the following:</p>
<pre><code>pd.DataFrame(["SSDILFJKSIDHFKJSHDKUFH", "SLIDFSOIUDHFIUSDHF", "K<NFSKJGHSDUFSDK"], ["SKDJF", "FDKSJFSSDF", "SIDFDS"])
</code></pre>
<p>I want to extract subsequences from the first column, but the length of the subsequence I want depends on the length of ... | <p>This is one way using a list comprehension:</p>
<pre><code>df = pd.DataFrame({'A': ["SSDILFJKSIDHFKJSHDKUFH", "SLIDFSOIUDHFIUSDHF",
"K<NFSKJGHSDUFSDK"]},
index=["SKDJF", "FDKSJFSSDF", "SIDFDS"])
df['B'] = [j[1:i+1] for i, j in zip(s.index.map(len), s.values)]
print(df... | python|pandas | 2 |
360,648 | 50,242,754 | Plot a two dimensional array using a dictionary with pandas/python | <p>I want to make a simple XY-plot based on the data in a dictionary. My data looks like thit: </p>
<pre><code>D = {'str1': [[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]],'str2': [[8, 9,
10, 11, 12], [8, 9, 10, 11, 12]]}
</code></pre>
<p>Is there a way to just plot, for example, the first dictionary form D.
The co... | <p>The command would look like</p>
<pre><code>plt.plot(*D["str1"])
</code></pre>
<p>i.e. you select the <code>"str1"</code> entry from the dictionary and unpack it to the <code>x</code> and <code>y</code> arguments of <code>plot</code>.</p> | python|python-2.7|pandas|matplotlib|plot | 2 |
360,649 | 50,616,978 | Python - pick a value from a list basing on another list | <p>I've got a dataframe. In column <code>A</code> there is a list of integers, in column <code>B</code> - an integer. I want to pick n-th value of the column <code>A</code> list, where n is a number from column <code>B</code>. So if in columns <code>A</code> there is [1,5,6,3,4] and in column <code>B</code>: 2, I want ... | <p>You can go for apply i.e </p>
<pre><code>df = pd.DataFrame({'A':[[1,2,3,4,5],[1,2,3,4]],'B':[1,2]})
A B
0 [1, 2, 3, 4, 5] 1
1 [1, 2, 3, 4] 2
# df.apply(lambda x : np.array(x['A'])[x['B']],1)
# You dont need np.array here, use it when the column B is also a list.
df.apply(lambda x : x['A']... | python|pandas | 2 |
360,650 | 50,258,427 | Pandas Value Counts With Constraint For More Than One Occurance | <p>Working with the Wine Review Data from Kaggle <a href="https://www.kaggle.com/zynicide/wine-reviews/data" rel="nofollow noreferrer">here</a>. I am able to return the number of occurrences by variety using value_counts()</p>
<p><a href="https://i.stack.imgur.com/fOAXf.png" rel="nofollow noreferrer"><img src="https:/... | <p>@wen ansered this in the comments. </p>
<pre><code>df['variety'].value_counts().loc[lambda x : x>1]
</code></pre> | pandas|dataframe|jupyter-notebook|kaggle | 11 |
360,651 | 50,336,735 | Want to concatenate the random uniformly generated values | <p>I have code as following and I want to write a function for it. output should be x as dataframe and y as series, even dataframe having x and y as columns is enough.</p>
<pre><code>x = np.arange(0,50)
x = pd.DataFrame({'x':x})
# just random uniform distributions in differnt range
y1 = np.random.uniform(10,15,10)
y... | <p>Try to modify the function like this:</p>
<pre><code>def colm(p, q, chunk_len=10):
x = np.arange(0,5 * chunk_len)
x = pd.DataFrame({'x':x})
# just random uniform distributions in differnt range
ys = [np.random.uniform(p_, q_, chunk_len) for p_, q_ in zip(p, q)]
y = np.concatenate(ys)
ret... | python|pandas|function|numpy|dataframe | 1 |
360,652 | 50,328,796 | How to calculate certain values per hour using dataframes | <p>i'm new at python and pandas library and i need help on solving this problem.</p>
<p>I've a dataframe that looks like this:</p>
<pre><code> timestamp battery_level
0 2017-10-09 15:33:09 0.37
1 2017-10-09 15:36:17 0.38
2 2017-10-09 15:36:27 0.37
3 2017-10-09 15:38:08 0.38
4 2017-10-... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="nofollow noreferrer"><code>hour</code></a>s or <a href="http://pandas... | python|pandas | 4 |
360,653 | 50,314,243 | Fourier Transform in Python 2D | <p>I want to perform numerically <code>Fourier transform</code> of <code>Gaussian function</code> using <code>fft2</code>. Under this transformation the function is preserved up to a constant.</p>
<p>I create 2 grids: one for <code>real space</code>, the second for <code>frequency</code> (momentum, k, etc.). (Frequenc... | <p>I think you are a bit puzzled by the shape of your output <code>F</code>. Especially, you might wonder why you see such a sharp peak and not a wide-spread gaussian.</p>
<p>I changed your code a little bit:</p>
<pre><code> import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft2, ifft2
f... | python|numpy|scipy|fft | 3 |
360,654 | 50,565,322 | Why did the numpy core size shrink from 1.14.0 to 1.14.1? | <p>When creating an AWS lambda package I noticed that the ZIP became a lot smaller when I updated from numpy 1.14.0 to 1.14.3. From 24.6MB to 8.4MB.</p>
<p>The directory numpy/random went from 4.3MB to 1.2MB, according to Ubuntus Disc Usage analyzer. When I, however, compare the directories with meld they seem to be i... | <p>It appears that the difference is in the debug symbols. Perhaps one was built with a higher level of debug symbols than the other, or perhaps the smaller one was built with compressed debug info (a relatively new feature). One way to find out more would be to inspect the compiler and linker flags used during each ... | python|numpy|shared-libraries | 0 |
360,655 | 50,297,777 | Remove low frequency words | <p>I have a dataframe with 2 columns, 1 column has string of words, ex:</p>
<pre><code> Col1 Col2
0 1 how to remove this word
1 5 how to remove the word
</code></pre>
<p>I would like to remove all words that occurred once in the whole dataframe (threshold =1), I woul... | <p>Let's try using a <code>Counter</code> here:</p>
<ol>
<li>Split sentences into words</li>
<li>Compute global word frequency</li>
<li>Filter words based on computed frequencies</li>
<li>Join and re-assign</li>
</ol>
<p></p>
<pre><code>from collections import Counter
from itertools import chain
# split words into ... | python|pandas|dataframe|text|replace | 9 |
360,656 | 50,582,821 | A grid over probability vectors | <p>I am trying to get a "grid" of n-dimensional probability vectors---vectors in which every entry is between 0 and 1, and all entries add up to 1. I wish to have every possible vector in which coordinates can take any of a number <em>v</em> of evenly spaced values between 0 and 1.</p>
<p>In order to illustrate this, ... | <p>Here is a recursive solution. It does not use NumPy and is not super efficient either although it should be faster than the posted snippet:</p>
<pre><code>import math
from itertools import permutations
def probability_grid(values, n):
values = set(values)
# Check if we can extend the probability distributi... | python|numpy|scientific-computing | 2 |
360,657 | 50,302,662 | Vectorizing text from data frame column using pandas | <p>I have a Data Frame wich looks like this: </p>
<p><a href="https://i.stack.imgur.com/WkvX9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WkvX9.png" alt="enter image description here"></a></p>
<p>I am trying to vectorize every row, but only from the text column. I wrote this code:</p>
<pre><co... | <p>There are a number of problems with your code. You probably need something like</p>
<pre><code>allDataVectorized = pd.DataFrame(vectorizerCount.fit_transform(allData[['headline_text']]))
</code></pre>
<ul>
<li><p><code>allData[['headline_text']])</code> (with the double brackets) is a DataFrame, which transforms t... | pandas|dataframe|vectorization | 1 |
360,658 | 50,249,880 | GroupBy and Cut in Pandas | <p>I am trying to group a set of things and perform cuts within the groups dynamically based on the min, max and average of both (min and max) value. </p>
<p>My dataset looks something like this:</p>
<pre><code>Country Value
Uganda 210
Kenya 423
Kenya 315
Tanzania 780
Uganda 124
Ug... | <p>This is how I did it:</p>
<pre><code>df['range'] = df.groupby('country')[['value']].transform(lambda x: pd.cut(x, bins = 2).astype(str))
</code></pre> | python|pandas | 5 |
360,659 | 50,631,867 | How to apply dropout to the outputs of an RNN in TensorFlow Eager using the Keras API? | <p>I would like to apply dropout to the outputs from an RNN. For example, in Tensorflow 1.8.0, I could do this:</p>
<pre><code>import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
x = tf.random_uniform((10, 5, 3))
gru_cell1 = tf.contrib.rnn.GRUCell(2)
gru_cell1 = tf.contrib.rn... | <p>To get the model output, without training, like you're doing in the TF code, the following code should work. Indeed, you need an <code>Input</code> layer, and to hook each layer to the previous one, and a <code>Model</code> as well:</p>
<pre><code>import numpy as np
from keras.models import Model
from keras.layers ... | python|tensorflow|keras|recurrent-neural-network|dropout | 0 |
360,660 | 50,456,251 | How to use python's "ord" function in Tensorflow without py_func | <p>In my program I need to obtain the base 10 value of a char as per the ASCII table, which I would normally get in python with <code>x = ord('a')</code> for example.</p>
<p>I have a string placeholder which I'm mapping to get every single character and from that I need to get back the equivalent base 10 number.</p>
... | <p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/decode_raw" rel="nofollow noreferrer">tf.decode_raw</a>:</p>
<pre><code>import tensorflow as tf
a = tf.placeholder(dtype=tf.string, shape=())
number = tf.decode_raw(a, out_type=tf.uint8)
with tf.Session() as sess:
print(sess.run(number, feed_dict={a: ... | python|tensorflow | 0 |
360,661 | 50,240,083 | tensorflow c++ batch inference | <p>I have a problem with making inference on a batchsize greater than 1 using the c++ tensorflow api. The network input planes are 8x8x13 and the output is a single float. When I try to infer on multiple samples as follows, the result is correct only for the first sample. I used keras2tensorflow tool for converting the... | <p>The problem turned out to be due to a bug the keras_to_tensorflow I used for conversion. I reported the issue <a href="https://github.com/bitbionic/keras-to-tensorflow/issues/3" rel="nofollow noreferrer">here</a>. The bug is still there in <a href="https://github.com/bitbionic/keras-to-tensorflow/blob/master/k2tf_co... | c++|tensorflow|neural-network|keras|inference | 0 |
360,662 | 50,592,595 | Merge dataframes including extreme values | <p>I have 2 data frames, df1 and df2:</p>
<pre><code>df1
Out[66]:
A B
0 1 11
1 1 2
2 1 32
3 1 42
4 1 54
5 1 66
6 2 16
7 2 23
8 3 13
9 3 24
10 3 35
11 3 46
12 3 51
13 4 12
14 4 28
15 4 39
16 4 49
df2
Out[80]:
B
0 32
1 42
2 13
3 24
4 35
5 39
6 49
</code></... | <p>Here's one way to do it using <code>merge</code> with indicator, <code>groupby</code>, and <code>rolling</code>:</p>
<pre><code>df[df.merge(df2, on='B', how='left', indicator='Ind').eval('Found=Ind == "both"')
.groupby('A')['Found']
.apply(lambda x: x.rolling(3, center=True, min_periods=2).max()).astype(b... | python|pandas|dataframe|merge | 3 |
360,663 | 50,307,666 | what is the fastest way to populate a pandas dataframe from two for loops? | <p>I already have a dataframe and I need to do computations at each index with respect to all preceding indices (so for 187 indicies there are 17766 computations). This needs to be efficient as to scale up to millions of computations.</p>
<pre><code>#this is the original dataframe
df = pd.DataFrame(np.random.rand(187,... | <p>Let's try broadcasted array arithmetic:</p>
<pre><code>v = df.values
v = v - v[:, None]
i, j = np.triu_indices(df.shape[0])
df2 = pd.DataFrame(v[i, j])
</code></pre>
<p>This is <em>very</em> fast, but can quickly get out of hand for too many records (~millions) because it results in a memory blowout, and half the... | python|pandas | 4 |
360,664 | 45,273,731 | Binning a column with pandas | <p>I have a data frame column with numeric values:</p>
<pre><code>df['percentage'].head()
46.5
44.2
100.0
42.12
</code></pre>
<p>I want to see the column as <a href="https://en.wikipedia.org/wiki/Data_binning" rel="noreferrer">bin counts</a>:</p>
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
</code></pre>
<p>How can I g... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="noreferrer"><code>pandas.cut</code></a>:</p>
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50... | python|pandas|numpy|dataframe|binning | 310 |
360,665 | 45,628,908 | Data frame with unique values from other data frame(pandas, python) | <p>I have data frame in which I have duplicates values (in each column not duplicated rows).
Data look like that:</p>
<pre><code>|Col1|Col2|Cold3|Col4|
| 1| A| John| -10|
| 2| A|Scoot| 234|
| 2| B|Kerry| 346|
| 6| B| Adam| -10|
</code></pre>
<p>I would like to create another df from this one which wou... | <p>I think you need:</p>
<pre><code>df = df.apply(lambda x: pd.Series(x.unique()))
print (df)
Col1 Col2 Cold3 Col4
0 1.0 A John -10.0
1 2.0 B Scoot 234.0
2 6.0 NaN Kerry 346.0
3 NaN NaN Adam NaN
</code></pre>
<p>Or:</p>
<pre><code>df = df.apply(lambda x: pd.Series(x.drop_duplicates(... | python|pandas | 0 |
360,666 | 45,439,274 | convert dataframe(with one column) to {index -> value} | <p>I have used to_dict() to transform dataframe like this:
<a href="https://i.stack.imgur.com/EDMVF.png" rel="nofollow noreferrer">it is very simple</a>
and I got </p>
<pre><code>{'point_dis': {'025ec525073fea4f6433b691c65b45cd': 12365.093765441219,
'02b697dc2e9214a46aa40e7fb0609310': 2315.3360224791882}
</code></p... | <p>First select column and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow noreferrer"><code>Series.to_dict</code></a>:</p>
<pre><code>d = df['point_dis'].to_dict()
print (d)
{'025ec525073fea4f6433b691c65b45cd': 12365.093765441219,
'02b697dc2e9214a46a... | python|pandas|dataframe | 0 |
360,667 | 45,717,328 | String matching plus Boolean value reassignment in Pandas | <p>I'm trying to find all the value, which is a more complex query than I'm used to. I'll be changing the values of millions of values potentially, so the most efficient way to find rows, which meet these conditions, and how to change their values would be really helpful.</p>
<p>What I'm trying to do is the following:... | <p>we can use <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer">Pandas boolean indexing</a>:</p>
<pre><code>In [126]: example
Out[126]:
a b
0 9+ False
1 10- False
2 9 True
3 1 True
4 2 False
In [127]: example.loc[example['a'].s... | python|pandas|numpy | 2 |
360,668 | 45,666,991 | How to store variable in loss function into instance variable | <p>I am using Keras with Tensorflow.
Since I want to create <a href="https://arxiv.org/abs/1603.01360" rel="nofollow noreferrer">LSTM-CRF model</a>, I defined my own loss function using <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/crf/crf_log_likelihood" rel="nofollow noreferrer">tf.contrib.crf.crf_lo... | <p>The problem is the wrong function signature <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/crf/crf_log_likelihood" rel="nofollow noreferrer"><code>tf.contrib.crf.crf_log_likelihood</code></a>, you need to pass the <code>transition_params</code> with your current transition params. Following changes w... | python|machine-learning|tensorflow|nlp|keras | 3 |
360,669 | 45,604,291 | Pandas groupby on multi-columns and broadcast the result to the original dataframe | <p>I have a pandas dataframe of the form:</p>
<pre><code> bowler inning wickets Total_wickets matches balls
0 SL Malinga 1 69 143 44 4078
1 SL Malinga 2 74 143 54 4735
2 A Mishra 1 48 124 50 3908
3 A Mishra ... | <p>Your transform is failing because you're applying it along the wrong axis and you need to use an aggregation such as <code>sum()</code> first. Check this out:</p>
<pre><code>In [83]: df.groupby(['bowler', 'inning']).sum().transform(lambda x : x['balls'].astype(float)/x['wickets'].astype(float), axis=1)
Out[83]:
bo... | python|pandas|pandas-groupby | 2 |
360,670 | 45,345,944 | Pandas apply in 2 columns and substitute them in one line | <p>I'm trying to improve the performance of my code and I want to tokenize 2 columns of a dataframe and I had it like this </p>
<pre><code>submission_df['question1'] = submission_df.apply(lambda row: nltk.word_tokenize(row['question1']), axis=1)
submission_df['question2'] = submission_df.apply(lambda row: nltk.word_t... | <p>You can simply use <code>apply</code> for the selected columns with astype(str) i.e</p>
<pre><code>submission_df[['question1','question2']]=submission_df[['question1','question2']].astype(str).apply(lambda row: [nltk.word_tokenize(row['question1']),nltk.word_tokenize(row['question2'])], axis=1)
</code></pre>
<p>Ex... | python|pandas|machine-learning|kaggle | 1 |
360,671 | 45,358,426 | Fastest way to set elements of Pandas Dataframe based on a function with index and column value as input | <p>I have a single column Pandas dataframe:</p>
<pre><code>s =
VALUE
INDEX
A 12
B 21
C 7
...
Y 21
Z 7
</code></pre>
<p>I want to make it into a square matrix mask with the same index and columns as <code>s.index</code>, with each element either <code>True</code> if the value of column and i... | <p>Use <code>numpy</code> broadcasting</p>
<pre><code>v = s.VALUE.values
pd.DataFrame(v == v[:, None], s.index, s.index)
INDEX A B C Y Z
INDEX
A True False False False False
B False True False True False
C False False True False... | pandas|dataframe|elementwise-operations | 3 |
360,672 | 45,523,025 | How to slice strings in a column by another column in pandas | <pre><code>df=pd.DataFrame({'A':['abcde','fghij','klmno','pqrst'], 'B':[1,2,3,4]})
</code></pre>
<p>I want to slice column A by column B eg: <code>abcde[:1]=a, klmno[:3]=klm</code>
but two statements all failed:</p>
<pre><code>df['new_column']=df.A.map(lambda x: x.str[:df.B])
df['new_column']=df.apply(lambda x: x.A[... | <p>You need <code>axis=1</code> in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer"><code>apply</code></a> method to loop through rows:</p>
<pre><code>df['new_column'] = df.apply(lambda r: r.A[:r.B], axis=1)
df
# A B new_column
#0 abcde 1 a... | python|pandas | 11 |
360,673 | 45,524,189 | build matrix from multiple files using pandas | <p>Have multiple files(20) in a directory with 2 columns, for eg</p>
<pre><code>transcript_id value
ENMUST001 2
ENMUST003 3
ENMUST004 5
</code></pre>
<p>number of rows differ in each file what I would like to do is merge all the 20 files in one huge matrix in this way</p>
<pre><code>transcript_id value_f... | <p>The default behaviour for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">set_index</a> is <code>inplace=False</code>. Try replacing <code>df.set_index('transcript_id')</code> with <code>df = df.set_index('transcript_id')</code>. Also you can... | python|python-2.7|pandas | 3 |
360,674 | 45,681,873 | How can I combine datetime.date and datetime.time columns in pandas dataframe? | <p>Given df</p>
<pre><code> Date Time Data
3 2017-08-10 15:15:00 a
0 2017-08-11 15:15:00 b
1 2017-08-12 15:15:00 c
2 2017-08-13 15:15:00 d
1 2017-08-14 15:15:00 e
</code></pre>
<p>And</p>
<pre><code>print (type(df['Date'].iat[0]))
<class 'dat... | <p>The issue here is that both date and time are already in datetime format. Try </p>
<pre><code>df['datetime'] = pd.to_datetime(df['Date'].dt.strftime('%Y-%m-%d') + df['Time'].astype(str), format = '%Y-%m-%d%H:%M:%S')
</code></pre>
<p>Though I don't know if it would be more efficient than using datetime.combine</p> | python|python-3.x|pandas|datetime|dataframe | 2 |
360,675 | 45,345,245 | Flattening index in python pandas | <p>I am very new to the python and I have been playing around with Panda dataframes, but when I use a groupby, I am not longer able to iterate over the dataframes using the labels.</p>
<p>Can some help me ?</p>
<pre><code>newDF=df[df['Currency'].str.contains(currency)&df['Description'].str.contains('fx')]
newDF=n... | <p>I think you need change:</p>
<pre><code>moneyWithdrawnByUserDF=pd.DataFrame(newDF.groupby(['FirstName'])[['Withdrawn']].sum())
</code></pre>
<p>by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p>
<pre><cod... | python|pandas|dataframe | 1 |
360,676 | 45,436,708 | how to add and subtract a day either side of my datetime index in pandas df | <p>I have a df with FOMC announcements dates in it and i want to have a new df with the FOMC date + the next day and also the previous day. As an example - 2017-06-13 has been added to the new df. Any ideas? i am using pandas 0.20.3 and Offsets looks like my best option.</p>
<pre><code>2017-06-13
2017-06-14 The Federa... | <p>Using this sample dataset:</p>
<pre><code> date
0 2017-01-01
1 2017-01-02
2 2017-01-03
3 2017-01-04
4 2017-01-05
5 2017-01-06
6 2017-01-07
7 2017-01-08
</code></pre>
<p>We can use <code>pd.offsets.Day()</code> to add or subtract time values.</p>
<pre><code>df['date_plus_one'] = df['date'] + pd.off... | python|pandas | 3 |
360,677 | 45,646,232 | Database engine fails to connect to a sql-server instance while trying to insert using to_sql function | <p>I am trying to insert pandas dataframe <code>CAPE</code> into <code>SQL Server</code> DB using dataframe.to_SQL. I have referred the following solution to insert rows.
<a href="https://stackoverflow.com/questions/30465284/pyodbc-fails-to-connect-to-a-sql-server-instance">PyOdbc fails to connect to a sql server insta... | <p>The first positional parameter of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">DataFrame.to_sql()</a> is a table name, you passed <code>engine</code> (SQLAlchemy object) as a first parameter.</p>
<p>So try this instead:</p>
<pre><code>CAPE.... | python|sql-server|pandas|database-connection | 2 |
360,678 | 45,556,503 | How to get float_val from a PredictResponse object? | <p>I'm having exactly <a href="https://stackoverflow.com/questions/44785847/how-to-retrieve-float-val-from-a-predictresponse-object">this</a> problem:</p>
<p>After running a prediction on a tensorflow-serving model, I'm getting back this PredictResponse object as output:</p>
<pre><code>outputs {
key: "scores"
val... | <p><code>result.outputs['scores'].float_val[0]</code> and <code>result.outputs['scores'].float_val[1]</code> are the float values in this response.</p>
<p>For future reference, the <a href="https://developers.google.com/protocol-buffers/docs/reference/python-generated" rel="nofollow noreferrer">documentation for the p... | python|tensorflow|protocol-buffers|tensorflow-serving | 5 |
360,679 | 45,525,684 | How to define the data to fit the classifier | <p>I am new to tensorflow. I created a 204x4 matrix where the first 3 colums are feature and the last colum is the target. How do I need to convert the array so that tensorflow can train the data?</p>
<pre><code>TRAINING_SET = np.asarray(seq[:llength])
VALIDATION_SET= np.asarray(seq[llength:llength+tlength])
TEST_SET ... | <p>You need use a function for the input_fn not just a <code>tensor</code></p>
<pre><code>TRAINING_SET = np.asarray(seq[:llength])
VALIDATION_SET= np.asarray(seq[llength:llength+tlength])
TEST_SET = np.asarray(seq[llength+tlength:])
num_epochs=100
batch_size = 32
# define a function to get data as batch, you can us... | tensorflow | 1 |
360,680 | 45,439,506 | Pandas replace only working with regex | <p>I already found a workaround, but I'm still curious about what's going on:</p>
<p>When I try to do replace in Pandas like so:</p>
<pre><code>merged4[['column1', 'column2', 'column3']] = merged4[['column1', 'column2', 'column3']].replace(to_replace='.', value=',')
</code></pre>
<p>It's not working. I tried all dif... | <p>When you don't use <code>regex=True</code> the method will look for the exact match of the replace_to value. When you use <code>regex=True</code> it will look for the sub strings too. So your code works when you use that parameter.
Example </p>
<p>When you dont use the <code>regex=True</code> parameter, the replac... | python|pandas | 4 |
360,681 | 45,488,408 | Google Object Detection API - full description of the config files parameters and structure? | <p>The following link provides brief description of the configuration file required for training <a href="https://github.com/tensorflow/models/blob/master/object_detection/g3doc/configuring_jobs.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/object_detection/g3doc/configuring_jobs.md</a>... | <p>As the docs mention, the configuration file represents ultimately a hierarchy of <a href="https://developers.google.com/protocol-buffers/" rel="nofollow noreferrer">protocol buffers</a> objects, and the specification of these objects can be checked in <a href="https://github.com/tensorflow/models/tree/master/object_... | tensorflow | 0 |
360,682 | 45,690,928 | How to sum up combined string has serval numbers in a pandas DataFrame column | <p>I have a string contains comma delimited int values, such as x = "1,2,3,4,5,6"
, how to calculate the sum of x contained values?</p>
<p>I tried:</p>
<pre><code>values = x.split(",").map(lambda a:int(a))
sum(values)
</code></pre>
<blockquote>
<p>AttributeError: 'list' object has no attribute 'map'</p>
</blockquo... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>, for <code>sum</code>s columns use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split<... | python-3.x|pandas|dataframe|split|sum | 1 |
360,683 | 45,434,781 | TensorFlow, when can Python-like negative indexing be used if ever? | <p>I'm new to TensorFlow (version 1.2), but not to Python or Numpy. I am building a model to predict the shape of a protein molecule. I need to wrap TensorFlow's standard tf.losses.cosine_distance function in some extra code, because I need to stop the propagation of some NaN values into the loss calculation.</p>
<p... | <p>It can be used with tensorflow's bindings to python slicing operators. So for example, <code>loss[-1]</code> is a valid slicing of <code>loss</code>.</p>
<p>In your case, if you have only three slices, you could assign them individually:</p>
<pre><code>update_op0 = indices[0,0,0].assign(updates[0])
update_op1 = in... | python|numpy|tensorflow | 0 |
360,684 | 45,556,357 | Pandas filtering/pooling and keeping the old Indices | <p>Here is my question:</p>
<p>I have 2 columns in the same data. One column for ID (several Id's are repeated) and the Other column is about age (many ages are repeated).
I want to create new columns in which I regroup the Ids then call/display their indices where they where in the OLD table.
An example:
age = [12, 1... | <p>If you want to create a column that stores the indices of repeated ages, you can use</p>
<pre><code>frame = pd.DataFrame(np.random.randint(1,5,(10,2)),columns=['ID','Age'])
frame['Age2'] = [[dex for y,dex in zip(frame.Age,frame.index) if x == y] for x in frame.Age]
</code></pre> | python|python-2.7|pandas|indexing | 0 |
360,685 | 45,684,445 | Tensorflow Update first matching element in each row | <p>Building on this <a href="https://stackoverflow.com/questions/42184663/how-to-find-an-index-of-the-first-matching-element-in-tensorflow">question</a> I am looking to update the values of a 2-D tensor the first time in a row the tf.where condition is met. Here is a sample code I am using to simulate:</p>
<pre><code... | <p>One easy workaround is to use <code>tf.py_func</code> with numpy array</p>
<pre><code>def ch_val(array, val, new_val):
idx = np.array([[s, list(row).index(val)]
for s, row in enumerate(array) if val in row])
idx = tuple((idx[:, 0], idx[:, 1]))
array[idx] = new_val
return array
...
m... | python|tensorflow | 0 |
360,686 | 45,627,199 | How do retrieve data from another dataframe in python pandas? | <p>I have 2 table:</p>
<p>First table</p>
<pre><code>Course Price
English $250
Chinese $300
Math $500
</code></pre>
<p>Second table:</p>
<pre><code>Name Course
Vivian English
Vivian Math
Shar Math
Nick Math
Tan Chinese
</code></pre>
<p>I wish to have a code to get ... | <p>Use <code>merge</code>:</p>
<pre><code>table_2.merge(table_1, on='Course')
</code></pre>
<p>Output:</p>
<pre><code> Name Course Price
0 Vivian English $250
1 Vivian Math $500
2 Shar Math $500
3 Nick Math $500
4 Tan Chinese $300
</code></pre> | python|pandas | 2 |
360,687 | 45,514,533 | ValueError on tensorflow while_loop shape invariants | <pre><code>import tensorflow as tf
cluster_size = tf.constant(6) # size of the cluster
m = tf.constant(6) # number of contigs (column size)
n = tf.constant(3) # number of points in a single contigs (column size)
contigs_index = tf.reshape(tf.range(0, m, 1, dtype=tf.int32), [1, -1])
contigs = tf.constant(
[[1.1, 2.2,... | <p><code>shape_invariants=[contigs_index.get_shape(), tf.TensorShape([None, 6])]))</code> should become <code>shape_invariants=[tf.TensorShape([None, None]), tf.TensorShape([None, 6])]))</code>, to allow for shape changes of <code>contigs_index</code> variable (in the <code>rpad_with_zero</code> call).</p> | python-2.7|tensorflow|while-loop|loop-invariant | 1 |
360,688 | 45,618,482 | Pivot Rows in Pandas Dataframe | <p>My dataframe currently looks like:</p>
<pre><code>ID FIELD VALUE
12463634 TEST 22.2
12463634 E_REASON 010
12463634 IN_SCOPE Y
12463635 TEST 99.5
12463635 E_REASON 020
12463635 IN_SCOPE N
</code></pre... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>:</p>
<pre><code>df = df.pi... | python|pandas|dataframe|pivot | 2 |
360,689 | 45,681,654 | Efficient way to determine total time taking overlap into account | <p>I am using pandas dataframe for the following:</p>
<p>I am trying to find the best way to determine the total time spent by a ship at a particular berth taking into account overlap in the duration of the visit.
Here is what the data looks like:</p>
<pre><code> IN OUT BERTH... | <p>Here's a solution for one berth. I hope you can expand it to multiple berths.</p>
<p>Split the dataframe into arrivals and departures:</p>
<pre><code>dfIN = df[['IN']]
dfOUT = df[['OUT']]
dfIN['direction'] = 1
dfOUT['diretcion'] = -1
</code></pre>
<p>As of now, IN and OUT are just timestamps:</p>
<pre><code>dfIN... | python|pandas|time|overlap|calculation | 1 |
360,690 | 45,423,917 | Pandas: [Errno 75] Value too large for defined data type | <p>I'm having this strange error when converting a datetime column.</p>
<p>This is the offending line of code:</p>
<pre><code>data['date'] = data['datetime'].map(lambda x:datetime.utcfromtimestamp(x/1000))
</code></pre>
<p>To make things more interesting this works:</p>
<pre><code>datetime.utcfromtimestamp(data.dat... | <p>In Pandas we can do it this way:</p>
<pre><code>data['date'] = data['datetime'].astype(np.int64) // 10**9
</code></pre>
<p>that gives us a number of <strong>seconds</strong> since 1970-01-01 00:00:00 UTC.</p>
<p>If you want/need to get # of <strong>milliseconds</strong>:</p>
<pre><code>data['date'] = data['datet... | python|pandas | 4 |
360,691 | 45,609,738 | high precision calculation in numpy | <p>How to perform high precision calculation in numpy?
By high precision I mean 100 precision in decimal.</p> | <p>Numpy doesn't have arbitrary floating-point precision. You'll want to use <a href="https://docs.python.org/3/library/decimal.html" rel="nofollow noreferrer">decimal</a> from the standard library, or a third-party library like <a href="http://mpmath.org/" rel="nofollow noreferrer">mpmath</a>. Both of those libraries ... | numpy|precision | 1 |
360,692 | 45,625,065 | Replacing the values of a time series with the values of another time series in pandas | <p>I have two DataFrames:</p>
<pre><code>s1:
time X1
0 1234567000 96.32
1 1234567005 96.01
2 1234567009 96.05
s2:
time X2
0 1234566999 23.88
1 1234567006 23.96
</code></pre>
<p>I would like to replace the values of the first time series/DataFrame with the second DataFrame while ... | <p>Here is my solution , I break down the step. </p>
<p>1st only search in the past:</p>
<pre><code>M1=pd.DataFrame({},index=df1.time,columns=df2.time)
M1=M1.apply(lambda x:x.index-x.name)
del M1.index.name
M2=M1.stack().reset_index()
M2=M2.loc[M2[0]>=0,]
M2[0]=abs(M2[0])
M2=M2.sort_values(['level_0',0]).drop_dupl... | python|pandas|dataframe | 4 |
360,693 | 45,701,564 | a python import is working from command line, and not working from pycharm | <p>I have a script that imports tensorflow.
At the beginning of the script is manually set the sys.path, and working directory with:</p>
<pre><code>import os; os.chdir('/home/my_project'); print(os.getcwd())
import sys; sys.path = [...]; print(sys.path)
</code></pre>
<p>When I run the script from PyCharm, I'm gettin... | <p>I seems that from some reason the settings of the <code>LD_LIBRARY_PATH</code> from the PyCharm environment variables don't really affect it, and setting <code>os.environ['LD_LIBRARY_PATH']</code> don't help for the imports if it's set from the script itself. What solved the problem was that I ran PyCharm directly f... | python|tensorflow|pycharm | 0 |
360,694 | 45,434,811 | Calculate time difference of a Datetime object and get output as floatvalues? | <p>I have a dataframe column of Date and time:</p>
<pre><code>0 2017-06-24 08:37:00
1 2017-06-24 08:40:00
2 2017-06-24 08:42:01
3 2017-06-24 08:44:01
4 2017-06-24 08:46:00
5 2017-06-24 08:48:00
6 2017-06-24 08:50:01
7 2017-06-24 08:52:01
8 2017-06-24 08:54:01
9 2017-06-24 08:56:00
10 20... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a> - output is <code>timedelta</code>s, so need convert by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html" rel="nofollow no... | python|pandas|datetime|dataframe|timedelta | 0 |
360,695 | 45,337,939 | finding initial guesses for exponential curve fit | <p>So I don't know how to do this, and I'm not sure if there's some math that I'm completely forgetting right now but I'm at a loss. In short, I have some fairly simple initial code using scipy and numpy, and I want to fit an exponential curve to it:</p>
<pre><code>from scipy.optimize import curve_fit
import numpy as... | <p>To me this data is more close to a lign than an exponential curve, are you sure your model is right?</p>
<p>About the initial guesses, I assume you don't have any further knowledge about the function, if so use it:</p>
<p>For x->\inf the fucntion approaches b. So I would use a guess of about 0.025 for b.
For the o... | python|numpy|curve-fitting|exponential-distribution | 0 |
360,696 | 45,390,699 | Faster index computation from Scipy labelled array apart from np.where | <p>I am working on a large array (3000 x 3000) over which I use <code>scipy.ndimage.label</code>. The return is 3403 labels and the labelled array. I would like to know the indices of these labels for e.g. for label 1 I should know the rows and columns in the labelled array.
So basically like this </p>
<pre><code>a[0]... | <p>Well the idea with gaining efficiency would be to minimize the work once inside the loop. A vectorized method isn't possible given that you would have variable number of elements per label. So, with those factors in mind, here's one solution -</p>
<pre><code>a_flattened = a[0].ravel()
sidx = np.argsort(a_flattened)... | python|arrays|numpy|scipy|ndimage | 0 |
360,697 | 45,599,701 | How to Change File Extension (.npy to .csv) in Python? | <p>I have 100 files with <code>.npy</code> extenstion. What should I do to convert all of them to <code>.csv</code> via loop <code>for</code>? </p>
<p>Besides, how can I load all of them simultaneously to concatenate the arrays with each other to a new one?</p>
<p>Regards</p> | <p>Here is an example for converting the arrays into CSV.</p>
<p><code>numpy.savetxt</code>, by the way, saves an array to a text file.</p>
<pre><code>import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")
</code></pre> | python|python-3.x|csv|numpy|export-to-csv | 2 |
360,698 | 45,687,019 | How exactly does Keras take dimension argumentsfor LSTM / time series problems? | <p>I can't seem to find a concrete answer to the question of how to feed data into Keras. Most examples seem to work off image / text data and have clearly defined data points. </p>
<p>I'm trying to feed music into an LSTM neural network. I want the network to take ~3 seconds of music and nominate the next 2 seconds. ... | <p>Keras convention is that the batch dimension is typically omitted in the <code>input_shape</code> arguments. From the <a href="https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-shape" rel="nofollow noreferrer">guide</a>:</p>
<blockquote>
<p>Pass an input_shape argument to the first lay... | python|numpy|tensorflow|keras|sequence-to-sequence | 1 |
360,699 | 62,686,436 | How to make a list of 2D 3x3 array and save the ndarray with numpy save? | <p>So let's say I have some 3x3 matrix I get with a calculation I am doing, let's say</p>
<p><code>np.array([[1,2,3],[4,5,6],[7,8,9]])</code></p>
<p><code>np.array([[0,0,0],[0,0,0],[0,0,0]])</code></p>
<p>I want to add this onto some matrix <code>A</code> and be able to access them so that if I do</p>
<pre><code>> A... | <p>You can convert list to array it is the same:</p>
<pre><code>A = list()
A.append(x)
A.append(y)
X = np.array(A)
np.save('X', X)
</code></pre> | python|arrays|python-3.x|numpy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.