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 |
|---|---|---|---|---|---|---|
355,000 | 57,011,517 | How to generate a new dataframe with concrete information of an existing one | <p>I want to create a new dataframe from an existing one, generating two new columns ("topic" and "num") with information of the column "total" from the old dataframe.</p>
<p>This is the old dataframe where I want to take the info from:</p>
<pre><code>d = {'username': ['low_bu', 'kik', 'serg'],
'total': ['topic:... | <p>You could try regex to extract it the way you want, like the example below:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
d = {'username': ['low_bu', 'kik', 'serg'],
'total': ['topic:tele,num:3,randomnums,topic:ordena,num:2','topic:pc,num:5,morenums,topic:ordena,num:3,things,topic:te... | python|pandas | 0 |
355,001 | 57,081,743 | Choose higher value based off column value between two dataframes | <p>question to choose value based on two df. </p>
<pre><code>>>> df[['age','name']]
age name
0 44 Anna
1 22 Bob
2 33 Cindy
3 44 Danis
4 55 Cindy
5 66 Danis
6 11 Anna
7 43 Bob
8 12 Cindy
9 19 Danis
10 11 Anna
11 32 Anna
12 55 Anna
13 33 Anna
1... | <p>Per comments, use merge and filter dataframe:</p>
<pre><code>df.merge(df2, on='name', suffixes={'','_y'}).query('age > age_y')[['name','age']]
</code></pre>
<p>Output:</p>
<pre><code> name age
4 Anna 55
</code></pre>
<hr>
<p>IIUC, you can use this to find the max age of all names:</p>
<pre><code>pd.co... | python|pandas | 1 |
355,002 | 57,260,823 | How to return column index for every row where a certain value appears for the first time | <p>I have a data frame in pandas, where 1 appears in different columns for every rows. The column where 1 appears for the first time in a row is different for different rows. I need to create an additional column (column index) in which as value I want to return the index number of the column where 1 appears for the fi... | <p>You can always just write a simple function and then use apply on the dataframe.</p>
<pre class="lang-py prettyprint-override"><code>def get_first(row):
for i, col in enumerate(row.index.tolist()):
if row[col] == 1:
return i
df['column_index'] = df.apply(get_first, axis=1)
</code></pre>
<p... | python-3.x|pandas | 2 |
355,003 | 56,872,205 | pandas groupby rolling mean/median with dropping missing values | <p>How can get in pandas groupby rolling mean/median with dropping missing values? I.e. the output should drop missing values before calculating mean/median instead of giving me NaN if a missing value is present.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
t = pd.DataFrame(data={v.date:[0,0... | <p>You're looking for <code>min_periods</code>? Note that you don't need <code>apply</code>, call<code>GroupBy.Rolling</code> directly:</p>
<pre><code>t.groupby('date', group_keys=False).rolling(window=2, min_periods=1).mean()
x
date i0 i1
0 0 A 10.0
1 A 15.0
2 A 25.0
3 ... | python|pandas|dataframe|pandas-groupby|rolling-computation | 5 |
355,004 | 57,019,289 | Pandas: Convert only numbers in dataframe to numeric, keep everything else | <h2>Source Dataframe</h2>
<pre><code>df1 = pd.DataFrame({'x': ['a', '2.0', '3.0'], 'y': ['4.0', 'b', '6.0']})
x y
0 a 4.0
1 2.0 b
2 3.0 6.0
</code></pre>
<h2>First Try (use 'coerce')</h2>
<p>If I use 'coerce' to handle strings, they will be replaced by NaN</p>
<pre><code>df2 = df1.apply(lambda x: pd.... | <p>It is expected output, because if check <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> you can see:</p>
<blockquote>
<p>errors : {'ignore', 'raise', 'coerce'}, default 'raise'</p>
<p>If 'raise', then invalid parsing wil... | python|pandas|dataframe | 7 |
355,005 | 56,955,091 | How to convert 2d into row | <p>I have a data-frame like:</p>
<pre><code> a b
[[35.6113, -95.855]] [[[36.028, -95.93], [36.10, -95.82] .... ]]]
</code></pre>
<p>How can i convert it into like this:</p>
<pre><code> a b
[35.6113, -95.855] [36.028, -95.... | <p>Check with </p>
<pre><code>s=pd.DataFrame({'a':df.a.repeat(df.b.str.len()),'b':sum(df.b.tolist(),[])})
s.apply(lambda x : x.str[0])
Out[104]:
a b
0 [35.6113, -95.855] [35.6113, -95.855]
0 [35.6113, -95.855] [35.6113, -95.855]
</code></pre> | python|python-3.x|pandas|python-2.7 | 3 |
355,006 | 56,964,820 | Append function outcome to a dataframe | <p>I try to assign values depening on a loop to a dataframe in python.</p>
<p>I have the following start dataframe:</p>
<pre><code>thres = 0.1
d = { 'T': [0.], 'TN': [0], 'FN': [0], 'FP':[0], 'TP':[0]}
dataframef = pd.DataFrame(data=d)
</code></pre>
<p>with my start varialbe <code>thres</code>.</p>
<p>Now I am ente... | <p>Change the assignments like this:</p>
<pre><code>dataframe.loc[0,'T'] = thres
dataframe.loc[0,'TN'] = tn
dataframe.loc[0,'FP'] = fp
dataframe.loc[0,'FN'] = fn
dataframe.loc[0,'TP'] = tp
</code></pre>
<p>When using <code>dataframe.loc[0]['TP'] = tp</code> you assign <code>tp</code> to a copy, not to the original d... | python|pandas|machine-learning|random-forest|confusion-matrix | 1 |
355,007 | 57,180,538 | Apply custom function to each combination of columns in a pandas dataframe | <p>I'm trying to calculate the cosine similarity between each combination of columns in my pandas dataframe. I've written a custom function to calculate cosine similarity, and now need to apply it to every combination pair of columns. Each column contains a 0 if a user has not interacted with it, and a 1 if the user ha... | <pre><code>import scipy.spatial.distance
result = pd.DataFrame(list(itertools.combinations(sm_views.columns, 2)), columns=['a','b'])
result['association'] = scipy.spatial.distance.pdist(sm_views.T, 'cosine')
</code></pre>
<p>With this example sm_view:</p>
<pre><code> col1 col2 col3
0 0 0 0
1 3 ... | python|pandas|dataframe|lambda | 1 |
355,008 | 57,237,193 | Delete rows in pandas given a regex | <p>I have a dataframe that I previously transposed. Before the transposition, the numerical column had values float64 and that was expected. However, after the transpose, the float values turned into strings. I tried to convert the dataframe using the .as_type('float') but it got raised with an exception because some c... | <p>You were quite close with your regex, some small problems though.</p>
<hr>
<h3>Method 1, cleaning up in specific column</h3>
<p>If you know which column is giving the problem, we can use <code>str.contains</code> on a specific column:</p>
<pre><code>m = ~df['q1'].str.contains('\d+\.\d+\s\d+\.\d+')
df[m]
</code><... | python|regex|pandas | 2 |
355,009 | 57,008,837 | Efficient double for loop over large matrices | <p>I have the following code which I need to runt it more than one time. Currently, it takes too long. Is there an efficient way to write these two for loops.</p>
<pre><code>ErrorEst=[]
for i in range(len(embedingFea)):#17000
temp=[]
for j in range(len(emedingEnt)):#15000
if cooccurrenceCount[i][j]>... | <p>If you need to increase the performance of your code you should write it in low level language like C and try to avoid the usage of floating point numbers.</p>
<p>Possible solution: <a href="https://stackoverflow.com/questions/18762621/can-we-use-c-code-in-python">Can we use C code in Python?</a></p> | python|algorithm|numpy | 0 |
355,010 | 57,043,712 | Numpy Array bug | <p>I have an array</p>
<pre><code>array = [np.array([[0.76103773], [0.12167502]]),
np.array([[ 0.72017135, 0.1633635 , 0.39956811, 0.91484082, 0.76242736, -0.39897202],
[0.38787197, -0.06179132, -0.04213892, 0.16762614, 0.05880554, 0.59370467]])]
</code></pre>
<p>And I want to convert ... | <p>Your list contains (2,1) and (2,6) shaped arrays.</p>
<p><code>np.array</code> tries to create a multidimensional array from the inputs. That works fine with inputs that have matching shapes (or length and nesting). Failing that it falls back on creating object dtype arrays.</p>
<p>But in cases where the first d... | python|python-3.x|numpy|numpy-ndarray | 2 |
355,011 | 56,940,623 | df.sort_values is not sorting table (python/pandas) | <p>df.sort_values in pandas is not working for me, the same df is getting returned without being sorted.</p>
<pre><code>def findExpression(transType, sortColName=None):
global df
if transType == 'sortAscending':
df.sort_values(sortColName)
return df
print(findExpression('sortAscending', sortC... | <p>Most pandas function don't modify the elements directly but return a modified copy of it. If you want to modify the object directly you have to add the option <code>inplace = True</code> :</p>
<pre><code>df.sort_values(sortColName, inplace = True)
</code></pre>
<p>which is the same as doing :</p>
<pre><code>df = ... | python|pandas|csv|sorting | 1 |
355,012 | 57,001,509 | Python GPU programming for bulk simple calculations with Pandas | <p>Raw data in Excel (as screenshot) of 3 columns. The script is to calculate the result by a simple formula with the columns. When the result reaches a limit, it prints result.</p>
<pre><code>import pandas as pd
df = pd.read_excel("C:\excel_file.xlsx", sheet_name = "Sheet1")
P1 = df['Period 1']
P2 = df['Period 2']
... | <p>Is your calculation really "return all the rows that meet this criteria"? (I am not a pandas pro, so maybe missing something). If I am reading it right, 6000 multiplications and comparisons should take drastically less then a second. In a quick experiment, The length of the data to get it to take a whole second was ... | python|pandas|gpu | 2 |
355,013 | 57,058,346 | Add a Total and Count Row to a Dataframe | <p>I have a dataframe as follow: </p>
<pre><code>dashboard = pd.DataFrame({
'id':[1,2,3,4],
'category': ['a', 'b', 'a', 'c'],
'price': [123, 151, 21, 24],
'description': ['IT related', 'IT related', 'Marketing','']
})
</code></pre>
<p>I need to add a row to show both sum and count only for some categories as foll... | <p>An option using <code>.agg</code>:</p>
<pre class="lang-py prettyprint-override"><code>dashboard = pd.DataFrame({
'id': [1, 2, 3, 4],
'category': ['a', 'b', 'a', 'c'],
'price': [123, 151, 21, 24],
'description': ['IT related', 'IT related', 'Marketing', '']
})
a_b = dashboard[dashboard['category'].i... | python|pandas | 1 |
355,014 | 45,816,800 | Anaconda package for cufft keeping arrays in gpu memory between fft / ifft calls | <p>I am using the anaconda suite with ipython 3.6.1 and their accelerate package. There is a <a href="https://docs.continuum.io/accelerate/cufft" rel="nofollow noreferrer">cufft</a> sub-package in this two functions fft and ifft. These, as far as I understand, takes in a numpy array and outputs to a numpy array, both i... | <p>So I found <a href="https://github.com/arrayfire/arrayfire-python" rel="nofollow noreferrer">Arrayfire</a> which seems rather easy to work with.</p> | python|numpy|anaconda|cufft | 0 |
355,015 | 45,804,700 | Broadcasting error when counting occurance of data in multiple column | <p>I am using pandas for calculating occurrence of data on a particular row in all column. The data I use is a pressure values which I need to find if the acutal observation data (D3) is appearing on other rows of all colums. Here is the data I use:-</p>
<pre><code>Date AA1 BB1 CC1 AA2 BB2 ... | <p>Found the issue. There is a value <code>100.9.0</code> in one of the column I have extracted for calculation. But I believe that the error message seems to point something else. Similarly, I had another data set where <code>T</code> was there in between data set and it produced the same ValueError. Really strange de... | python|pandas | 0 |
355,016 | 46,103,044 | Index n dimensional array with (n-1) d array | <p>What is the most elegant way to access an n dimensional array with an (n-1) dimensional array along a given dimension as in the dummy example</p>
<pre><code>a = np.random.random_sample((3,4,4))
b = np.random.random_sample((3,4,4))
idx = np.argmax(a, axis=0)
</code></pre>
<p>How can I access now with <code>idx a</c... | <p>Make use of <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#advanced-indexing" rel="noreferrer"><code>advanced-indexing</code></a> -</p>
<pre><code>m,n = a.shape[1:]
I,J = np.ogrid[:m,:n]
a_max_values = a[idx, I, J]
b_max_values = b[idx, I, J]
</code></pre>
<hr>
<p>For the general ... | python|numpy | 15 |
355,017 | 46,131,462 | Python / Pandas - Transform phone numbers from float to ints in a column with NaNs | <p>I have a dataframe with a column with floats and NaNs.
Those are phone numbers and they look strange as floats (it gets a ".0" in the end, and the phone number looks like this 5551981180099.0). I tried to use <code>df['phone'].astype(int)</code> to fix that, however it bugs with the NaNs and I get a "can't convert N... | <p>If you have <code>NaN</code> values with <code>int</code>, by design all values are convert to <code>float</code>s.</p>
<p>You can replace <code>NaN</code> to some <code>int</code> and then is possible convert column to <code>int</code>.</p>
<pre><code>df['phone'] = df['phone'].fillna(0).astype(int)
</code></pre>
... | python|pandas | 2 |
355,018 | 45,910,839 | How to count string with pattern in series object? | <p>Suppose a data like this:</p>
<pre><code>>>> data
x
0 [wdq, sda, q]
1 [q, d, qasd]
2 [d, b, sdaaaa]
</code></pre>
<p>I wonder how many string contains <code>a</code> in each list, which means I need an answer like this:</p>
<pre><code>>>> data
x count_a
0 ... | <p>Assuming this is a <code>pandas.DataFrame</code> and <code>x</code> is a <code>list</code> object:</p>
<pre><code>df['count_a'] = df['x'].apply(lambda x: sum('a' in e for e in x))
</code></pre> | python|pandas | 2 |
355,019 | 46,172,220 | Python Matrix - Limiting Matrix to top 20 | <p>I have a Matrix that counts the number of links between two sets of disciplines that I did through this code from a DF that I created:</p>
<pre><code>new_df = df[['GrantRefNumber','Subject']]
a = ['Psychology','Education','Social policy','Sociology','Pol. sci. & internat. studies','Development studies','Social... | <p>You can use:</p>
<pre><code>df = pd.DataFrame({'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]})
print (df)
B C D E
0 4 7 1 5
1 5 8 3 3
2 4 9 5 6
3 5 4 7 9
4 5 2 1 2
5 4 3 0 4
</code></pre>
<p>You can... | python|pandas | 1 |
355,020 | 45,856,989 | Merging dataframes based on index | <p>How can I merge 2 dataframe <code>df1</code> and <code>df2</code> in order to get <code>df3</code> that has the rows of <code>df1</code> and <code>df2</code> that have the same index (and the same values in the columns)? </p>
<pre><code>df1 = pd.DataFrame({'A': ['A0', 'A2', 'A3', 'A7'],
'B':... | <p>Just <code>merge</code>:</p>
<pre><code>In[111]:
df1.merge(df2)
Out[111]:
A B C D
0 A0 B0 C0 D0
</code></pre>
<p>The default params for <code>merge</code> is to merge all columns, performing an <code>inner</code> merge so only where all values agree</p>
<p>Looking at the index matching requirement... | python|pandas|dataframe|merge | 2 |
355,021 | 46,160,656 | Successfully pretty printing pandas.Series subclass with more than 60 elements | <p>This is likely an easy fix, but I don't know how to do it.</p>
<p>I have extended the <code>pandas.Series</code> class so that it can contain datasets for my research. Here's the code that I've written so far:</p>
<pre><code>import pandas as pd
import numpy as np
from allantools import oadev
class Tombstone(pd.Ser... | <p>I found <strong>a</strong> fix, which should work in my case. I still think there is a way to solve it by representing the slices as NDFrame objects. Maybe someone else on SO can figure that out.</p>
<p>If I override the <code>__repr__</code> built-in function inside of my <code>Tombstone</code> class,</p>
<pre><c... | python|pandas|jupyter|pretty-print|extending-classes | 0 |
355,022 | 45,992,664 | tf.subtract cost too long time for large array | <p>The Tensorflow tf.subtract cost too long time for the large array. </p>
<p>My workstation configuration: </p>
<p>CPU: Xeon E5 2699 v3<br>
Mem: 384 GB<br>
GPU: NVIDIA K80<br>
CUDA: 8.5<br>
CUDNN: 5.1<br>
Tensorflow: 1.1.0, GPU version</p>
<p>The following is the test code and result.</p>
<pre><code> impo... | <p>You're measuring not only the execution time of <code>tf.subtract</code> but also the time required from transferring the input data from the CPU memory to the GPU memory: this is your bottleneck.</p>
<p>To avoid it, don't use placeholders to feed the data but generate it with tensorflow (if you have to randomly ge... | tensorflow | 1 |
355,023 | 45,794,094 | Conditional evaluation of expression over columns in a pandas dataframe | <p>I have following data frame:
<a href="https://i.stack.imgur.com/6N90c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6N90c.png" alt="enter image description here"></a></p>
<p>I am trying to calculate sigma according to following rule based on CHART_TYPE column values according to following condi... | <p>You should be able to use <code>df.apply</code> here.</p>
<p>First, create a helper:</p>
<pre><code>def func(row):
if row['CHART_TYPE'] == 'X_BAR':
return (row['UPPER_CONTROL_LIMIT'] - row['LOW_CONTROL_LIMIT']) / 6
elif row['CHART_TYPE'] == 'MIN':
return (row['TARGET'] - row['LOW_CONTROL_L... | python|pandas|dataframe|conditional | 1 |
355,024 | 45,891,747 | pandas 'outer' merge of multiple csvs using too much memory | <p>I am new to coding and have a lot of big data to deal with. Currently I am trying to merge 26 <code>tsv</code> files (each has two columns without a header, one is a <code>contig _number</code> the other is a count. </p>
<p>If a <code>tsv</code> did not have a count for a particular <code>contig_number</code>, it d... | <p>I usually do these types of operations with <code>pd.concat</code>. I don't know the exact details of why it's more efficient, but pandas has some optimizations for combining indices.</p>
<p>I would do</p>
<pre><code>for fp in files:
# read in the files and put them into dataframes
df = pd.read_csv(fp, sep... | python-2.7|pandas|csv|merge | 0 |
355,025 | 45,989,090 | Groupby + correlation between DataFrame and Series | <p>I have a DataFrame <code>a</code> and Series <code>b</code>. I want to find conditional correlation of each column of <code>a</code> to <code>b</code>, conditional on the value of <code>b</code>. Specifically, I'm using <code>pd.cut</code> to break up <code>b</code> into 5 groups. But instead of a standard quanti... | <p>One solution that's functional but not pretty:</p>
<pre><code>full = a.join(b.to_frame(name='_drop'))
corrs = (full.groupby(groups)
.corr()
.loc[(slice(None), a.columns), '_drop']
.unstack()
.T)
print(corrs)
[-inf,-2] (-2,-1] (-1,1] (1,2] (2,inf]
col0 0.43708 0.... | python|python-3.x|pandas | 0 |
355,026 | 46,036,718 | How can I rename the input tensor name of an op in Tensorflow? | <p>My graph definition before removing the dropout layers looks like this :</p>
<pre><code>fc6/BiasAdd : BiasAdd ( [u'fc6/Conv2D', u'fc6/biases/read'] )
fc6/Relu : Relu ( [u'fc6/BiasAdd'] )
dropout/keep_prob : Const ( [] )
dropout/Shape : Shape ( [u'fc6/Relu'] )
dropout/random_uniform/min : Const ( [] )
dropout/random... | <p>There is no straightforward way of doing something like that. In general, the computation graph can be augmented with new operations, but the existing nodes cannot be modified. There are three possible paths you can follow:</p>
<ul>
<li>The easiest thing would be to leave the dropout layer as it is, and simply pass... | python|tensorflow | 2 |
355,027 | 46,129,890 | how tensorflow detemines which variable to compute grandients and update it | <p>I recently work on <code>tensorflow</code> and have some doubt about auto grad in <code>tensorflow</code>. Say we have a lost function <code>loss = sigmod (theta * x)</code>, where <code>x</code> is a placeholder and represent out input features and <code>theta</code> is the parameter. when we call <code>sess.run</c... | <blockquote>
<p>how to determine <code>x</code> or <code>theta</code> to compute gradient and update to it?</p>
</blockquote>
<p>Actually, it's pretty straightforward. A <a href="https://www.tensorflow.org/api_docs/python/tf/Variable" rel="nofollow noreferrer"><code>tf.Variable</code></a> constructor has an argument... | machine-learning|tensorflow | 1 |
355,028 | 45,870,590 | analyzing FFT data for mean frequency? | <p>I used numpy fft.fft to analyze some time series data (black) and generate a plot like the following:</p>
<p><a href="https://i.stack.imgur.com/QhZc9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QhZc9.png" alt="enter image description here"></a></p>
<p>From the FFT data (in red) i calculated ... | <p>First of all you probably want to do this in terms of power not amplitude, so I would square the y axis. Also, to calculate the mean you multiply x*y at each data point, add them up, and at the end you divide by the total power, so the sum of all the y values.</p> | numpy|fft | 0 |
355,029 | 45,962,548 | Converting a 2D numpy array to dataframe rows | <p>I have a list of list that I would like to make it as a row. The closest I got was using this <a href="https://stackoverflow.com/questions/19112398/getting-list-of-lists-into-pandas-dataframe">post</a>. However, I could not get my answer.</p>
<p>For example lets say I have a <code>testarray</code> of values,</p>
<... | <p>Use DataFrame constructor only with parameter columns:</p>
<pre><code>df = pd.DataFrame(a, columns=['a'])
print (df)
a
0 26.854065
1 27.854065
2 28.854065
3 29.854065
4 30.854065
5 31.854065
6 32.854065
7 33.854065
8 34.854065
9 35.854065
10 36.854065
11 37.854065
12 38.854065
13 ... | python|pandas|numpy|dataframe | 10 |
355,030 | 45,732,286 | TFLearn regression, shape incompatibility in loss calculation | <p>I am working with protein sequences. My goal is to create a convolutional network which will predict three angles for each amino acid in the protein. I'm having trouble debugging a TFLearn DNN model that requires a reshape operation.</p>
<p>The input data describes (currently) 25 proteins of varying lengths. To ... | <p>Well, it looks like I am answering my own question. </p>
<p>I tried various permutations of what Geert was suggesting, and I couldn't make anything work. When I was building the non-convolutional network that preceded the one I am discussing here, attempting to reshape the training data to [-1,3,2] was appropriat... | python|tensorflow|tflearn | 0 |
355,031 | 45,777,023 | Pandas plot multiple series but only showing legend for one series | <p>I'm using an ipython notebook (python 2) and am plotting both a barchart and a line plot on the same plot. There are two series (NPS and Count Ratings). However, when I try to display the legend, it only shows a legend for the second series. </p>
<p>Below is my code: </p>
<pre><code>ax=nps_funding_month[35:][nps_... | <p>The following code </p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({"x" : np.arange(5),
"a" : np.exp(np.linspace(3,5,5)),
"b" : np.exp(-np.linspace(-1,0.5,5)**2)})
ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS... | python|pandas|matplotlib|plot | 2 |
355,032 | 45,950,399 | Representing a list of strings as a numpy array of their ascii codes | <p>What I have is a list of strings. What I would like to do with it is to convert it to a 2D numpy array, where <code>result[i, j]</code> would be the ascii code of j-th character from i-th string (preferably as float). </p>
<p>I know I can use <code>list(map(float, map(ord, single_line_from_list)))</code> to get a l... | <p>You can use nested list comprehension.</p>
<pre><code>import numpy as np
array = np.array([[float(ord(character)) for character in word] for word in words])
</code></pre> | python|arrays|numpy | 2 |
355,033 | 45,786,104 | Integer array indexing python | <pre><code>import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
</code></pre>
<p>I don't understand why it results <code>[1 4 5]</code> and <code>[2 2]</code></p> | <p>Because you're slicing the array with indexes</p>
<p><code>a[[0, 1, 2], [0, 1, 0]]</code> is equivalent to</p>
<pre class="lang-python prettyprint-override"><code>a[0, 0] # 1
a[1, 1] # 4
a[2, 0] # 5
</code></pre>
<p>whereas <code>a[[0, 0], [1, 1]]</code> is equivalent to twice <code>a[0, 1]</code></p>
<p>More... | python|arrays|python-3.x|numpy|indexing | 3 |
355,034 | 46,073,406 | Move data from a column to seven days in advance - pandas Dataframe | <p>I have a pandas Dataframe with 2 columns. One of them is the index in date format and the other one is a rate R (a number between 0 and 1). How can I add another column to the pandas Dataframe that contains the rate R for the one-week before day?</p>
<p>So at the end I have the dates, the rate of that day and the r... | <p>You can use pandas shift like this:</p>
<pre><code>df['newColumn'] = df['RateColumn'].shift(7)
</code></pre>
<p>Keep in mind that first 7 values of the new column will be Nans as there are no data for them.</p> | python|pandas|dataframe|sklearn-pandas | 2 |
355,035 | 45,997,002 | Python: plot on top of scipy plot? (voronoi) | <p>how do I plot on top of a voronoi plot (which is a scipy plot)? Note my question is slightly different than <a href="https://stackoverflow.com/questions/20515554/colorize-voronoi-diagram">here</a> where they explain how to <strong>color</strong> a voronoi plot</p>
<p>For instance, imagine that I have some more poin... | <p>I think you can simply reuse plot like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import voronoi_plot_2d, Voronoi
points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]])
v = Voronoi(points)
voronoi_plot_2d(v)
p2 = [[0.25, 1], [1, ... | python|numpy|matplotlib|scipy|voronoi | 4 |
355,036 | 45,947,593 | ValueError when trying to find the difference between two dataframes | <p>This is my code to compare difference between 2 xlsx files:</p>
<pre><code>import pandas as pd
df1 = pd.read_excel('SnapshotID_Old.xlsx')
df2 = pd.read_excel('SnapshotID_New.xlsx')
difference = df1[df1 != df2]
print difference
</code></pre>
<p>It gives me this error: </p>
<pre><code>ValueError: Can only compare... | <p>You probably solved this already, but as <a href="https://stackoverflow.com/questions/45947593/valueerror-when-trying-to-find-the-difference-between-two-dataframes#comment78854395_45947593">COLDSPEED</a> said, you probably have different headers in your Excel.</p>
<p>You could try using <code>eq</code> or <code>ne<... | python|excel|pandas|dataframe|diff | 0 |
355,037 | 45,863,650 | Apply 3-argument function to 3D numpy array | <p>I have a 3D numpy array A of shape (2133, 3, 3). Basically this is a list of 2133 lists with three 3D points. Furthermore I have a function which takes three 3D points and returns one 3D point, <code>x = f(a, b, c)</code>, with a, b, c, x numpy arrays of length 3. Now I want to apply f to A, so that the output is an... | <p>Thanks to the great help of @jdehesa I was able to produce an alternative solution to the one given by @hpaulj. I am not sure if this solution is the most elegant one but it worked so far. Comments are appreciated.</p>
<pre><code>def sort_triple(a, b, c):
pts = np.stack((a, b, c), axis=1)
xSorted = pts[np.a... | python|numpy | 1 |
355,038 | 45,757,363 | reaching python with R | <p>I am trying to install tensorflow in <code>Rstudio</code>, when I run <code>install_tensorflow()</code>, I get</p>
<pre><code>Error: Prerequisites for installing TensorFlow not available.
Execute the following at a terminal to install the prerequisites:
$ sudo pip install --upgrade virtualenv
</code></pre>
<p>Bu... | <p>try:</p>
<pre><code>install_tensorflow("virtualenv", envname="myenv")
</code></pre>
<p>this will create a new python virtualenv environment.</p> | python|r|tensorflow|rstudio | 0 |
355,039 | 23,129,407 | Return zero value if division by zero encountered | <p>I have two lists <code>a</code> and <code>b</code> of equal length. I want to calculate the sum of their ratio:</p>
<pre><code>c = np.sum(a/b)
</code></pre>
<p>how can I have a zero (0) value in the summation coefficient when there is division by zero?</p>
<p>EDIT: Here a couple of answers I tested for my case, a... | <p>To sum values except <code>divide by 0</code>,</p>
<pre><code>sel = b != 0
c = np.sum(a[sel]/b[sel])
</code></pre>
<p>The arrays are <code>float</code>, you may need to use</p>
<pre><code>sel = np.bitwise_not(np.isclose(b, 0))
</code></pre>
<p><strong>UPDATE</strong> </p>
<p>If <code>a</code> and <code>b</code>... | python|numpy|divide-by-zero | 3 |
355,040 | 23,183,224 | Verbose debug output with pandas Series | <p>I have a Pandas Series with 76 elements, when I try to print out the Series (for debugging) it is abbreviated with "..." in the output. Is there a way to pretty print all of the elements of the Series?</p>
<p>In this example, the Series is called "data"</p>
<pre><code>print str(data)
</code></pre>
<p>gives me th... | <pre><code>pd.options.display.max_rows = 100
</code></pre>
<p>The default is set at 60 (so dataframes or series with more elements will be truncated when printed).</p> | python|python-2.7|pandas | 3 |
355,041 | 23,009,509 | How to modify pandas plotting integration? | <p>I'm trying to modify the <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot-matrix" rel="nofollow noreferrer">scatter_matrix</a> plot available on Pandas.</p>
<p>Simple usage would be<img src="https://i.stack.imgur.com/drKS1.png" alt="IRIS scatter matrix viz"></p>
<p>Obtained doin... | <p><code>pd.tools.plotting.scatter_matrix</code> returns an array of the axes it draws; The lower left boundary axes corresponds to indices <code>[:,0]</code> and <code>[-1,:]</code>. One can loop over these elements and apply any sort of modifications. For example:</p>
<pre><code>axs = pd.tools.plotting.scatter_matri... | python|matplotlib|pandas | 7 |
355,042 | 23,283,111 | Grabbing data from entire index (e.g., DJIA) using pandas web.DataReader | <p>I know how to get individual stocks. How might I get data for an entire index, like the DJI?
<a href="https://www.google.com/finance?q=INDEXDJX%3A.DJI&ei=zsVZU4iADYKI6AGoXA" rel="nofollow">https://www.google.com/finance?q=INDEXDJX%3A.DJI&ei=zsVZU4iADYKI6AGoXA</a></p>
<p>I'd like to analyze the stock market ... | <p>Google Finance and Yahoo Finance handle their symbols for indices differently. Google would denote the Dow as ".DJI" whereas in Yahoo it would be "^DJI".</p>
<p>For some reason when I run the code Pandas is having trouble finding data for the Dow from Yahoo, but it can find it for the S&P and the Nasdaq.</p>
<... | python|pandas|finance|quandl | 7 |
355,043 | 23,380,349 | pandas groupby add column from apply operation | <p>Given a dataframe like this,</p>
<pre><code>chrom first_bp_intron last_bp_intron unique_junction_reads
chr1 100 200 10
chr1 100 150 40
chr1 110 200 90
</code></pre>
<p>What's an elegant way to do this? <code>groupby</code> on the column <code>first_bp_intron</code> and divide the values in <code>unique... | <p>I'd do something like the following using <code>groupby</code> and <code>transform</code>:</p>
<pre><code>In [9]: by_first = df.groupby('first_bp_intron')
In [10]: df['phi5'] = by_first['unique_junction_reads'].transform(lambda x: x/x.sum())
In [11]: by_last = df.groupby('last_bp_intron')
In [12]: df['phi3'] = by_... | python|pandas | 11 |
355,044 | 23,309,743 | Mixing NumPy longdouble and SymPy numerical evaluation – what about precision? | <p>I have a code where one part of calculations is done using NumPy functions and longdoubles and the other using SymPy symbolic differentiation and numerical evaluation, then joined together (to SymPy float). Sympy evaluation can be done with arbitrary precision, but what precision would be just good enough, i.e. woul... | <p>IIRC, the precision is actually platform dependent. Anyway, to the question: I think you are looking at the wrong details.</p>
<pre><code>>>> print numpy.finfo(numpy.longdouble)
Machine parameters for float128
---------------------------------------------------------------------
precision= 18 resolution=... | python|numpy|sympy|long-double | 1 |
355,045 | 23,156,640 | Number of non-missing values in array? Len(x) excluding missing values? | <p>Is there a function in python that allows me to count the number of non-missing values in an array?</p>
<p>My data:</p>
<pre><code>df.wealth1[df.wealth < 25000] = df.wealth
df.wealth2[df.wealth <50000 & df.wealth > 25000] = df.wealth
df.wealth3[df.wealth < 75000 & df.wealth > 50000] = df.wea... | <p>The best way to do this is with the <code>count</code> method of <code>DataFrame</code> objects:</p>
<pre><code>In [18]: data = randn(1000, 3)
In [19]: data
Out[19]:
array([[ 0.1035, 0.9239, 0.3902],
[ 0.2022, -0.1755, -0.4633],
[ 0.0595, -1.3779, -1.1187],
...,
[ 1.3931, 0.4087, 2.... | python|for-loop|count|pandas|missing-data | 2 |
355,046 | 23,103,345 | Finding the distance of points to an axis | <p>I have an array of points in 3D Cartesian space:</p>
<pre><code>P = np.random.random((10, 3))
</code></pre>
<p>Now I'd like to find their distances to a given axis and on that given axis</p>
<pre><code>Ax_support = array([3, 2, 1])
Ax_direction = array([1, 2, 3])
</code></pre>
<p>I've found a solution that first fin... | <p>I would be surprised to see such an operation among the standard operations of numpy/scipy. What you are looking for is the projection distance onto your line. Start by subtracting <code>Ax_support</code>:</p>
<pre><code>P_centered = P - Ax_support
</code></pre>
<p>The points on the line through 0 with direction <... | python|numpy|linear-algebra | 1 |
355,047 | 23,421,063 | Divide by zero encountered in orthogonal regression with python (scipy.odr) | <p>Following <a href="https://stackoverflow.com/questions/23404134/orthogonal-distance-regression-in-python-meaning-of-returned-values">this discussion</a> to perform <a href="http://docs.scipy.org/doc/scipy/reference/odr.html#id1" rel="nofollow noreferrer">Orthogonal distance regression</a>, it happens that for a spec... | <p>The associated errors must not be zero. They can be replaced with NaN values for example or removed from the dataset.</p> | python|numpy|scipy | 1 |
355,048 | 23,169,503 | Pythonic strategy to overwrite global variables in a for loop | <p>EDIT2:</p>
<p>Thanks for your help, problem solved, went with an intermediate approach:</p>
<p><img src="https://i.stack.imgur.com/6k2gh.png" alt="enter image description here"></p>
<p>Will accept the answer when it becomes eligible to be accepted!</p>
<hr>
<p>EDIT:</p>
<p>I was asked for simpler variables, ok... | <p><strong>UPDATE</strong></p>
<p>Don't assign some data to<code>var</code>. because it's just reference.</p>
<pre><code>a, b, c, d = [], [], [], []
for var,data in zip([a,b,c,d], some_data_array):
# call var.extend or var.append
# var = some_value # don't do this. because it's just reference.
var.extend... | python|for-loop|numpy | 0 |
355,049 | 35,424,400 | Pandas: Group By Elements of a Column | <p>Looking for assistance to <code>group by</code> elements of a column in a Pandas df.</p>
<p>Original df:</p>
<pre><code> Country Feature Number
0 US A 1
1 DE A 2
2 FR A 3
3 US B 0
4 DE B 5
5 FR ... | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> for that:</p>
<pre><code>In [39]: df.pivot_table(index='Country', columns='Feature')
Out[39]:
Number
Feature A B C
Country
DE 2 5 0
F... | python|pandas | 3 |
355,050 | 35,692,781 | Plotting percentage in seaborn bar plot | <p>For a dataframe</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'group':list("AADABCBCCCD"),'Values':[1,0,1,0,1,0,0,1,0,1,0]})
</code></pre>
<p>I am trying to plot a barplot showing percentage of times <code>A, B, C, D</code> takes zero (or one). </p>
<p>I have a round about way which works but I am thinking ... | <p>You can use Pandas in conjunction with seaborn to make this easier:</p>
<pre><code>import pandas as pd
import seaborn as sns
df = sns.load_dataset("tips")
x, y, hue = "day", "proportion", "sex"
hue_order = ["Male", "Female"]
(df[x]
.groupby(df[hue])
.value_counts(normalize=True)
.rename(y)
.reset_index()
.pi... | python|pandas|seaborn|bar-chart|plot-annotations | 21 |
355,051 | 35,352,463 | Python: In DataFrame, add value in a new column for row with highest value in another column and string identical in a third one | <p>I'm trying to find an efficient way to determine in a DataFrame which row have the highest value in a column (value) when their "String" in another column (String) are identical, creating a new column (motif) with this information for later use.</p>
<p>Here an example of a dataframe:</p>
<pre><code> String N... | <p>IIUC then you can <code>groupby</code> on 'String', <code>filter</code> it and then call <code>idxmax</code> to return the row labels that have the max value and assign those rows to <code>1</code>:</p>
<pre><code>In [201]:
df.loc[df.groupby('String').filter(lambda x: len(x) > 1)['value'].idxmax(), 'motif'] = 1
... | python|pandas|dataframe | 1 |
355,052 | 35,659,286 | numpy matrix updating every second | <p>I have a problem with Numpy matrix</p>
<p>I want to do this;
I am using "googlefinance" library to pull live stock price data, and from here, I want to make a matrix of the data I pull. For example,</p>
<pre><code>from googlefinance import getQuotes
def live_price(symbol):
price = getQuotes(symbol)[0].values(... | <p>Every ten seconds you should run:</p>
<pre><code>A[0,0] = live_price('a')
</code></pre>
<p>to update the first element of the matrix. </p>
<p>For your mental health, 'explicit is better than implicit'.</p> | numpy|matrix | 1 |
355,053 | 35,713,357 | Applying functions to DataFrame columns in plots | <p>I'd like to apply functions to columns of a DataFrame when plotting them. </p>
<p>I understand that the standard way to plot when using Pandas is the .plot method. </p>
<p>How can I do math operations within this method, say for example multiply two columns in the plot? </p>
<p>Thanks!</p> | <p>Series actually have a plot method as well, so it should work to apply</p>
<pre><code>(df['col1'] * df['col2']).plot()
</code></pre>
<p>Otherwise, if you need to do this more than once it would be the usual thing to make a new column in your dataframe:</p>
<pre><code>df['newcol'] = df['col1'] * df['col2']
</code>... | pandas | 1 |
355,054 | 35,486,571 | Calculating date time from start time and elapsed seconds | <p>I have a dataframe where my index is an elapsed seconds series. </p>
<pre class="lang-none prettyprint-override"><code>Depth_m | Temperature_degC | Salinity_PSU | OBS S9604_mV | OBS highsens S9604_mV | OBS S9602_mV | OBS S9603_mV | Time elapsed_sec
0.00 | 35.687 | 28.9931... | <p>Something like this?</p>
<pre><code>start_time = pd.Timestamp('2016-1-1 00:00')
df = pd.DataFrame({'seconds': [ 1, 2, 3]})
df['new_time'] = [start_time + dt.timedelta(seconds=s) for s in df.seconds]
>>> df
seconds new_time
0 1 2016-01-01 00:00:01
1 2 2016-01-01 00:00:02
2 ... | python|pandas|time-series|data-analysis | 1 |
355,055 | 35,379,394 | pandas percentage change with missing data | <p>I need to get percentage change of multiple columns.</p>
<pre><code>import pandas as pd
t="""Year\tChild\tBehaviour
1987\tBoy\tGood
1987\tGirl\tGood
1987\tBoy\tBad
1987\tGirl\tBad
2020\tBoy\tBad
2020\tBoy\tBad
2020\tGirl\tBad
2020\tGirl\tBad"""
from io import StringIO
df=pd.read_table(StringIO(t))
pv=pd.crosstab(df... | <p>You probably want something like this, using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a> method?</p>
<pre><code>>>> (pv[2020]/pv[1987]).fillna(0) - 1
Behaviour Bad Good
Child
Boy 1 -1
Girl ... | python|pandas|division|percentage | 1 |
355,056 | 35,604,948 | Access individual array in numpy | <p>How can I individually access one specific element in each row with numpy?</p>
<pre><code>In[308]: cards
Out[296]:
array([[ 3., 8., 7., 12., 1., 4., 12.],
[ 5., 6., 2., 11., 10., 9., 6.],
[ 3., 4., 3., 9., 3., 3., 10.]])
</code></pre>
<p>The following will access th... | <p>You can pass indices for both, the rows and the columns:</p>
<pre><code>In [91]: cards[[0, 1, 2], [1, 2, 1]]
Out[91]: array([ 8., 2., 4.])
</code></pre>
<p>If the indices have matching shape, they are processed pair-wise. More details can be found in the <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basic... | numpy | 1 |
355,057 | 35,592,867 | Possible use case/real application for mobile distributed version of Tensorflow? | <p>I'm developing this project where I'm trying to create a distributed version of <a href="https://www.tensorflow.org/" rel="nofollow">Tensorflow</a> (the actual open source version is single node) and where the cluster is entirely composed by mobile devices (e.g. smartphones).</p>
<p>In your opinion, what is a possi... | <p><a href="https://boinc.berkeley.edu" rel="nofollow">https://boinc.berkeley.edu</a></p>
<p>I think all my answers could run on individual phones with communication between them. If you want them to act like a cluster as @Yaroslav pointed out there is Seti@home and other projects running in the BOINC client.</p>
<p>... | machine-learning|tensorflow|smartphone | 0 |
355,058 | 35,474,974 | Not able to run fully_connected_feed.py in Tensorflow | <p>I am following the tutorial of <a href="https://www.tensorflow.org/versions/r0.7/tutorials/mnist/tf/index.html" rel="nofollow">TensorFlow Mechanics 101</a> (version 0.7.0). As per the document, I download the two files (<code>mnist.py</code> and <code>fully_connected_feed.py</code>) and save them to the same directo... | <p>This is a bug in the 0.7.0 release of TensorFlow, which was fixed in <a href="https://github.com/tensorflow/tensorflow/commit/42f06d870014dec70769cbdd8697821c92880be9" rel="nofollow">a recent commit</a> and will appear in a bugfix release shortly. The issue is caused when the <code>--train_dir</code> flag doesn't co... | python|tensorflow | 1 |
355,059 | 35,589,302 | importing pandas, numpy 'module' object has no attribute 'Integral' | <p>I have been working with a script using pandas, numpy, and scikit-learn that worked just fine.</p>
<p>Out of the blue (for sure I did something, but I do not know what) I am getting this error message:</p>
<pre><code>C:\Users\xx\Anaconda3\python.exe
C:/Users/xxxx/create_predictions_2.py
Traceback (most recent call... | <p>i think the issue is due to some <strong>jython</strong> calls means you tried to create a jython program executed python code in java then without destroying the process you tried to call a python program from python interpreter.</p> | numpy|pandas|anaconda|python-import | 0 |
355,060 | 35,764,715 | Dato: What's the equivalent function for graphlab.random_split() in pandas? | <p>I'm doing a course on Machine Learning on Coursera. In the course, it is emphasised that we use GraphLab from <a href="https://dato.com/" rel="nofollow">Dato</a>. In one of the exercises, the instructor used graphlab.random_split() to split an SFrame, like this:</p>
<pre><code>sales = graphlab.SFrame('home_data.gl/... | <p>The closest equivalent is probably <code>sklearn.cross_validation.train_test_split</code>. However, it's behavior is NOT identical to <code>SFrame.random_split</code>. Quick check:</p>
<pre><code>from __future__ import print_function
import numpy as np
import pandas as pd
import graphlab as gl
from sklearn.cross_va... | python|pandas|graphlab|sframe | 2 |
355,061 | 35,491,836 | Numpy FFT fails on meshgrids? | <p>I'm running into an odd problem using Numpy meshgrids with the FFT functions. Specifically, either the fft2 or the ifft2 function seems to fail when used on an array built using meshgrids. </p>
<pre><code>x = np.arange(-4, 4, .08)
y = np.arange(-4, 4, .08)
X, Y = np.meshgrid(x, y)
field = (X + i*Y)*np.exp(X**2 + Y*... | <p>The problem (after replacing <code>^</code> with <code>**</code> in your code) is that the contrast between your smallest and largest values is nearly 30 orders of magnitude:</p>
<pre><code>>>> abs(field).max() / abs(field).min()
8.8904389513698014e+28
</code></pre>
<p>Floating point arithmetic only has f... | python|arrays|numpy|fft | 3 |
355,062 | 35,340,877 | Combine integer and string in array and save to a text file | <p>I have several numpy arrays, all but one contain integers. I want to combine them into a single array and save it in a .txt file. This very last line causes me troubles, since I'm trying to combine integer with string:</p>
<pre><code>import numpy as np
specimen = np.array(['one1', 'two2', 'three3'])
outpath = '/... | <p>Define int as string?</p>
<p><code>int1=str( /*insert whatever your integer is here*/ )</code></p>
<p>Then add <code>int1</code> to the array.</p> | python|arrays|string|numpy | 0 |
355,063 | 11,851,297 | Plotting with numpy and pylab | <p>I have some data, that I have loaded up into <code>numpy</code>, I do not have a <code>csv</code> or any file loaded up with the range of dates I need, however I know what this array length is.</p>
<p>Currently I am just doing this to print up a simple graph:</p>
<pre><code>t = numpy.arange(0.0, len(data), 1)
pyla... | <p>You might want to take a look at <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot_date" rel="nofollow">plot_date()</a>
and the <a href="http://matplotlib.sourceforge.net/api/dates_api.html" rel="nofollow">matliplot dates api</a>.</p> | python|numpy|matplotlib | 2 |
355,064 | 11,773,862 | Unexpected result when upsampling hourly values using the pandas resample function | <p>I try to upsample daily <code>TimeSeries</code> values using the pandas resample function. When i'm upsampling a single day (2012-01-01) i expect the result to be the mean of the day considered for upsampling. The result should look like this:</p>
<pre><code>2012-01-01 -0,285344
Freq: D
</code></pre>
<p>However,... | <p>You could get the result you want by using the loffset and closed options. </p>
<pre><code>>>> ts.resample('D', how='mean', closed="left", loffset=datetime.timedelta(days=-1))
2012-01-01 0.200299
</code></pre> | python|time-series|pandas | 2 |
355,065 | 11,495,051 | Difference in Python statsmodels OLS and R's lm | <p>I'm not sure why I'm getting slightly different results for a simple OLS, depending on whether I go through <a href="http://pandas.pydata.org/pandas-docs/dev/r_interface.html" rel="nofollow noreferrer">panda's experimental rpy interface</a> to do the regression in <code>R</code> or whether I use <a href="http://stat... | <p>Looks like Python does not add an intercept by default to your expression, whereas R does when you use the formula interface..</p>
<p>This means you did fit two different models. Try</p>
<pre><code>lm( y ~ x - 1, data)
</code></pre>
<p>in R to exclude the intercept, or in your case and with somewhat more standard... | python|r|pandas|rpy2|statsmodels | 17 |
355,066 | 12,009,762 | Should I put effort on learning Matlab if I already know and use Numpy/Scipy | <p>I use and love Numpy and Scipy, but in one of the fields I'm involved (biomechanics research), MATLAB dominates the scene.</p>
<p>I believe this domination is pretty much due to tradition, similar to what happens with Windows or Office, but perhaps there is some intrinsic reason to prefer one over another.</p>
<p>... | <p>Let's say you apply for work in my lab. You say "I know Numpy/Scipy". Then I say "That's awesome, then it will be much easier for you to learn Matlab". Why? Because our code-base is in Matlab, our collaborators' code-base is in Matlab, and I won't pay you to re-invent the wheel, and I won't pay you to write code tha... | matlab|numpy|scipy | 6 |
355,067 | 28,726,877 | Joining np.arrays Python with a padding | <p>Analogous to:</p>
<pre><code>"True".join(['False','False'])
</code></pre>
<p>I'd like to join numpy arrays, e.g.</p>
<pre><code>arr = np.zeros((15,10), dtype=bool)
joiner = np.ones((15,1), dtype=bool)
result = np.hstack((arr, joiner, arr))
result.shape
(15, 21)
</code></pre>
<p>That is, I'd like to join a variab... | <p>I came up with a simple quite silly appending method (I expect it to be really slow compared to some solutions out there):</p>
<pre><code>def mergeArrays(*args):
if args:
joiner = np.ones((args[0].shape[0], 1))
new = []
for x in args[:-1]:
new.append(x)
new.append... | python|arrays|numpy | 0 |
355,068 | 28,394,956 | Should I store the values in dictionary or compute on-the-fly? | <p>I have a problem where I have tuples called state and action and I want to compute its "binary features". The function to compute the features of state and action are described below. Mind you this is just a toy code.</p>
<p>I have about 700,000 combination of states and actions. I also need to have the features in... | <p>If it is highly critical to return the results as fast as possible, than you should consider option one. However, you should keep in mind the memory and setup time overhead, which might be too expensive.</p>
<p>If performance is not an issue at all, you should prefer option two. This will make your code simpler and... | python|numpy|dictionary | 2 |
355,069 | 28,525,281 | Split data into sub cubes in numpy | <p>Is there an easy way to take a numpy array of 3-d data, and split it into octants, or finer resolution. So with data something like</p>
<pre><code>[[0,0,0], [1,0,0], [2,0,0], [3,0,0], [0,1,0], [0,2,0], [0,3,0] ...]
</code></pre>
<p>I want 8 arrays split along the 2,2,2 planes.
So the first sub array would have val... | <p>You can simply use filter ...</p>
<pre><code>filter(lambda m: all([m[0]<2, m[1]<2, m[2]<2]), xs)
</code></pre>
<p>to get your first quadrant ...</p>
<p>Now, since the plane is defined, the conditions are simply >2, <=2 an iterative split would be interesting. Lets say, you create a function that takes... | python|numpy | 1 |
355,070 | 28,772,494 | How do you update the levels of a pandas MultiIndex after slicing its DataFrame? | <p>I have a Dataframe with a pandas MultiIndex:</p>
<pre><code>In [1]: import pandas as pd
In [2]: multi_index = pd.MultiIndex.from_product([['CAN','USA'],['total']],names=['country','sex'])
In [3]: df = pd.DataFrame({'pop':[35,318]},index=multi_index)
In [4]: df
Out[4]:
pop
country sex
CAN total ... | <p>From version <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-shown-levels" rel="noreferrer"><code>pandas 0.20.0+</code></a> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.remove_unused_levels.html" rel="noreferrer"><code>MultiIndex.remove_unused_level... | python|pandas | 20 |
355,071 | 28,389,890 | IndexError: too many indices for array while plotting ROC curve with scikit-learn? | <p>I would like to plott the ROC curve that scikit-lern implements so I tried the following:</p>
<pre><code>from sklearn.metrics import roc_curve, auc
false_positive_rate, recall, thresholds = roc_curve(y_test, prediction[:, 1])
roc_auc = auc(false_positive_rate, recall)
plt.title('Receiver Operating Characteristic')
... | <p>The variable <code>prediction</code> needs to be a <code>1d array</code> (the same shape as <code>y_test</code>). You can check by inspecting the shape attribute e.g. <code>y_test.shape</code>. I think</p>
<pre><code>prediction[0].values
</code></pre>
<p>returns</p>
<pre><code>AttributeError: 'numpy.int64' obje... | python|numpy|matplotlib|scikit-learn | 1 |
355,072 | 28,538,536 | Deleting multiple columns based on column names in Pandas | <p>I have some data and when I import it, I get the following unneeded columns. I'm looking for an easy way to delete all of these.</p>
<pre><code>'Unnamed: 24', 'Unnamed: 25', 'Unnamed: 26', 'Unnamed: 27',
'Unnamed: 28', 'Unnamed: 29', 'Unnamed: 30', 'Unnamed: 31',
'Unnamed: 32', 'Unnamed: 33', 'Unnamed: 34', 'Unnamed... | <p>By far the simplest approach is:</p>
<pre><code>yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
</code></pre> | python|pandas | 275 |
355,073 | 28,741,546 | Drop values satisfying condition plus arbitrary number of next values in a pandas DataFrame | <p>So my final goal is to drop values in one column of a <code>pandas</code> <code>DataFrame</code> according to some condition on another column of the same <code>DataFrame</code>, <strong>plus</strong> several next values e.g.:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': [0, 0.5, 0.2, 0, 0, 0, 0, 0.2... | <p>We can use the boolean condition index to slice the df using <code>loc</code> and set the following values:</p>
<pre><code>In [392]:
# take the first value of the index
idx = (df['a'] > 0).index[0]
idx
Out[392]:
Timestamp('2015-01-01 00:00:00', offset='D')
In [393]:
# we have to offset the range by 1 at begin ... | python|pandas | 2 |
355,074 | 28,623,780 | AttributeError: 'module' object has no attribute 'genfromtxt' | <p>I tried running the following program</p>
<pre><code>import numpy as np
data = np.genfromtxt('data.csv', delimiter = ',')
</code></pre>
<p>which gives</p>
<blockquote>
<p>AttributeError: 'module' object has no attribute 'genfromtxt'</p>
</blockquote>
<p>Help much appreciated</p> | <p>You must import matplotlib and it will work
copy and past next code</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
data = np.genfromtxt('data.csv', delimiter = ',')
</code></pre> | python|numpy|python-2.7 | 0 |
355,075 | 28,774,914 | Cleanest iteration/functional application on Pandas Dataframe regardless of length | <p>I constantly struggle with cleanly iterating or applying a function to Pandas DataFrames of variable length. Specifically, a length 1 DataFrame slice (Pandas Series).</p>
<p>Simple example, a DataFrame and a function that acts on each row of it. The format of the dataframe is known/expected.</p>
<pre><code>def str... | <p>There is no generic way to write a function which will seemlessly handle both
DataFrames and Series. You would either need to use an <code>if-statement</code> to check
for type, or use <code>try..except</code> to handle exceptions.</p>
<p>Instead of doing either of those things, I think it is better to make sure yo... | python|pandas|apply | 3 |
355,076 | 28,714,469 | Bug in pandas query() method? | <p>I was experimenting several use cases for the pandas query() method, and tried one argument that threw an exception, but yet caused an unwanted modification to the data in my DataFrame.</p>
<pre><code>In [549]: syn_fmax_sort
Out[549]:
build_number name fmax
0 390 adpcm 143.45
1 ... | <p>It looks like you had a typo, you probably wanted to use <code>==</code> rather than <code>=</code>, a simple example shows the same problem:</p>
<pre><code>In [286]:
df = pd.DataFrame({'a':np.arange(5)})
df
Out[286]:
a
0 0
1 1
2 2
3 3
4 4
In [287]:
df.query('a = 3')
--------------------------------------... | python|pandas|dataframe | 21 |
355,077 | 50,817,442 | Counting the no. of black to white pixels in the image using OpenCV | <p>I'm new to python and any help would be greatly appreciated.</p>
<p><a href="https://i.stack.imgur.com/Va5q5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Va5q5.png" alt="enter image description here"></a></p>
<p>What I'm trying to do from this image is to count the number of black pixels (0,0... | <pre><code>colors, counts = np.unique(img.reshape(-1, 3), axis=0, return_counts=True)
for color, count in zip(colors, counts):
print("{} = {} pixels".format(color, count))
[1 1 0] = 6977 pixels
[3 3 3] = 7477 pixels
[6 6 6] = 5343 pixels
[8 8 8] = 4790 pixels
[11 11 11] = 4290 pixels
[13 13 13] = 3681 pixels
[16 ... | python|numpy|opencv|image-processing | 2 |
355,078 | 50,911,306 | Pandas sum rows by step | <p>I have the following table:</p>
<pre><code> A A_pct B B_pct
Player1 1.0 12.5 15.0 18.75
Player2 7.0 87.5 65.0 81.25
Total 8.0 100.0 80.0 100.00
</code></pre>
<p>I'm trying to add a column at the end with the sum of all the columns that <strong>don't</strong> have a <strong>_pct<... | <p>This will select all columns without the '_pct' and sum by row</p>
<pre><code>df['Total'] = df[df.columns[~df.columns.str.contains('_pct')]].sum(axis=1)
df
Out[]:
A A_pct B B_pct Total
Player1 1.0 12.5 15.0 18.75 16.0
Player2 7.0 87.5 65.0 81.25 72.0
Total 8.0 100.0 80.0 10... | pandas | 2 |
355,079 | 50,856,522 | Run Faster-rcnn on mobile iOS | <p>I have faster rcnn model that I trained and work on my google cloud instance with GPU ( train with google models API),<br>
I want to run it on mobile, I found some GitHub that shows how to run SSDmobileNet but I could not found one that runs Faster-rcnn.<br>
real time is not my concern for now.<br>
I have iPhone 6,... | <p>Faster R-CNN requires a number of custom layers that are not available in Metal, CoreML, etc. You will have to implement these custom layers yourself (or hire someone to implement them for you, wink wink).</p>
<p>I'm not sure if TF-lite will work. It only supports a limited number of operations on iOS, so chances a... | tensorflow|coreml|object-detection-api|tensorflow-lite|coremltools | 1 |
355,080 | 51,093,970 | Multiprocessing code works using numpy but deadlocked using pytorch | <p>I'm hitting what appears to be a deadlock when trying to make use of multiprocessing with pytorch. The equivalent numpy code works like I expect it to.</p>
<p>I've made a simplified version of my code: a pool of 4 workers executing an array-wide broadcast operation 1000 times (so ~250 each worker). The array in que... | <p>You can try to set OMP_NUM_THREADS=1 environment variable as an attempt to crunch-fix this. It helped me with DataLoader+OpenCV deadlock.</p> | numpy|deadlock|shared-memory|python-multiprocessing|pytorch | 0 |
355,081 | 51,025,188 | Tensorflow Notfound Error | <p>I am using Spyder (Python 3.5). The tensorflow version is 1.8.0. I was trying to implement a deep neural network using the tf.estimator.DNNClassifier method.However, I encountered this error, which is listed as follows. The codes are pasted as the following. I am not sure what is wrong here. Thank you so much for y... | <p>You probably have checkpoint files for an old version or your model.</p>
<p>Clear the <code>output</code> folder and re-run your script.</p>
<p><em>P.S.: I ran it on my machine and it works fine</em></p> | python|tensorflow|deep-learning | 1 |
355,082 | 51,026,819 | Transform DTM to text | <p>I would like to transform the following DTM </p>
<pre><code>pd.DataFrame({"ID": [1,2,3,4,5],
"t1": [0,0,1,1,0],
"t2": [1,1,0,0,0],
"t3": [1,0,1,0,0],
"t4": [0,0,0,0,0]})
</code></pre>
<p>to this DF </p>
<pre><code>pd.DataFrame({"ID": [1,2,3,4,5],
... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>DataFrame.dot</code></a> with filter columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a>... | python|pandas | 1 |
355,083 | 50,702,464 | tf.Session.run not executing as expected | <p>I'm working on a tensorflow project, and I'm having a problem I don't know how to solve. I guess it is because I am not understanding properly how tensorflow runs.</p>
<p>The code I think is relevant to the problem is:</p>
<pre><code>tf.reset_default_graph()
network_model.define_structure()
input_data = tf.placeho... | <p>I have already solved it. The problem was in the feedforward function. In order to get the output of the neural network, I was using in each of the layers the sigmoid function as activation function. </p>
<pre><code>output_data = tf.nn.sigmoid(output)
</code></pre>
<p>The output of this activation function is eith... | python|python-3.x|tensorflow | 0 |
355,084 | 50,861,066 | How to recover more detailed metrics in TensorFlow object detection library? | <p>I use the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">object detection</a> library to train models on my own dataset given different hyper-parameters, pre-processing, etc.
Then I want to evaluate those models to compare them.</p>
<p>I know that the ... | <p>I finally implemented my own <code>object_detection.utils.object_detection_evaluation.DetectionEvaluator</code>. I give it lists of: categories, IOU thresholds, score thresolds, max number of detections and area ranges (for small, medium, big detections).</p>
<p>Then, it computes a confusion matrix for each combina... | python|tensorflow|object-detection | 0 |
355,085 | 51,071,460 | numpy write the permuted version of the array | <p>I have to dump the contents of a numpy ndarray to a binary file which is going to be read by a third party program. However, what I want to do is write the contents of a permuted axes. As an example, I have something like:</p>
<pre><code>import numpy as np
x = np.random.rand(3, 3, 3)
a = np.transpose(x, (1, 0, 2))... | <p>I cannot reproduce your findings: I get different arrays:</p>
<pre><code>In [11]: np.fromfile('a.bin').reshape((3,3,3))
Out[11]:
array([[[0.95499073, 0.53044188, 0.31122484],
[0.44293225, 0.23932913, 0.13954034],
[0.08992127, 0.59397388, 0.72471928]],
[[0.43503453, 0.15910105, 0.10589887],
... | python|numpy | 2 |
355,086 | 50,767,648 | Convert Pandas DataFrame columns to rows | <p>I have the following dict which I converted to dataframe </p>
<pre><code>players_info = {'Afghanistan': {'Asghar Stanikzai': 809.0,
'Mohammad Nabi': 851.0,
'Mohammad Shahzad': 1713.0,
'Najibullah Zadran': 643.0,
'Samiullah Shenwari': 774.0},
'Australia': {'AJ Finch': 1082.0,
'CL White': 988.0,
'DA Warn... | <p>You need:</p>
<pre><code>df = df.stack().reset_index()
df.columns=['Player', 'Team', 'Score']
</code></pre>
<p>Output of <code>df.head(5)</code>:</p>
<pre><code> Player Team Score
0 AD Hales Score 1340.0
1 AJ Finch Team 1082.0
2 Asghar Stanikzai Player 809.0
3 CL White Team ... | python|pandas|dataframe | 6 |
355,087 | 50,706,936 | Manipulating dataframe in python for Glicko calculation | <p>I'm trying to run Glicko v2 calculations on a dataframe that I've loaded into python. Since each race is independent, I can only compare athletes that've competed in the same race.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_excel("MyDirectory/sample.xlsx")
</code></pre>
<hr>
<pre><code>A... | <p>We can use a cartesian self-join and filtering to create your resulting dataframe:</p>
<pre><code>(df.merge(df, on='Race_Id',suffixes=('1','2'))
.query('Rank1 != Rank2 and Athlete1 < Athlete2')
[['Athlete1','Race_Id','Ranking1','RD1','Athelete2','Ranking2','RD2']])
</code></pre>
<h1>Update for dynamic suf... | python|pandas|dataframe | 1 |
355,088 | 50,843,487 | Neural Network Steps after Training | <p>I am currently doing a grade 11 school project on neural networks. I have managed to create one with <code>keras</code> but I have no idea what to do after training. My big question is, how do I input a new data set with the same parameters, same weights, same everything for the training data, but with a whole new s... | <p>So if i understand your question correctly you want to load the weights of already trained network and train new data set or new set of images.</p>
<p>If that's the case then you will have to first use the <code>ModelCheckpoint</code> Callback in keras to save model after every epoch.</p>
<pre><code>from keras.ca... | python|tensorflow|neural-network|keras | 0 |
355,089 | 50,778,593 | tensorflow save and restore autoencoder | <p>I used tf.layers.dense to build a fully connected autoencoder. and I want to save it and restore only the encoder to get the embedding output.</p>
<p>How to use tf.train.saver to restore only the encoder? Because I want to set different batch size of the restored model, to input only one data into it. </p>
<p>I sa... | <p>If you don't care about memory space the easiest way is by saving the whole graph (encoder and decoder) and when using it for prediction, you can pass the last layer of the encoder as the fetch argument. Tensorflow will only calculate to this point and you don't have any computational difference compared to only sav... | python|tensorflow | 0 |
355,090 | 50,859,183 | Python plot after string | <p>I want to plot data from .dat file. But this .dat file starts with string. For example, My file includes col 1 col 2 col 3 and I want to read under the col 3 data. I want skip two rows because they have string and wanna read only under col 3. How can skip the strings?. If we accept the data is 5x3 data so that I wi... | <p>Since you are already importing <code>numpy</code>, you could use <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer"><code>np.genfromtext</code></a> here to make things a lot simpler, since it has the option <code>skip_header</code> which tells it ho... | python|python-3.x|numpy|matplotlib|plot | 3 |
355,091 | 50,930,393 | How to automatically group conditions together in python? | <p>I'm trying to automatically group conditions together in python. The difficulty lies in that if there are several conditions, like 100 conditions, it would be tedious to "AND" all of these by hand. How can I use a loop to achieve this? </p>
<pre><code>import pandas as pd
s1 = pd.Series([1,2,3,4,5,6])
s2 = pd.Series... | <p>You can achive it by creating a list of conditions and using <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow noreferrer"><code>reduce</code></a>:</p>
<pre><code>from functools import reduce
conditions = [
df['A'] > 3,
df['B'] > 6,
df['C'] > 5,
]
total... | python|pandas|numpy|logical-operators | 5 |
355,092 | 50,881,789 | Selecting a row interval according to a Column value in Pandas | <p>Hi everyone I have a dataset that looks like this</p>
<pre><code>transferid value type
5545 100 X
5123 40 A
5566 35 A
5675 700 X
5235 1100 A
5616 350 A
5772 170 X
</code></pre>
<p>it has it index for an... | <p>IIUC:</p>
<pre><code>i = np.where(df.type == "X")[0]
pd.concat({j: df.iloc[x:y] for j, (x, y) in enumerate(zip(i, i[1:] + 1))})
transferid value type
0 0 5545 100 X
1 5123 40 A
2 5566 35 A
3 5675 700 X
1 3 5675 700 X
4 5235 1... | python|pandas|dataframe|numpy-slicing | 1 |
355,093 | 50,824,943 | how to efficiently split a large dataframe into many parquet files? | <p>Consider the following dataframe</p>
<pre><code>import pandas as pd
import numpy as np
import pyarrow.parquet as pq
import pyarrow as pa
idx = pd.date_range('2017-01-01 12:00:00.000', '2017-03-01 12:00:00.000', freq = 'T')
dataframe = pd.DataFrame({'numeric_col' : np.random.rand(len(idx)),
... | <p>Making a string column<code>dt</code> based off of the index will then allow you to write out the data partitioned by date by running</p>
<pre><code>pq.write_to_dataset(table, root_path='dataset_name', partition_cols=['dt'], flavor ='spark')
</code></pre>
<p>Answer is based off of this <a href="https://arrow.apach... | python|pandas|parquet|pyarrow | 7 |
355,094 | 51,057,034 | Can I use real probability distributions as labels for tf.nn.softmax_cross_entropy_with_logits? | <p>In Tensorflow manual, description for labels is like below:</p>
<blockquote>
<p>labels: Each row labels[i] must be a valid probability distribution.</p>
</blockquote>
<p>Then, does it mean labels can be like below, if I have real probability distributions of classes for each input.</p>
<pre><code>[[0.1, 0.2, 0.... | <p>In a word, yes, you can use probabilities as labels.</p>
<p>The documentation for <code>tf.nn.softmax_cross_entropy_with_logits</code> says you can:</p>
<blockquote>
<p><strong>NOTE:</strong> While the classes are mutually exclusive, their probabilities
need not be. All that is required is that each row of <... | tensorflow|neural-network|softmax | 0 |
355,095 | 50,927,787 | Iterating through selected columns and rows in Pandas | <p>I have just begun using Pandas for my study and I am facing an issue with the following step. </p>
<p>Suppose I have a Dataframe with 'n' columns and 'm' rows. </p>
<p>I want to iterate on a column indexed #2 and from row #5 omitting the preceding rows. How do I go about it?</p>
<p>I could select either the requi... | <p>Using <code>pd.DataFrame.iloc</code>, you can use integer indexers to isolate part of your dataframe. Given a dataframe <code>df</code>:</p>
<pre><code>res = df.iloc[5:, 2]
</code></pre>
<p>Note that indexing in Python begins with 0, so this is the 6th row onwards (or index 5 onwards). Similarly, 2 represents the ... | python|pandas|dataframe|rows | 2 |
355,096 | 50,985,906 | How to get the mean for a whole dataframe instead of columns? | <p>How do I get the mean for all of the values (except for NaN) in a pandas dataframe? </p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="noreferrer"><code>pd.DataFrame.mean()</code></a> only gives the means for each column (or row, when setting <code>axis=1</code>)... | <p>You can use <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.nanmean.html" rel="noreferrer"><code>numpy.nanmean</code></a>:</p>
<pre><code>triang = np.triu_indices(4)
data2 = np.arange(4.,20.).reshape(4, 4)
data2[triang]=np.nan
df2 = pd.DataFrame(data=data2)
res = np.nanmean(df2) # 14.0
... | python|pandas|dataframe|mean | 5 |
355,097 | 51,028,324 | Tensorflow loss not converge | <p>I am doing research on eye landmarks extraction. I have done some augmentations and normalization on the training data. But in the training phase, the error function doesn't seem to decrease.
The initial learning rate is set 1e-3 and will decay every 20 epochs and the batch size is 64.
Here is my code:</p>
<pre><c... | <p>I think your l2_loss is way to high.</p>
<p>maybe try:</p>
<pre><code>error = tf.reduce_mean(tf.squared_difference(landmarks, y_conv)) + 0.01 * tf.nn.l2_loss(W_fc2)
</code></pre>
<p>Other than that you should consider using higher level APIs such as tf.layers it will save you a lot of work, will probably do some... | python|tensorflow|convolutional-neural-network | 0 |
355,098 | 50,954,589 | Pandas rolling corr with no overlap | <p>I have several series of price returns and I would like to calculate the rolling N days correlation in such a way that there is no overlap between dates, i.e, if my first correlation matrix belongs to [2000-04-05 - 2000-06-04], the next correlation matrix should belong to [2000-06-05 - 2000-08-04]. Using the convent... | <h1><code>resample</code></h1>
<p>You can use <code>pd.DataFrame.resample</code> to specify a time rule of 20 days with <code>"20D"</code>. Use the <code>on</code> argument to specify the column that is to be resampled. The resulting <code>resample</code> object is similar to the <code>groupby</code> object and can ... | python|pandas|correlation | 7 |
355,099 | 50,849,789 | What does the numpy.linalg.norm function? | <p>What is the function of <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.norm.html" rel="nofollow noreferrer">numpy.linalg.norm</a> method?</p>
<p><a href="https://mubaris.com/2017/10/01/kmeans-clustering-in-python/" rel="nofollow noreferrer">In this Kmeans Clustering sample</a> the... | <p><code>numpy.linalg.norm</code> is used to calculate the norm of a vector or a matrix.</p>
<hr>
<p>This is the help document taken from <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.norm.html#numpy-linalg-norm" rel="noreferrer">numpy.linalg.norm</a>:</p>
<pre><code>numpy.linalg.... | python|numpy|k-means | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.