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 |
|---|---|---|---|---|---|---|
19,500 | 70,593,859 | Grouping and sum the value for every 5min / resampling the data for 5min with string values | <p>I want to sum the value of each gender for every 5 min timestamp.</p>
<p>Main Table:-</p>
<pre><code>Time Gender value
10:01 Male 5
10:02 Female 1
10:03 Male 5
10:04 Male 5
10:05 Female 1
10:06 Female 1
10:07 Male 5
10:08 Male 5
10:09 Male 5
10:10 Male 5
</co... | <p>You could convert to <code>TimeDelta</code>, <code>floor</code> the result, and use it to <code>groupby</code>+<code>agg</code>:</p>
<pre><code>t = pd.to_timedelta(df['Time']+':00')
(df
.groupby([t.dt.floor('5min'), 'Gender'])
.agg({'value': 'sum'})
.reset_index()
)
</code></pre>
<p>output:</p>
<pre><code> ... | python|pandas|dataframe|pandas-groupby|pandas-resample | 0 |
19,501 | 51,399,741 | pandas assign multiple columns with conditional lambda expression | <p>I would like to add 2 columns (<code>cat_a</code>, <code>cat_b</code>) to DataFrame <code>df</code> using the <code>.assign()</code> method. But I don't get the code working...</p>
<pre><code>import pandas as pd
np.random.seed(999)
num = 10
df = pd.DataFrame({'id': np.random.choice(range(1000, 10000), num, replace=... | <p>Use vectorized solution with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="noreferrer"><code>numpy.select</code></a>:</p>
<pre><code>m1 = df.year ... | python-3.x|pandas|lambda|multiple-columns|assign | 7 |
19,502 | 51,176,922 | Split series of tuples in Pandas | <p>I have a dataframe with the index that consists of two parts: id and datetime of the form: <em>(2345, Timestamp('2009-10-21 17:00:00'))</em>. This index was created by using the following command: </p>
<pre><code>df=df.set_index(df['int'],append=True)
</code></pre>
<p>After some loop, I would like to split the ind... | <p>One efficient method is to extract the NumPy array representation of your tuple series, convert to a list of lists and feed into the <code>pd.DataFrame</code> constructor. You can then join onto your original dataframe.</p>
<p>With this method, data types are preserved. Here's a demo:</p>
<pre><code># set up dataf... | python|pandas|dataframe|indexing | 1 |
19,503 | 51,390,323 | Mapping data from a Pandas Dataframe column whose name is given in another column | <p>I have two dataframes and am trying to map data from one dataframe to the next. The first dataframe has player names as its index and a player/game ID as its header.</p>
<p>Dataframe 1:</p>
<pre><code>Date + Game 2015-04-12 PIT@MIL 2015-04-12 SEA@OAK \
Alcides Escobar 0 ... | <p>If I understand your intention correctly, more appropriate example datasets would be:</p>
<p><code>df1</code></p>
<pre><code> Date + Game 2015-04-12 PIT@MIL 2015-04-12 KAN@LAA
0 Alcides Escobar 1 5
1 Mike Moustakas 2 6
2 Lorenzo... | python|pandas|mapping | 1 |
19,504 | 71,012,495 | Vectorization using numpy | <p>I translated this code from matlab.It is part of a larger body of code But I would like to get some advice on how to vectorize this section in order to make it faster. my major concern is with the for loops and if statements. If possible I would like to write it without using an if else statement. (Jax is not able t... | <p>This is challenging to fully vectorize, but I assume it is possible. Here is a start that removes the if/else logic for the first loop. The trick is precomputing the k values (<code>smf_1</code> is trivial so I removed it):</p>
<pre><code>num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_in... | python|numpy|vectorization | 1 |
19,505 | 70,921,849 | Element wise operation on nested numpy array | <p>Background</p>
<p>I have a nested numpy array and I want to:</p>
<ol>
<li>First, add a different random value to each <strong>scaler element</strong> of nested numpy array</li>
<li>And then, delete the value larger than 10.</li>
</ol>
<p>...</p>
<pre><code>[[1, 2, 3], [4, 5], [6, 7, 8]]
#(add random value for each ... | <p>You can compute the length of each parts, compute the offset of each sections (number of item preceding the current item in a flatten representation), merge the parts with <code>np.concatenate</code>, add random number using a simple sum with <code>np.random.randn</code>, find the location of the maximum with <code>... | python|numpy|numpy-ndarray | 1 |
19,506 | 51,977,643 | How to use pandas to create a crosstab to show the prediction result of random forest predictor? | <p>I'm a newbie to the random forest (as well as python).
I'm using random forest classifier, the dataset is defined 't2002'.</p>
<pre><code> t2002.column
</code></pre>
<p>So here are the columns: </p>
<pre><code>Index(['IndividualID', 'ES2000_B01ID', 'NSSec_B03ID', 'Vehicle',
'Age_B01ID',
'IndIncome2002_B0... | <p>Its easy to show all the predicted results using pandas. Use <code>cv_results_</code> as described in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html" rel="nofollow noreferrer">docs</a>.</p>
<pre><code>import pandas as pd
results = pd.DataFrame(clf.cv_results_) #... | python|pandas|scikit-learn|random-forest|sklearn-pandas | 0 |
19,507 | 37,237,940 | How to serve retrained Inception model using Tensorflow Serving? | <p>So I have trained inception model to recognize flowers according to this guide. <a href="https://www.tensorflow.org/versions/r0.8/how_tos/image_retraining/index.html" rel="noreferrer">https://www.tensorflow.org/versions/r0.8/how_tos/image_retraining/index.html</a></p>
<pre><code>bazel build tensorflow/examples/imag... | <p>To serve the graph after you have trained it, you would need to export it using this api: <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/train.html#export_meta_graph" rel="nofollow">https://www.tensorflow.org/versions/r0.8/api_docs/python/train.html#export_meta_graph</a> </p>
<p>That api generate... | tensorflow|tensorflow-serving | 2 |
19,508 | 37,364,859 | Pandas Add Header Row for MultiIndex | <p>Given the following data frame:</p>
<pre><code>d2=pd.DataFrame({'Item':['y','y','z','x'],
'other':['aa','bb','cc','dd']})
d2
Item other
0 y aa
1 y bb
2 z cc
3 x dd
</code></pre>
<p>I'd like to add a row to the top and then use that as level 1 of a multiIndexe... | <p>I think you can first find number of columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html" rel="nofollow"><code>shape</code></a> and then create list by <code>range</code>. Last create <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.fr... | python-3.x|pandas|multi-index | 2 |
19,509 | 37,197,576 | Convert a pandas dataframe in the form of a matrix into a table | <p>I have a dataframe in the following form:</p>
<pre><code> P Q R S
A 0 2 1 1
B 2 0 1 1
C 1 1 0 0
D 1 1 0 0
</code></pre>
<p>I want to change it into the following form:</p>
<pre><code>A P 0
A Q 2
A R 1
A S 1
B P 2
B Q 0
B R 1
B S 1 and so on...
</code></pre>
<p>Basically, the fomat is:</p>
<... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="noreferrer"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a>:</p>
<pre><code>df = df... | python|pandas|matrix | 9 |
19,510 | 37,476,525 | Dynamically do a join on pandas dataframes | <p>I want to filter on a column and then dynamically join resulting dataframes. My naive approach is; given a dataframe, write a function that filters based on values in a column to get smaller then join. But I don't know how to join dynamically. Any better way of doing this?</p>
<pre><code>data = {'name': ['Jason', '... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>, <code>df</... | python|pandas | 1 |
19,511 | 42,052,798 | Python structured array not working | <p>I am importing a <code>153,673*25</code> csv data matrix with integers, floats and strings using pandas, through the IPython console in Anaconda's Spyder (Python 2). I then want to transform this data into a structured array, by specifying the column names through the pandaframe columns names and the types manually.... | <p>Reconstructing your problem without all the pandas complications:</p>
<pre><code>In [695]: names=['a','b','c']
In [696]: type_list=['int','float','int']
In [697]: datatype=list(zip(names,type_list))
In [698]: dt = np.dtype(datatype)
In [699]: dt
Out[699]: dtype([('a', '<i4'), ('b', '<f8'), ('c', '<i4')])
<... | python|pandas|numpy|structured-array | 0 |
19,512 | 37,897,894 | Shorter version of this numpy array indexing | <p>I have the following code in python (numpy array or scipy.sparse.matrices), it works:</p>
<pre><code>X[a,:][:,b]
</code></pre>
<p>But it doesn't look elegant. 'a' and 'b' are 1-D boolean mask.</p>
<p>'a' has the same length as X.shape[0] and 'b' has the same length as X.shape[1]</p>
<p>I tried <code>X[a,b]</code... | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> for such a <code>broadcasted indexing</code>, like so -</p>
<pre><code>X[np.ix_(a,b)]
</code></pre>
<p>Though this won't be any shorter than the original code, but hopefully shou... | python|numpy|matrix|indexing | 5 |
19,513 | 31,291,584 | Appending a multi-indexed column to the index of a DataFrame | <p>I have generated a initial dataframe called df and then an adjusted dataframe called df_new.</p>
<p>I wish to get from df to df_new using a set_index() operation.
My problem is how to negotiate the hierarchical index on columns</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.ones((5,5))... | <p>The DataFrame.set_index method takes an append keyword argument, so you can simply do like this:</p>
<pre><code>df_new = df.set_index(("Y", "d"), append=True)
</code></pre>
<p>If you want to add multiple columns, just provide them as a list:</p>
<pre><code>df_new = df.set_index([("Y", "d"), ("Y", "e")], append=Tr... | python|pandas | 1 |
19,514 | 64,315,635 | Numpy slicing by array? | <pre><code>import numpy as np
a = np.array([4, 3, 2, 1])
b = np.array([1, 2, 4, 3])
c = np.stack((a, b))
i = np.array([0, 1])
print(c[i])
</code></pre>
<p>I got:</p>
<pre><code>[[4 3 2 1]
[1 2 4 3]]
</code></pre>
<p>but my expectd output:</p>
<pre><code>[4 2]
</code></pre>
<p>How can I implement this?</p> | <p>What do you want to achieve here?</p>
<p><code>c = [[4 3 2 1] [1 2 4 3]];</code> from np.stack call</p>
<p><code>[c[0][0],c[1][1]]</code> returns <code>[4 2]</code> which is what you want.</p> | python|numpy | 1 |
19,515 | 64,521,261 | Why the dictionary element is not working with the max function in python? | <p>While working with a trainer module I used dictionary to store the parameter being observed and the corresponding accuracy of the data for the parameter value. The parameter being the key to the dictionary and the accuracy being the value.</p>
<p>I have used sklearn.metrics tool to calculate the accuracy here. But t... | <p>This use of <code>max</code> on dictionary is valid:</p>
<pre><code>In [1]: acc = {}
In [2]: acc = {'a':1, 'b':3, 'c':2}
In [3]: max(acc, key=acc.get)
Out[3]: 'b'
In [4]: type(max)
Out[4]: builtin_function_or_method
</code></pre>
<p>The error suggests that you have redefined <code>max</code>. It is no longer the bu... | python-3.x|list|numpy|dictionary|max | 1 |
19,516 | 64,212,979 | Order of plotting in Pandas.plotting.parallel_coordinates | <p>I have a series of measurements I want to plot as pandas.plotting.parallel_coordinates, where the color of the individual line is given by the value of one pandas.column.</p>
<p>Code looks like this:</p>
<pre><code>... data retrieval and praparation from a couple of Excel files
---> output = 'largeDataFrame'
the... | <p>I ran some tests with the pandas versions 1.1.2 and 1.0.3 and in both cases the lines are drawn from low to high value of the coloring column, independent of the dataframe order.</p>
<p>You can temporarily add <code>parallel_coordinates(...., lw=5)</code> which makes it very clear. With thin lines, the order is les... | python|pandas|matplotlib|parallel-coordinates | 1 |
19,517 | 47,972,932 | Detecting Curvature of a Plot | <p>I have a data set that I am plotting. The result looks like the following image:
<a href="https://i.stack.imgur.com/qwfrU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qwfrU.png" alt="enter image description here"></a></p>
<p>Here is my python code:</p>
<pre><code>import numpy as np
# Extra p... | <p>the curvature can be interpreted as the second derivative so:</p>
<pre><code>def derivative(x_data, y_data):
N = len(x_data)
delta_x = [x_data[i+1] - x_data[i] for i in range(N - 1)]
x_prim = [(x_data[i+1] + x_data[i]) / 2. for i in range(N - 1)]
y_prim = [(y_data[i+1] - y_data[i]) / delta_x[i] for ... | python|numpy|matplotlib|plot | 0 |
19,518 | 47,921,648 | Checking for a condition within a timeframe period in a dataframe. [Python] [Pandas] | <p>So I have a data frame, and I'm trying to check whether:</p>
<p>If a perpetrator and victim are in relation at a certain time (time stamp), whether the reverse happens, and the victim becomes a perpetrator, and vice versa, within a certain time frame.</p>
<p>E.g. <code>if X attacks Y at time Z</code> then add a co... | <p>Here is a solution that seems to work using <code>pd.merge_asof</code> which you can see the API here: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="nofollow noreferrer" title="merge_asof">merge_asof docs</a></p>
<pre><code>data = """
perpetrator,victim,date
FvdP,Jmall... | python|pandas|datetime|dataframe | 0 |
19,519 | 49,094,854 | Naive Bayes classifier - empty vocabulary | <p>I am trying to use Naive Bayes to detect humor in texts. I have this code taken from <a href="https://youtu.be/N-hJTaM9dEI" rel="nofollow noreferrer"><strong>here</strong></a> but I have some errors and I don't know how to resolve them because I am pretty new to Machine Learning and these algorithms. My train data c... | <p>The problem was not with the code, but with the train data. First of all, <code>G:/PyCharmProjects/naive_bayes_classifier/train_jokes</code> and <code>G:/PyCharmProjects/naive_bayes_classifier/train_non_jokes</code> must be the path to the directories that contain the files with train data (so train_jokes and train_... | python|machine-learning|scikit-learn|naivebayes|sklearn-pandas | 0 |
19,520 | 58,872,437 | How do you read files on desktop with jupyter notebook? | <p>I launched <code>Jupyter Notebook</code>, created a new notebook in <code>python</code>, imported the necessary <code>libraries</code> and tried to access a <code>.xlsx</code> file on the desktop with this <code>code</code>:</p>
<p><code>haber = pd.read_csv('filename.xlsx')</code> </p>
<p>but error keeps popping u... | <p>This is an obvious path problem, because your notebook is not booted on the desktop path, you must indicate the absolute path to the desktop file, or the relative path relative to the jupyter boot directory.</p> | python|python-3.x|pandas | 2 |
19,521 | 70,152,165 | How to parse a complex text file using Python string methods or regex and export into tabular form | <p>As the title mentions, my issue is that I don't understand quite how to extract the data I need for my table (The columns for the table I need are <code>Date</code>, <code>Time</code>, <code>Courtroom</code>, <code>File Number</code>, <code>Defendant Name</code>, <code>Attorney</code>, <code>Bond</code>, <code>Charg... | <p>It is quite a lot of work to achieve that, but it is possible. If you split it in a couple of sub-tasks.
First, your input looks like a text file so you could parse it line by line. -- using <a href="https://www.w3schools.com/python/ref_file_readlines.asp" rel="nofollow noreferrer">https://www.w3schools.com/python/r... | python|regex|pandas|list|csv | 1 |
19,522 | 56,417,784 | How to make a sequential adition of values in a dataframe | <p>I'm doing a research on land consumption and demographic growth.
I have a dataframe with a chronological sequence of population listed for a period of years.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'year': [2014, 2015, 2016, 2017, 2018], 'population': [66354, 63322,83381, 91563, 93709]})
</code></pre>... | <p>IIUC you're searching for the cumulative sum function <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum()</code></a>:</p>
<pre><code>df.population.cumsum()
# 0 66354
# 1 129676 ... | python|pandas|dataframe | 0 |
19,523 | 56,048,412 | Resample DataFrame at certain time intervals | <p>I have been working on a publicly available dataset in pandas which has some air quality statistics by each state of USA.</p>
<p>What I am doing is aggregating the measurements for each of the state and the issue I have is that different states have measurements available across different time periods. So, I am col... | <p>Try:</p>
<pre><code>all_dates = poll.index.levels[1]
date_range = pd.date_range(all_dates.min(), all_dates.max(), freq='MS')
flt = (poll.groupby('State')
.apply(lambda x: x.reset_index(level=1)
.resample('MS', on='Date Local')
.mean()
... | python|pandas | 1 |
19,524 | 55,724,579 | How to create a new column in dataframe, which will be a function of other columns and conditionals without iteratng over the rows with a for loop? | <p>I have a relatively large data frame (8737 rows and 16 columns of all variable types, strings, integers, booleans etc.) and I want to create a new column based on an equation and some conditionals. Basically, I want to iterate over one particular column, take its values and after multiplications, sums etc. create a ... | <p>You can do that really easily in two steps:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[1:, 'S'] = df.loc[1:, "D"] * 0.5 * df.loc[1:, "C"].abs() # Computes the numerical expression you want
df["S"] = df["S"].cumsum() # Add the previous to the current item of S
# Then compute your `if` condition
df... | python|pandas | 1 |
19,525 | 39,666,845 | How does "tf.train.replica_device_setter" work? | <p>I understood that <code>tf.train.replica_device_setter</code> can be used for automatically assigning the variables always on the same parameter server (PS) (using round-robin) and the compute intensive nodes on one worker.</p>
<p>How do the same variables get reused across multiple graph replicas, build up by diff... | <p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#replica_device_setter" rel="noreferrer"><code>tf.train.replica_device_setter()</code></a> is quite simple in its behavior: it makes a purely local decision to assign a device to each <a href="https://www.tensorflow.org/versions/r0.10/a... | python|tensorflow | 22 |
19,526 | 39,773,425 | python - Pandas - FillNa with another non null row having similar column | <p>I would like to fill missing value in one column with the value of another column.</p>
<p>I read that looping through each row would be very bad practice and that it would be better to do everything in one go but I could not find out how to do it with the fillna method.</p>
<p>Data Before</p>
<pre><code>Day Cat1... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> and pass the df without <code>NaN</code> rows, setting the index to <code>Cat2</code> and then calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Ser... | python|pandas|numpy|jupyter-notebook | 2 |
19,527 | 69,636,507 | Create key only if within intervall and add values of same keys | <p>I have the following code</p>
<pre><code> avg_lat={}
g_coords={}
for year,lat,num,long in zip(years,latitudes,quantities,longitudes):
if year in avg_lat:
avg_lat[year] += lat #Ignore avg_lat, this bit is irrelevant, but I gotta keep it for the code to work
if 58.50>lat&... | <p>You can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">defaultdict</a> from the standar library:</p>
<pre><code>from collections import defaultdict
# outside of the loop
g_coords = defaultdict(int)
# inside the loop
g_coords['some_key']+=1
</code... | python|list|numpy | 1 |
19,528 | 69,622,772 | how to order dictionary of dataframes by length | <p>I am trying to merge dataframes in a dictionary</p>
<pre><code>example_dict = {key1: df1, key2: df2, ....}
</code></pre>
<p>each of the dataframes are of different row length, and all have a column called <code>id</code></p>
<p>my plan was to do this:</p>
<pre><code>merged_dfs = partial(pd.merge, on='id', how='inner... | <p>You can get the length of a <code>DataFrame</code> through its <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html" rel="nofollow noreferrer">shape</a>, which you can use as a key to sort on:</p>
<pre class="lang-py prettyprint-override"><code>sorted_dict = dict(sorted(exa... | python|python-3.x|pandas|dataframe | 2 |
19,529 | 69,348,450 | How to convert a pandas dataframe to matrix format in Python? | <p>I have a pandas dataframe <code>df</code> which looks as shown. (<code>df.to_dict()</code> is given at the end):</p>
<pre><code>model scenario module
AIM/CGE 2.0 ADVANCE_2020_1.5C-2100 wind_total_share high high
SSP1-19 wind_total_share high high
SSP2-19 wind_total_share high high
AIM/C... | <p><code>pivot_table</code> could help here.</p>
<p>The 2nd matrix can be directly obtained with:</p>
<pre><code>df.assign(values=1).pivot_table(values='values', index='Infrastructure',
columns='Investment', aggfunc=sum)
</code></pre>
<p>which gives:</p>
<pre><code>Investment high low medium
Infrastruc... | python|python-3.x|pandas|dataframe|matrix | 3 |
19,530 | 69,627,654 | Converting pseudo algorithm to python -> pandas code | <p>I am trying to convert a pseudo code to pandas code. Would appreciate any help or guidance.</p>
<p>General idea is to come up with a function <code>f</code> to select rows from a toy example dataset which -> has 100 rows and 5 columns <code>["X", "Y", "Z", "F", "V"... | <p>Something like this, perhaps? It's not the cleanest, but I think it gets the work done.<br />
I was not clear on your intentions by <code>There are 5 probabilities for the second argument of the function -> selection based on [1, 2, 3, 4, 5] columns.</code> though.<br />
The idea here is to separate the columns a... | python|pandas|dataframe | 1 |
19,531 | 53,966,712 | How to change color to specific portion of an image in opencv python? | <p>I have an image of front facing man in which:</p>
<p>1) I used facial landmark detection to detect the chin point.</p>
<p>2) Add some specific value to lower its y-coordinate value.</p>
<p>3) Find out the width of image.</p>
<p>4) Draw an line through the point.</p>
<p>Now, what I want to do is change the color... | <p>Assumpt you have the chin point.</p>
<pre><code>import cv2
img = cv2.imread("2.png")
chin_point = (370,230)
img[chin_point[0]:,:] = [255,255,255]
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/JJR2h.jpg" rel="nofollow noreferrer"><img src=... | python|numpy|opencv|image-processing | 0 |
19,532 | 65,962,469 | I need to plot grouped data using matplotlib or seaborn | <p>I am trying to plot countries departments and their sales. So i have country, departments and their sales numbers in diff columns. And i need to create bar plot, so it should look like country1 and its departments on x-axis and sales y-axis, then country2 and so-on.</p>
<p>I tried seaborn's catplot but its giving me... | <p>You could create a <a href="https://seaborn.pydata.org/generated/seaborn.barplot.html" rel="nofollow noreferrer"><code>barplot()</code></a> using <code>'Country'</code> as <code>x</code> and <code>'Department'</code> as <code>hue</code>:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as... | python|pandas|matplotlib|plot|seaborn | 1 |
19,533 | 52,533,797 | gallery instead of camera activity (Tensorflow) in Android | <p>Is it possible to not use the camera activity and load the images from gallery for object detection using Tensorflow object detection API?</p> | <p>Obviously yes!</p>
<p>When you use the camera (not talking about real-time image detection, such as using Yolo with Tensorflow), you take a snapshot image and then you process that bitmap with Tensorflow. Instead of that, what you can do is, select an image from the gallery, convert it to bitmap and then process it... | android|tensorflow | 0 |
19,534 | 46,314,956 | Incrementally adding to a (2,n) array in a for loop in python | <p>I want to incrementally add to an array of shape (2,N) in a for loop with arrays of size (2,1) at each step of the loop. This is how I'm doing it right now:</p>
<pre><code>x = []
a = np.array([[0.5], [0.5]])
for i in range(0, N):
x = np.append(x, a + (np.random.randn(2, 1)/np.sqrt(5))).reshape(i+1, 2)
x = x.T
<... | <p>You can try by initializing the array at the beginning:
<code>x = np.zeros((2,N))</code> and then in the for loop fill it in with the <code>np.random.randn(2) / np.sqrt(5)</code>.</p> | python|arrays|numpy | 1 |
19,535 | 58,232,890 | How to work on "age bins" in Pandas Dataframe which are saved as string? | <p>I downloaded a dataset in .csv format from <strong>kaggle</strong> which is about lego. There's a "Ages" column like this:</p>
<pre><code>df['Ages'].unique()
array(['6-12', '12+', '7-12', '10+', '5-12', '8-12', '4-7', '4-99', '4+',
'9-12', '16+', '14+', '9-14', '7-14', '8-14', '6+', '2-5', '1½-3',
'1½-5', '9+... | <p>Not entirely sure what output you are looking for. See if the below code & output helps you.</p>
<pre><code>df['Lage'] = df['Ages'].str.split('[-+]').str[0]
df['Uage'] = df['Ages'].str.split('[-+]').str[-1]
</code></pre>
<p>or </p>
<pre><code>df['Lage'] = df['Ages'].str.extract('(\d+)', expand=True) #you don'... | python-3.x|pandas|dataframe|kaggle | 1 |
19,536 | 58,596,551 | How to update a single value in a complex numpy array | <p>I have the (1, 2, 2) Python numpy array (X) below that needs to be updated by replacing a single value at a time. I am for instance looking to replace 0.54 with 0.99 while dropping [0.11, 0.45] at the same time. I am struggling with replacing it appropriately. </p>
<p>I am just showing one slice of X but it is a ra... | <p>Just experimented a ton and here is how I am solving it now.</p>
<pre><code>val = current value to input (0.99)
</code></pre>
<p>then </p>
<pre><code>X[:,1:,1:] = val
</code></pre> | python|arrays|numpy|multidimensional-array | 0 |
19,537 | 58,422,361 | How to apply fillna to last N columns of a pandas dataframe? | <p>I have a data frame with many columns. I would like to fill the nan's with 0's for the last x number of columns. I used the following code but it doesn't seem to work.</p>
<pre><code>df.iloc[:, -10:-1].fillna(value=0, inplace=True)
</code></pre>
<p>What am I doing wrong? when I specifically refer to a column by na... | <p>A recipe that should work here is</p>
<pre><code>df.iloc[:, -x:] = df.iloc[:, -x:].fillna(value=0)
</code></pre>
<p>A reproducible example here is</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1':range(10),
'col2':range(1, 11),
'col3':range(2, 12),
... | python|pandas|fillna | 2 |
19,538 | 58,564,821 | Is it possible to integrate Levenberg-Marquardt optimizer from Tensorflow Graphics with a Tensorflow 2.0 model? | <p>I have a Tensorflow 2.0 <code>tf.keras.Sequential</code> model. Now, my technical specification prescribes using the Levenberg-Marquardt optimizer to fit the model. Tensorflow 2.0 doesn't provide it as an optimizer out of the box, but it is available in the <a href="https://www.tensorflow.org/graphics/api_docs/pytho... | <p>There's a major difference between <code>tfg.math.optimizer.levenberg_marquardt.minimize</code> and Keras optimizers from the implementation/API perspective.</p>
<p>Keras optimizers, such as <code>tf.keras.optimizers.Adam</code> consume gradients as input and updates <code>tf.Variable</code>s.</p>
<p>In contrast, <c... | tensorflow2.0|tf.keras | 1 |
19,539 | 58,351,454 | Python: Calling Inherited Parent Class Method Fails | <p>I created a pass-through wrapper class around an existing class from <code>sklearn</code> and it does not behave as expected:</p>
<pre><code>import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
tiny_df = pd.DataFrame({'x': ['a', 'b']})
class Foo(OrdinalEncoder):
def __init__(self, *args, **kw... | <p>You don't have to pass <code>self</code> again to the <code>super</code> function. And <code>scikit-learn</code>'s estimators should always specify their parameters in the signature of their <code>__init__</code> and no <code>varargs</code> are allowed else you will get a <code>RUNTIMEERROR</code>, so you have to re... | python|pandas|oop|scikit-learn | 3 |
19,540 | 44,516,511 | Difference between parallel and sequential Convolutions in Convolutional Neural Network | <p>I'm trying to implement a Convolutional Neural Networks with tensorflow for classifying text. I already found some implemented models and found especially two implementations: </p>
<p><em>[I'm not allowed to post more than 2 Links, I will try to provide the sources in the comments]</em></p>
<p>However they seem to... | <p>This is not necessary 'parallel' vs. 'sequential'. From what i'm seeing is that the 'parallel' implementation is actually just óne convolutional layer, however with <em>different filter sizes</em>.</p>
<p>Basically, if you just had a convolutional layer with 93x3 features it would be:</p>
<pre><code>input ... | tensorflow|neural-network|deep-learning|conv-neural-network | 3 |
19,541 | 44,614,276 | How does this class work? (Related to Quantopian, Python and Pandas) | <p>From here: <a href="https://www.quantopian.com/posts/wsj-example-algorithm" rel="nofollow noreferrer">https://www.quantopian.com/posts/wsj-example-algorithm</a> </p>
<pre><code>class Reversion(CustomFactor):
"""
Here we define a basic mean reversion factor using a CustomFactor. We
take a ratio of the ... | <p><strong>TL;DR</strong></p>
<ul>
<li><p><code>Reversion()</code> doesn't return a DataFrame, it returns an instance of the
<code>Reversion</code> class, which you can think of as a <strong>formula</strong> for performing a
trailing window computation. You can run that formula over a particular time
period using eith... | python|pandas | 7 |
19,542 | 44,633,033 | How to properly obtain date user input? | <p>This is the code I currently have:</p>
<pre><code>security = input('Security: $')
print ('Date format: YEAR,MO,DA')
s = input('Start date: ')
e = input('End date: ')
start = dt.datetime(s)
end = dt.datetime(e)
df = web.DataReader(security, 'google', start, end)
print (df.tail())
</code></pre>
<p>How do I properly... | <p>We are the most perverse species on the planet. It can be as well to take that into account. And dates are wicked. If the user doesn't put the commas in we can detect that and inform them. However, once they've done that we should be able to provide some support, assuming that they can get the order right. Here's a ... | python|pandas|datetime | 1 |
19,543 | 44,643,964 | Python "Most Recent Value Backfill" Is Slow | <p>I currently have an R-based algorithm that sorts a data.table by date and then finds the most recent non-NA / non-null value. I've found some success with the following
StackOverflow question to implement a backfilling algorithm for some relatively large datasets:</p>
<p><a href="https://stackoverflow.com/questio... | <p>Edited to add another perhaps clearer answer. Define a function that gets the first non-missing value unless they are all missing then returns null.</p>
<pre><code>def find_first(s):
s = s.dropna()
if len(s) == 0:
return np.nan
return s.iloc[0]
GT = DT.sort_values(['id', 'date'], ascending=[Tru... | python|r|pandas|data.table | 2 |
19,544 | 60,911,357 | Creating a matrix of matrices using numpy.array() | <p>I've been trying to create a matrix of matrices using the numpy function numpy.array() and am facing difficulties</p>
<p>I'm specifically trying to create the following matrix </p>
<p>[</p>
<p>[</p>
<pre><code> [ [
[ 1 ,2 ] [ 1 , 2 ]
[ 3 ,4 ] [ 3 , 4 ]
] ... | <pre><code>>>> a = np.array([[[[1,2],[3,4]], [[1,2], [3,4]]], [[[1,2],[3,4]], [[1,2], [3,4]]]])
>>> a
array([[[[1, 2],
[3, 4]],
[[1, 2],
[3, 4]]],
[[[1, 2],
[3, 4]],
[[1, 2],
[3, 4]]]])
</code></pre> | python|numpy|matrix | 1 |
19,545 | 61,046,093 | Load all mat files from subdirectories | <p>I have lots of data in .mat format. Moreover, my main data folder has lots of subfolders. Under each subfolders, I have 1000 .mat data files. I want to load all of them by using python. I am trying , but unable to do it automatically. I want help to write a function in which</p>
<ol>
<li>It will go to each director... | <p>try this function - it loop over all subfolders and find and load .mat files and load those to a struct, which organizes each folder and file names as subfields.</p>
<pre><code>function data=loadmatfromdir(rootdir)
fd=dir(rootdir);
data=struct();
for i=1:length(fd)
fname=[fd(i).folder filesep fd(i).name];
i... | python-3.x|matlab|directory|scipy|numpy-ndarray | 1 |
19,546 | 60,878,841 | Is it possible to drop a specific column in a numpy array? | <p>I have this dataset</p>
<pre><code>[[0.96570218 0.97916859 0. 0.98769127]
[0.96570218 0.97916859 0. 0.98769127]
[1. 1. 0. 1. ]
[1. 1. 0. 1. ]
[0.86415196 0.86027468 0. 0.85840598]
[0.86415196 0.86027468 0. 0.85840598]... | <pre><code>import numpy as np
arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
# using indices
cols = [0,2,3]
arr2 = arr[:,cols]
# using boolean condition
cond = np.arange(arr.shape[-1])!=1 # [True,False,True,True]
arr2 = arr[:,cond]
</code></pre> | python|numpy | 1 |
19,547 | 42,319,337 | Tensorflow Type Error: Value passed to parameter 'shape' has DataType float32 not in list of allowed values: int32, int64 | <p>I am trying to create a DCGAN and I'm running into this error when I think I'm trying to use a linear() method:</p>
<pre><code>Traceback (most recent call last):
File "spritegen.py", line 71, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line... | <p>The error raises in the following line:</p>
<pre><code>self.h0 = tf.reshape(self.z,[-1, sample_H16, sample_W16, self.gen_dimension * 8])
</code></pre>
<p>you probably only have to cast to int the parameters that may not be:</p>
<pre><code>self.h0 = tf.reshape(self.z,[-1, sample_H16, sample_W16, int(self.gen_dimen... | python|tensorflow|artificial-intelligence | 5 |
19,548 | 69,782,280 | df.value.counts() doesn't show number of occurrences in dataset | <p>Here is a small sample of the data I'm working on.</p>
<p><a href="https://i.stack.imgur.com/jsgWE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jsgWE.png" alt="enter image description here" /></a></p>
<p>I'm trying to calculate how many times the same ID appears in the data using</p>
<pre><code... | <p>Using <code>groupby</code> + <code>transform</code> or <code>value_counts</code> + <code>map</code> should be the preferred ways of doing it.</p>
<pre><code>df['Total Occurences'] = df.groupby('ID')['ID'].transform('count')
</code></pre>
<p>or</p>
<pre><code>df['Total Occurences'] = df['ID'].map(df.value_counts('ID'... | python|pandas | 5 |
19,549 | 43,105,783 | Trying to compute the error from comparing two arrays | <p><strong>Some context:</strong> I have an explicit formula which is the exact solution to my problem. I have written code which implements a finite-difference scheme (explicit Forward-Euler, i.e: forward march-in-time iterative scheme) to approximate the solution to a partial differential equation (PDE). I have discr... | <p>Maybe it would help to go through your program line-by-line:</p>
<pre><code># Compute the Error
E = np.zeros((N+1, M+1)) # so that E has NxM entries--one for each time-step and node in space
# to get NxM use np.zeros((N, M))
for m in range(1, M+1):
for j in range(0, N+1):
# any reason you start the outer l... | python|arrays|numpy | 2 |
19,550 | 72,431,984 | Index a pandas dataframe based on row string value conditionally containing some row specific regex | <p>I would like to conditionally select rows in a pandas dataframe if a string value contains some other string values, defined as a regex. The string values to check for change per row, and right now are stored in a series, with the formats displayed below:</p>
<pre><code>df = pd.DataFrame(["a", "a"... | <p>Well, I will let you <code>timeit</code> the code below:</p>
<p>First concat the "regex" serie to the original DF:</p>
<pre><code>df = pd.DataFrame(["a", "a", "b", "c", "de", "de"], columns=["value"])
regex = pd.Series(["a|b|c"... | python|pandas|dataframe | 1 |
19,551 | 50,419,135 | Pandas rolling function with shifted indices | <p>The code</p>
<pre><code>s = pd.Series([0,1,2,3,4])
sr = s.rolling(3)
sr.apply(np.sum)
</code></pre>
<p>returns the series with indices [0,1,2,3,4] and values [NaN, NaN, 3, 6, 9]. Is there a quick hack, <em>specifically using pandas rolling functions,</em> so that it returns the rolling sum from the <em>following</... | <p>The only difference is a shift by -2:</p>
<pre><code>w = 3
s.rolling(w).sum().shift(-w + 1)
0 3.0
1 6.0
2 9.0
3 NaN
4 NaN
dtype: float64
</code></pre> | python|pandas | 3 |
19,552 | 62,714,673 | How can I calculate the gradient of a vector field from its values? | <p>I'd like some help with numpy and arrays. I want to calculate the gradient of a vector field.</p>
<p>Suppose I have a function foo that takes a tuple of coordinates (x,y,z) and returns a vector (u,v,w).</p>
<p>Then if I have an array of coordinates POS = [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],etc] I can generate an array... | <p>You can use <code>numpy.gradient</code> for this in the following way:</p>
<pre><code>import numpy as np
N = 100
limit = .1
def vec(x,y,z): # Example vector field
return np.array([x,x,z])
x = np.arange(-limit, limit, 2*limit/N) # np.arange takes the spacing as 3. arg
y = np.arange(-limit, limit, 2*limit/N)
z ... | python-3.x|numpy|vector|gradient|derivative | 0 |
19,553 | 62,614,399 | Ambiguous argument is not working in df['datetime'].dt.tz_localize('America/Los_Angeles', ambiguous ='NaT') for date that spans DST change | <p>I am trying to convert my datetime column of my pandas DataFrame to the timezone 'America/Los_Angeles' on a date where there is a switch from <strong>standard time</strong> to <strong>daylight savings time</strong>. It was my understanding that to get pandas to accept any ambiguous times generated due to this switch... | <p>2019-03-10 02:00:00 'America/Los_Angeles' is <em>not</em> ambiguous. It never existed at all. But no worries, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tz_localize.html" rel="nofollow noreferrer">pandas.Series.tz_localize</a> can deal with that case too:</p>
<p>nonexistent :... | python-3.x|pandas|timezone | 1 |
19,554 | 62,599,169 | Solving systems of equations modulo a certain number, with or without numpy | <p>Suppose I have this system of equations:</p>
<p><a href="https://i.stack.imgur.com/bUoI1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bUoI1.png" alt="enter image description here" /></a></p>
<p>If I wanted to solve it using numpy, I would simply do this:</p>
<pre><code>a = numpy.array([[1, 1, 1... | <p>If <code>gcd(a.det(), m) == 1</code> you can do following. The idea is to use <code>adj(a) = det(a) * a^(-1)</code> so keeping all parts as integer.</p>
<pre><code>import sympy
from math import gcd
a = sympy.Matrix([[1, 1, 1],[1,3,9],[1,5,8]])
b = sympy.Matrix([8, 10, 11])
m = 17
det = int(a.det())
if gcd(det, m) ... | python|numpy|linear-algebra|equation|modulo | 1 |
19,555 | 62,665,805 | Unable to add lines to `axes` used by pandas `plot` method | <p>I find the <code>pandas</code> <code>DataFrame.plot</code> method very useful and I especially like the way it formats the x ticks when the x variable is a date. However, there are times when I want to add more complicated marks on top of a plot that was generated using <code>DataFrame.plot</code>. For example, plot... | <p>Use <code>x_compat=True</code>, see docs <a href="https://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#suppressing-tick-resolution-adjustment" rel="nofollow noreferrer">here</a>:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
test = pd.DataFrame({
"a": pd.date_ra... | python|pandas|matplotlib | 1 |
19,556 | 54,570,264 | Scaling without losing value importance Python Sklearn | <p>The sample of the csv is: </p>
<pre><code>0.03528821669081923,0.4209514856338501
0.4755249949860231,0.4248427748680115
0.09710556840327728,0.4209169149398804
0.07149631133318766,0.4201127290725708
-0.2400341908399068,0.417565792798996
-0.17768551828033466,0.4184338748455048
-0.30025757809215714,0.416279673576355
-... | <p>One thing you could do is to instead use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" rel="nofollow noreferrer"><code>sklearn.preprocessing.StandardScaler</code></a>, which can be fitted using an array, and then transform o... | python|python-3.x|pandas|scikit-learn | 1 |
19,557 | 54,654,556 | How to add series of dictionary with unknown number of keys | <p>I have created following dictionary <code>test</code>, consisting of <code>Series</code> objects:</p>
<pre><code>test = {
'A': pd.Series([True, False, True]),
'B' : pd.Series([True,False,False])
}
</code></pre>
<p>I would like to perfrom <code>test['A'] & test['B']</code>. My problem is that I want to ... | <p>There are many advantages to working with a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><code>DataFrame</code></a> instead of a dictionary of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html" rel="nofollow ... | python|pandas|dictionary|series|bitwise-and | 1 |
19,558 | 73,815,635 | How to create separate legend sections for colors and markers | <p>I would like to plot two features in the same plot. My problem is with the legend. I would like to have one legend for colors(species) and one for the marker (Label defined by me). And I don't need to repeat the colors in the legend, as is happening in this example.</p>
<p>this is what I'm trying:</p>
<pre><code>imp... | <ul>
<li>This is more easily done by reshaping the dataframe into a long form with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>pandas.DataFrame.melt</code></a>.
<ul>
<li>The seaborn plot API works best with <code>data=</code> in a long form.</li>
<li... | python|pandas|seaborn|scatter-plot | 2 |
19,559 | 73,662,035 | DF1 is a subset of DF2 DF3 = DF2 - DF1 that will give rows that are not same store in df3 | <p>Dataframe 1 (df1):-</p>
<pre><code> date L120_active_cohort_logins L120_active_cohort percentage_L120_active_cohort_logins
0 2022-09-01 32679 195345 16.728865
1 2022-09-02 32938 196457 ... | <p>This worked for me</p>
<pre><code> pd_df1 = pd.merge(click_df1, click_df2, on="L120_active_cohort_logins", how='outer', indicator='Exist')
pd_df1 = pd_df1.loc[pd_df1['Exist'] != 'both']
final_df = pd_df1[pd_df1['Exist'] == 'right_only'][['date_y','L120_active_cohort_logins','L120_active_cohort... | python|pandas|dataframe | 0 |
19,560 | 73,804,090 | Is it possible to convert a TensorFlow (Keras) model from BGR to RGB? | <p>I have converted a Caffe model, learned on BGR data, to ONNX format and then from ONNX to TensorFlow (Keras)
So now I have a Keras model, learned on BGR data. Is it possible to convert it in such a way, that it will properly work with RGB data?</p>
<p>I've tried to convert it to OpenVINO with the --reverse_input_cha... | <p>You can create a new model: first a lambda layer which will reverse the channel order, than your saved model:</p>
<pre><code>input_shape = old_model.get_layer(index = 0).input_shape[0][1:]
inputs = Input(shape=input_shape)
lambda_layer = Lambda(lambda x: x[:,:,:,::-1])(inputs)
outputs = old_model(lambda_layer)
new_m... | python|java|tensorflow|keras|tf.keras | 1 |
19,561 | 71,124,194 | Pairwise match and merging of overlapping sequences in pandas dataframe | <p>I have a pandas dataframe, containing four columns; a reference sequence, a read from that reference sequence, and start/end positions of that read. I am trying to iterate over this dataframe and check rows pairwise to see if the reads overlap based on their start and end positions, and merge them if they do. Next, ... | <p>You could use a custom group to identify the non overlapping stretches, then use it to aggregate with <code>join</code>/<code>min</code>/<code>max</code>:</p>
<pre><code>group = df['start'].gt(df.groupby('reference')['end'].shift()-1).cumsum()
# [0, 0, 0, 0, 1, 1]
(df.groupby(['reference', group])
.agg({'read': ... | python|pandas|overlapping | 0 |
19,562 | 71,294,008 | Transform json data into a dataframe | <p>I tried to transform JSON data into a dataframe with the following code:</p>
<pre><code>import json
l = []
for line in open('data.json', 'r'):
l.append(json.loads(line))
df = pd.DataFrame(l)
df.parameters.head(1))
</code></pre>
<p>l looks like this :</p>
<pre><code>{"user_id":0,"client":&quo... | <p>Use list comprehension with DataFrame constructor:</p>
<pre><code>m = df['parameters'].notna()
df1 = pd.DataFrame([{y['key']: y['value'] for y in x} for x in df.pop('parameters').dropna()],
index=df.index[m])
df = df.join(df1)
</code></pre> | python|json|pandas|dataframe | 3 |
19,563 | 71,334,421 | Is there a better and fast way to check user input beside IF statement using python and streamlit? | <p>I have a dataframe that includes about 22 columns. I want to allow the user to perform a custom filter based on his input. Where the app displays a list of checkboxes that the filter is made based on the checked one.</p>
<p>Example of dataframe:</p>
<pre><code>data = {'name':['Tom', 'nick', 'krish', 'jack', 'Tom'],
... | <p>Assuming the filtering of each field is independent, you can filter the row of the dataframe by producing a column (ie. Numpy array) of boolean for each filter. Then you can apply several logical-ORs and logical-ANDs to mix the result of each filter so to produce a final filtering mask. Here is a simplified example:... | python|pandas|if-statement|filter|streamlit | 0 |
19,564 | 60,615,115 | How to execute a script in a virtual environment from a bash script on server? | <p>I am trying to run a python script in a virtual environment in a server using oarsub :</p>
<p>So firstly I run this command in a server name "a" : </p>
<pre><code>oarsub -l /host=1/gpu=1,walltime=2:00:00 './training_corpus1.sh'
</code></pre>
<p>training_corpus1.sh looks like this at the beguinning :</p>
<pre><c... | <p>For a virtual environment and <code>bash</code> the activation command is</p>
<pre><code>source env/bin/activate
</code></pre>
<p>where <em>env</em> is the directory of the virtual environment to activate.</p>
<p>PS. Let me advice you to start any script with <code>set -e</code> to allow fast failing on any error... | python|anaconda|pytorch|virtualenv | 0 |
19,565 | 60,749,614 | efficient way of concat columns depending on condition | <p>MRE:</p>
<pre><code>dictionary = {'2018-10': 50, '2018-11': 76}
df = pd.DataFrame({
"date":["2018-10", "2018-10", "2018-10", "2018-11","2018-11"]
})
</code></pre>
<p>that looks like (I have milions of rows and multiple rows):</p>
<pre><code> date
0 2018-10
1 2018-10
2 2018-10
3 2018-11
4 2018-1... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>pd.Series.map</code></a> can take a <code>dict</code> as the mapping, and strings and string columns can be added, so it's actually as easy as</p>
<pre><code>df['date'] = df['date'] + ' (' + d... | python|pandas | 1 |
19,566 | 60,384,752 | Pandas Dataframe how to iterate over rows and perform calculations on their values | <p>I've started to work with Pandas Dataframe and try to figure out how to deal with the below task.
I have an excel spreadsheet that needs to be imported to Pandas DataFrame and the below calculations need to be done to populate PercentageOnSale , Bonus and EmployeesIncome columns.
If the sum of all SalesValues for th... | <p>You could try <code>groupby-apply</code> as follows:</p>
<pre><code># Data
df = pd.DataFrame({"EmployeeID":[1,1,2,3,1,3,5,1],
"ProductSold":["P1","P2","P3","P1","P2","P3","P1","P2"],
"SalesValue":[3000,3500,4000,3000,5000,3000,3000,4000]})
# Calculations
def calculate(x):
... | pandas|dataframe | 0 |
19,567 | 59,505,713 | How to sort DataFrame and show it in Pandas? | <p>I have Pandas DataFrame like this: </p>
<pre><code>data = pd.DataFrame({"car":["mazda", "audi", "audi", "bmw", "mazda"], "price":[10000, 20000, 30000, 40000, 50000]})
</code></pre>
<p>And now by using my code below I acheived in columns: car, mean, min, max price, but I want to have 1 column more in this table whi... | <p>First of all, its better to create your groupby dataframe like this, to prevent <code>MultiIndex</code>:</p>
<pre><code>dfg = data.groupby("car")['price'].agg(['mean', 'min', 'max'])
</code></pre>
<p>Then to create a rank column, use <code>Series.rank</code>:</p>
<pre><code>dfg['rank'] = dfg['mean'].rank().astype... | python|pandas | 1 |
19,568 | 40,710,747 | How to create Histograms in Panda Python Using Specific Rows and Columns in Data Frame | <p>I have the following data frame in the picture, i want to take a <strong>Plot a histogram</strong> to show the distribution of all countries in the world for any given year (e.g. 2010). </p>
<p>Following is my code table generates after the following code of cleaning:</p>
<pre><code>dataSheet = pd.read_excel("http... | <p>In order to plot a histogram of all countries for any given year (e.g. 2010), I would do the following. After your code:</p>
<pre><code>dataSheet = pd.read_excel("http://api.worldbank.org/v2/en/indicator/EN.ATM.CO2E.PC? downloadformat=excel",sheetname="Data")
dataSheet = dataSheet.transpose()
dataSheet = dataShe... | python|pandas|histogram|data-science | 2 |
19,569 | 40,414,045 | How to use tf.nn.embedding_look() when the first dim of the embedding matrix will increase? | <p>I'm applying the word vector model to online news articles. Since I could get new articles everyday, I won't be able to know the 'true' vocabulary size.</p>
<p>Say I have 10 articles now and have a vocabulary of 1000. I initialise the word embedding matrix to a shape of <code>[1000, emb_size]</code> and train the m... | <p>You can use <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#pad" rel="nofollow noreferrer">tf.pad()</a> to expand on the dimension. </p> | python|tensorflow | 0 |
19,570 | 40,656,090 | how you use .query with pandas and numpy? | <p>From the file output_hc_v1.csv
with headers :emplid pay_status count location deptid grade_desc date version</p>
<p>I would like via python save a new csv filtered on "pay_status=Active".
with this code:</p>
<pre><code>a1=a.query ('"pay_status" == ["Active"]')
</code></pre>
<p>==========================... | <p>You do not need to quote column names in the query string. Therefore you could use,</p>
<pre><code>a1 = a.query('pay_status == "Active"')
</code></pre> | python|csv|pandas|numpy | 1 |
19,571 | 18,242,617 | Plotting Weekly Tick Data From A Year Time Series | <p>I have a time series that lists tick price data for a futures contract for a few months worth of trading history. I would like to have one plot (line chart) that shows the trading history of the tick data for each week for the most recent 4 weeks in the time series (the series is continually being updated)</p>
<p>... | <p>To give you some fake data:</p>
<pre><code>In [11]: rng = pd.date_range('2013', freq='H', periods=1000)
In [12]: df = pd.DataFrame(np.random.randn(len(rng)), index=rng, columns=['data'])
</code></pre>
<p>First, populate the week number (as a column):</p>
<pre><code>In [13]: df['week'] = df.index.week
</code></pr... | python|matplotlib|pandas|time-series | 1 |
19,572 | 58,163,011 | Merge Dataframes with missing data in either one or the other column | <p>I have two dataframes (<code>df1</code> and <code>df2</code>) I want to merge. There is a common key (<code>id</code>) to both dataframes. Both dataframes have the columns <code>Feature1</code> and <code>Feature2</code>. For each id the data belonging to <code>Feature1</code> would be either in <code>df1</code> or <... | <p>If values in <code>id</code> are same in both <code>DataFrame</code>s and also index are same in both:</p>
<pre><code>df1.update(df2)
print (df1)
id Feature1 Feature2
0 1 A B
1 2 C D
2 3 E F
3 4 G H
4 5 I J
</code></pre>
<p>If not sure po... | python|pandas|merge | 0 |
19,573 | 57,927,746 | How to combine data frames with different (but sometimes overlapping) indexes over a period of time in pandas? | <p>This is a continuation of my <a href="https://stackoverflow.com/questions/57913979/how-to-combine-data-frames-of-different-sizes-and-overlapping-indexes-vertically/">other StackOverflow post</a>. Suppose I have a few data frames that are coming in with any random order (below, I'll mock those data frames). </p>
<pr... | <p><code>concat</code> + <code>groupby</code> on <code>axis=1</code></p>
<pre><code>l=[df1,df2,df3,df4]
m=pd.concat(l,axis=1,sort=False)
m.groupby(m.columns,axis=1).first().fillna('') #ideally don't use the fillna
</code></pre>
<hr>
<pre><code> 2016-01 2016-02 2016-03 2016-04 2017-01 2017-02 2017-03 2017-04
N1 ... | python|pandas|dataframe | 2 |
19,574 | 57,995,172 | "You should never modify something you are iterating over". How do I modify it then? | <p>I've read in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer">Pandas documentation</a> and many comments here that you should never modify something you are iterating over. </p>
<p>Let's say I have this <code>dataframe</code>:</p>
<pre><c... | <p>You should always escape from <code>for</code> loop while using <code>pandas</code>. <code>pandas</code> stands for optimizing those loops.</p>
<p>Here is the code that solves your problem:</p>
<pre><code>idx_smith = mydf[mydf["name"].str.startswith("j")].index
idx_age = mydf[mydf["age"] > 40].index
mydf.loc[id... | python|pandas | 0 |
19,575 | 58,118,995 | Using a DataFrame filter on a different DataFrame | <p>I have two dataframes:</p>
<pre><code>df1:
ID var1
1 Foo
2 Foo
3 Foo
4 Bar
df2:
ID var1
2 Foo
3 Bar
4 Bar
5 Foo
6 Bar
</code></pre>
<p>I have created a filter for df1 where var1 = 'Foo':</p>
<pre><code>foo_filter=df1['var1']=='Foo'
</code></pre>
<p>Which when applied to df1 correctly returns:</p>
<pre><cod... | <p>Only you need:</p>
<p><strong>if ID is the index, putting ID as column:</strong></p>
<pre><code>df1.reset_index(inplace=True) #if ID is the index
df2.reset_index(inplace=True) #if ID is the index
filtered_df1=df1[df1['var1'].eq('Foo')]
print(filtered_df1)
ID var1
0 1 Foo
1 2 Foo
2 3 Foo
</code></pre>... | python|pandas|dataframe | 1 |
19,576 | 34,335,393 | Bokeh Line chart not plotting complete pandas dataframe | <p>I'm not sure if this is an issue because charts are currently being updated in Bokeh but I can no longer plot a complete dataframe using Line charts from Bokeh in my Jupyter notebook. Using <a href="http://bokeh.pydata.org/en/0.8.1/docs/user_guide/charts.html" rel="nofollow">this example from the docs</a>:</p>
<pre... | <p>Updating to <code>0.11.0dev4</code> through conda fixed the issue.</p>
<pre><code>conda install -c bokeh/channel/dev bokeh
</code></pre> | python-2.7|pandas|bokeh|jupyter-notebook | 2 |
19,577 | 36,875,978 | Merge of more than 2 python pandas data frames | <p>I have some data frames like this</p>
<pre><code>num a -- num b -- num c -- num d
101 0 101 1 102 0 101 1
102 1 103 1 103 0 102 0
103 0 104 0 104 1 103 1
104 0 105 0 105 1 104 1
105 1 107... | <p>Apart from <code>pd.concat</code>, you can also use <code>pd.merge</code>.</p>
<pre><code>import pandas as pd
import io
a = pd.read_csv(
io.StringIO(
"num,a\n101,0\n102,1\n103,0\n104,0\n105,1\n106,1\n"
),
header = 0
)
b = pd.read_csv(
io.StringIO(
"num,b\n101,1\n103,1\n104,0\n105,0\... | python|pandas|dataframe|merge|concat | 1 |
19,578 | 36,781,698 | Function to compute 3D gradient with unevenly spaced sample locations | <p>I have experimental observations in a volume:</p>
<pre><code>import numpy as np
# observations are not uniformly spaced
x = np.random.normal(0, 1, 10)
y = np.random.normal(5, 2, 10)
z = np.random.normal(10, 3, 10)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
# fake temperatures at those coords
tt = xx*2 + yy... | <p>Two things to note: First, scalars are single values, not arrays. Second, the signature of the function is <code>numpy.gradient(f, *varargs, **kwargs)</code>. Note the * before <code>varargs</code>. That means if <code>varargs</code> is a list, you pass <code>*varargs</code>. Or you can just provide the elements of ... | python|numpy|multidimensional-array|data-manipulation|gradient | 3 |
19,579 | 54,754,711 | Hot to use pd.datetime() on milliseconds timestamp? | <p>I am trying to convert my time from an object (as I read it from csv file) to a datetime format.
my time format is 07:00:00.16 (hour:minutes:seconds.milliseconds)</p>
<pre><code>import pandas as pd
df=pd.read_csv('Copy.txt')
df.columns = df.columns.str.strip()
df['Time']=pd.to_datetime(df.Time, errors = 'coerce')
... | <p>If your csv has time stored in string format like <code>'07:00:00.16'</code> you can simply specify the format and extract the <code>time</code> part to convert your column into <code>datetime</code> object: </p>
<pre><code>df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f').dt.time
</code></pre> | python|pandas|milliseconds | 2 |
19,580 | 54,904,448 | boost python - nullptr while extracting ndarray | <p>I have a C++ code which execute python script with boost_python package. Everything is fine, as longa as I extract int, string, or other not-array variables from python. However I have to extract a <code>numpy::ndarray</code> and convert it to <code>cpp vector</code>. I tried as follow:</p>
<p><code>main.cpp</code>... | <p>That error occurs since you're using the <code>numpy</code> module without first initializing it.</p>
<p>Notice the beginning of the official <a href="https://www.boost.org/doc/libs/1_69_0/libs/python/doc/html/numpy/tutorial/simple.html" rel="nofollow noreferrer">tutorial</a>:</p>
<blockquote>
<p>Initialise the ... | python|c++|boost|boost-python|numpy-ndarray | 2 |
19,581 | 49,614,569 | Insert value from one dataframe to another without using list? | <p>I have a <code>dictionary</code> in the following format</p>
<pre><code>cust_dict = {ABC:['Particulars','Date'], BCD:['Particulars','Date']}
</code></pre>
<p>The <code>'Particulars'</code> and <code>'Date'</code> are columns of the <code>DataFrame</code> i.e. <code>ABC</code> and <code>BCD</code></p>
<p>There is ... | <p>Your dictionary contains a list each. So, you'd solve your problem by:</p>
<pre><code>for index,row in df.iterrows():
cust_name = row[0]
cust_dict[cust_name][0] = row[0]
cust_dict[cust_name][1] = row[1]
</code></pre>
<p>Hope that helps...</p> | python|pandas | 1 |
19,582 | 73,511,472 | Add an additional column to a panda dataframe comparing two columns | <p>I have a dataframe (df) containing two columns:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Banana</td>
</tr>
<tr>
<td>Chicken</td>
<td>Chicken</td>
</tr>
<tr>
<td>Dragonfruit</td>
<td>Egg</td>
</tr>
<tr>
... | <p>You can simply use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><strong><code>np.where</code></strong></a> :</p>
<pre><code>import numpy as np
df['Same'] = np.where(df['Column 1'] == df['Column 2'], 'Yes', 'No')
</code></pre>
<h4><code>>>> print(df)<... | python|pandas|dataframe|comparison | 2 |
19,583 | 73,378,502 | Memory Error using np.unique on large array to get unique rows | <p>I have a large 2D Numpy array like <code>arr = np.random.randint(0,255,(243327132, 3), dtype=np.uint8)</code>.</p>
<p>I'm trying to get the unique rows of the array. Using np.unique I get the following memory error:</p>
<pre><code>unique_arr = np.unique(arr,axis=1)
--------------------------------------------------... | <blockquote>
<p>Is there a way to avoid the memory error ?</p>
</blockquote>
<p>Yes. The idea comes from <a href="https://discuss.dizzycoding.com/find-unique-rows-in-numpy-array/?amp=1" rel="nofollow noreferrer">this</a> blog post, where the author explore eight different ways to find unique rows in numpy (Actually thi... | python|numpy|memory|numpy-memmap | 1 |
19,584 | 35,139,762 | Finding the indices of all points corresponding to a particular centroid using kmeans clustering | <p>Here is a simple implementation of kmeans clustering (with the points in cluster labelled from 1 to 500):</p>
<pre><code>from pylab import plot,show
from numpy import vstack,array
from numpy.random import rand
from scipy.cluster.vq import kmeans,vq
# data generation
data = vstack((rand(150,2) + array([.5,.5]),rand... | <p>In this line:</p>
<pre><code>idx,_ = vq(data,centroids)
</code></pre>
<p>you have already generated a vector containing the index of the nearest centroid for each point (row) in your <code>data</code> array.</p>
<p>It seems you want the row indices of all of the points that are nearest to centroid 0, centroid 1 e... | python|numpy|scipy|cluster-analysis|k-means | 2 |
19,585 | 30,898,318 | Beatbox: Possible to add condition to query when pulling SFDC data? | <p>In Pandas, I want to pull Opportunity data with CreatedDate >= 1/1/2015.</p>
<p>Currently, I am extracting all Opportunity data before filtering for CreatedDate. Is it possible to optimize this process by adding the CreatedDate condition to the query?</p>
<p><strong>Current State:</strong></p>
<pre><code>query_re... | <p>Yes, you can add the condition to the salesforce query, e.g.</p>
<p>SELECT ID, CreatedDate from Opportunity WHERE CreatedDate > 2015-01-01T00:00:00Z</p>
<p>As CreatedDate is a Date/Time field, you need to provide a full dateTime for the comparison value.</p>
<p>the <a href="https://developer.salesforce.com/docs/a... | python|pandas|salesforce|beatbox | 2 |
19,586 | 67,452,378 | How to remove a outliers with z-scores (3 or -3) using apply function | <p>I was working on UCI heart disease, and changed all the measurable values into z scores, and I want replace the values which are greater than 3 or smaller than -3 with 3 and 3 respectively or with mean.</p>
<p>My sample code is:</p>
<pre><code>> import pandas as pd import numpy as np
>
> df= pd.DataFrame({... | <p>The <code>lambda</code> syntax is such that after <code>x:</code>, you just state the function value, without repeating the <code>x</code> (except for the conditions in this case).</p>
<pre class="lang-py prettyprint-override"><code>df['X'].apply(lambda x: 3 if x > 3 else (-3 if x < -3 else x))
</code></pre> | python-3.x|pandas|data-cleaning | 0 |
19,587 | 67,361,824 | Convert dataframe objects to float by iterating over columns | <p>I want to convert data in Pandas.Series by iterating over Series</p>
<p>DataFrame df looks like</p>
<pre><code> c1 c2
0 - 75.0%
1 -5.5% 65.8%
.
n - 6.9%
</code></pre>
<p>'%' and '-' only values should be removed. Desired result:</p>
<pre><code> c1 c2
0 0.0 75.0
1 -5.5 65.8
.
n 0.0 6.9
</cod... | <p>EDIT: Improved regex</p>
<pre><code># Thanks to @tdy
df.replace({'\%':'', r'^\s*-\s*$':0}, regex=True)
</code></pre>
<p>Explanation - Since string-based data can often have random spaces. also you can just replace it with 0 since the subsequent float conversion will handle the decimals.</p>
<p><strong>Output</strong... | python|pandas|dataframe | 2 |
19,588 | 67,199,789 | Aggregate groups based on index from external object | <p>I have a dataframe with a categorical column and some other stuff:</p>
<pre><code>>>> np.random.seed(0xFEE7)
>>> df = pd.DataFrame({'A': np.random.randint(10, size=10),
'B': np.random.randint(10, size=10),
'C': np.random.choice(['A', 'B'], size=10)})
&... | <p>You can use a <code>series.groupby</code> for this usecase which is faster than <code>dataframe.groupby</code>.</p>
<p>Since we already have a calculated series and we get the mean of the result using a grouper column, its better we use the grouper column in the <code>series.groupby</code> and then <code>.mean()</co... | python|pandas|pandas-groupby | 3 |
19,589 | 60,193,458 | Plotly heatmap plot not rendering all yaxis labels | <p>I built an dash plotly dashboard with a heatmap. However I am noticing that t=some of the labels in my y-axis are not being shown. I am only getting a limited I am not sure what is going wrong. Here is my dashboard:</p>
<pre><code>import dash
import dash_table
import plotly.graph_objs as go
import dash_html_compone... | <p>You can use the <code>yaxis_nticks</code> property of the layout to specify the number of ticks you want to show.</p>
<p>For example, you can have as many ticks as you have rows in your dataframe.</p>
<pre class="lang-py prettyprint-override"><code>corr_fig.update_layout(title="Correlation heatmap",
... | python|pandas|plotly|plotly-dash | 5 |
19,590 | 60,322,754 | Find any negative values in a given set of dataframes and replace whole column with np.nan | <p>I have a large dataframe and I want to search 144 of the columns to check if there are any negative values in them. If there is even one negative value in a column, I want to replace the whole column with np.nan. I then want to use the new version of the dataframe for later analysis.</p>
<p>I've tried a varied of m... | <p>You could use a loop to iterate over the columns:</p>
<pre><code>for i in col:
if df[i].isna().any():
df[i] = np.nan
</code></pre>
<p>Minumum reproducible example:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[1,2,3]})
for i in df:
if df[i].isna().any():
df[i... | python|python-3.x|pandas | 2 |
19,591 | 60,166,307 | Compare columns in Pandas between two unequal size Dataframes for condition check | <p>I have two pandas DF. Of unequal sizes. For example : </p>
<pre><code>Df1
id value
a 2
b 3
c 22
d 5
Df2
id value
c 22
a 2
</code></pre>
<p>No I want to extract from DF1 those <strong>rows</strong> which has the same id as in DF2. Now my first approach is to run 2 for loops,... | <pre><code>import pandas as pd
data1={'id':['a','b','c','d'],
'value':[2,3,22,5]}
data2={'id':['c','a'],
'value':[22,2]}
df1=pd.DataFrame(data1)
df2=pd.DataFrame(data2)
finaldf=pd.concat([df1,df2],ignore_index=True)
</code></pre>
<p><strong>Output after concat</strong></p>
<pre><code> id value
0 ... | python|pandas|loops|compare|data-files | 2 |
19,592 | 65,075,091 | How to import from excel into a 2d numpy array? | <p>I'm trying to import the below data (excel file) into a 2D numpy array</p>
<pre><code>x1 | x2
12 | 56
34 | 89
43 | 10
34 | 11
</code></pre>
<p>My Python code:</p>
<pre><code>spreadsheet = 'zone.xlsx'
data = pd.read_excel(spreadsheet)
x = data['x1'].values
y = data['x2'].values
x_train = np.concatenate((x,y))
</code... | <pre><code>x = np.array([1,2,3]).reshape(-1,1)
y= np.array([2,3,4]).reshape(-1,1)
np.concatenate([x,y],axis=1)
#output
array([[1, 2],
[2, 3],
[3, 4]])
</code></pre>
<pre><code>np.concatenate([x,y],axis=1).tolist()
[[1, 2], [2, 3], [3, 4]]
</code></pre> | python|pandas|numpy | 1 |
19,593 | 50,138,413 | Convert/ reshape a wide pandas dataframe into long/ tabular form? | <p>I have a dataframe as below, with Dates as columns, and want to convert it into a tabular (long) form.</p>
<pre><code>> PPPP = pd.DataFrame({'1/1/2001': [5,6,7,8,9],
> '1/1/2001':[45,46,47,48,49],
> '1/2/2001':[15,16,17,18,19],
> '1/3/2001':... | <p>I suggest use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a>:</p>
<pre><code>df = PPPP.melt(['Category1','Category2'], value_name='a', var_name='b')
print (df)
Category1 Category2 b a
0 aa XX 1/1... | pandas|dataframe|reshape|melt | 3 |
19,594 | 49,838,269 | Tensorflow possible update to high level estimator | <p>I have trained a Deep Neural Network Regressor on some weather data. When I tried classifier.predict(), it return a generator object. Usually what we do is to put list() over the object to get the prediction. </p>
<p>It used to work but I believe that after a recent update, it is no longer working. I'm currently on... | <p>I'm not sure if you have other bugs here. Based on the traceback, it is clear that this specific error is resulted from using <code>np.array(onehot)</code> as <code>input_fn</code> for <code>classifier.predict</code>, i.e. numpy array is not a callable object. To fix this, you can use <a href="https://www.tensorflow... | python|tensorflow|machine-learning|deep-learning|generator | 0 |
19,595 | 50,225,723 | Is there a Python library where I can import a gradient descent function/method? | <p>One way to do gradient descent in Python is to code it myself. However, given how popular a concept it is in machine learning, I was wondering if there is a Python library that I can import that gives me a gradient descent method (preferably mini-batch gradient descent since it's generally better than batch and stoc... | <p>To state the obvious, gradient descent is optimizing a function. When you use some implementation of gradient descent from some library, you need to specify the function using this library's constructs. For example, functions are represented as computation graphs in TensorFlow. You cannot just take some pure python ... | python|tensorflow|import|gradient-descent|mini-batch | 4 |
19,596 | 49,869,644 | Generating all possible combinations in a range using numpy in python | <p>I am looking for an efficient way to generate all possible combinations within a certain big range using numpy or any faster method. I tried:</p>
<pre><code>from numpy import *
from itertools import *
dt=dtype('i,i,i,i,i,i')
fromiter(combinations(range(10000000),6), dtype=dt, count=-1)
</code></pre>
<p>but I get ... | <p>There is around 1,000,000,000,000,000,000,000,000,000,000,000,000,000,000
(1 Septillion) possible combinations of 6 elements with the range you are using. You'll never process them all. The best you can do is to process them in the "lazy way" with a iterator:</p>
<pre><code>for c in combinations(range(10000000),6)... | python|numpy|combinations | 5 |
19,597 | 63,843,469 | pandas equivalent of select sum(t.col1 * t.col2) / sum(t.col3) from table as t group by t.col4 | <p>I want to find pandas equivalent of sql...</p>
<pre><code>select sum(t.col1 * t.col2) / sum(t.col3) from table as t group by t.col4
</code></pre>
<p>I did</p>
<pre><code>df.groupby(['col4'])[['col3']].sum()
</code></pre>
<p>but it only produce the sum(t.3)...</p>
<p>is there a one-line statement to achieve this kind... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>df['n'] = df['col1'].mul(df['col2'])
gr = df.groupby(['col4'])
res = gr['n'].sum().div(gr['col3'].sum())
</code></pre> | python|pandas | 1 |
19,598 | 63,766,815 | Determinate of a Singular 4x4 matrix is non zero using numpy det | <p>I am trying to calculate the determinate of the (4x4) matrix A using <code>np.linalg.det([A])</code></p>
<p>Here A is defined as below</p>
<pre><code> import numpy as np
A = np.array([
[1, 3, 1, 2],
[5, 8, 5, 3],
[0, 4, 0, 0],
[2, 3, 2, 8]
], dtype=np.fl... | <p>It's probably because of an accuracy. Try <code>float64</code>.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
A = np.array([
[1, 3, 1, 2],
[5, 8, 5, 3],
[0, 4, 0, 0],
[2, 3, 2, 8]
], dtype=np.float64)
np.linalg.det([A])
</code></pre> | python|python-3.x|numpy|matrix | 0 |
19,599 | 46,791,626 | One-hot encoding multi-level column data | <p>I have the following data frame where there are records with features about different subjects:</p>
<pre><code>ID Feature
-------------------------
1 A
1 B
2 A
1 A
3 B
3 B
1 C
2 C
3 D
</code></pre>
<p>I'd like to get another (aggregated?) data frame where each row represents a specific... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="noreferrer"><code>join</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="noreferrer"><code>get_dummies</code></a>, then <a href="http://pandas.pydata.org/pand... | python|pandas|encoding | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.