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 |
|---|---|---|---|---|---|---|
350,600 | 53,011,418 | first column in dataframe lost after grouping | <p>Please excuse me if this question is too n00bish, I am brand new to Python and need to use it for work, which unfortunately means diving into higher level stuff without first understanding the basics...</p>
<p>I have a massive CSV with text transcripts which I read into a pandas dataframe. These transcripts are bro... | <p>The groupby will return groupby-ed column as the index. Looking at your code this is what I see.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'ID':[1,1,1,2],
'TEXT':['This is the beginning of a convo', 'heres the
middle', 'heres the end of the convo', 'this is ... | python|pandas|dataframe|nltk|primary-key | 1 |
350,601 | 53,020,764 | Efficiently return the index of the first value satisfying condition in array | <p>I need to find the index of the first value in a 1d NumPy array, or Pandas numeric series, satisfying a condition. The array is large and the index may be near the start <em>or</em> end of the array, <em>or</em> the condition may not be met at all. I can't tell in advance which is more likely. If the condition is no... | <h3><code>numba</code></h3>
<p>With <a href="http://numba.pydata.org/" rel="noreferrer"><code>numba</code></a> it's possible to optimise <em>both</em> scenarios. Syntactically, you need only construct a function with a simple <code>for</code> loop:</p>
<pre><code>from numba import njit
@njit
def get_first_index_nb(A... | python|arrays|pandas|performance|numpy | 7 |
350,602 | 52,975,301 | Prometheus for Tensorflow Serving | <p>What are the steps to use the Prometheus exporter for Tensorflow serving?
According to 1.11 TF serving supports prometheus metrics:
<a href="https://github.com/tensorflow/serving/releases/tag/1.11.0" rel="nofollow noreferrer">https://github.com/tensorflow/serving/releases/tag/1.11.0</a></p>
<p>I'm starting a docker... | <p><a href="https://github.com/tensorflow/serving/commit/021efbd3281aa815cab0b35eab6d6d25249c12d4" rel="noreferrer">According to the release notes you linked to</a> TensorFlow exports Prometheus metrics at <code>/monitoring/prometheus/metrics</code> (as opposed to Prometheus' default <code>/metrics</code>). So at the v... | docker|tensorflow|prometheus|tensorflow-serving | 5 |
350,603 | 53,108,867 | Pandas: Joining dataframes from different sources | <p>Have the following datasets from two different sources i.e. Oracle and MySQL: </p>
<p>DF1 (Oracle):</p>
<pre><code>A B C
1122 8827
822 8282 6622
727 72 1183
91 5092
992 113 7281
</code></pre>
<p>DF2 (MySQL):</p>
<pre><code>E F G
8827 6363
822 5526 9393
727 9... | <p>Your problem is complicated by nulls in the join key. You try some logic like this to achieve your result, or create a different key for joins that doesn't have nulls.</p>
<pre><code>DF11 = DF1.set_index(DF1['A'].fillna(DF1.groupby('A').cumcount().astype(str)+'A'))
DF22 = DF2.set_index(DF2['E'].fillna(DF2.groupby(... | sql|pandas|dataframe | 2 |
350,604 | 53,074,758 | Calculating Mean Squared Error through Matrix Arithmetic on Numpy Matrices of Binary Images | <p>I have 2 binary images, one is a ground truth, and one is an image segmentation that I produced.</p>
<p>I am trying to calculate the mean squared distance ...</p>
<p><a href="https://i.stack.imgur.com/IZMeG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IZMeG.png" alt="enter image description h... | <p>So if I understand your formula and code correctly, you have one (binary) image <code>B</code> and a (ground truth) image <code>G</code>. "Points" are defined by the pixel positions where either image has a <code>True</code> (or at least nonzero) value. From your <code>bitwise_xor</code> I deduce that both images ha... | python|arrays|numpy|image-processing|image-segmentation | 3 |
350,605 | 53,311,885 | Keras' fit_generator() for binary classification predictions always 50% | <p>I have set up a model to train on classifying whether an image is a certain video game or not. I <code>pre-scaled</code> my images into <code>250x250</code> pixels and have them separated into two folders (the two binary classes) labelled <code>0</code> and <code>1</code>. The amount of both classes are within <code... | <p>The problem is that you are using <code>softmax</code> on a Dense layer with one unit. Softmax function normalizes its input such that the sum of its elements becomes equal to one. So if it has one unit, then the output would be always 1. Instead, for binary classification you need to use <code>sigmoid</code> functi... | python|tensorflow|machine-learning|keras|classification | 0 |
350,606 | 53,241,375 | how to extract a column in a for loop out of a dataframe from multiple list glob created by glob | <p>I am a beginner in Python and just started with machine learning. I can not figure out how to extract a column out of df_test.</p>
<p>I would like to extract column 280 (this is the target y for a linearregression, y_test)</p>
<p>I used glob, to combine multiple cvs files, which are the test set for the regression... | <p>You can use pandas .iloc for this. </p>
<pre><code>x_test = new_df.iloc[:, :280]
y_test = new_df.iloc[:, 280]
</code></pre>
<p>But in your code, you still first have to fill new_df with actual data... I would append all your different files to a list of DataFrames and then use concat to combine the list of DataFra... | python-3.x|pandas|glob | 0 |
350,607 | 53,073,080 | Get the rolling sum of values of id from two different column? | <p>df:</p>
<pre><code>id1 id2 value1 value2
-----------------------------------
a b 10 5
c a 5 10
b c 0 0
c d 2 1
d a 10 20
a c 5 10
</code></pre>
<p>get sum of values associated with id 'a... | <p>Here's one way to do it</p>
<pre><code>i = df.filter(like='id')
v = df.filter(like='va')
x, y = np.where(i == 'a')
df.iloc[x].assign(A=v.values[x, y]).assign(Roll=lambda d: d.A.rolling(2).sum())
id1 id2 value1 value2 A Roll
0 a b 10 5 10 NaN
1 c a 5 10 10 20.0
4 d a ... | python|pandas|dataframe|pandas-groupby|data-manipulation | 5 |
350,608 | 53,003,900 | Randomly selecting a % of elements in a string and changing the value | <p>I have an array of string values and need loop through them, to randomly replace 5% of the elements in each, and flip them to 0 if they are 1, and flip them to 1 if they are 0.</p>
<p>I have a array of string values that looks like this:</p>
<pre><code>['100110000001000000000111011000100010001101111011001001011000... | <p>Try this loop:</p>
<pre><code>for idx,i in enumerate(l):
y=list(i)
for x in random.sample(range(len(i)),(len(i)*5)//100):
y[x]=str(abs(int(y[x])-1))
l[idx]=''.join(y)
</code></pre>
<p>Does flip from one to zero, and vice versa, and only 5% of them.</p> | python|pandas | 1 |
350,609 | 53,274,696 | Replace value in existing column .csv pandas | <p>Let's say I have a csv where a sample row looks like: <code>[' ', 1, 2, 3, 4, 5]</code> where <code></code> indicates an empty cell. I want to iterate through all of the rows in the .csv and replace all of the values in the first column for each row with another value, i.e. <code>[100, 1, 2, 3, 4, 5]</code>. How cou... | <p>You don't need a for loop while using pandas and numpy, </p>
<p>Just an example Below where we have <code>b</code> and <code>c</code> are empty which is been replaced by <code>replace</code> method:</p>
<pre><code> import pandas as pd
import numpy as np
>>> df
0
a 1
b
c
>>> df.replace('',... | python|pandas|csv | 2 |
350,610 | 53,123,026 | Finding all the possible combinations of a Dataframe | <p>I have a data like this:</p>
<pre><code> Price Web Destinations Airport Flight Afterflight Global
0 1 1 0 0 0 0 0
1 1 1 1 1 1 1 1
2 1 1 1 1 0 1 1
3 0 ... | <p>You can use <code>GroupBy</code> + <code>size</code>:</p>
<pre><code>res = df.groupby(df.columns[:-1].tolist()).size().rename('Count').reset_index()
print(res)
Price Web Destinations Airport Flight Afterflight Count
0 0 0 0 0 0 0 1
1 0 1 ... | python|pandas|counter|pandas-groupby | 3 |
350,611 | 53,003,801 | Using bins in pandas data frame | <p>I am working on a data frame which has 4 columns in total, i want to bin each column of that data frame iteratively in 8 equal parts. The bin number should be assigned to the data in a separate column for each column.
The code should work even if any different data frame is provided with different column names.
Here... | <p>I would use a couple of functions from numpy, namely <code>np.linspace</code> to make the bin boundaries and <code>np.digitize</code> to put the dataframe's values into bins:</p>
<pre><code>import numpy as np
def binner(df,num_bins):
for c in df.columns:
cbins = np.linspace(min(df[c]),max(df[c]),num_bin... | python|pandas|dataframe|data-science|data-cleaning | 0 |
350,612 | 53,196,739 | how to shorten a code to generate a pandas dataframe? | <p>I want to create a pandas dataframe <code>df1</code> with specific column name from a column <code>col</code> of another dataframe <code>df</code> and do a merge with another dataframe <code>df2</code>.</p>
<pre><code>df
Name House
0 John London
1 John London
2 John London
3 Tom New York
4 ... | <p>Are you just looking for a better way to do what you're doing? This is what I generally do when I need to filter a dataframe.</p>
<pre><code>import pandas as pd
names = set(df['Name'].values)
smaller_df = df2[df2['Col'].isin(names)]
</code></pre>
<p>Edited because I didn't understand OP's question.</p> | python|pandas | -1 |
350,613 | 53,158,120 | Find all rows which have different values in the columns of a Pandas DataFrame (time series) | <p>Let's assume I have a pandas DataFrame in Python which shows the <strong>name of the business unit leader for different units over time</strong>. It could look something like <a href="https://i.stack.imgur.com/zrKaC.jpg" rel="nofollow noreferrer">this</a>
and can be recreated like:</p>
<pre><code>import pandas as p... | <p>You can check for equality with the first series, test all values are <code>True</code>, then take the negative:</p>
<pre><code>res = df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
print(res)
Boss_February Boss_January Boss_March
1 Emilia Lena Lena
2 Max Max Mark
3 ... | python|pandas|duplicates | 2 |
350,614 | 65,901,303 | Tensorflow: How to save a 'DNNRegressorV2' model? python | <p>I run into problem when trying to save a trained model, I've tried:</p>
<pre><code>model.save('~/Desktop/models/')
</code></pre>
<p>but it gave me an error <code>AttributeError: 'DNNRegressorV2' object has no attribute 'save'</code></p>
<p>I have also tried:</p>
<pre><code>tf.saved_model.save(model, mobilenet_save_p... | <p>To save an Estimator you need to create a serving_input_receiver. This function builds a part of a tf.Graph that parses the raw data received by the SavedModel.</p>
<p>The tf.estimator.export module contains functions to help build these receivers.</p>
<p>The following code builds a receiver, based on the feature_co... | python|tensorflow|model | 0 |
350,615 | 65,669,016 | How to make hour visible in Pandas to_datetime? | <p>This is the given dataframe ;</p>
<pre><code>>>> df3
15 Minutes LINK NAME secState
0 2021-01-11 00:00 hbretmask_sec10 0
1 2021-01-11 00:00 hgretmask_sec10 0
2 2021-01-11 00:00 hlretmask_sec10 0
3 2021-01-11 00:00 hmretmask_sec10 0
4 20... | <p>to show hour, you would need to use 'strftime':</p>
<pre><code>df['Minutes'] = df['Minutes'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M'))
</code></pre> | python|pandas|datetime|strtotime | 1 |
350,616 | 65,626,330 | tensorflow multiplication between 2 3d tensors | <p>I have two tensors:</p>
<pre><code>A.shape = (3000, 1, 5)
B.shape = (3000, 5, 259)
</code></pre>
<p>I want to get a result tensor whose shape is (3000, 1, 259).</p>
<p>So intuitively I am multiplying every (1, 5) matrix in A with its corresponding (5, 259) matrix in B to get 3000 (1, 259) matrices.</p>
<p>Thanks in ... | <p>I think I get it to work.</p>
<p>It is as simple as:</p>
<pre><code>tf.matmul(A, B)
</code></pre> | python|tensorflow|keras | 0 |
350,617 | 65,758,677 | Converting both a dictionary's keys and values to columns in a pandas dataframe efficiently | <p>I have a dictionary like so:</p>
<pre><code>dict1 = {k1:v1,k2:v2,k3:v3}
</code></pre>
<p>and I want to turn this dictionary into a dataframe. I have previously seen other questions here using <code>pd.Series(dict1)</code>, and this yields a DataFrame like so:</p>
<pre><code> Index col1
k1 v1
k2 v2
... | <p>You can get the items of the <code>dict</code> and flatten it.<br />
I've used <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow noreferrer"><code>itertools.chain</code></a> to flatten the <code>dict</code>.<br />
Then take the transpose of the resulting dataframe created from ... | python|json|pandas|dataframe|dictionary | 1 |
350,618 | 65,634,289 | iterate through unique value combinations to create multiple train test splits | <p>I am seeking to run multiple passes of a model while splitting my data based on year. I have data in a pandas dataframe ranging from 1/1/2015 to 12/31/2019 in this format:</p>
<pre><code>IN: df.date.dt.year.value_counts().keys()
OUT: Int64Index([2019, 2018, 2017, 2016, 2015], dtype='int64')
</code></pre>
<p>I want t... | <p>You might need to work on the syntax because I don't have your dataset. Essentially this captures the possible combinations then finds the year that is not in the test years. dtest is returned as list of one element.</p>
<pre><code>from itertools import combinations
years = [2019, 2018, 2017, 2016, 2015]
combs = com... | python|pandas | 1 |
350,619 | 65,905,694 | pandas.MultiIndex: assign all elements in first level | <p>I have a dataframe with a multiindex, as per the following example:</p>
<pre><code>dates = pandas.date_range(datetime.date(2020,1,1), datetime.date(2020,1,4))
columns = ['a', 'b', 'c']
index = pandas.MultiIndex.from_product([dates,columns])
panel = pandas.DataFrame(index=index, columns=columns)
</code></pre>
<p>This... | <p>Try broadcasing on the values:</p>
<pre><code>a = df.to_numpy()
panel = pd.DataFrame((a[...,None] * a[:,None,:]).reshape(-1, df.shape[1]),
index=panel.index, columns=panel.columns)
</code></pre>
<p>Output:</p>
<pre><code> a b c
2020-01-01 a 0.292537 0.2305... | python|pandas|dataframe|multi-index | 1 |
350,620 | 65,803,690 | Apply scipy stats function as a layer in a Keras neural network | <p>I want to apply a scipy stats function as a layer in a Keras neural network, something like this:</p>
<pre class="lang-py prettyprint-override"><code>from scipy import stats
class BoxCox(layers.Layer):
def call(self, inputs):
return stats.boxcox(inputs)
# part of usage in model
x1 = layers.Dense(81)(x... | <p>Layer must support backpropagation of gradient. Only tensorflow function supporting it. You can not use other functions.</p> | python|tensorflow|keras|neural-network|statistics | 0 |
350,621 | 65,628,578 | Counting total number of occurrences in selected (multiple) columns in Pandas | <p>I would like to summarize occurrences of categorical values in multiple columns, and as a result have a number of times that specific categorical value appeared in multiple columns.</p>
<p>Here's my dataframe:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({'user_id': [1,2,3,4,5,6],
.... | <p>Apply <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer">value_counts</a> to each column and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html" rel="nofollow noreferrer">sum</a> along the second ax... | python|pandas|dataframe | 3 |
350,622 | 65,529,254 | Splitting column of array of type ['a', 'b'] into multiple column fails because of unequal lengths | <p>I have this issue that I cannot seem to get right. Whether it is because I missunderstand lists and arrays, I don't know. I have a dataframe consisting of data in this form:</p>
<pre><code> index artists Title language \
0 0 Carl Woitschach ['de', 'ger... | <p>First you need to <code>evaluate</code> the strings in the columns <code>Artist Name language</code> and <code>Title language</code> as python lists this can be done with the help of <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>literal_eval</code></a> from <co... | python-3.x|pandas | 3 |
350,623 | 65,734,186 | Dynamic filtering/ masking in Pandas | <p>I have a pandas data frame containing employee information like this:</p>
<pre><code>df=pd.DataFrame({
'Id':[1,2,3,4],
'Name':['Joe','Henry','Sam','Max'],
'Salary':[70000,80000,60000,90000],
'ManagerId':[3,4,np.nan,np.nan]
})
Id Name Salary ManagerId
0 1 Joe 70000 3.0
1 2 Hen... | <p>Idea is match <code>ManagerID</code> by <code>Salary</code> by <code>Id</code>, so possible compare for greater and filter:</p>
<pre><code>df = df[df['Salary'].gt(df['ManagerID'].map(df.set_index(['Id'])['Salary']))]
print (df)
Id Name Salary ManagerID
0 1 Joe 70000 3.0
</code></pre>
<p><strong>Deta... | python|pandas | 2 |
350,624 | 65,492,787 | Pandas - plotting user RFM | <p>Given the following DF of user RFM activity:</p>
<pre><code> uid R F M
0 1 10 1 5
1 1 2 2 10
2 1 4 3 1
3 1 5 4 10
4 2 10 1 3
5 2 1 2 10
6 2 1 3 4
</code></pre>
<blockquote>
<p>Recency: The time between the last purchase and today, represented by
the distance ... | <p>you can use matplotlib's <code>scatter()</code> with the <code>s=</code> argument to draw markers with an area proportional to the value in <code>M</code>. The rest is just tweaking the appearance of the plot.</p>
<pre class="lang-py prettyprint-override"><code>c = 'xkcd:dark grey'
fig, ax = plt.subplots()
ax.axis('... | python|pandas|plot|plotly|seaborn | 3 |
350,625 | 65,677,275 | hub.get_expected_image_size generates an error | <p>I am trying to determine the expected image size a tensorflow classifier model. From</p>
<p><a href="https://www.tensorflow.org/hub/tutorials/image_feature_vector" rel="nofollow noreferrer">https://www.tensorflow.org/hub/tutorials/image_feature_vector</a></p>
<p>this is accomplished by</p>
<pre><code> image_modul... | <p>hub.get_expected_image_size only works for some models in Hub.Module format that were exported in a certain way, this function will not work on TF2 SavedModels.</p> | python|tensorflow|tensorflow-hub | 2 |
350,626 | 65,582,498 | torch.nn.CrossEntropyLoss().ignore_index is crashing when importing transfomers library | <p>I am using <code>layoutlm</code> <a href="https://github.com/microsoft/unilm/tree/master/layoutlm" rel="nofollow noreferrer">github</a> which require <code>python 3.6</code>, <code>transformer 2.9.0</code>. I created an <code>conda</code> env:</p>
<pre><code>name: env_test
channels:
- defaults
- conda-f... | <p>It seems something was broken on <code>layoutlm</code> with <code>pytorch 1.4</code> <a href="https://github.com/microsoft/unilm/issues/181" rel="nofollow noreferrer">related issue</a>. Switching to pytorch 1.6 fix the issue with the core dump, and the <code>layoutlm</code> code run without any modification.</p> | python-3.x|segmentation-fault|pytorch|huggingface-transformers | 0 |
350,627 | 65,742,344 | Solving for rate to make NPV zero Python | <p>My solution so far (which does not work and gets stuck) which uses NPV formula for monthly cashflow and attempts to find the discount rate to make it zero:</p>
<pre><code>def goal_seek(target,cashflows,_threshold):
threshold = _threshold
lower = -10000
upper = 10000
solve = (lower + upper)/2
whil... | <p>I'm not sure if this is what you want.</p>
<p><code>np.npv()</code><br />
<a href="https://numpy.org/doc/stable/reference/generated/numpy.npv.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.npv.html</a><br />
<code>np.irr()</code><br />
<a href="https://numpy.org/doc/stable/ref... | python|numpy | 0 |
350,628 | 65,541,423 | How to iterate through a time frame? | <p>Okay so I have some S&P 500 minute data from a csv file. I am looking to iterate through a timestamp based on time. So far the code looks like this:</p>
<pre><code>import datetime as dt
import pandas as pd
d = pd.read_csv('/Volumes/Seagate Portable/usindex_2020_all_tickers_awvbxk9/SPX_2020_2020.txt')
d.columns =... | <p><code>in</code> is used to test for membership in a collection or to find substring within a string. You cannot use it to test for the time in a Timestamp.</p>
<p>If you want to use a <code>for</code> loop:</p>
<pre><code>for i in d.index:
if d.loc[i, 'Date'].time() == dt.time(16,0):
d.loc[i, 'Open'] == ... | python|pandas|datetime|indexing|time | 2 |
350,629 | 65,781,993 | Damping harmonic oscillation code with python | <p>I don't know that how make the code the three graph in damping harmonic oscillation model,
<code>[X - t(time)], [V(velocity) - t(time)], [a(acceleration) - t(time)]</code> graph</p>
<p>i can make the <code>[X - t(time)]</code> graph
but i don`t know how to make another graphs..</p>
<pre><code>import numpy as np
fr... | <p>Why can't you just take the derivative of X to get V and A?</p>
<pre><code>V = np.diff(X)
A = np.diff(V)
fig, (ax1, ax2, ax3) = plt.subplots(3)
fig.suptitle('Vertically stacked subplots')
ax1.plot(t, X)
ax2.plot(t[1:], V)
ax3.plot(t[2:], A)
plt.show()
</code></pre>
<p>Gives,</p>
<p><a href="https://i.stack.imgur.co... | python|arrays|numpy | 0 |
350,630 | 65,619,812 | dataframe with list of links to networkx digraph | <p>I have a dataframe for a collection of linked documents that I'd like to convert to a directed graph with edge weights <code>link_weight</code> and node attributes <code>doc_attribute</code>. What is an <em>efficient</em> way for this to be done? I've provided a small example here but actual data targeted for ~100... | <p>You could use <a href="https://networkx.org/documentation/stable/reference/generated/networkx.convert.from_dict_of_dicts.html#networkx.convert.from_dict_of_dicts" rel="nofollow noreferrer">from_dict_of_dicts</a> and then set the attributes of the nodes with <a href="https://networkx.org/documentation//networkx-2.0/r... | pandas|networkx | 1 |
350,631 | 65,750,044 | Adding value from one pandas dataframe to another dataframe by matching a variable | <p>Suppose I have a pandas dataframe <code>df</code> with 2 columns</p>
<pre><code> c1 c2
0 v1 b1
1 v2 b2
2 v3 b3
3 v4 b4
4 v5 b5
</code></pre>
<p>A second dataframe, <code>df2</code> contains c1, c... | <p>One easy way you can do is to use the merge of pandas based on similar column.</p>
<p><code>df2.drop('c1', axis=1, inplace=True)</code>
<br>
<code>main_df = pd.merge(df2, df, on="c2", how="left")</code>
<br>
<code>df2['c1'] = main_df['c1']</code>
<br>
<code>df2.columns = ['c1','c2','c3','c4']</co... | python|pandas|dataframe|matching | 1 |
350,632 | 65,580,064 | replacing columns values only on specific columns using regex in pandas | <p>I want to replace the values of specific columns. I can change the values one by one but, I have hundreds of columns and I need to change the columns starting with a specific string. Here is an example, I want to replace the string when the column name starts with <code>"Q14"</code></p>
<pre><code>df.filte... | <p>Consider below <code>df</code>:</p>
<pre><code>In [439]: df = pd.DataFrame({'Q14_A':[ 1,0,0,2], 'Q14_B':[0,1,1,2], 'Q12_A':[1,0,0,0]})
In [440]: df
Out[440]:
Q14_A Q14_B Q12_A
0 1 0 1
1 0 1 0
2 0 1 0
3 2 2 0
</code></pre>
<p>Filter columns that start... | python|python-3.x|pandas|dataframe|replace | 2 |
350,633 | 65,673,667 | getting unusual line chart on weekly time series data in matplotlib | <p>I have weekly car sales data and I made line charts by different car producers. However, I got little unusual line charts because the days one margin like <code>12-31-xxxx</code> and <code>01-01-xxxx</code> still stays in the same weeks, which gave me quite an unexpected plot. How should I make line charts if week n... | <p>You can use:</p>
<pre><code>df['week'] = np.select([(df['week'] == 53) & (df['date'].dt.month == 1),
(df['week'] == 53) & (df['date'].dt.month == 12)],
[1, 52], df['week'])
</code></pre>
<p>This will ensure that week is either 1 or 52. As shown in the image, 20... | python|pandas|matplotlib | 2 |
350,634 | 65,895,382 | Generate simulated data in Python while meeting a range of correlations with respect to a predefined variable | <p>Let's denote refVar, a variable of interest that contains experimental data.
For the simulation study, I would like to generate other variables V0.05, V0.10, V0.15 until V0.95.
Note that for the variable name, the value following V represents the correlation between the variable and refVar (in order to quick track i... | <p>Following <a href="https://stackoverflow.com/questions/65895382/generate-simulated-data-in-python-while-meeting-a-range-of-correlations-with-res">this answer</a> we can generate the sequence as follow:</p>
<pre><code>def rand_with_corr(refVar, corr):
# center and normalize refVar
X = np.array(refVar) - np.me... | python|pandas|numpy|simulation | 1 |
350,635 | 65,856,324 | How to remove integer values from column with pandas | <p>I have a dataframe with info on multiple countries. The data is not very clean and some of the country names have integer values in them. like this <code>China2</code> or <code>Ukraine18</code>.</p>
<p>I want to remove the integer values from all entries in the <code>Country</code> column but am not able to find a r... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a>:</p>
<pre><code>df['Country'] = df['Country'].str.replace('\d+', '')
</code></pre> | python|pandas|dataframe | 2 |
350,636 | 65,885,183 | pyarrow.parquet.write_table: memory usage | <p>I need to prepare .parquet file using Python, so this is my code:</p>
<pre><code>import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd
import sys
import mysql.connector
import json
def write_table(databaseServer, databaseDatabase, databaseUser, databasePassword, sql, fileName):
... | <p>At the momment you are:</p>
<ul>
<li>Loading data into memory (in vectors)</li>
<li>Converting the data to a df</li>
<li>Storing the data in parquet</li>
</ul>
<p>This strategy only works if all the data can be stored in memory.</p>
<p>You could instead write smaller batches of data to the parquet file, using <a hre... | python|pandas|parquet|pyarrow | 0 |
350,637 | 65,747,993 | I can't install tensorflow on Jetson Nano | <p>I am currently working on my Nvidia Jetson Nano 4GB following <a href="https://www.pyimagesearch.com/2019/05/06/getting-started-with-the-nvidia-jetson-nano/" rel="nofollow noreferrer">this guide</a>. I try to install tensorflow but a few moments later I have THAT 2500lines error: 'python version don't match your env... | <p>just write <code>python</code> in terminal to see your python version if that is what you are asking?</p> | python|tensorflow|opencv|machine-learning|nvidia-jetson-nano | 0 |
350,638 | 65,713,294 | Using Pandas " | " operator between two boolean Series objects behaving strangely | <p>I have two large pandas Series.</p>
<pre><code>In [32]: mask.shape
Out[32]: (13919455,)
In [33]: t.shape
Out[33]: (13919455,)
</code></pre>
<p>Both are bool arrays, mask is only False, while t contains a few True values</p>
<pre><code>In [28]: sum(mask)
Out[28]: 0
In [29]: sum(t)
Out[29]: 7724
</code></pre>
<p>I w... | <p>I just figured this out, its a "feature" of how pandas must do OR operations.
It turned out that I had previously dropped some rows from "t", and while it was the same size as the other variable, its index was slightly larger.</p>
<p>After dropping the index to a default using Series.reset_index(... | python-3.x|pandas|dataframe|series | 1 |
350,639 | 65,785,321 | Check for leading zero in DataFrame | <p>I have a <code>DataFrame</code> with values for username column like <code>07562</code>.
I would like to check for columns that don't contains <code>leading zero</code> like <code>7562</code> and delete them.
I'm doing it this way, but this pass if there is a zero somewhere in the username</p>
<pre class="lang-py pr... | <p>This should be easiest this way:</p>
<pre><code>df = df[df['username'].str.startswith("0"))]
</code></pre>
<p>You just need to filter the dataframe based on username, would not need to create and drop NA too.</p> | python|python-3.x|pandas | 1 |
350,640 | 65,742,797 | Why can't I use Pandas in Jupyter even with "Requirement already satisfied" | <p><a href="https://i.stack.imgur.com/LxbuN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LxbuN.png" alt="Issue With Jupyter" /></a></p>
<p>Hey there. So I'm trying to learn Python for data manipulation. Obviously pandas is needed. I am using Windows 10 and have installed Jupyter through the consol... | <p>Is this a new kernel? If so, <code>!pip</code> runs pip using the system environment, not the kernel environment. Delete the <code>!</code> at the beginning.</p> | python|pandas|jupyter-notebook | 2 |
350,641 | 65,554,804 | Searching a Numpy Array for the index of a subarray based on a subarray of the subarray | <p>I want to get the index of a 2d array which contains a specific array. In this case I want to know where in the array <code>array</code> the array <code>[[4, 5], 6]</code> is but only based on the inner most array <code>[4, 5]</code> so that I get its position even if instead of the six it would be an eight.</p>
<p>... | <p>The issue is that you are working with a dtype object where your first numpy column contains list objects.</p>
<p>You can create a <code>vectorized function</code> to check each object individually.</p>
<pre><code>f = np.vectorize(lambda x: x==[4,5])
idx = np.where(f(array))
idx
</code></pre>
<pre><code>(array([1]),... | python|arrays|numpy|multidimensional-array|numpy-ndarray | 0 |
350,642 | 65,874,433 | Finding the nearest element in a 2D Numpy array | <p>I have a two-dimensional numpy array like:</p>
<pre><code> [[0 0 0 0 0 0 0 0 1 1]
[0 0 0 1 0 1 0 0 0 1]
[1 0 1 0 0 0 1 0 0 1]
[1 0 0 0 0 0 0 0 1 0]
[0 1 0 0 0 1 0 1 1 0]
[0 0 0 1 1 0 0 0 0 0]
[0 1 1 1 1 1 0 0 0 0]
[1 0 0 0 1 0 1 0 0 0]
[0 0 0 0 0 0 0 1 0 0]
[0 1 0 0 0 0 0 0 0 0]]
</code></pre>
<p>We can thi... | <p>This is a simple "path-finding" problem. Prepare an empty queue of coordinates and push a starting position to the queue. Then, pop the first element from the queue and check location and if it's 1 return the coordinates, otherwise push all neighbours to the queue and repeat.</p>
<pre class="lang-py pretty... | python|python-3.x|numpy|numpy-ndarray | 1 |
350,643 | 65,550,815 | Pandas group by row number producing unexpected output | <p>I have a data frame like as shown below</p>
<pre><code>import pandas as pd
import numpy as np
df=pd.DataFrame({'Adm DateTime':['02/25/2012','03/05/1996','11/12/2010','31/05/2012','21/07/2019','31/10/2020'],
's_id':[1,1,1,1,2,2],
't_id':['t1','t2','t3','t3','t4','t5']})
</code></pre>
... | <p>You can <code>group</code> on <code>s_id</code> and <code>transform</code> the column <code>t_id</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a> to encodes the values in <code>t_id</code> as categorica... | python|python-3.x|pandas|dataframe|pandas-groupby | 2 |
350,644 | 65,528,374 | read_excel() function auto convert int to float | <p>when I am reading the file using <em>read_excel()</em> function integer columns are auto-converted into the float datatype in pandas python when any <em>NAN</em> value present.
like in below example:</p>
<pre><code>A B C D
1 2 s 3.9
3 4 d 2.0
when I am reading the file using read_excel().
Dataframe is lik... | <p>You can set <code>dtype=object</code> to avoid that.</p>
<pre><code>import pandas as pd
df=pd.read_excel('sample.xlsx')
df
A B C D
0 1.0 2.0 s 3.9
1 NaN NaN NaN NaN
2 3.0 4.0 d 2.0
df=pd.read_excel('sample.xlsx', dtype=object)
df
A B C D
0 1 2 s 3.9
1 NaN NaN ... | python|pandas | 0 |
350,645 | 65,657,526 | How to compare all values of a list in python? | <p>This is my code:</p>
<pre><code>ticker = 'NFLX'
price = get_data(ticker, start_date='2020-01-01', end_date=None, index_as_date=bool, interval ='1d')
price.to_csv(r'D:\Python Stuff\pythonProject\NFLX.csv')
df = pd.read_csv('NFLX.csv')
price_list = df['adjclose']
def SMA():
SMA_days = 20
sma = price_list.rol... | <p>You can change your if-statement to <code>if (price_list[-6:] > simple_moving_average[-6:]).all():</code></p> | python|pandas|list|numpy|series | 0 |
350,646 | 65,776,839 | Pandas Cumulative sum of 2 cumulative columns | <p>Trying to add a cumulative column to a pandas df.</p>
<p>Have tried this code but get a NaNs:</p>
<pre><code>df['Total_Coins_Bought'] = df.query("side == 'buy'")['amount'].cumsum()
df['Total_Coins_Sold'] = -df.query("side == 'sell'")['amount'].cumsum()
df['Total_Coins'] = df['Total_Coins_Bought'... | <pre class="lang-py prettyprint-override"><code>df["sign_amount"] = df["amount"] * df["side"].map({"buy": +1, "sell": -1})
df["total_coins"] = df["sign_amount"].cumsum()
</code></pre>
<p>Basically, I add a <code>sign_amount</code> column, which is id... | python|pandas|dataframe | 0 |
350,647 | 65,766,409 | "NameError: name 'numpy' is not defined" when calling eval() | <pre><code>x = 0
x2 = 0
f = "numpy.sin(x)"
e1 = eval(f)
e2 = eval(f, {"x":x2})
</code></pre>
<p>The line for e2 (but not e1) generates an error:</p>
<pre><code>NameError: name 'numpy' is not defined
</code></pre>
<p>Why?</p> | <p>Since in e1, you aren't overriding the globals, numpy exists. In e2, you are, so your import can't be seen by the interpreter. Just pass in numpy as a variable.</p>
<p><code>e2 = eval(f, {'numpy': numpy, 'x':x2})</code></p> | python|numpy|eval | 1 |
350,648 | 65,693,547 | checking elements on either side of current element in list | <p>I have an array:</p>
<pre><code>array1 = [0, 0, 0, 1, 1, 2, 1, 2, 2, 1]
</code></pre>
<p>I'd like to iterate through the elements and if there is a 2 that is not next to another 2, either on the left or right, I want to convert that 2 to a 1. I could create a new array, instead of modifying the old one, but I don't ... | <pre><code>array1 = [0, 0, 0, 1, 1, 2, 1, 2, 2, 1]
array2 = []
for i in range(len(array1)):
if array1[i] == 2:
if array1[i-1] != 2 and array1[i+1] != 2:
array2.append(1)
else:
array2.append(2)
else:
array2.append(array1[i])
</code></pre>
<p>will give
<code>[0, 0, 0, 1, 1, 1, 1, 2, 2, 1]</co... | python|numpy | 2 |
350,649 | 65,556,758 | Why doesn't custom training loop average loss over batch_size? | <p>Below code snippet is the custom training loop from Tensorflow official tutorial.https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch . Another tutorial also does not average loss over <code>batch_size</code>, as shown here <a href="https://www.tensorflow.org/tutorials/customization/custom_tra... | <p>I've figured it out, the <code>loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)</code> indeed averages loss over batch_size by default.</p> | tensorflow|machine-learning|deep-learning | 0 |
350,650 | 65,815,668 | How to select indices according to another tensor in pytorch | <p>The task seems to be simple, but I cannot figure out how to do it.</p>
<p>So what I have are two tensors:</p>
<ul>
<li>an indices tensor <code>indices</code> with shape <code>(2, 5, 2)</code>, where the last dimensions corresponds to indices in x and y dimension</li>
<li>a "value tensor" <code>value</code>... | <p>What you could do is flatten the first three axes together and apply <a href="https://pytorch.org/docs/stable/generated/torch.gather.html" rel="nofollow noreferrer"><code>torch.gather</code></a>:</p>
<pre><code>>>> grid.flatten(start_dim=0, end_dim=2).shape
torch.Size([6, 16, 16])
>>> torch.gather... | python|pytorch|indices | 3 |
350,651 | 65,797,318 | How to get class indices from a quantized TFLite? | <p>I have been training a quantized Mobilenet V2 with TensorFlow, but I don't know how to get the class index from it.</p>
<p>I am using Tensorflow 1.12</p>
<p>Below are my input and output details.</p>
<pre><code>Input details [{'name': 'normalized_input_image_tensor', 'index': 260, 'shape': array([ 1, 300, 300, 3]... | <p>After lots of experimentation, it turns out it was not a quantization issue. We were using the wrong <code>graph_def</code> .pb file when creating our .tflite, so it was predicting classes that did not exist.</p> | python|tensorflow|tensorflow-lite | 1 |
350,652 | 65,605,818 | Could the first loop be replaced by a faster way like more matrix operations? | <p>Three are a great amount of calculations in the code below. rlist has about 1000 to 5000 float numbers.</p>
<p>The final goal is to obtain temph001, but I find the calculations too slow.</p>
<p><strong>How to improve the speed?</strong></p>
<p><strong>For example, the first loop (for f in ft:) could be replaced by ... | <pre class="lang-py prettyprint-override"><code>rlist = np.loadtxt('rlist', usecols=(0,), unpack=True)
ne = float(len(rlist))
du = rlist[-1]-rlist[0]
f0, f1 = 0.00001, 0.003
ft = np.arange(f0, f1, 0.5/du)
nf = len(ft)
aa = open('temph', 'w')
seq = 0
rlist_m, ft_m= np.meshgrid(rlist,ft)
ta1 = 2.712*(rlist_m*ft_m% 1.2)
... | python|numpy|calculation | 0 |
350,653 | 65,583,157 | (Tensorflow 2.0) Keras Dataframe cannot detect the validation images | <p>I tried to use <strong>keras.ImageDataGenerator.flow_from_dataframe</strong>, but it cannot detect the validation images and I get this</p>
<p>Found 162770 validated image filenames.</p>
<p>Found 0 validated image filenames.</p>
<p>Can anyone help me please</p>
<p>My code is here:</p>
<pre><code>traindf=pd.read_csv(... | <p>It turns out that you have to set a validation fraction in your call to ImageDataGenerator, for example:</p>
<pre><code>datagen=ImageDataGenerator(validation_split=0.2)
</code></pre>
<p>I just had this same problem, and it is now fixed.
Found answer in <a href="https://keras.io/api/preprocessing/image/#flowfromdataf... | python-3.x|tensorflow|tensorflow2.0|tensorflow-datasets|image-classification | 0 |
350,654 | 65,716,939 | select cells from an excel table python | <p>i have a an excel table that contains :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID product</th>
<th>03/1/2021</th>
<th>16/1/2022</th>
<th>12/2/2022</th>
<th>14/3/2023</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>B</td>
<td... | <p>Assuming your excel file looks like below:</p>
<p><a href="https://i.stack.imgur.com/ShI1w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ShI1w.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>Final Code</strong> looks like below:</p>
<pre><code>import xlrd
file = r'C:\path\te... | python|excel|pandas|select | 0 |
350,655 | 65,600,860 | Add leading zeroes only if it begin with digit in pandas dataframe | <p>I have a data frame column which have special characters and numbers. I want to have leading zeroes only if it begin with a digit. I need a total of 3 digits.
I tried the following code:</p>
<pre class="lang-py prettyprint-override"><code>df['input'] = df['input'].str.zfill(3)
</code></pre>
<h1>Input:</h1>
<div cla... | <p>Here is a elegant way using <code>zfill</code> along with a mask.</p>
<pre><code>df = pd.DataFrame({'strings':['1','$500','333','2','(8','?8','5','1','444']})
#Mask for checking if first alphabet is digit
mask = df.strings.str[0].str.isdigit()
#Apply zfill on values where mask is True
df.loc[mask, 'strings'] = df.... | python|pandas | 2 |
350,656 | 65,584,850 | Numpy fromfunction returns error: Arrays used as indices must be of integer (or boolean) type | <p>I am implementing a neural network and have a problem with numpy.fromfunction function, which after running the following code:</p>
<pre><code>def sigmoid(x, D=False):
if not D:
return 1 / (1 + np.exp(-x))
else:
return x * (1.0 - x)
class Neural_net:
def __init__(self, n_input, n_hidden,... | <p>Change the problem line to:</p>
<pre><code> def f1(i):
print('i',i)
a1 = self.layer1_weights[i]
a2 = self.layer1_bias[i]
temp = self.activation(a1, a2, input)
return self.transfer(temp)
hidden_layer = np.fromfunction(f1, (self.n_hidden,))
</code></pre>
<p>The run:</p>
<... | python|numpy|neural-network | 0 |
350,657 | 65,569,574 | BeautifulSoup initialization type Error -- trouble troubleshooting | <p>The error points to this <a href="https://bazaar.launchpad.net/%7Eleonardr/beautifulsoup/bs4/view/head:/bs4/__init__.py#L310" rel="nofollow noreferrer">line of the bs4 source code</a></p>
<p>I'm using a 3rd party module that depends on BeautifulSoup. I am using it to create DataFrames of NBA players' stats individu... | <p>My guess is that the sites server is recognizing that you are making many requests in a small timeframe and at some point in the loop is blocking you. There's a couple things you could do. The simpliest is just put a little time delay after each iteration. If that doesn't work, let me know, and we can fix that up a ... | python|python-3.x|pandas|beautifulsoup | 1 |
350,658 | 65,719,005 | RuntimeError: Given groups=1, weight of size [16, 1, 3, 3], expected input[16, 3, 1, 28] to have 1 channels, but got 3 channels instead | <p>I know my images have only 1 channel so the first conv layer is (1,16,3,1) , but I have no idea why I got such an error.</p>
<p>Here is my code (I post only the related part).</p>
<pre><code> org_x = train_csv.drop(['id', 'digit', 'letter'], axis=1).values
org_x = org_x.reshape(-1, 28, 28, 1)
org_x = or... | <p>I tried a small demo with your code. and it works fine until your code had <code>x = x.view(-1, 64*14*14)</code> and input shape of <code>torch.Size([1, 1, 28 ,28])</code></p>
<pre><code>import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
s... | pytorch | 2 |
350,659 | 65,808,713 | Pandas: How to add the sum of a group to the max value of the group | <p>I have three columns on a pandas <code>df</code>: <code>id, hazard, probability</code></p>
<p>I want to make sure the sum of probabilities for each id, hazard combo is 1.</p>
<p>So I wanted to find the sum of probabilities for each id, hazard.</p>
<p>And also find the index of the max probability for each id, hazard... | <p>Try this -</p>
<ol>
<li><code>new_proba</code> calculates the new values of probability for each group that they need to replace their max values.</li>
<li>Then, you can use <code>idxmax</code> to find the row indexes and <code>df.loc</code> to find those rows and update them with the <code>new_proba</code></li>
</o... | python|pandas|dataframe|sum|max | 1 |
350,660 | 65,498,376 | Modelling membrane evolution over time | <p>I am trying to model the time evolution of a membrane based on the following code in MATLAB.
<a href="https://i.stack.imgur.com/MieJN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MieJN.png" alt="enter image description here" /></a></p>
<p>The basic outline is that the evolution is based on a di... | <p>Your definition of <code>x0</code> is wrong.
In the Matlab code, it is equal to</p>
<pre><code>x0 = 2*pi*R/N/2 # which is pi*R/N
</code></pre>
<p>while in your Python code it is</p>
<pre><code>x0 = 2*np.pi*R0/(N/2) # which is 4*np.pi*R0/N
</code></pre>
<p>Correcting that, the end result is a circular shape, but wi... | matlab|numpy | 1 |
350,661 | 65,654,656 | convert Pandas dataframe into adjacency matrix | <p>I have a Pandas dataframe (930 rows × 50 columns) that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">index</th>
<th style="text-align: center;">Keyword A</th>
<th style="text-align: center;">Keyword B</th>
<th style="text-align: center;">Key... | <p>The solution is deceptively simple:</p>
<pre><code>adj = df.T @ df
np.fill_diagonal(adj.values, 0)
</code></pre>
<p>E.g.:</p>
<pre><code>>>> df = pd.DataFrame([[1, 1, 3, 1], [2, 4, 0, 2], [3, 0, 1, 1]],
columns=["index", "A", "B", "C"]).set_index... | python|pandas|adjacency-matrix | 4 |
350,662 | 65,803,355 | How to index ndarray in tuple using boolean with Numpy Python? | <p>I would like to index <code>ndarray</code> in a <code>tuple</code> using a <code>boolean mask</code> such as below</p>
<pre><code>import numpy as np
n_max = 5
list_no = np.arange ( 0, n_max )
lateral = np.tril_indices ( n_max, -1 )
mask= np.diff ( lateral [0].astype ( int ) )
mask [-1] = 1
Expected=lateral[mask!= 0]... | <p>So it seems like the size of the mask and lateral[0] are different. Since mask is the difference between each element in the array, it is of size n-1 when lateral[0] is of size n. You might want to append to the mask array instead.
Also, since lateral is a tuple, you would need to index on the tuple before applying ... | numpy|indexing|boolean-operations | 1 |
350,663 | 65,545,367 | Cython modifiy pointer from c++ | <p>I need to modify my NumPy arrays which I am passing from cython to c++ function. Everything works fine but when I print out the value after calling the c++ modifier function, the value remains the same as it was before calling the function. I also tried the same with string but it does not work out as well. I used t... | <pre><code>cdef float[:, :, ::1] d_view = d.astype(np.float32)
</code></pre>
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html" rel="nofollow noreferrer">Docs</a>:</p>
<blockquote>
<p>By default, <code>astype</code> always returns a newly allocated array</p>
</blockquote>
<p>i.e. <c... | python|c++|numpy|pointers|cython | 2 |
350,664 | 65,544,171 | When I try to handle missing values in pandas, some methods are not working | <p>I am trying to handle some missing values in a dataset. This is the <a href="https://www.geeksforgeeks.org/working-with-missing-data-in-pandas/" rel="nofollow noreferrer">link</a> for the tutorial that I am using to learn. Below is the code that I am using to read the data.</p>
<pre><code>import pandas as pd
import ... | <p>Can you try to specify the <code>axis</code> explicitly and see if it will work? The other fillna() should still work without axis, but for pad you need it so it knows how to fill the missing values.</p>
<pre><code>>>> questions.fillna(method='pad', axis=1)
Id CreationDate ClosedDate ... | python-3.x|pandas|dataframe|nan|missing-data | 1 |
350,665 | 21,015,674 | 'list' object has no attribute 'shape' | <p>how to create an array to numpy array?</p>
<pre><code>def test(X, N):
[n,T] = X.shape
print "n : ", n
print "T : ", T
if __name__=="__main__":
X = [[[-9.035250067710876], [7.453250169754028], [33.34074878692627]], [[-6.63700008392334], [5.132999956607819], [31.66075038909912]], [[-5.127249956130... | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html"><code>numpy.array</code></a> to use <code>shape</code> attribute.</p>
<pre><code>>>> import numpy as np
>>> X = np.array([
... [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
... [[-6.63700... | python|list|numpy | 86 |
350,666 | 20,888,954 | Add subtotal columns in pandas with multi-index | <p>I have a dataframe with a 3-level deep multi-index on the columns. I would like to compute subtotals across rows (<code>sum(axis=1)</code>) where I sum across one of the levels while preserving the others. I think I know how to do this using the <code>level</code> keyword argument of <code>pd.DataFrame.sum</code>.... | <p>Here is a way without loops:</p>
<pre><code>s = df.sum(axis=1, level=[0,1]).T
s["shape"] = "sum(shape)"
s.set_index("shape", append=True, inplace=True)
df.combine_first(s.T)
</code></pre>
<p>The trick is to use the transposed sum. So we can insert another column (i.e. row) with the name of the additional level, wh... | python|pandas | 5 |
350,667 | 21,367,710 | Replace values in Pandas data frame within a loop | <p>I am trying to loop through a pandas data frame and replace values in certain columns if they meet certain conditions. I realize there are more straightforward ways to do this in general, but in my specific example I need a loop because the result for one row can depend on the prior row. Below is a reproducible exam... | <p>You can write to the original frame using <code>.loc</code>:</p>
<pre><code>>>> for index, row in df.iterrows():
... df.loc[index, "A"] = "I am working! {}".format(row["B"])
...
>>> df
A B C
0 I am working! 20 20 32
1 I am working! 30 30 234
2 I am wor... | python|pandas | 17 |
350,668 | 21,149,920 | Pandas: import multiple csv files into dataframe using a loop and hierarchical indexing | <p>I would like to read multiple CSV files (with a different number of columns) from a target directory into a single Python Pandas DataFrame to efficiently search and extract data.</p>
<p>Example file:</p>
<pre><code>Events
1,0.32,0.20,0.67
2,0.94,0.19,0.14,0.21,0.94
3,0.32,0.20,0.64,0.32
4,0.87,0.13,0.61,0.54,0.25... | <p>You need to decide in what axis you want to append your files. Pandas will always try to do the right thing by:</p>
<ol>
<li>Assuming that each column from each file is different, and appending digits to columns with similar names across files if necessary, so that they don't get mixed;</li>
<li>Items that belong t... | python|csv|pandas|hierarchical-data | 15 |
350,669 | 21,033,144 | Remove repeating lines of characters when reading text files in python? | <p>I am reading a text file which was copied from a CSV file. When I read the file in python, I get a ton of unnecessary repeating lines as seen below. How can i strip away those three unwanted lines, including \cf0 and \cell\row at the beginning and end of each text?</p>
<p>Or should I read the text directly from the... | <p>Your real problem here appears to be that you pasted the CSV into an <a href="http://en.wikipedia.org/wiki/Rich_Text_Format" rel="nofollow">RTF</a> file, not a text file. Pasting into Wordpad on Windows or TextEdit on Mac (especially if you copied from, say, Excel or Numbers) and saving it without explicitly telling... | python|pandas|readlines | 0 |
350,670 | 20,929,731 | to find if list have the negative sign | <p>I have a function. In that function I am passing a list.</p>
<pre><code>l = [1, 2, 3]
</code></pre>
<p>Now I wanted to write 2 conditions of l is passed or of -l is passed. -l means negation of all vales in list.<br>
For example</p>
<pre><code>-l = [ -1, -2, -3]
</code></pre>
<p>so, in function either l or -l wi... | <p>I don't think it's possible, since when you are calling</p>
<pre><code>test(-l)
</code></pre>
<p><code>-l</code> is evaluated, and then passed to the function. Instead, you could try something like this:</p>
<pre><code>def test(l, negative = False):
if (negative == True):
l = -l
...
else: ... | python|numpy | 1 |
350,671 | 20,911,423 | Conflicting Numpy and OpenCV2 Datatypes when calling OpenCV functions | <p>I have a big problem when using the OpenCV 2 Python API. There are no more separate OpenCV Matrix types. Every matrix is actually a numpy matrix. So far so good. The problem arises when calling OpenCV functions on these matrices that require a specific data type. OpenCV seems to have problems reconciling numpy data ... | <p>Could not reproduce...</p>
<pre><code>import cv2
import numpy as np
thr = np.random.rand(100,100).astype(np.uint8)
map = np.zeros((100,100,1), np.uint8)
out = cv2.distanceTransform(thr, cv2.DIST_LABEL_CCOMP, 3, map)
# no errors
</code></pre>
<p>You could double-check used datatypes.</p>
<pre><code>python 2.7.3
n... | python|opencv|numpy | 1 |
350,672 | 20,897,890 | Find max non-infinity element in pytables CArray | <p>This must be easy, but I'm very new to pytables. My application has dataset sizes so large they cannot be held in memory, thus I use PyTable CArrays. However, I need to find the maximum element in an array that is not infinity. Naively in numpy I'd do this:</p>
<pre><code>max_element = numpy.max(array[array != n... | <p>If your CArray is one dimensional, it is probably easier to stick it in a single-column Table. Then you have access to the <code>where()</code> method and can easily evaluate expressions like the following.</p>
<pre><code>from itertools import imap
max(imap(lamdba r: r['col'], tab.where('col != np.inf')))
</code><... | python|numpy|pytables|numexpr | 4 |
350,673 | 21,255,234 | dataframe re-indexing object unnecessarily preserved in memory | <p>In continuation from <a href="https://stackoverflow.com/questions/21234279/selection-with-hierarchical-index-getting-subset-of-the-dataframe">this question</a> I've implemented 2 functions doing the same thing, one is using re-indexing and the other does not. the functions differ in the 3rd line:</p>
<pre><code>def... | <p>Here is my debug code, when you do indexing, Index object will create <code>_tuples</code> and <code>engine map</code>, I think the memory is used by this two cache object. If I add the lines marked by <code>****</code>, then the memory increase is very small, about 6M on my PC:</p>
<pre><code>import pandas as pd
p... | python|pandas|ipython|ipython-notebook | 0 |
350,674 | 3,107,991 | a indexing question of ndarray | <p>for example, there is a matrix: </p>
<pre><code>import numpy as np
A = np.array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
</code></pre>
<p>It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U])<br>
I want to get L and U from A.<br>
U should be: </p>
... | <p>You don't need any index manipulation. Just use <code>tril</code>, <code>triu</code> and <code>identity</code> functions:</p>
<pre><code>import numpy as np
A = np.array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
U = np.triu(A)
#[[ 8. -6. 2.]
# [-0. 8. -6.]
# [ 0. -0... | python|numpy | 2 |
350,675 | 2,981,563 | speeding up parsing of files | <p>the following function parses a CSV file into a list of dictionaries, where each element in the list is a dictionary where the values are indexed by the header of the file (assumed to be the first line.)</p>
<p>this function is very very slow, taking ~6 seconds for a file that's relatively small (less than 30,000 l... | <pre><code>import ast
# find field types
for row in csv.DictReader(my_csvfile, delimiter=delimiter):
break
else:
assert 0, "no rows to process"
cast = {}
for k, v in row.iteritems():
for f in (int, float, ast.literal_eval):
try:
f(v)
cast[k] = f
break
ex... | python|csv|numpy|scipy | 3 |
350,676 | 63,482,476 | Flatten a nested dictionary and convert it into columns of Dataframe | <p>I have a JSON which I converted into a dictionary and trying to make a dataframe out of it. the problem is that it is multiple nested and with inconsistent data</p>
<p>For e.g.</p>
<pre><code>d = """[
{
"id": 51,
"kits": [
{
"i... | <p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html#pandas-json-normalize" rel="nofollow noreferrer">json_normalize</a> function should be what you are looking for.</p>
<p>Here is how to normalize your Json input:</p>
<pre class="lang-py prettyprint-override"><code>p... | python|pandas|dataframe | 1 |
350,677 | 63,486,440 | Use TensorFlow model with Swift for iOS | <p>We are trying to use TensorFlow Face Mesh model within our iOS app. Model details: <a href="https://drive.google.com/file/d/1VFC_wIpw4O7xBOiTgUldl79d9LA-LsnA/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1VFC_wIpw4O7xBOiTgUldl79d9LA-LsnA/view</a>.</p>
<p>I followed TS official tutorial for setting ... | <p>What those numbers mean completely depends on the model you're using. It's unrelated to both TensorFlow and Core ML.</p>
<p>The output is a 1x1x1x1404 tensor, which basically means you get a list of 1404 numbers. How to interpret those numbers depends on what the model was designed to do.</p>
<p>If you didn't design... | swift|tensorflow|tensorflow2.0|coreml|coremltools | 0 |
350,678 | 63,587,633 | Why does keras (SGD) optimizer.minimize() not reach global minimum in this example? | <p>I'm in the process of completing a TensorFlow tutorial via DataCamp and am transcribing/replicating the code examples I am working through in my own Jupyter notebook.</p>
<p>Here are the original instructions from the coding problem :</p>
<p><a href="https://i.stack.imgur.com/0BAiU.png" rel="nofollow noreferrer"><im... | <p>As it turned out, the difference in outputs arose from the default precision of tf.division() (vs np.division()) and tf.cos() (vs math.cos()) -- operations which were specified in (my transcribed, "custom") definition of the loss_function().</p>
<p>The loss_function() had been predefined in the body of the... | tensorflow|optimization|keras|minimize|sgd | 0 |
350,679 | 63,714,650 | Pandas: Dataframe from the 2nd level of a dictionary | <p>I have a json file like so:</p>
<pre><code>dict = {'2020-04-13TVL 0620M-Su 6p-12m': {'syscode': '0620',
'weekStartDate': '2020-04-13'},
'2020-04-20HSTE0620M-Su 6p-12m': {'syscode': '0620',
'weekStartDate': '2020-04-20'},
'2020-06-15MTV 6032M-Su 12m-2a': {'syscode': '6032',
'weekStartDate': '2020-06-15'},
'2... | <p>Construct dataframe on dictionary values.</p>
<p><strong>Note</strong>: <em><code>d1</code> is your dict</em>. Don't use keyword <code>dict</code> as variable name. It will overwrite the python keyword <code>dict</code>.</p>
<pre><code>df = pd.DataFrame(d1.values())
Out[25]:
syscode weekStartDate
0 0620 202... | python|pandas | 2 |
350,680 | 63,669,905 | Check if several rows of datetime is between other two values | <p>I am trying to get a return of all values that is between two other rows. I seem to constantly running into valueerrors. Any idea of how to solve this?</p>
<p>I have found one half-baked solution, but it is ...ugly...</p>
<p>My sample input looks like this:</p>
<pre><code>| patient_id | delirium_sae | syncope_sae | ... | <p>I think you need to <code>apply</code> it:</p>
<pre><code>df = df.set_index("patient_id").apply(lambda d: pd.to_datetime(d, format="%d-%m-%Y"))
mask = df.filter(like="_sae").apply(lambda d: (df["start_monitoring"]<=d)&(d<=df["end_monitoring"]))
print (df[... | pandas|dataframe|conditional-statements | 1 |
350,681 | 63,669,323 | Calculate date using different columns of a dataframe | <p>I have a dataframe with columns like this. The final df should contain a new column after taking the First_Date column and subtracting the corresponding unit and the corresponding value
<code>df = pd.DataFrame({"First_Date":[pd.to_datetime("2020-01-01")]*5, "Unit":['Years','Months','Day... | <p>Named arguments cannot be supplied from a variable as far as I am aware.</p>
<p>You could, however, create a one-hot encoding for your <code>Unit</code>-column and scale it by the <code>Value</code>-column to create a description of your delta:</p>
<pre class="lang-py prettyprint-override"><code>df_augmented = df.me... | python|pandas|dataframe | 1 |
350,682 | 63,464,633 | how to remove certain strings in pandas dataframe | <p>I have a dataframe, <code>df</code> with a column that has different school names, <code>school_name</code>. I want to remove certain words, and wonder what the best way to go about this might be.</p>
<p>For example, I want to remove <code>‘male’</code> and <code>‘female’</code> from strings like:</p>
<pre><code>‘gp... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html#pandas-series-str-replace" rel="nofollow noreferrer"><code>str.replace</code></a></p>
<pre><code>pattern = '|'.join(['male','female'])
df['school_name'] = df.school_name.str.replace(pattern, '')
</code></pre>
<p>It... | python|pandas|dataframe | 1 |
350,683 | 63,710,485 | Pandas change month while calculating the corresponding last business day | <p>In the below <code>pandas</code> dataframe example, <code>MyDate</code> consists of the <em><strong>1st day of the month</strong></em> and the <em><strong>last business day</strong></em> of the month. The dataset will always run to 1st of <code>(current month - 1)</code>.</p>
<p>I would like to dynamically increase... | <p>You may create a boolean mask to identify Business-month-end dates in your <code>MyDate</code> columns (Business-month-end dates returns <code>True</code>, others returns <code>False</code>). Use this mask to adding 1 month-begin and 1 business-month-end separately</p>
<pre><code>m = df.MyDate == (df.MyDate + pd.off... | python|pandas | 2 |
350,684 | 63,460,992 | How do I fix the Dataset to return desired output (pytorch) | <p>I am trying to use information from the outside functions to decide which data to return. Here, I have added a simplified code to demonstrate the problem. When I use <code>num_workers = 0</code>, I get the desired behavior (The output after 3 epochs is 18). But, when I increase the value of <code>num_workers</code>,... | <p>The reason for this is the underlying nature of multiprocessing in python. Setting <code>num_workers</code> means that your <code>DataLoader</code> creates that number of sub-processes. Each sub-process is effectively a separate python instance with its own global state, and has no idea of what's going on in the oth... | python|multiprocessing|dataset|pytorch|dataloader | 1 |
350,685 | 63,735,255 | How do I compute bootstrapped cross entropy loss in PyTorch? | <p>I have read some papers that use something called "Bootstrapped Cross Entropy Loss" to train their segmentation network. The idea is to focus only on the hardest k% (say 15%) of the pixels into account to improve learning performance, especially when easy pixels dominate.</p>
<p>Currently, I am using the s... | <p>Often we would also add a "warm-up" period to the loss such that the network can learn to adapt to the easy regions first and transit to the harder regions.</p>
<p>This implementation starts from <code>k=100</code> and continues for 20000 iterations, then linearly decay it to <code>k=15</code> for another ... | deep-learning|neural-network|pytorch|loss-function | 3 |
350,686 | 63,460,440 | Python equivalent of select * from a where account_id in (select account_id from b) | <p>As the title suggests. I come from an SQL background was looking for the best way of doing this.</p>
<pre><code>c = a.account_id.isin(b.account_id).astype(bool)
a[c]
</code></pre>
<p>Is the above the most efficient way?</p> | <p>Yes it is, but we can put them into on row , and you do not need to convert the <code>isin</code> out put as bool, since it is already bool type data</p>
<pre><code>a[a.account_id.isin(b.account_id)]
</code></pre> | python|pandas | 3 |
350,687 | 63,338,754 | input of LSTM network | <p>I'm having trouble with preparing input data for LSTM on Keras.
my data shape is:</p>
<ul>
<li>number of files: 276</li>
<li>dimensions of files: 213*276</li>
</ul>
<p>each file belongs to one month from 1993-2015.</p>
<p>I want to prepare this data to be fed into LSTM on Keras. i want to predict the last 12 months(... | <p>The input to an LSTM model should be three dimensional, in the format [samples, timestep, features]. In this case it suggests that your input could be something like [276, 213, 276]: this is speculation however, and will depend on how the data that you are using was organised. Check the appropriate length timestep f... | python|tensorflow|keras|lstm | 1 |
350,688 | 63,666,509 | How can I recreate this plot of a pandas DataFrame, line and bar | <p>Previously I managed to create the following plot</p>
<p><a href="https://i.stack.imgur.com/lPkBY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lPkBY.png" alt="enter image description here" /></a></p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df_prog = pd.DataFrame({"P... | <p>You need to convert the time axis to string. Then you can plot them together.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
df_prog.index = df_prog.in... | python|pandas|matplotlib | 2 |
350,689 | 63,605,303 | Extract values from dictionary and conditionally assign them to columns in pandas | <p>I am trying to extract values from a column of dictionaries in pandas and assign them to their respective columns that already exist. I have hardcoded an example below of the data set that I have:</p>
<pre><code>df_have = pd.DataFrame(
{
'value_column':[np.nan, np.nan, np.nan]
,'date':[np.nan, np.nan, np.nan... | <p>You could use pandas string methods to pull the data out, although I think it is inefficient nesting data structures within Pandas :</p>
<pre><code>df_have.loc[:, "value_column"] = df_have["dict"].str.get(0).str.get("value_column")
df_have.loc[:, "date"] = df_have["dict&q... | python|pandas|conditional-statements|calculated-columns | 0 |
350,690 | 63,715,192 | Using FreqDist and writing to CSV | <p>I'm trying to use nltk and pandas to find the top 100 words from another csv and list them on a new CSV. I am able to plot the words but when I print to CSV I get</p>
<pre><code>word | count
52 | 7 <- This is current CSV output
</code></pre>
<p>Not sure where I am going wrong, looking for some guidance... | <p>Here you go. The code is quite compressed, so feel free to expand if you like.</p>
<p>First, ensure the source file is actually a CSV file (i.e. comma separated). I copied/pasted the sample text from the question into a text file and added commas (as shown below).</p>
<p>Breaking the code down line by line:</p>
<ul>... | python|pandas|csv|nltk | 1 |
350,691 | 63,495,831 | implementation decision trees in tensorflow | <pre><code>feature_columns = []
for feature_name in train.columns.tolist() :
feature_columns.append(tf.feature_column.numeric_column(feature_name,dtype=tf.float32))
# Use entire batch since this is such a small dataset.
NUM_EXAMPLES = len(y_train)
def make_input_fn(X, y, n_epochs=None, shuffle=True):
def input_f... | <pre><code>test_input_fn = make_input_fn(test, test.index, shuffle=False, n_epochs=1)
preds = est.predict(test_input_fn)
preds = [pred['class_ids'][0] for pred in preds]
pd.DataFrame({'PassengerId': dataTest.PassengerId, 'Survived':
preds}).to_csv('submission.csv', index=False)
!head submission.csv
</code></pre> | python|tensorflow|keras | 0 |
350,692 | 63,594,267 | Artifacts in StyleGAN generated images | <p>I've written my own implementation of StyleGAN (paper here <a href="https://arxiv.org/abs/1812.04948" rel="nofollow noreferrer">https://arxiv.org/abs/1812.04948</a>), using PyTorch instead of Tensorflow, which is what the official implementation uses. I'm doing this partly as an exercise in implementing a scientific... | <p>I've been working with StyleGAN for a while and I couldn't guess the reason with such little information..</p>
<p>One possible reason is the effect of the truncation trick, this makes the results to represent an average face but with higher quality or deviate it to obtain results variability but with possibility of ... | neural-network|pytorch|generative-adversarial-network|stylegan | 1 |
350,693 | 63,384,314 | Change elements of boolean matrix to True based on value from another array | <p>I'm trying to update the values of False elements in my boolean matrix to True based on the index value of that row which is contained in another numpy array.</p>
<p>Here is my array, <code>change</code>, that identifies the element that needs to be changed in the matrix, <code>mask_matrix</code>:</p>
<pre><code>imp... | <p>This should help:</p>
<pre><code>mask_matrix[np.arange(change.size),change]=True
</code></pre>
<p>Which is basically using advanced indexing in numpy to call row-column elements of an array.</p> | python|arrays|numpy | 3 |
350,694 | 63,496,945 | Decimal date manipulation with Pandas in Python | <p>This may be a little silly to ask but I've tried to search examples to manipulate dates in a Data Frame using pandas. But what confuses me is that my dates have this format:</p>
<pre><code>Time A B C D
1.000347257 626.9966431 0 0 -99.98999786
1.001041651 626.9967651 0 0 -99.98999786
1.001736164 627.0130005 ... | <p>Your column <code>Time</code> seems to be day fractions. If you know the year, you can convert that to a datetime column using</p>
<pre><code># 1 - convert the year to nanoseconds since the epoch
# 2 - add the day fraction, after you convert that to nanoseconds as well
# 3 - convert the resulting nanoseconds since t... | python-3.x|pandas|python-datetime | 1 |
350,695 | 63,707,092 | Output full string without ellipsis with Pandas and Flask | <p>I am trying to print out the full string for each column in pandas using Flask. More specifically, the tweet_text column is cut short,</p>
<p>This follows the tutorial:
<a href="https://www.analyticsvidhya.com/blog/2020/04/how-to-deploy-machine-learning-model-flask/" rel="nofollow noreferrer">https://www.analyticsvi... | <p>I found out that the converting a pandas DataFrame to string via str(df) limits the width of each column. Conversion via df.to_string() works without this limitation, hence without the use of ellipsis.</p>
<pre><code>def requestResults(name):
tweets = get_related_tweets(name)
tweets['prediction'] = pipeline.... | python|pandas|flask|tweepy | 1 |
350,696 | 63,694,704 | How to groupby, and filter a dataframe based on the sum? | <p>So I have a dataframe, milk_countries_exports, that consists of columns of:</p>
<ul>
<li>The 'Period', the year and month for a particular row (the dataset is month by month for a year)</li>
<li>The 'Reporter' country, that is doing the exporting</li>
<li>The 'Partner' countries that are importing from the 'reporter... | <ul>
<li><code>g['Trade Value (US$)'].min() >= 2000000</code> filters everything out, because it means the minimum must be greater than 2000000.</li>
<li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>pandas.Grouper</code></a> to groupby <... | python|pandas|dataframe|pandas-groupby | 3 |
350,697 | 63,659,998 | How convert column datatype int64 to categorical column datatype in python? | <p>how can i change int to categorical</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.read_excel('data.xlsx',header=0)
data.info()
</code></pre>
<p>there is now a column damage which is int64. It shows different damage-groups. How can this column be convert to a categorical column? (background is, the... | <p>According to <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html" rel="nofollow noreferrer">pandas documentation</a> categorical <code>Series</code> or columns in a <code>DataFrame</code> can be created by several ways. One way is converting an existing <code>Series</code> or column to ... | python|pandas|types|type-conversion|multiclass-classification | 1 |
350,698 | 63,645,979 | Change font format with xlwings on Mac and get an AttributeError | <p>I have simple table in an Excel file called Book1.xlsx
<a href="https://i.stack.imgur.com/RTE7Q.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I was trying to get the font information of cell 'A1' with xlwings, code like below</p>
<pre><code>app = App(visible = False, add_book = False)
wb = a... | <pre><code>print(sht.range('A1').api.font_object.properties.get())
</code></pre>
<p>Using this, you will get the correct way to write xlwings font API in Mac OS X</p> | python|excel|pandas|xlwings | 1 |
350,699 | 63,347,421 | Keras 3D input to 1D output | <p>I am trying to model tabular data combining cross sectional with a time series component, essentially using the last n records of my X to predict a single Y value.</p>
<p>I am using the lastest versions of both tensorflow and keras</p>
<pre><code>def build_model(input_shape):
model = Sequential([
Dense(units... | <p>You need to flatten your (n, m) dimensions, either beforehand or with the Keras flatten layer. E.g.</p>
<pre><code>model = Sequential([
Flatten(),
Dense(units = (len(input_variables) * 2) - 1
, activation= activation_func
, input_shape=input_shape
, kernel_i... | python-3.x|tensorflow|machine-learning|keras|neural-network | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.