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 |
|---|---|---|---|---|---|---|
18,500 | 12,494,819 | Writing list to array and write it to file (Python) | <p>I guess this is pretty easy, but I can not get it to work. I am having a function giving me a list (1x128). The function is inside a loop (1x32). I want to write all the lists (32x128) from the function into to a file. This is the code:</p>
<pre><code>count = 0
savez = np.zeros((waveforms.size/len(waveforms),len... | <p>Instead of creating a <code>(waveforms.size/len(waveforms),len(waveforms))</code> array of zeros, you may want to make <code>savez</code> a basic list <code>[]</code>.</p>
<p>Then, when you loop on your <code>waveforms</code>, just append the new <code>z</code>:</p>
<pre><code>savez.append(z)
</code></pre>
<p>Onc... | python|numpy | 1 |
18,501 | 72,103,345 | How do I drop certain columns by colname for workbooks using Python? | <p>I am trying to understand how I can add to my current script where I'm able to make changes at sheet level. I want to be able to delete columns from the worksheets in my flat file here. For example, if a column is called 'company' I want to delete it so that my final wb.save drops those columns. I have multiple colu... | <p>Since you've tagged the question as <code>pandas</code>, you could just use <code>pandas</code> to read and <code>drop</code>:</p>
<pre><code>for file in os.listdir("C:/Users/hhh/Desktop/aaa/python/Matching"):
if file.startswith("TVC"):
dfs = pd.read_excel(file, sheet_name=None)
... | python|pandas|for-loop|operating-system|openpyxl | 0 |
18,502 | 71,917,505 | Pandas replacing string in one column leads to other column disappearing | <p>New to Pandas, and Im doing something wrong. While running the bellow code to replace cells in column "data" that dont contain the string "fiels" with empty strings, instead of returning two columns (id, data), the whole of id column disappears with all rows starting with a delimiter instead. My ... | <p>You need to assign the results back to the dataframe chunk's column. When you assign to <code>chunk_results</code> you're setting it to a dataframe with just the <code>data</code> column</p>
<pre><code>chunk_df['data'] = chunk_df['data'].astype(str).str.replace('^((?!field).)*$','', regex=True)
chunk_df.to_csv(out_c... | python|pandas|data-cleaning | 1 |
18,503 | 17,035,435 | How to group by data using pandas in python | <p>I have a list of hashes that look like the below.</p>
<pre><code>import pandas as pd
import datetime
rows = [{
"version" : "v1",
"timestamp" : "2013-06-04T06:00:00.000Z",
"event" : {
"campaign_id" : "cid2504649263",
"country" : "AU",
"region" : "Cai... | <p>You're looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>:</p>
<pre><code>In [11]: data.drop_duplicates()
Out[11]:
campaign_id country impressions region utcdt
0 cid2504649263 AU... | python|pandas | 0 |
18,504 | 17,882,862 | Elegant numpy array shifting and NaN filling? | <p>I have a specific performance problem here. I'm working with meteorological forecast timeseries, which I compile into a numpy 2d array such that </p>
<ul>
<li>dim0 = time at which forecast series starts </li>
<li>dim1 = the forecast horizon, eg. 0 to 120 hrs</li>
</ul>
<p>Now, I would like dim0 to have hourly inte... | <p>Behold, the power of boolean indexing!!!</p>
<pre><code>def shift_nans(arr) :
while True:
nan_mask = np.isnan(arr)
write_mask = nan_mask[1:, :-1]
read_mask = nan_mask[:-1, 1:]
write_mask &= ~read_mask
if not np.any(write_mask):
return arr
arr[1:, :... | python|numpy|nan | 6 |
18,505 | 55,431,621 | CNN for image classification overfits, apparently don't take the next batch | <p>I'm trying to create a CNN with TensorFlow that classifies images from <a href="https://www.tensorflow.org/tutorials/estimators/cnn" rel="nofollow noreferrer">google tutorials on CNNs</a>. I created a <a href="https://github.com/MatteoSid/cnn_genetic/blob/master/load_dataset.py" rel="nofollow noreferrer">function</a... | <p>You were not using tensorflow placeholders. Make sure that X_batch_placeholder and Y_batch_placeholder are defined and used in your loss function like this:</p>
<pre><code>Y_batch_placeholder = tf.placeholder(tf.float32 ,[None, 2] )
X_batch_placeholder = tf.placeholder(tf.float32 ,[None, 1000, 48])
logits = cnn_m... | python|tensorflow|machine-learning|deep-learning|conv-neural-network | 0 |
18,506 | 55,340,504 | How do I pip install pandas under the new system? | <p>I have pip installed many packages using the windows powershell from my python 37 window, but havent for a few months and now I am getting an error instead of an install.</p>
<p>I have tried installing two packages (pandas and numpy) and get the same results for both.</p>
<p>I tried switching pip and pandas, as we... | <p>follow steps</p>
<p>1.open cmd</p>
<p>2.give full path to the script folder
e.g. </p>
<blockquote>
<p>C:\Python37-32\Scripts</p>
</blockquote>
<p>3.then try pip commands</p>
<blockquote>
<p>pip install pandas</p>
<p>C:\Python37-32\Scripts>pip install pandas</p>
</blockquote> | windows|pandas|powershell|pip|pypi | 1 |
18,507 | 55,214,532 | How to convert column value to array from csv python | <p>hallo sorry for my bad English, I want to convert my pixels column to separated numpy array for every row (if read using pandas dataframe it columns values will be read as array).
this is example of my dataset, I have tried split every row of pixels for every space, but because of the dataset is about 35.000 data an... | <p>Not very much clear on your question, but hope below suggestion will help,</p>
<p>Try to convert the column in matrix
--load it into a numpy array and reshape it so that it is in desired dimensional</p>
<p>I think for image pixle data, Digit Recognizer problem on MNIST data is very helpful
Give a look to kaggle ke... | python|pandas|csv|numpy|dataset | 1 |
18,508 | 10,104,245 | Combining an array using Python and NumPy | <p>I have two arrays of the form:</p>
<pre><code>a = np.array([1,2,3])
b = np.array([4,5,6])
</code></pre>
<p>Is there a NumPy function which I can apply to these arrays to get the followng output?</p>
<pre><code>[[1,4],[2,5][3,6]]
</code></pre> | <pre><code>np.vstack((a,b)).T
</code></pre>
<p>returns</p>
<pre><code>array([[1, 4],
[2, 5],
[3, 6]])
</code></pre>
<p>and</p>
<pre><code>np.vstack((a,b)).T.tolist()
</code></pre>
<p>returns exactly what you need:</p>
<pre><code>[[1, 4], [2, 5], [3, 6]]
</code></pre> | python|arrays|numpy | 7 |
18,509 | 56,646,261 | Can someone please explain np.less_equal.outer(range(1,18),range(1,13)) | <p>I was debugging a code written by someone who has left the organization and came across a line, which uses <code>np.less_equal.outer</code> & <code>np.greater_equal.outer</code> functions. I know that <code>np.outer</code> creates a Cartesian cross product of two 1-dimensional arrays and creates two arrays, and ... | <p><code>less_equal</code> and <code>greater_equal</code> are special types of <code>numpy</code> functions called <code>ufunc</code>s, in that they have extendible functionalities, including <code>accumulate</code>, <code>at</code>, and <code>outer</code>.</p>
<p>In this case <a href="https://docs.scipy.org/doc/numpy... | python|numpy | 2 |
18,510 | 56,750,399 | Update a specific position in a column of a pandas dataframe based on some condition | <p>For example, one of my column of my dataframe has data like below:</p>
<pre><code>29-APR-19 11.50.00.000000000 PM
29-APR-19 11.50.00.000000000 AM
</code></pre>
<p>Hence, I need to update the column having PM to:</p>
<pre><code>29-APR-19 23.50.00.000000000 PM
</code></pre>
<p>How can we do that?</p>
<p>I have t... | <p>If need same format here is necessary add <code>12</code> hours for datetimes below <code>12:00:00</code>.</p>
<p>Solution is first convert column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, then add <code>12<... | python|pandas|dataframe | 0 |
18,511 | 25,570,773 | Selecting rows from two nump.nd arrays and insert 0 for the missing match | <p>I have two nd.numpy arrays named 'a' and 'b', I want to select only certain rows from array 'b' based on the comparison with 'a' and insert 0 for the rows if a match is not found. I did the first part. eg;</p>
<pre><code>a = np.array([[1,5,9],
[2,6,10],
[5,14,10]])
b = np.array([[ 1,0,9],
... | <p>If you would like any element of <code>b[:, 0]</code> that is not in <code>a[:, 0]</code> to be zero you can do the following:</p>
<pre><code>>>> b[~np.in1d(b[:, 0], a[:, 0]), :] = 0
>>> b
array([[ 1, 0, 9],
[ 2, 6, 10],
[ 0, 0, 0]])
</code></pre>
<p>If you would like any eleme... | python|arrays|numpy | 1 |
18,512 | 25,663,999 | Smart way to convert polars to Cartesian coordinates with numpy | <p>I have an array of Cartesian coordinates produced from polars in a usual way:</p>
<pre><code>for k in range(0, Phi_term):
for j in range(0, R_term):
X[k,j] = R[j]*np.cos(phi[k]);
Y[k,j] = R[j]*np.sin(phi[k]);
</code></pre>
<p>The problem is that the zeroth element of such an array corresponds t... | <pre><code>def quasiCartesianOrder(arr, R_term, Phi_term):
# deal with odd phi count by starting from top of top spike.
rhsOddOffset = 0
if Phi_term % 2 == 1:
rhsOddOffset = R_term
for r in xrange(0, R_term):
yield (Phi_term + 1)/2 * R_term - r - 1
# 'rectan... | math|numpy|geometry|coordinates|polar-coordinates | 1 |
18,513 | 26,186,937 | interpolate values between sample years with Pandas | <p>I'm trying to get interpolated values for the metric shown below using Pandas time series.</p>
<p><strong>test.csv</strong></p>
<pre><code>year,metric
2020,290.72
2025,221.763
2030,152.806
2035,154.016
</code></pre>
<p><strong>Code</strong></p>
<pre><code>import pandas as pd
df = pd.read_csv('test.csv', parse_da... | <p>It turns out, interpolation only fills in values, where there are none. In my case above, what I had to do was to re-index so that the interval was 12 months. </p>
<pre><code># reindex with interval 12 months (M: month, S: beginning of the month)
df_reindexed = df.reindex(pd.date_range(start='20120101', end='203501... | python|pandas|time-series | 0 |
18,514 | 66,890,897 | subsetting dataframe based on multiple conditions from one-hot encoded columns | <pre><code>id is_happy is_sad is_mad is_sorry
1 1 0 1 0
2 1 0 1 0
3 0 1 1 0
4 0 0 0 1
5 0 1 1 0
6 1 0 1 0
7 1 1 1 1
</code></pre>
<p>i want to get rows where is_happy, is_sad, and is_so... | <p>Try with</p>
<pre><code>out = df[df.drop(['id','is_mad'],1).all(1)]
id is_happy is_sad is_mad is_sorry
6 7 1 1 1 1
</code></pre> | python|pandas | 1 |
18,515 | 66,769,766 | NumPy - Adding a vector multiplied by a scalar to a matrix | <p>I'm new to NumPy and try to do the following thing <strong>without</strong> using loops.</p>
<p>I have a (n, n) square matrix A and a vector x with size (1,n), and I would like to add the vector to each row of the matrix, while multiplying the vector by the index of the row. <br>
That is, adding the vector * 1 to th... | <p>You can use <a href="https://numpy.org/doc/stable/user/theory.broadcasting.html#array-broadcasting-in-numpy" rel="nofollow noreferrer">broadcasting</a> to achieve this.</p>
<pre><code>A = np.ones((5,5))
x = np.arange(5)
indices = np.arange(5)[None,:].T
A * x + indices
array([[0., 1., 2., 3., 4.],
[1., 2., 3.... | python|numpy | 0 |
18,516 | 67,159,328 | Cumulative sales data with threshold value forming a new series / column with a boolean value? | <p>I have this type of data, but in real life it has millions of entries. Product id is always product specific, but occurs several times during its lifetime.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>date</th>
<th>product id</th>
<th>revenue</th>
<th>estimated lifetime value</th>
</t... | <ol>
<li><strong>Cumulative Revenue</strong>: Can be calculated fairly simply with <code>groupby</code> and <code>cumsum</code>.</li>
<li><strong>dwk1k_thresh</strong>: We are first checking whether cum_rev is greater than 1000 and then apply the function that helps us keep 1 <strong>only once</strong>, and after that ... | python|python-3.x|pandas | 4 |
18,517 | 66,794,633 | Iterate over unique date and hour in the pandas dataframe to run a function | <p>Hi I am currently running a for loop through by unique dates in the dataframe to pass it to a function.
However what I wanted is to iterate over the unique date and hour (e.g. 2020-12-18 15:00, 2020-12-18 16:00) through my dataframe. Is there any possible way to do this?</p>
<p>This is my code and a sample of my dat... | <p>You can use <code>groupby</code> if need filter by all dates in DataFrame:</p>
<pre><code>for day, testdf in df.groupby('DateTime'):
testdf.set_index('DateTimeStarted', inplace=True)
output = mk.original_test(testdf, alpha =0.05)
output_df = pd.DataFrame(output).T
output_df.rename({0:"Trend"... | python-3.x|pandas|datetime|time-series | 1 |
18,518 | 66,970,826 | Python pandas how to print first 10 max and min value from dataframe | <p>How can I get only the 10 items with highest value? and also the 10 items with lowest value?
i have tried .max() it only returns the value
<a href="https://i.stack.imgur.com/ICnw6.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>import warnings
warnings.filterwarnings('ignore')
import p... | <p>You should really make use of the search engine and look at the document of pandas. Google <code>pandas sort_values</code> or <code>pandas nlargest</code> will lead you to the right place.</p>
<p>Take a look at <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow nor... | python|pandas | 1 |
18,519 | 47,113,299 | How can I display numbers in scientific form inside a numpy matrix? | <p>I know the Python code for displaying numbers in scientific form is:</p>
<pre><code>print("Number is {:.2e}".format(Number))
</code></pre>
<p>How would I do the same for a (numpy) matrix? I've tried the same format for a 2 by 2 matrix and receive the error message: "TypeError: non-empty format string passed to obj... | <p>Here is the exact code that allows you to do this: </p>
<pre><code>j = 0
for j, i in TheMatrix.flat:
j += 1
print("The Matrix Value {} is {:.2e}".format(j, i))
</code></pre> | python|numpy|matrix|scientific-notation | 0 |
18,520 | 47,091,810 | Pandas dataframe apply list to columns auto-matching behaviour | <p>Take a look at this minimal example:</p>
<pre><code>import pandas as pd
s1 = """A,B
a,1
b,1
"""
df = pd.read_csv(io.StringIO(s1))
print(df.apply(lambda x: 1 * [x.A],axis=1))
print("==================")
print(df.apply(lambda x: 2 * [x.A],axis=1))
print("==================")
print(df.apply(lambda x: 3 * [x.A],axis... | <p>Try a different approach:</p>
<pre><code>In [9]: df['A'].apply(list) * 1
Out[9]:
0 [a]
1 [b]
Name: A, dtype: object
In [10]: df['A'].apply(list) * 2
Out[10]:
0 [a, a]
1 [b, b]
Name: A, dtype: object
In [11]: df['A'].apply(list) * 3
Out[11]:
0 [a, a, a]
1 [b, b, b]
Name: A, dtype: object
</code><... | python|pandas | 0 |
18,521 | 47,186,604 | Numpy Finding Matching number with Array | <p>Any help is greatly appreciated!! I have been trying to solve this for the last few days....</p>
<p>I have two arrays:
import pandas as pd</p>
<pre><code> OldDataSet = {
'id': [20,30,40,50,60,70]
,'OdoLength': [26.12,43.12,46.81,56.23,111.07,166.38]}
NewDataSet = {
'id': [3000,4000,5000,6000,7000,8000]
... | <p>You can use NumPy broadcasting to build a distance matrix:</p>
<pre><code>a = numpy.array([26.12, 43.12, 46.81, 56.23, 111.07, 166.38,])
b = numpy.array([25.03, 42.12, 45.74, 46, 110.05, 165.41,])
numpy.abs(a[:, None] - b[None, :])
# array([[ 1.09, 16. , 19.62, 19.88, 83.93, 139.29],
# [ 18.09,... | python|arrays|numpy | 2 |
18,522 | 47,421,880 | pandas: split dataframe into multiple csvs | <p>I have a large file, imported into a single dataframe in Pandas.
I'm using pandas to split up a file into many segments, by the number of rows in the dataframe.</p>
<p>eg: 10 rows:
file 1 gets [0:4]
file 2 gets [5:9]</p>
<p>Is there a way to do this without having to create more dataframes?</p> | <p><code>assign</code> a new column g here, you just need to specific how many item you want in each groupby, here I am using 3 .</p>
<pre><code>df.assign(g=df.index//3)
Out[324]:
0 g
0 1 0
1 2 0
2 3 0
3 4 1
4 5 1
5 6 1
6 7 2
7 8 2
8 9 2
9 10 3
</code></pre>
<p>and you can call the ... | python-3.x|pandas | 4 |
18,523 | 68,306,397 | Create a new dataframe by filtering characters from an existing dataframe | <p>I have a <code>pandas</code> dataframe:</p>
<pre><code>id name
63 T台
64 4S店
66 江南style
68 1号店
69 小S
70 大S
72 一
73 一一
74 一一二
77 一一列举
79 一一对应
80 一一记
81 一一道来
82 一丁
84 一丁点
</code></pre>
<p>I'm trying to crea... | <p>You can use regular expression:</p>
<pre class="lang-py prettyprint-override"><code>import re
pat = re.compile("|".join(re.escape(l) for l in letters), flags=re.I)
print(df[~df["name"].str.contains(pat)])
</code></pre>
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code> id name... | python|pandas|dataframe | 2 |
18,524 | 68,380,849 | Specify bar colors in simple pandas/matplotlib "barh" plot with one column | <p>I have a bar plot from a pandas DataFrame with one column:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
columns = ["Foo"]
data = [50, 201, 279]
index=["Item 1", "Item 2", "Item 3"]
df = pd.DataFrame(data=data, index=index, columns=columns)
</code></pre>... | <p>This might not be the most elegant way, but you can always loop over matplotlib patches and change their colors invidividually:</p>
<pre><code>ax = df.plot(kind="barh", color="#00576B", rot=0, legend=False, align='center', width=0.5)
ax.set_title("My title")
ax.set_ylabel("")
... | python|pandas|matplotlib | 1 |
18,525 | 68,422,297 | Batch matrix multiplication in numpy | <p>I have two numpy arrays <code>a</code> and <code>b</code> of shape <code>[5, 5, 5]</code> and <code>[5, 5]</code>, respectively. For both <code>a</code> and <code>b</code> the first entry in the shape is the batch size. When I perform matrix multiplication option, I get an array of shape <code>[5, 5, 5]</code>. An M... | <p>Add an extra dimension to <code>b</code> to make the matrix multiplications <em>batch</em> compatible and remove the redundant last dimension at the end by <a href="https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html" rel="nofollow noreferrer">squeezing</a>:</p>
<pre class="lang-py prettyprint-overri... | python|arrays|python-3.x|numpy|matrix-multiplication | 4 |
18,526 | 68,334,111 | Converting columns names from a list | <p>I am reading multiple csv files into a pandas data frame as a list before concatenating them together. All the files from the first have different column names, but I wanted to convert those names to have the same as the first file, so that I can combine them by rows relative to the same column names.</p>
<p>I can c... | <p>Use <code>np.concatenate</code> to keep only values.</p>
<p>IIUC, something like that should work:</p>
<pre><code>dfs = [fs, ds]
df_row_merged = pd.DataFrame(np.concatenate(dfs), columns=dfs[0].columns)
</code></pre>
<pre><code>>>> df_row_merged
bgif datasetkey occurrenceid
0 -0.414690 0.842747 ... | python|pandas | 0 |
18,527 | 316,410 | Is there a good NumPy clone for Jython? | <p>I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone fo... | <p>I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages <a href="http://math.nist.gov/javanumerics/" rel="noreferrer">here</a> - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.</p> | java|python|numpy|jython | 12 |
18,528 | 59,094,620 | how to write data in the sequential format in the dataframe | <pre><code>import json
import pandas as pd
import numpy as np
class Decoder(json.JSONDecoder):
def decode(self, s):
result = super(Decoder, self).decode(s)
return self._decode(result)
def _decode(self, o):
if isinstance(o, str):
try:
return int(o)
... | <p>Your three lines:</p>
<pre><code>df = pd.DataFrame(list,columns=['id','value'])
new_df = df.set_index('id')
new_df1=new_df.reindex(np.arange(1, 14)).fillna(' ')
</code></pre>
<p>can be rewritten as:</p>
<pre><code>df = (pd.DataFrame(list, columns = ['id','value'])
.set_index('id')
.reindex(np.aran... | python|pandas|numpy|dataframe | 0 |
18,529 | 59,173,464 | Adding value from a pandas dataframe only if other value from the same row is True | <p>I am new to pandas.</p>
<p>I have a dataset which looks like this:</p>
<pre><code>Date_1 Hour_1 id_1 Date_2 Hour_2 id_2 Date_3 Hour_3 id_3
2019-12-04 00 ABC 2019-12-04 01 ABC 2019-12-04 02 ABC
2019-12-04 00 ABCD 2019-12-04 01 ... | <p>Something like that should work:</p>
<pre><code>mask_id2 = df.id_1 == df.id_2
mask_id3 = df.id_1 == df.id_3
df.id_2 = mask_id2
df.id_3 = mask_id3
df.loc[~mask_id2, ['Date_2', 'Hour_2']] = ""
df.loc[~mask_id3, ['Date_3', 'Hour_3']] = ""
</code></pre>
<p>Output:</p>
<pre><code> Date_1 Hour_1 id_1 ... | python|pandas|dataframe | 2 |
18,530 | 59,365,364 | Calculate unique values in one column based upon non-null values in another | <p>Working through this: <a href="https://towardsdatascience.com/exploratory-statistical-data-analysis-with-a-real-dataset-using-pandas-208007798b92" rel="nofollow noreferrer">https://towardsdatascience.com/exploratory-statistical-data-analysis-with-a-real-dataset-using-pandas-208007798b92</a></p>
<p>A little shy of h... | <p>I just figured it out, but even with groupby() the solution is still longer than I expected -- or maybe I should say I did not achieve what I thought would be increased simplification:</p>
<pre><code>medal_winners = df[df['Medal'].notnull()].groupby('Name')['Name'].nunique().sum()
</code></pre>
<p>Both my groupby(... | python|python-3.x|pandas|pandas-groupby | 0 |
18,531 | 13,973,952 | sign recognition like hand written digits example in scikit-learn (python) | <p>I watch out this example: <a href="http://scikit-learn.org/stable/auto_examples/plot_digits_classification.html#example-plot-digits-classification-py" rel="nofollow">http://scikit-learn.org/stable/auto_examples/plot_digits_classification.html#example-plot-digits-classification-py</a>
on handwritten digits in scikit-... | <p>You have to resize all your images to a fixed size. For instance using the <code>Image</code> class of PIL or <a href="http://pypi.python.org/pypi/Pillow/" rel="nofollow">Pillow</a>:</p>
<pre><code>from PIL import Image
image = Image.open("/path/to/input_image.jpeg")
image.thumbnail((200, 200), Image.ANTIALIAS)
ima... | multidimensional-array|numpy|python-2.7|machine-learning|scikit-learn | 1 |
18,532 | 45,093,688 | How to understand sess.as_default() and sess.graph.as_default()? | <p>I read the <a href="https://www.tensorflow.org/api_docs/python/tf/Session#as_default" rel="noreferrer">docs of sess.as_default()</a></p>
<blockquote>
<p>N.B. The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly... | <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/Session" rel="noreferrer">tf.Session</a> API mentions that a graph is launched in a session. The following code illustrates this:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
graph1 = tf.Graph()
graph2 = tf.Graph()
with grap... | tensorflow | 30 |
18,533 | 45,066,756 | Python Pandas: dataframe.loc returns "KeyError: label not in [index]", but dataframe.index shows it is | <p>I'm using the pandas toolkit in Python, and I'm have an issue.</p>
<p>I have a list of values, <code>lst</code>, and to make it easy let's say it has only the first 20 natural numbers:</p>
<pre><code>>>> lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
</code></pre>
<p>I then create a <code>Dat... | <p>The index value is not <em>exactly</em> equal to 0.7 here; to a very small precision there is a difference. You can confirm this by running:</p>
<pre><code>assert qts.index[6] == 0.7
</code></pre>
<p>or</p>
<pre><code>print(qts.index[6] - 0.7)
</code></pre>
<p>If you round the index using <code>numpy.round</code... | python|pandas|statistics | 3 |
18,534 | 45,259,685 | Output layer for multi-label, multi-class classification? | <p>I'm looking for a way to achieve multiple classifications for an input. The number of outputs is specified, and the class sets may or may not be the same for the outputs. The sample belongs to one class of each class set.</p>
<p>My question is, what should the target data and the output layer look like? What activa... | <p>Maybe it's not a good time to response to the question, but I am working on the multi-label classification and just found an solution.
As for Keras, there's a example:</p>
<ul>
<li><strong>target label</strong>: [1, 0, 0, 1, 0]</li>
<li><strong>output layer</strong>: Dense(5, activation='sigmoid')</li>
<li><strong>... | tensorflow|neural-network|keras|multilabel-classification|multiclass-classification | 0 |
18,535 | 44,990,104 | Implementing TensorFlow Attention OCR on iOS | <p>I have successfully trained (using Inception V3 weights as initialization) the Attention OCR model described here: <a href="https://github.com/tensorflow/models/tree/master/attention_ocr" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/attention_ocr</a> and frozen the resulting checkpoint ... | <p>As suggested by others you can use some existing iOS demos (<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/ios" rel="nofollow noreferrer">1</a>, <a href="http://machinethink.net/blog/tensorflow-on-ios/" rel="nofollow noreferrer">2</a>) as a starting point, but pay close attention t... | c++|ios|tensorflow|ocr|tensorflow-serving | 2 |
18,536 | 57,179,545 | Changing (date) x-axis tick frequency | <p>For hours on end, I have been trying to change the x-axis tick frequency. I want every data point to have a corresponding tick (or every other, at least every third).</p>
<p>My graph is supposed to show the amount of goods sold <code>kolicina</code> and the discount in percentages <code>popust (%)</code> over time,... | <p>Just pass the value of <strong>x in the plt.xticks()</strong> and set x-axis using <strong>'plt.gcf'</strong> it will work.<br/></p>
<pre class="lang-py prettyprint-override"><code>plt.xticks(x,rotation=90)
</code></pre>
<p>have create a <strong>random dataframe</strong> and plot the graph check it.</p>
<pre clas... | python|pandas|matplotlib|plot | 1 |
18,537 | 45,940,681 | How to create a histogram for the given DataFrame? | <p>I have the following DataFrame <code>df</code> (a small extract is given):</p>
<pre><code>time_diff avg_qty_per_day
1.450000 1.0
1.483333 1.0
1.500000 1.0
2.516667 1.0
2.533333 1.0
2.533333 1.5
3.633333 1.8
3.644567 5.0
</code></pre>
<p>I want to create the histogram for variable <code>ti... | <p>I think you need first to group by "time_diff" taking the sum of "avg_qty_per_day".
Here is a dummy code </p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=list('AB'))
print(df.head())
df.groupby("A").sum()
plt.hist... | python|python-2.7|pandas|matplotlib | 0 |
18,538 | 45,862,882 | Why are no colors shown in kde subplots in seaborn pairplot? | <p>I am looking at the iris data set (Fisher 1936). e.g. <a href="https://www.kaggle.com/uciml/iris/downloads/Iris.csv" rel="nofollow noreferrer">https://www.kaggle.com/uciml/iris/downloads/Iris.csv</a></p>
<p>Creating the seaborn pairplot with the arguments</p>
<pre><code>sns.pairplot(iris.drop("Id", axis=1), diag_k... | <p>There was an <a href="https://github.com/mwaskom/seaborn/issues/1265" rel="nofollow noreferrer">the issue</a> with producing hues on the diagonal of <code>sns.pairplot</code>. This issue is now fixed in version 0.8.1 of seaborn.</p>
<p>In case one is still interested, the following may be a workaround. You may crea... | python|pandas|matplotlib|seaborn | 5 |
18,539 | 46,054,880 | fill empty rows in columns with the average value of a certain interval in pandas | <p>I have a dataframe with empty cells, which I need to fill with the average of the previous values in a certain interval of scale. Part of the dataframe for the example:</p>
<pre><code>code scale s1 s2 s3
1111 -8 4 17 21
1111 -7 14 46 33
1111 -6 31 47 23
1111 -5 8 ... | <p>I assume <code>code</code> is the index of the dataframe.</p>
<p><strong>First</strong>, get the mean values:</p>
<pre><code>df[df['scale'].between(-4, 0)].groupby(level=0).mean()
</code></pre>
<p>This returns:</p>
<pre><code> scale s1 s2 s3
code
1111 -2 8.40 21.00 24.... | python|pandas | 3 |
18,540 | 35,610,868 | Tensorflow code breaking | <p>I am modifying cifar multi GPU tensorflow code to read the Imagenet dataset.</p>
<p>The edits that I made are:</p>
<p><strong>Cifar10.py:</strong></p>
<p>1) Changed tf.app.flags.DEFINE_string('data_dir',...)</p>
<p>2) Removed the later part in data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')</p>
... | <p>Looks like you're not getting any data input from your readers.</p>
<p>You changed:</p>
<pre><code>[os.path.join(data_dir, i) for i in os.listdir(data_dir)]
</code></pre>
<p>What's actually in data_dir/ ? (Are you sure the right dirname is being used, etc.?)</p>
<p>My suggestion would be to <code>print filename... | python|python-2.7|tensorflow | 1 |
18,541 | 35,413,189 | how to clean or convert unknown characters in an otherwise integer field in python? | <p>I am building a data set by downloading data from disparate sources. The source files are all excel files. I am using pandas data frame to accomplish this. After writing the compiled file to a .csv file, I noticed that some of the cells in the dataset has unnatural characters in it. For example, in a field with all ... | <p>This depends on what is the «expected» value of the cell. If it should be <code>1,056</code> then you can use this approach:</p>
<pre><code>val = ''.join(c for c in val if c.isdigit() or c in ',.')
</code></pre>
<p>This can also be expressed in functional style:</p>
<pre><code>val = ''.join(filter(lambda c: c.isd... | python|pandas | 1 |
18,542 | 50,671,996 | Perform mean subtraction on a list of images? | <p>I have a numpy array of shape <code>(100,320,320)</code>, 100 Images and each image is 320*320. </p>
<p>I tried doing:</p>
<pre><code>mean = np.mean(train_x)
train_x -= mean
</code></pre>
<p>I get a <code>Cannot cast ufunc subtract output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'</code... | <p>Either allow the result to be a floating point number:</p>
<pre><code>mean = np.mean(train_x)
train_x = train_x - mean
</code></pre>
<p>Or calculate the mean as a <code>np.uint8</code> (which loses precision):</p>
<pre><code>mean = np.mean(train_x, dtype=train_x.dtype)
train_x -= mean
</code></pre> | numpy|machine-learning|computer-vision | 0 |
18,543 | 51,002,335 | Expanding a matrix | <p>Given a matrix, such as:</p>
<pre><code>1 0 0
0 1 1
1 1 0
</code></pre>
<p>I would like to expand each element to a "sub-matrix" of size AxA, e.g., 3x3, the result will be:</p>
<pre><code>1 1 1 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1
1 1 1 1 1 1 0 0 0
... | <p>Since what you're describing is the <a href="https://en.wikipedia.org/wiki/Kronecker_product" rel="nofollow noreferrer">Kronecker product</a>:</p>
<p>Use <strong><code>np.kron</code></strong></p>
<blockquote>
<p>Computes the Kronecker product, a composite array made of blocks of the second array scaled by the fi... | python|numpy | 3 |
18,544 | 51,065,571 | KeyError: 'labels [data] not contained in axis' | <p>I have tried several different methods to add a row to an existing Pandas Dataframe. For example I tried the solution <a href="https://www.quantopian.com/posts/how-to-add-entries-to-a-dataframe" rel="nofollow noreferrer">here</a>. However I was not able to correct the issue. I have reverted back to my original co... | <p>Given that XDFDF is a <code>pandas.DataFrame</code>, shouldn't the following work?</p>
<pre><code>XDFDFdrop = pd.DataFrame.duplicated(XDFDF,subset='LastSurveyMachineID')
goodBucket = XDFDF.loc[~XDFDFdrop] #the ~ negates a boolean array
badBucket = XDFDF.loc[XDFDFdrop]
</code></pre>
<p>Edit: </p>
<p>The updated er... | python|pandas|append|typeerror|delete-row | 1 |
18,545 | 66,757,394 | Python Pandas fill missing column with left join | <p>I have following two data-frames.</p>
<p>df_1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AA</th>
<th>BB</th>
<th>CC</th>
<th>DD</th>
</tr>
</thead>
<tbody>
<tr>
<td>"Apple"</td>
<td>XYZ1</td>
<td>XYZ2</td>
<td></td>
</tr>
<tr>
<td>"Apple"</td>
<td>PQR1</td>
<td>P... | <p>When you merge two dataframes in pandas, you have have to pass a <code>how =</code> argument, otherwise pandas defaults to an inner join. The error is then caused because you have 501 values in your inner joined <code>apple_merged</code> dataframe and 602 in <code>df_1</code>.</p>
<p>Link: <a href="https://pandas.p... | python|pandas|dataframe|python-3.8 | 1 |
18,546 | 57,299,135 | Convert excel formula to python code in order to make calculations of different dataframes | <p>I want to calculate some dataframe with other dataframes. When I make
tihs calculation in excel, a complex formula shows up. How can I convert
this calculation that is condition, to python code?</p>
<p>I have only dataframes which are create new dataframe what I want.
I have 'Opened', 'Buy' and 'Sell' datafram... | <pre><code>df = pd.read_csv('data_1.csv', decimal=b',', dtype='float')
df
</code></pre>
<p><a href="https://i.stack.imgur.com/zOcIi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zOcIi.png" alt="enter image description here"></a></p>
<pre><code>def decision(x):
return np.where(x[0] <=0, -m... | excel|pandas|dataframe | 1 |
18,547 | 57,684,172 | What is the advantage of using tensorflow instead of scikit-learn for doing regression? | <p>I am new to machine learning and I want to start doing basic regression analysis. I saw that scikit-learn provides a simple way to do this. But why people use tensorflow for regression instead? Thanks!</p> | <p>If the only thing you are doing is regression, scikit-learn is good enough and will definitely do you job. Tensorflow is more a deep learning framework for building deep neural networks.</p>
<p>There're people using Tensorflow to do regression maybe just out of personal interests or they think Tensorflow is more fa... | tensorflow|machine-learning|scikit-learn|linear-regression | 2 |
18,548 | 57,421,766 | Plotting subclassed model in tensorflow-2.0 beta | <p>I have a subclassed model that instantiates a few custom layers via subclassing. I tried using <code>keras.utils.plot_model()</code> but all it does is print the model block, none of the layers appeared. </p>
<p>Can a Tensorflow expert comment on this? Will this feature ever be implemented in the future? If not... | <p>Accodring to the officical documentation <a href="https://www.tensorflow.org/tensorboard/graphs" rel="nofollow noreferrer">https://www.tensorflow.org/tensorboard/graphs</a>,
you can </p>
<blockquote>
<p>use <strong>TensorFlow Summary Trace API</strong> to log autographed functions for
visualization in TensorBoa... | python|tensorboard|tensorflow2.0 | 2 |
18,549 | 57,374,843 | Best data types for binary variables in Pandas CSV import to decrease memory usage | <p>My original file for training purpose have 25Gb. My machine has 64Gb of RAM. Importing data with default options always ends up in "Memory Error", therefore after reading some posts, I find out that the best option is to define all data types. </p>
<p>For purpose of this question I use a CSV file of: 100.7Mb (it's ... | <p>Referring to the NumPy document <a href="https://numpy.org/devdocs/user/basics.types.html" rel="nofollow noreferrer">here</a> the least possible choice for allocating items in the array/list is "int8" dtype of numpy which has the corresponding "int8_t" in C.</p>
<p>For binary lists / list-like objects, "uint8", "in... | python|python-3.x|pandas|csv | 0 |
18,550 | 23,976,176 | ranks within groupby in pandas | <p>I have a typical "panel data" (in econometric terms, not pandas panel object). The dataframe has a <code>Date</code> column and a <code>ID</code> column, and other columns that contain certain values. For each Date, I need to cross-sectionally rank across IDs based on V1 into 10 groups (deciles) and create a new col... | <p>A way I just find figured out:</p>
<pre><code>def grouping(data):
dec=pd.qcut(data['V1'],10,labels=False)
data['ranks']=dec
return data
df_ranked=df.groupby('Date').apply(grouping)
</code></pre>
<p>This assumes <code>dec</code> preserve the right position for each row.</p>
<p>Please post if you have a... | python|pandas|group-by | 7 |
18,551 | 43,712,867 | Unimplemented Error: TensorArray has size zero | <p>I am getting this weird error when trying to train a sequence to sequence model in tensorflow. The sequence to sequence model is a video captioning system. I have encoded the frames of the videos in sequence features of the SequenceExampleProto. After I prefetch the features containing the list of jpeg encoded strin... | <p>Fixed. I followed the suggestion from <a href="https://stackoverflow.com/questions/43270849/tensorflow-map-fn-tensorarray-has-inconsistent-shapes">tensorflow map_fn TensorArray has inconsistent shapes</a> and implemented the following:</p>
<pre><code>with tf.name_scope("decode", values=[encoded_video]):
input_j... | tensorflow | -1 |
18,552 | 43,859,236 | tensorflow: block-wise array/matrix sums | <p>Is there any tensorflow function that allows one to do block-wise sums on an array or matrix.</p>
<p>For example, if I have an array</p>
<pre><code>tf.constant(np.array([1,2,3,4,5,6]))
</code></pre>
<p>I need to return an array of sums of blocks of <code>2</code> elements. In other words, the sums of <code>1 + 2,... | <p>You can do it using <code>tf.reshape</code> and <code>tf.reduce_sum</code> as follows:</p>
<pre><code>import tensorflow as tf
n=tf.constant([1,2,3,4,5,6])
res=tf.reduce_sum(tf.reshape(n,(3,2)),1)
sess=tf.Session()
res.eval(session=sess)
</code></pre>
<p>This prints <code>array([ 3, 7, 11])</code></p>
<p>In the g... | tensorflow | 0 |
18,553 | 43,859,483 | drop multiple numpy axis's in array data | <p>I have a numpy array that is (3, 3, 3, 64). I would like to eliminate data from two axis's of this array to get a (3, 3, 1, 64) array. I am sure there is a simple method of doing this, but I am not seeing it. I was hoping a numpy guru could point me in the right direction on how to do this. I have tried something l... | <p><strong>Setup</strong></p>
<pre><code>a = np.zeros((3, 3, 3, 64))
a.shape
Out[289]: (3L, 3L, 3L, 64L)
</code></pre>
<p><strong>Solution</strong></p>
<pre><code>#Slice the array and reshape to desired shape
a_cut = a[:,:,0,:].reshape((3,3,1,64))
#check
a_cut.shape
Out[291]: (3L, 3L, 1L, 64L)
</code></pre>
<p>Or ... | arrays|numpy | 0 |
18,554 | 43,610,906 | Very large array handling with astropy and numpy | <p>For some reasons I need to use astropy to convert comoving distance to redshift. Basically this involves reading in, looping through and writing out a list or a numpy array... My problem is that each of my lists typically consists of ~ 9.5 x 10^6 elements. And this gives me the MemoryError every time I try to save t... | <p>I don't know any solution intrinsic to numpy, but you can save some memory allocation by writing each solution promptly to file, and not after the for loop. That saves the memory allocation for <code>Redshift</code> and the memory allocation done behind the scenes when <code>numpy.savetxt()</code> formats floating p... | arrays|list|numpy|astropy | 1 |
18,555 | 43,916,715 | Apply function to dataset to replace dynamically | <p>I have a pandas which is 6x3 and the columns represent times.</p>
<p>I want to replace values on conditions:</p>
<pre><code>def substituteMin(x,n,c,k):
if x < (1 - c)^n+sqrt(k):
x = (1 - c)^n+sqrt(k)
else:
pass
return x
df1 = df.apply(lambda x: compareMin(x, x.name))
print (df1)
</co... | <p>Here I have simplified your code.</p>
<pre><code>def func(x,n=0,c=1,k=2):
if x < (1 - c)^n+sqrt(k):
x = (1 - c)^n+sqrt(k)
return x
df1 = df.applymap(lambda x: func(x))
print (df1)
</code></pre>
<p>Modifications:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/19798153/difference-betwe... | python|pandas | 0 |
18,556 | 73,065,778 | Compare two pandas DataFrames in the most efficient way | <p>Let's consider two pandas dataframes:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame([1, 2, 3, 2, 5, 4, 3, 6, 7])
check_df = pd.DataFrame([3, 2, 5, 4, 3, 6, 4, 2, 1])
</code></pre>
<p>If want to do the following thing:</p>
<ol>
<li>If <code>df[1] > check_df[1]</code> or <code>df[2] >... | <p>IIUC, this is easily done with a <code>rolling.min</code>:</p>
<pre><code>df['out'] = np.where(df[0].rolling(N, min_periods=1).max().shift(1-N).gt(check_df[0]),
1, -1)
</code></pre>
<p>output:</p>
<pre><code> 0 out
0 1 -1
1 2 1
2 3 -1
3 2 1
4 5 1
5 4 -1
6 3 1
7 6 ... | python|pandas|dataframe | 3 |
18,557 | 72,985,464 | how to make colab use GPU for spacy training NER model | <p>I have <strong>40,000</strong> records and I the training process is very <em>slow</em>, this is the line I use in colab for training</p>
<pre><code>! python -m spacy train config.cfg --output /content/ --paths.train /content/training_data.spacy --paths.dev /content/training_data.spacy
</code></pre>
<p>when I run th... | <p>The key steps to make it happen are:</p>
<ol>
<li><p>enable the GPU (edit -> notebook settings -> hardware acceleration)</p>
</li>
<li><p>install spacy with CUDA support (<code>pip install spacy[cuda100]</code>)</p>
</li>
<li><p>Validate if it is all set by running the following code (it must return <code>True... | tensorflow|nlp|spacy|named-entity-recognition|transformer-model | 1 |
18,558 | 72,985,587 | Side by Side Horizontal Boxplots Pandas | <p>I'm trying to plot side-by-side horizontal boxplots in Pandas. Any idea why I get the following error?</p>
<p><a href="https://i.stack.imgur.com/Rw47R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rw47R.png" alt="Error" /></a></p> | <p>You need to use <code>ax[0]</code> and <code>ax[1]</code> not <code>ax[0][0]</code> and <code>ax[0][1]</code></p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
"column1" : ["ABC", "DEF"],
"column2" : [4,1],
"column3" : [1,4],
})
fi... | python|pandas|boxplot | 0 |
18,559 | 72,914,480 | Repeated repeated sampling without replacement | <p>I have a Slots dataframe with ~1,000,000 race+gender slots (so <strong>efficiency is a slight concern</strong>, I think). There are 3 race categories (White, Black, Hispanic) and 2 gender categories (Male, Female), for a total of 6 race-gender categories (e.g. White-Male (WM), Black-Female (BF), etc.). The dataframe... | <p>A much smarter friend of mine found an answer (code solution below). The key thing he explained to me is that the <strong>bottleneck is storing things in memory</strong>. For example, every time I went to fill a slot I created a subsetted dataframe (subpop). And every time I'd used up the people from a race-gender, ... | python|pandas|random | 0 |
18,560 | 73,166,297 | How to merge two dataframes based on cell value within other dataframe? | <p>My first dataframe is something like this:</p>
<pre><code>df1=pd.DataFrame({'ID':['514401202200037121','514401202200037334','514401202200037010','514401202200037210','514401202200036890'], 'ModEff':['0.207','0.205','0.211','0.204','0.206'], 'Rs':['0.297020','0.297250','0.296899','0.297111','0.297035'], 'Isc':['11.29... | <p>Please let me know if this works:</p>
<pre><code>pd.merge(df1, df2, on='ID')
</code></pre> | python|pandas | 0 |
18,561 | 72,874,580 | How to convert numpy array to a tensor in this case? | <p>I have used this code previously, and it worked fine, but I am trying to differentiate between two variables, male & female in this case. I have a .csv file of names that generally correspond to females and males. I am trying to run this model, but it is not able to convert the array to a to a tensor in this cas... | <p>You can convert <code>numpy</code> array into tensor using <code>tf.convert_to_tensor()</code>.
<br>
<strong>For example:</strong></p>
<pre><code>import numpy as np
a=np.array([1,2,3,4,5,5,])
type(a)
</code></pre>
<p>Output:</p>
<pre><code>numpy.ndarray
</code></pre>
<p>Converting <code>numpy</code> array to <code>t... | arrays|numpy|tensorflow|artificial-intelligence|google-colaboratory | 0 |
18,562 | 10,276,857 | ValueError: Unknown format code 'g' for object of type 'str' | <p>I am new to Python and I am trying to write a simple print function but I am getting a strange error. This is my code:</p>
<pre><code>#! /usr/bin/env python3.2
import numpy as np
a=np.arange(1,10,1)
print(a)
for i in a:
print(i)
print(type(i))
print("{0:<12g}".format(i))
</code></pre>
<p>The output... | <p>This is a <a href="http://projects.scipy.org/numpy/ticket/1675" rel="nofollow">known bug</a> and should be fixed in version 2.0. In the interim, you can use the old syntax <code>%f</code> that works.</p> | python|numpy | 2 |
18,563 | 70,646,328 | How to create a polar density plot having a list of angles values in degrees in (.txt) file | <p>I am trying to produce a density plot in polar coordinates if I have a list of angles amplitudes in degrees in a dihedrals.txt file:
for example:
359.262
13.174
352.603
334.395
351.922
8.914
354.485
340.591
15.376
351.65
21.108
338.342
9.592
359.583
13.285
354.237
22.613
6.483
0.542
336.274
12.243
12.563
346.091</p>... | <p>Here is one approach, which is heavily inspired by <a href="https://stackoverflow.com/a/31142319/4585963">this answer</a>.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
np.random.seed(0)
# get fake data for angles, measured in radians
angles = 2 * np.pi * np.... | python|numpy|matplotlib|plot | 0 |
18,564 | 70,647,743 | Pytorch Index Error ('index out of range in self'): How to Solve? | <p>I recently encountered a roadblock following a <a href="https://www.youtube.com/watch?v=YbKnsJQKazA&ab_channel=NicholasRenotte" rel="nofollow noreferrer">deep learning tutorial</a> on youtube (entire code can be found <a href="https://github.com/nicknochnack/Stock-and-Crypto-News-ScrapingSummarizationSentiment/b... | <p>Your article length might exceed the model max input length. Use:</p>
<pre><code>tokenizer.encode(article, return_tensors='pt', max_length=512, truncation=True)
</code></pre> | python|pytorch | 0 |
18,565 | 70,536,170 | Pandas groupby over consecutive duplicates | <p>Given a table,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>4</td... | <p>Unfortunately, the answers from eshirvana and wwnde doesn't seem to work for a long dataset. Inspired from answer of wwnde, I found a workaround,</p>
<pre><code># create a series referring to group of identicals
new=[]
i=-1
for item in df.Id:
if item !=seen:
i+=1
seen=items
new.append(i)
df['tem... | python|pandas|dataframe|group-by | 0 |
18,566 | 70,568,651 | How do I parse numbers with thousands separator in pandas read_csv? | <p>I have a CSV file with lines as follows:</p>
<p>"Dec 30, 2021","1,234.11","1,654.22","11,876.23","1,676,234"</p>
<p>I have learn from a previous <a href="https://stackoverflow.com/questions/70568436/parsing-date-in-pandas-read-csv/">post</a> that I can use:</p>
<pre>... | <p>Use <code>thousands</code> parameter.</p>
<pre><code>df = pd.read_csv("file.csv", parse_dates=['Date'], thousands=',')
</code></pre> | pandas|numpy | 3 |
18,567 | 70,497,435 | Fillna is not working in pandas DataFrame | <p>I have a DataFrame where some columns have NaNs values, but when I try to replace it by zero values with fillna(), It doesn't work.</p>
<pre><code>print(df_sample[["Cantidad_GofrePack_lag8_rol7_med", 'Cantidad_AdultoGeneral_lag8_rol7_med']].head(5))
Cantidad_GofrePack_lag8_rol7_med Cantidad_AdultoGene... | <p>It looks like <code>inplace=True</code> cannot be used for only a part of the DataFrame, like on the example, where only a few columns are gived to the <code>fillna()</code>, because it creates a copy but only of this part, not for the whole DataFrame, where the NaN remain.</p>
<p>It works properly in this way:</p>
... | python|pandas|dataframe | 0 |
18,568 | 42,818,670 | Pandas dataframe average calculation | <p>I have a dataframe that I would like to compute the average across columns. I have the following dataframe:</p>
<p><a href="https://i.stack.imgur.com/GOJVj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GOJVj.png" alt="Dataframe"></a></p>
<p>Column 'A' repeats but not column 'B'. I would like... | <p>You can use groupby and mean()</p>
<pre><code>df.groupby('A').B.mean()
</code></pre>
<p>As @fuglede mentioned</p>
<pre><code>df.groupby('A').mean()
</code></pre>
<p>would work as well as there is only column B left for aggregation.
Either way you get</p>
<pre><code>A
1 6.25
2 6.50
3 4.75
</code></pre> | python|pandas|jupyter-notebook | 2 |
18,569 | 42,840,195 | Convolution of two fft function | <p>For convolution theorem F(x.y) = F(x)*F(y) </p>
<p>However after implement it on python</p>
<pre><code>x = np.array([0,0,0,0,1, 2, 3, 4, 0 ,0,0,0])
y = np.array([0,0,0,0,-3, 5, -4, 0, 0, 0,0,0])
xy = x*y
inverse_fft_xy = np.fft.ifft(np.convolve(np.fft.fft(x),np.fft.fft(y)))
</code></pre>
<p>Will yield</p>
<pre>... | <p>The time-domain multiplication is actually in terms of a <strong>circular</strong> convolution in the frequency domain, as given on <a href="https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Convolution_theorem_duality" rel="nofollow noreferrer">wikipedia</a>:</p>
<p><a href="https://i.stack.imgur.com/7BwKp.... | python|numpy|fft | 3 |
18,570 | 42,783,862 | Did tensorflow at any point change 'tensorflow.sub' into 'tensorflow.subtract'? | <p>I was testing some code I was given and got an error saying: </p>
<pre><code>AttributeError: 'module' object has no attribute 'sub'
</code></pre>
<p>The module referred to is TensorFlow. To investigate this error I started looking into the TensorFlow source code and found a function 'tensorflow.subtract'. Replaci... | <p>The TensorFlow 1.0 release contained multiple breaking changes to the API, including the renaming of <code>tf.sub</code> to <code>tf.subtract</code> (likewise, <code>tf.mul</code> was renamed to <code>tf.multiply</code> et cetera). Comprehensive lists of all changes can be found here:</p>
<p><a href="https://www.te... | tensorflow | 5 |
18,571 | 25,276,965 | Initialising a vector field in numpy | <p>I'd like to initialize a numpy array to represent a two-dimensional vector field on a 100 x 100 grid of points defined by:</p>
<pre><code>import numpy as np
dx = dy = 0.1
nx = ny = 100
x, y = np.meshgrid(np.arange(0,nx*dx,dx), np.arange(0,ny*dy,dy))
</code></pre>
<p>The field is a constant-speed circulation about... | <p>From your initial setup:</p>
<pre><code>import numpy as np
dx = dy = 0.1
nx = ny = 100
x, y = np.meshgrid(np.arange(0, nx * dx, dx),
np.arange(0, ny * dy, dy))
cx = cy = 5
s = 2
</code></pre>
<p>You could compute <code>v</code> like this:</p>
<pre><code>rx, ry = y - cx, x - cy
r = np.hypot(rx,... | python|arrays|numpy|vector|vectorization | 0 |
18,572 | 25,430,866 | scipy sparse matrices and cython | <p>I need to perform a set of operations on a scipy sparse matrix in a <code>Cython</code> method.</p>
<p>To efficiently apply these I need access to <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html#scipy.sparse.lil_matrix" rel="nofollow"><code>lil_matrix</code></a> representat... | <p>The example below iterates over a <code>lil_matrix</code> and calculates the sum for each row. </p>
<p>Note I am doing no declarations and even though it is extremely fast <a href="http://docs.cython.org/src/reference/language_basics.html#for-loops" rel="nofollow">because Cython is already optimized for built-in ty... | python|numpy|scipy|cython|sparse-matrix | 5 |
18,573 | 30,511,543 | Which would be an efficient way to work with an array of polynomials? | <p>I have a function wich given two polynomials, p and q, calculates the integral of p/q between the real numbers a and b. The funcion I have is$\phi$: </p>
<pre><code>import numpy as np
def integrate_pdivq(a, b, P, Q, r):
"""
Calculates the definite integral of P(x)/Q(x) between a and b, assuming gr P<gr Q and th... | <p>I just demonstrated in another question (I think asked by you) how the logic of <code>polyder</code> can be applied to a 2d array of coefficients. Based on a quick glance at the code for <code>polyval</code> it should be just as easy to apply that to a 2d array of coefficients.</p>
<p>The core of `polyval' is:</p>... | arrays|numpy | 0 |
18,574 | 30,627,495 | How to filter a pandas DataFrame for a certain column value and only return columns that do not have NAN? | <p>Example data:</p>
<pre><code>In [42]:
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'])
Out[42]:
year state pop debt
0 2000 Ohio 1.5 NaN
1 2001 O... | <pre><code>dt[dt['year']==2001].dropna(axis=1)
</code></pre> | python|pandas|data-analysis | 1 |
18,575 | 30,580,155 | distance in 3D binary array to nearest point of other type | <p>I have a 3D numpy array consisting of 1's and zeros defining open versus filled space in a porous solid (it's currently a numpy Int64 array). I want to determine the euclidian distance from each of the "1" points (voxels) to its nearest zero point. Is there a simple way to do this? </p> | <p>What you are asking for is the <a href="http://en.wikipedia.org/wiki/Distance_transform" rel="nofollow">distance transform</a>, which you can compute using scipy's <code>ndimage</code> package and its <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.morphology.distance_transform_edt.html" r... | python|numpy|euclidean-distance | 4 |
18,576 | 30,685,083 | Split text in a column into three columns | <p>This question is a follow up to <a href="https://stackoverflow.com/a/21032532/2423246">Pietro's fantastic answer</a> on how to split a column into multiple columns. My goal is to take a column from an existing data frame, split it on a space, and then take the first three/four split values and place each in a partic... | <p>Assuming that state and zip are always present and contain valid data, one method to solve this problem is to first split your string. The state and zip are simply the second to last and last columns, respectively. I've used a list comprehension to extract them from <code>city_state_zip</code>. To extract the city... | python|regex|pandas | 1 |
18,577 | 39,043,282 | How to get pool3 features of Inception v3 model using Keras? | <p>Using Tensorflow, I get a 2048 dimensional vector as the output of the pool3 layer. However, using Keras's include_top=False gives a 8,8,2048 dimensional vector. How do I get that same vector which I get using Tensorflow's pool3 output layer?</p> | <p>Let's look at the <code>pool_3</code> layer in TensorBoard.</p>
<p><a href="https://i.stack.imgur.com/AXD8O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AXD8O.png" alt=""></a></p>
<p>It seems that the layer Keras returns is actually the <code>mixed_10</code> layer output.</p>
<p>To get the 2... | tensorflow|keras | 1 |
18,578 | 39,211,791 | Using pre-trained word embeddings in tensorflow's seq2seq function | <p>I am building a seq2seq model using functions in tensorflow's <code>seq2seq.py</code>, where they have a function like this:</p>
<pre><code>embedding_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size, output... | <p>There is no parameter you just hand over. Read in your embeddings (make sure vocabulary IDs match). Then, once you initialized all variables, find the embedding tensor (iterate through tf.all_variables to find the name). Then use tf.assign to overwrite the randomly initialized embeddings there with your embeddings.<... | python|machine-learning|tensorflow|recurrent-neural-network|lstm | 1 |
18,579 | 39,412,829 | pandas.read_html not support decimal comma | <p>I was reading an xlm file using <code>pandas.read_html</code> and works almost perfect, the problem is that the file has commas as decimal separators instead of dots (the default in <code>read_html</code>). </p>
<p>I could easily replace the commas by dots in one file, but i have almost 200 files with that configur... | <p>This did not start working for me until I used both decimal=',' and thousands='.'</p>
<p>Pandas version: 0.23.4</p>
<p>So try to use both decimal and thousands:
i.e.:
<code>pd.read_html(io="http://example.com", decimal=',', thousands='.')</code></p>
<p>Before I would only use decimal=',' and the number columns w... | python|pandas|decimal|xlm | 21 |
18,580 | 28,895,894 | How to quickly determine if a matrix is a permutation matrix | <p>How to quickly determine if a <strong>square logical matrix</strong> is a permutation matrix? For instance,</p>
<p><img src="https://i.stack.imgur.com/Zb9f8.gif" alt="enter image description here"></p>
<p>is <strong>not</strong> a permutation matrix since the 3rd row have 2 entries 1.</p>
<p>PS: A <a href="http:/... | <p>Here's a simple non-numpy solution that assumes that the matrix is a list of lists and that it only contains integers 0 or 1. It also functions correctly if the matrix contains Booleans.</p>
<pre><code>def is_perm_matrix(m):
#Check rows
if all(sum(row) == 1 for row in m):
#Check columns
retu... | python|numpy|matrix|linear-algebra | 4 |
18,581 | 23,660,275 | How to return groupby values from a Pandas dataFrame? | <p>I have a dataFrame I have summarized some data in and I am graphing it. I want to get the values from the groupby field to use as the labels in the graph. </p>
<p>Here is my summarized dataFrame:</p>
<pre><code>code_values = code_graph.groupby(['code_desc']).agg({'product_id': pd.Series.nunique })
</code></pre>
<... | <p>From the aggregated values, you should be able to use:</p>
<pre><code>code_values.index
</code></pre>
<p>You can also get the keys of the groups dictionary of the groupby object, like:</p>
<pre><code>grouped = code_graph.groupby(['code_desc'])
code_desc = grouped.groups.keys()
</code></pre> | python|matplotlib|pandas | 2 |
18,582 | 15,075,715 | How do I fill two (or more) numpy arrays from a single iterable of tuples? | <p>The actual problem I have is that I want to store a long sorted list of <code>(float, str)</code> tuples in RAM. A plain list doesn't fit in my 4Gb RAM, so I thought I could use two <code>numpy.ndarray</code>s.</p>
<p>The source of the data is an iterable of 2-tuples. <code>numpy</code> has a <code>fromiter</code> ... | <p>Perhaps build a single, structured array using <code>np.fromiter</code>:</p>
<pre><code>import numpy as np
def gendata():
# You, of course, have a different gendata...
for i in xrange(N):
yield (np.random.random(), str(i))
N = 100
arr = np.fromiter(gendata(), dtype='<f8,|S20')
</code></pre>
... | python|arrays|numpy|iteration | 8 |
18,583 | 15,001,237 | How to apply "first" and "last" functions to columns while using group by in pandas? | <p>I have a data frame and I would like to group it by a particular column (or, in other words, by values from a particular column). I can do it in the following way: <code>grouped = df.groupby(['ColumnName'])</code>.</p>
<p>I imagine the result of this operation as a table in which some cells can contain sets of valu... | <p>I think the issue is that there are two different <code>first</code> methods which share a name but act differently, one is for <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#splitting-an-object-into-groups" rel="noreferrer">groupby objects</a> and <a href="http://pandas.pydata.org/pandas-docs/dev... | python|pandas|group-by | 64 |
18,584 | 13,318,504 | Python List. Finding the maximum row with all elements not zero | <p>I have a python list which looks a little like this:</p>
<pre><code>[[0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,90,1,9999,0,0,0,0,0,0,0,00,0],
[0,0,0,0,0,0,0,0,0,0,0,0,00,0],[0,0,90,1,9999,1,2,0,0,9999,0,0,00,0].....till about 30 rows]
</code></pre>
<p>I need to find the maximum row from this list which has a 9999 or in o... | <p>Do you want:</p>
<pre><code>idx,row = max(enumerate(lst),key=lambda r: ( sum(r[1])==0, r[0] ) )
</code></pre>
<p>where <code>lst</code> is your list.</p>
<p>Or do you want:</p>
<pre><code>next(x for x in reversed(lst) if sum(x) != 0)
</code></pre> | python|list|numpy|max | 2 |
18,585 | 62,176,879 | Why are Pandas and Seaborn producing different KDE Plot for same data? | <p>I am trying to have a look at the distribution of a variable with the following values..</p>
<pre><code>+-------+-------+
| Value | Count |
+-------+-------+
| 0.0 | 355 |
| 1.0 | 935 |
| 2.0 | 1 |
| 3.0 | 2 |
| 4.0 | 1 |
+-------+-------+
</code></pre>
<p>The table continues with values ... | <p>What's going wrong is that the <a href="https://en.wikipedia.org/wiki/Kernel_density_estimation" rel="nofollow noreferrer">kde</a> is primarily meant for continuous data, while you seem to be working with discrete data. An important parameter is the <code>bandwidth</code>: the smaller it is, the closer the curve fi... | python|pandas|seaborn|kde-plasma | 2 |
18,586 | 62,425,860 | What should be noticed when using numpy.arange method? | <p>I encountered a question when I wanted to generate a numpy array using numpy.arange.
For example, I want to generate an array that contains 3862 elements:</p>
<pre><code>array1=numpy.arange(3.5678,3.5678+3862*0.0001,0.0001)
</code></pre>
<p>But the shape of array1 is <code>(3863,)</code>. And what made me more co... | <p>According to <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer">numpy doc</a>: </p>
<p><em>For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out bein... | python|numpy | 0 |
18,587 | 62,284,746 | Filling in Dataframe given one column and one row as coordinates | <p>If I have a partially empty dataframe such as:</p>
<pre><code>col1 col2 col3 col4 col5
4
3
2
1
4 3 2 1 0
</code></pre>
<p>I'd like to fill in the empty cells with a list as coordinat... | <p>Try with <code>bfill</code> with <code>axis</code>=0 and 1 , then add it up and <code>fillna</code> </p>
<pre><code>df = df.fillna(df.bfill().applymap(lambda x : [x]) + df.bfill(1).applymap(lambda x : [x]))
Out[431]:
col1 col2 col3 col4 col5
0 [4.0, 4.0] [3.0, 4.0] [2.0, 4.0] [1.... | python|pandas|dataframe | 1 |
18,588 | 62,179,971 | TensorFlow lite speech recognition with custom dataset is not working | <p>I am using the TensorFlow lite example which they are given for speech recognition <a href="https://github.com/tensorflow/examples/tree/master/lite/examples/speech_commands/android" rel="nofollow noreferrer">here</a>. I want to use my own custom dataset and train the model and use it in there example, but when i am ... | <p>Try to adjust the bitrate. Use <code>ffmpeg -i <file></code> to obtain the bitrate of your wave files. Then, when execute the training script, use the <code>--sample_rate</code> parameter.</p>
<p>For example my files have a sample rate of 44 kHz, then I use:</p>
<pre><code>python tensorflow/examples/speech_com... | python|tensorflow|machine-learning|speech-recognition|tensorflow-lite | 1 |
18,589 | 62,184,909 | Iterating a list to get the three highest numbers of each group | <p>I am working with US Census data. I am trying to display the three most populated counties per every state. I have been working for few days on the code but can't crack it. The only thing I need to work out is a way to iterate over all of the states to find the three highest numbers.</p>
<p>Here's my code so far:</... | <p>You can do <code>sort_values</code> with <code>groupby</code> + <code>head</code></p>
<pre><code>cdf= cdf.sort_values('CENSUS2010POP',ascending=False).groupby('STNAME').head(3)
</code></pre> | python|pandas | 0 |
18,590 | 62,442,269 | Pandas group by and sort by columns and need to add comma separated entries | <p>we have below Pandas Dataframe </p>
<p><a href="https://i.stack.imgur.com/JnaV7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JnaV7.png" alt="enter image description here"></a></p>
<p>Desired output:</p>
<p><a href="https://i.stack.imgur.com/8sQ9a.png" rel="nofollow noreferrer"><img src="http... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a> before <code>groupby</code> and if need same order like original by <code>data</code> column add <a href="http://pandas.pydata.org/pandas-docs/sta... | python|python-3.x|pandas|pandas-groupby | 2 |
18,591 | 62,238,044 | Is there a Pandas function to highlight a week's 10 lowest values in a time series? | <p>Rookie here so please excuse my question format: </p>
<p>I got an event time series dataset for two months (columns for "date/time" and "# of events", each row representing an hour).</p>
<p>I would like to highlight the 10 hours with the lowest numbers of events for each week. Is there a specific Pandas function f... | <p>Let's say you have a dataframe <code>df</code> with column <code>col</code> as well as a <code>datetime</code> column.</p>
<p>You can simply sort the column with</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col' : [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
'datetime' : ['2019-01-01 00:00:0... | python|pandas|jupyter | 0 |
18,592 | 62,137,813 | Is there a way to solve "DataError: No numeric types to aggregate" because of having "nan" values in the column? | <p>I have a Dataframe like this</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["john","peter","john","peter","peter"],
"height": ["6","5","4","nan","8"],
})
df
</code></pre>
<p>I want to do GROUPBY name and AGG the height for mean </p>
<pre><code>df2=df.groupby('name')
df3... | <p>You need to use sum() function</p>
<pre><code>df2=df.groupby('name').height.sum()
</code></pre>
<p>I hope you find it helpful</p> | python|pandas|pandas-groupby | 0 |
18,593 | 62,213,028 | R fuzzyjoin in python | <p><code>fuzzyjoin</code> is an R library that allows to do joins based on functions, instead of equality of ids. I am wondering if the same thing can be done in Python. For instance, I might want to do a join based on two inequalities. I have the following DataFrames:</p>
<pre><code>import pandas as pd
df = pd.DataFr... | <p>Yes it is possible to do the same in python. It can be done in the following manner - </p>
<pre><code>import pandas as pd
df = pd.DataFrame(dict(
x=range(10)
))
other_df = pd.DataFrame(dict(
min_x=[0, 6],
max_x=[5, 10],
category=['a', 'b']
))
df['category'] = df['x'].apply(lambda x: other_df.loc[(... | python|pandas | 1 |
18,594 | 62,345,442 | Pandas: Compare Datetime column on Datetime arrays | <p>I'm learning Pandas, specially now with Datetimes. I'm searching for days a way to select rows by their Datetime column. If the Datetime column values are on a range between the array <code>spacex</code> and <code>clonx</code> values.</p>
<p>The two arrays:</p>
<pre><code>clonx = array(['2019-08-14T23:32:00.000000... | <p>Not a better solution though:</p>
<pre><code>datelist = []
for i in range(len(first.datim)):
for j in range(len(clonx)):
if (spacex[j]<=first.datim[i]) and (first.datim[i]<=clonx[j]):
datelist.append(first.datim[i])
print(set(datelist))
</code></pre>
<hr>
<pre><code>{Timestamp('2019-... | python|pandas|datetime|data-science | 0 |
18,595 | 62,239,509 | How to simply check a previous row in pandas | <p>I'm starting to belive that pandas dataframes are much less intuitive to handle than Excel, but I'm not giving up yet! </p>
<p>So, I'm <strong>JUST</strong> trying to check data in the same column but in (various) previous rows using the .shift() method. I'm using the following DF as an example since the original i... | <p>If you are checking the previous row, you can use <code>np.where</code> along with <code>shift</code>:
Modified your df a little:</p>
<pre><code>df = pd.DataFrame([
["one", 1],
["two", 2],
["three", 3],
["three", 3],
[np.nan, np.nan],
["three", 3]
], columns=["Name", "Number"]
)
df['New col... | python|pandas|dataframe | 3 |
18,596 | 62,343,138 | Pandas delete rows with Groupby two columns using quartile | <p>Good morning all, </p>
<p>I have a problem, I want to delete the lines using a condition on percentile and groupby, example:</p>
<p>for each x, y .. in the column key and for each group of iden a, b, c .. it will delete the elements which are in the first pencetile/quantile and the last one using the function: Min... | <p>Use:</p>
<pre><code>g = df.groupby(['key', 'iden'])['val']
m = df['val'].between(g.transform('quantile', 0.1), g.transform('quantile', 0.9))
df = df[m]
</code></pre>
<p>Or use:</p>
<pre><code>m = (
df.groupby(['key', 'iden'])['val']
.transform(lambda s: s.between(s.quantile(0.1), s.quantile(0.9)))
)
df = ... | python|pandas|percentile | 2 |
18,597 | 62,375,615 | Python method (static method) which iterates through several methods based on the list of tags & gives output one at a time | <p>I am trying to take the output of a python method. But the output is not straight forward. The current python method have some tags & values where it iterates through the tags & corresponding functions & get the value as output. I would like to take the output as a list or DataFrame. But output is coming... | <pre class="lang-py prettyprint-override"><code># I'm starting with an assumption that you have lists of tags and values.
# However, if you need to build the lists from your method calls, e.g.
# mylist = list()
# mylist.append(myfunc())
# the code below is for 10 tags but scale as needed
# there are many ways to accom... | python|pandas|list|dataframe|static-methods | 0 |
18,598 | 62,371,391 | Get max count of dataframe rows with respect to 2 groupings | <p>I have a dataframe (df) and wish to obtain the largest counts of "NCT_ID" (not unique values only, but every occurrence) with respect to columns "COUNTRY" and "CONDITION". So that for each country in "COUNTRY", I will have the n (set n = 2 for simplicity) most common conditions in "CONDITION", sorted by largest.
The... | <pre><code>new_df = df.groupby(['CONDITION', 'COUNTRY']).apply(len).reset_index(name='COUNTS')
new_df.sort_values(by='COUNTS', axis=0, inplace=True, ascending=False)
</code></pre> | python|python-3.x|pandas|dataframe|pandas-groupby | 1 |
18,599 | 48,348,134 | Tensorflow: Naming variables | <p>I'm wondering where to put the following function and how to name the variables "r" and "p":</p>
<pre class="lang-py prettyprint-override"><code>def fit_mme(sample_data, name=None):
"""
Calculates the Maximum-of-Momentum Estimator of NB(r, p) for a given NxM matrix `sample_data`
:param sample_d... | <p>you can either do:</p>
<pre><code>r = tf.multiply(r_by_mean, mean, name = 'r')
</code></pre>
<p>and</p>
<pre><code>p = tf.divide(1, tf.add(r_by_mean, 1), name = 'p')
</code></pre>
<p>or you can (as suggested in <a href="https://stackoverflow.com/questions/47030369">Name the output of an expression in Tensorflow<... | python|tensorflow|naming-conventions | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.