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 |
|---|---|---|---|---|---|---|
371,300 | 54,158,746 | Pandas - How to make a groupment in which a new column is the result of (sum of a column)/(number of itens grouped)? | <p>I need to make some kind of groupment in which a new column (result) is the sum of the values column divided by number of items found? Could anyone help me, please?</p>
<p>For example: </p>
<p>Table A</p>
<pre><code>+-------+------+
| item | value|
+-------+------+
| x | 100 |
| y | 200 |
| y | 40... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a>:</p>
<pre><code>s = df.groupby('item')['value'].agg(lambda x: x.sum()/len(x))
print (s)
item
x 100
y 300
Name: value, dtype... | pandas|pandas-groupby|sklearn-pandas|pandasql | 1 |
371,301 | 53,904,436 | How to user lower() method when filtering pandas DataFrame? | <pre><code> 0 1 2 3 4 5
word
</s> 0.001129 -0.000896 0.000319 0.001534 0.001106 -0.001404
in 0.070312 0.086914 0.087891 0.062500 0.069336 -0.108887
for -0.011780 -0.047363 0.044678 0.06347... | <p>Would suggest not using regex comparisons (i.e., not using <code>str.lower</code> with regex) if you are doing simple substring checks. You can use a list comprehension here:</p>
<pre><code>df[['lebron' in x.lower() for x in df.index]]
</code></pre>
<p>If NaNs are possible in the index, you can modify your solutio... | python|pandas|dataframe | 3 |
371,302 | 54,089,834 | Tensorflow compatibility with Scikit Pipeline | <p>I need to combine Scikit preprocessing pipeline from OpenAPI with Tensorflow as learning backend instead of Scikit learning backend.
Do Scikit Pipelearn supports using Tensorflow's backend?</p> | <p>Ultimately, we implement a custom scikit estimator which build the Keras model on the fit function. This way, we can build a Keras Model with custom dimension, depending on the pipeline.</p> | tensorflow|scikit-learn|openapi | 1 |
371,303 | 54,235,643 | Access dict columns of a csv file in python pandas | <p>I have a dataset in csv file which contains one of the column as list(or dict which further includes several semi colons and commas because of key, value pair). Now trouble is accessing with Pandas and it is return mixed values because of the reason that it has several commas in the list which is in fact a single co... | <p>You can only set the delmiter to one character so you can't use square brackets in this Way. You would need to use a single character such as " so that it knows to ignore the commas between the delmieters. </p> | python|python-3.x|pandas | 0 |
371,304 | 53,874,115 | Keras model working fine locally but won't work on Flask API | <p>I'm working on this heart disease detection problem using different classifiers.
What I'm doing is i'm saving my model in <strong>h5</strong> file & creating an object of it & returning the response in json format.</p>
<p>but the same model won't work on flask api that ran perfectly on my terminal.</p>
<p>... | <p>You need to get default graph from Tensorflow, following these steps should solve this issue:</p>
<pre><code>import tensorflow as tf
ann = load_model('ann8524.h5')
graph = tf.get_default_graph()
def your_handler():
global graph
with graph.as_default():
print(ann.predict(x_test))
</code></pre> | tensorflow|machine-learning|flask|scikit-learn|keras | 5 |
371,305 | 53,902,147 | 'IndexError: list index out of range' when I used python split to string include Chinese | <p>I have a problem when I used split() to a dataframe.<br>
My python is python3.6.<br>
My code is:</p>
<pre><code>data = pd.DataFrame({'a':[1,2], 'b':['高 1', '中 2']})
print(data)
data['c'] = [x.split()[2] for x in data['b']]
# data['c'] = list(map(lambda x: x.split()[2], data['b']))
</code></pre>
<p>The error is:</p... | <p>Because python indexing starts from 0, so first element index is 0, second element index is 1, and so on..., so ya have to do:</p>
<pre><code>data['c'] = [x.split()[1] for x in data['b']]
</code></pre>
<p>Also, more pandasic is like:</p>
<pre><code>data['c'] = data['b'].apply(lambda x: x.split()[1])
</code></pre> | python|python-3.x|pandas|split | 3 |
371,306 | 54,130,465 | Python.exe crashes without error on pandas.from_json | <p>The following code returns a proper <code>DataFrame</code> object in python 3.6.4:</p>
<pre><code>from pandas import read_json
bad_data= '{"columns":["Week of: 2018 12 7"],
"index":["Gizlilik bildirgesini okudum, ankete kat\u0131lmay\u0131 kabul ediyorum","Gizlilik bildirgesini okudum\/okumad\u0131m ankete kat\... | <p>Looks like it could be related to a segfault in 3.7.0: <a href="https://github.com/pandas-dev/pandas/issues/22817" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/22817</a></p>
<p>Can you try updating to 3.7.1 and see if it still occurs?</p> | python|python-3.x|pandas | 3 |
371,307 | 54,014,687 | Populate Pandas DataFrame using a dictionary based on a condition | <p>I have a DataFrame</p>
<pre><code>>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]})
A B C D
0 a 1
1 b 2
2 b 3
3 b 4
</code></pre>
<p>I also have a dictionar... | <p>This may not be the most efficient solution, but from what I understand it got the job done:</p>
<pre><code>import pandas as pd
import numpy as np
test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4],
'C': [np.nan, np.nan, np.nan, np.nan],
'D': [np.nan, np.na... | python|pandas|dataframe|assign | 3 |
371,308 | 53,917,303 | Pandas Melt with Multi Index Data Set and Resetting Index - Why is this working? | <p>I created this dataset straight from the pandas documentation:</p>
<pre><code>In [28]: columns = pd.MultiIndex.from_tuples([('A', 'cat'), ('B', 'dog'),
....: ('B', 'cat'), ('A', 'dog')],
....: names=['exp', 'animal'])
....:
In [29]:... | <p>There is a function called <code>stack</code> </p>
<pre><code>yourdf=df.stack([0,1]).reset_index(name='value')
</code></pre> | python|pandas|dataframe | 2 |
371,309 | 54,021,117 | Convert Dictionary to Numpy array | <p>I am trying to convert the dictionary </p>
<pre><code>{0: {0: 173, 1: 342, 2: 666, 3: 506, 4: 94},
1: {0: 13, 1: 2171, 2: 1915, 3: 3075, 4: 630},
2: {0: 0, 1: 265, 2: 5036, 3: 508, 4: 11},
3: {0: 0, 1: 3229, 2: 2388, 3: 3649, 4: 193},
4: {0: 3, 1: 151, 2: 591, 3: 1629, 4: 410}}
</code></pre>
<p>to numpy array ... | <p>A Python-level loop is unavoidable here, so you can use a list comprehension:</p>
<pre><code>res = np.array([list(item.values()) for item in d.values()])
# array([[ 173, 342, 666, 506, 94],
# [ 13, 2171, 1915, 3075, 630],
# [ 0, 265, 5036, 508, 11],
# [ 0, 3229, 2388, 3649, 193... | python|python-3.x|numpy|dictionary|numpy-ndarray | 8 |
371,310 | 53,899,583 | Adding markers to a Folium Map | <p>I'm trying to add markers to a Folium Map of a city using the latitudes and longitudes from columns of a Pandas dataframe. But, all I get is an empty map as a result and no errors. </p>
<p>I've tried it using a for loop to iterate over the rows of the datframe and adding the markers for each item into the map, but ... | <p>Another way not mentioned by @bob
I used:</p>
<pre><code>dataframe.apply(lambda row:folium.CircleMarker(location=[row["lat"], row["lon"]],
radius=10, popup=row['name'])
.add_to(f_map), axis=1)
</code></pre>
<p>I assume dat... | python|pandas|dataframe|folium | 3 |
371,311 | 53,891,306 | Can not modify DataFrame using a simple condition statement. But works when using a static number | <p>I am trying to change the series of a pandas DataFrame object using the iterrows() function. The DataFrame is full of random floats. Below is a sample of both pieces of code:</p>
<p>This one works:</p>
<pre><code>for index,row in other_copy.iterrows()
other_copy.loc[index] = (other_copy.loc[index] > 30)
</c... | <p>The problem isn't <code>minimum</code>, it's the code that sets <code>minimum</code>. When you slice out your row, it turns into a series which has a dtype <code>object</code> (because there are mixed dtypes in your columns the <code>object</code> dtype is the only one that's compatible with all of them)</p>
<p>Whe... | python|pandas|numpy | 1 |
371,312 | 54,003,975 | Convert string back to numpy array | <p>I'am working on a video chat in python. I'am using CV2 to capture the current image(this gives me a numpy array), then I send the numpy over to my server. Now I have a string at the server and i need to decode it back to a numpy array.</p>
<p>I'am using Python 3.7 and i dindn't come up with somethink yet.</p>
<pre... | <p>The following pair of programs demonstrates one way to commmunicate a numpy <code>ndarray</code> object across a network socket. The client converts the array to a byte stream using the <code>save</code> method, writing the stream to a BytesIO object that is then sent across the socket to the server:</p>
<pre><code... | python|python-3.x|numpy | 2 |
371,313 | 53,827,441 | plotting a large matrix in python | <p>I have a data file in excel (.xlsx). The data represents a 100 micrometer by 100 micrometer area. Number of steps were set at 50 for x and 50 for y meaning each pixel is 2 micrometer in size. How can I create a 2D image from this data. </p> | <p>getting data from xslx files can be achieved using the <a href="https://openpyxl.readthedocs.io/en/stable/" rel="nofollow noreferrer">openpyxl</a> python module. after installing the module a simple example is (assuming you have an xslx as in the image attached):</p>
<pre><code>from openpyxl import load_workbook
wb... | python|numpy|matplotlib | 1 |
371,314 | 54,121,070 | Pandas Dataframe update the row values by previous one based on condition | <p>I have a dataframe as follows. I want to replace the row values based on the following condition.</p>
<p>if 3 consecutive previous row values are 0, then keep the values as it is or if only one previous row value is 0, then fill that row by rolling mean for last 3 rows for that particular IEMI. </p>
<p>First the <... | <p>Below is what i came up with:(I have added 3 extra rows with IMEI : 55674 just for testing)</p>
<p><strong>Removing consecutive 0s with a group of 3 (which needs no action) and slicing on the dataframe:</strong></p>
<pre><code>import itertools
def consecutive(data, stepsize=1):
return np.split(data, np.where(n... | python|pandas | 1 |
371,315 | 53,819,184 | Python function not working on Pandas Dataframe when subsetted in a loop | <p>I have created a number of very simple functions that I want to apply to a pandas DataFrame. For example:</p>
<pre><code>def dir_flag(start, end):
try:
if start < end:
return '+'
else:
return '-'
except:
return 'NA'
</code></pre>
<p>I have imported a csv file into a Dat... | <p>So the problem stems from doing a index slice on a multiindex where one of the levels contains nulls. The solution is therefore to replace the null value with a constant:</p>
<pre><code>mydata = pd.read_csv('/myloc/my_simple_data.txt', sep='|',
dtype={'idx_level1': 'int',
'idx_level2': 'int',
'idx... | python|pandas|dataframe|lambda|slice | 0 |
371,316 | 54,029,845 | Python input contains NaN, infinity or a value too large for dtype float32 | <p>I'm trying to classify using sklearn's decision tree classifier. I've stored my training and testing datasets into two seperate pandas dataframes. I'm calling the classifier like so:</p>
<pre><code>classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(features_in_training_set, ... | <p>Try to check the summary of the dataframe.
for e.g. if your data frame shows missing samples for any features, it means there are null values for some of the observations.</p>
<p>a possible divide by null scenario is being encountered.</p> | python|pandas|dataframe|sklearn-pandas | 0 |
371,317 | 54,013,070 | Possible to read an incomplete excel file? | <p>I am currently using <code>openpyxl</code> to read the first 1000 rows of a very large (1GB) excel file. Is it possible to read excel data in openpyxl from an incomplete file? For example, if I only downloaded the first 10MB of the file instead of 1GB. Would there be any way to view the first 1000 of that (incomplet... | <p>OOXML files are zip archives and, unlike gzip files, cannot really be streamed, ie. unpacked while still being transmitted. So, no, you cannot start reading the file while still downloading it.</p> | python|pandas|openpyxl|xlrd|pyexcel | 0 |
371,318 | 38,419,286 | Subtracting multiple columns and appending results in pandas DataFrame | <p>I have a table of sensor data, for which some columns are measurements and some columns are sensor bias. For example, something like this:</p>
<pre><code>df=pd.DataFrame({'x':[1.0,2.0,3.0],'y':[4.0,5.0,6.0],
'dx':[0.25,0.25,0.25],'dy':[0.5,0.5,0.5]})
</code></pre>
<blockquote>
<pre><code> dx ... | <p>DataFrames generally align operations such as arithmetic on column and row indices. Since <code>df[['x','y']]</code> and <code>df[['dx','dy']]</code> have different column names, the <code>dx</code> column is not subtracted from the <code>x</code> column, and similiarly for the <code>y</code> columns.</p>
<p>In co... | python|pandas | 12 |
371,319 | 38,242,368 | "Anti-merge" in pandas (Python) | <p>How can I pick out the difference between to columns of the same name in two dataframes?
I mean I have dataframe A with a column named X and dataframe B with column named X, if i do <code>pd.merge(A, B, on=['X'])</code>, i'll get the common X values of A and B, but how can i get the "non-common" ones?</p> | <p>If you change the merge type to <code>how='outer'</code> and <code>indicator=True</code> this will add a column to tell you whether the values are left/both/right only:</p>
<pre><code>In [2]:
A = pd.DataFrame({'x':np.arange(5)})
B = pd.DataFrame({'x':np.arange(3,8)})
print(A)
print(B)
x
0 0
1 1
2 2
3 3
4 4
... | python|pandas|merge | 75 |
371,320 | 38,095,605 | Python pandas 'ffill' method not working | <p>In the book 'Python for Data Analysis' there is an example using pandas' Series data structure for reindexing. I copied this simple code into an iPython notebook and run it but it does not change <code>obj3</code>.</p>
<pre><code>obj3 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])
print(obj3)
obj3.reindex(... | <p>You need assign <code>obj3 =</code>:</p>
<pre><code>obj3 = obj3.reindex(range(6), method='ffill')
print(obj3)
0 blue
1 blue
2 purple
3 purple
4 yellow
5 yellow
dtype: object
</code></pre> | python|pandas | 3 |
371,321 | 38,271,224 | pandas how to truncate minutes, seconds pandas.tslib.Timestamp | <p>I work with Cloudera VM 5.2 and pandas 0.18.0.</p>
<p>I have the following data</p>
<pre><code>adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv',
parse_dates=['timestamp'],
skipinitialspace=True).assign(adCount=1)
adclicksDF.head(n=5)
Out[107]:
timestamp txId use... | <p>You can use:</p>
<pre><code>adclicksDF["timestamp"] = pd.to_datetime(adclicksDF["timestamp"])
.apply(lambda x: x.replace(minute=0, second=0))
print (adclicksDF)
timestamp txId userSessionId teamId userId adId adCategory
0 2016-05-26 15:00:00 5974 5809 ... | python|pandas|timestamp|truncate|seconds | 3 |
371,322 | 38,338,809 | pandas dataframe extract strings | <p>My data frame has a column called 'a' and it may contain 'apple' and 'orange'. What I want is to extract them if they exist, otherwise label 'others'.</p>
<p>I can simply loop over the rows and extract them. However, I saw some usage of <code>numpy.where()</code> for similar purposes, but only two categories. </p>
... | <p>Simply look for items that are <code>apple</code> or <code>mango</code> with <code>np.in1d</code> to create a boolean mask, which could then be used with <code>np.where</code> to set rest of them as <code>others</code>. Thus, we would have -</p>
<pre><code>df['b'] = np.where(np.in1d(df.a,['apple','orange']),df.a,'o... | numpy|pandas|dataframe|text-extraction | 3 |
371,323 | 38,385,626 | How to make a numpy array of form ([1.], [2.], [3.]...) from list? | <p>I am trying to make a numpy array of the form <code>([1.], [2.], ...)</code> from a list <code>[1, 2, 3]</code> so I can use it as an input for <code>sklearn's linear_model</code>. </p>
<p>This command</p>
<pre><code>np.array(test_list)
</code></pre>
<p>produces this kind of array:</p>
<pre><code>array([1, 2, 3,... | <p>+1 to mgilson's answer. Here's another way:</p>
<pre><code>arr = np.array([np.array([float(i)]) for i in test_list])
</code></pre> | python|numpy | 2 |
371,324 | 38,370,763 | Installing Tensorflow from source when it is already installed using pip | <p>My machine already have Tensorflow 8.0 installed using pip.
I installed Tensorflow 9.0 from source to support cudnn 5. The thing is when I "import tensorflow" in python it still uses the pip installation.</p>
<p>Can I tell python to import my new installation and ignore the pip installation?</p>
<p>I want to keep ... | <p>You can try one of these (solution 2 is the one I prefer)</p>
<p>1) Install only for your user:</p>
<pre><code>sudo pip install --user /tmp/tensorflow_pkg/tensorflow-0.9.0-py2-none-any.whl
</code></pre>
<p>2) Create a virtual environment to isolate it from your system install:</p>
<p><a href="https://www.tensorf... | python|installation|tensorflow | 2 |
371,325 | 38,200,663 | Error using the substraction operator for two datetime64 empty series | <p>I have a dataframe with two datetime64 columns:</p>
<pre><code>In [119]: df.dtypes
Out[119]:
beg datetime64[ns]
end datetime64[ns]
dtype: object
</code></pre>
<p>Sometimes, this dataframe can be empty. In this case, the substraction of <code>end</code> by <code>beg</code> fails using the minus operator but ... | <p>It's answered in the documentation and in the sentence you copy-pasted:</p>
<blockquote>
<p>but with support to substitute a fill_value for missing data in one of the inputs</p>
</blockquote>
<p>It supports empty dataframes and missing data where the minus operator doesn't.<br>
With pandas and numpy, it's good p... | python|pandas | 0 |
371,326 | 38,204,283 | Add value to every "other" field ((i+j)%2==0) of numpy array | <p>I have an <code>m</code>-by-<code>n</code> numpy array, and I'd like to add 1.0 to all entries <code>[i, j]</code> when <code>(i + j) % 2 == 0</code>, i.e., "to every other square".</p>
<p>I could of course simply iterate over the fields</p>
<pre><code>import numpy as np
a = np.random.rand(5, 4)
for i in range... | <p>You can easily do the operation in two steps, like</p>
<pre><code>import numpy as np
a = np.zeros((5, 14))
# Even rows, odd columns
a[::2, 1::2] += 1
# Odd rows, even columns
a[1::2, ::2] += 1
print a
</code></pre> | python|arrays|numpy|matrix | 8 |
371,327 | 38,149,175 | OpenCV - python 3.x and windows - what version of Numpy? | <p>I downloaded openCV from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv</a> and installed it. When I tried to run it:</p>
<pre><code>import cv2
</code></pre>
<p>I got error message:</p>
<pre><code>RuntimeError: module compiled against A... | <p>You can try using the anaconda distribution for that.
I'm using it and it works great with opencv on windows.</p>
<p>You can download it from here:
<a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a></p>
<p>Then use conda to install opencv</p>
<p><code>conda install ... | windows|python-3.x|opencv|numpy | 2 |
371,328 | 38,443,703 | Numpy: can I do tensor Hadamard multiplication without einsum? | <p>I've got a rank four tensor A (say indices (a, b, i, j)) and a rank two tensor B (say indices (i, j)) and I want to compute a kind of Hadamard multiplication of them. </p>
<p>That is, if we call the product C, I want <code>C[a,b,i,j] == A[a,b,i,j] * B[i,j]</code>. There is a fairly straightforward way to do this w... | <pre><code>C = A * B
</code></pre>
<p>Following the <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting rules</a>, NumPy will line up the shapes of <code>A</code> and <code>B</code> starting from the last axes:</p>
<pre><code>A: (a, b, i, j)
B: (i, j)
</code></pre... | python|numpy | 4 |
371,329 | 38,079,887 | Efficient query pandas dataset | <p>Given a pandas dataset contains 8 million rows and 20 columns.</p>
<p>Program queries the dataset to find an average of certain column.</p>
<p>The average based on selections from other columns</p>
<p>Need a help to get fast response on bundle of 10k queries and reduce the query execution time</p>
<p>Setup :</p>... | <p>The columns A through D could be converted into categories as the values are non-unique and limited.</p>
<p>The sample below is based on the df you provided in your OP.</p>
<pre><code># Original data frame
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 5 c... | python|pandas|dataframe | 3 |
371,330 | 38,437,847 | Pandas split name column into first and last name if contains one space | <p>Let's say I have a pandas DataFrame containing names like so:</p>
<p><code>name_df = pd.DataFrame({'name':['Jack Fine','Kim Q. Danger','Jane Smith', 'Juan de la Cruz']})</code></p>
<pre><code> name
0 Jack Fine
1 Kim Q. Danger
2 Jane Smith
3 Juan de la Cruz
</code></pre>
<p>and I want to split the <code... | <p>You can use <code>str.split</code> to split the strings, then test the number of splits using <code>str.len</code> and use this as a boolean mask to assign just those rows with the last component of the split:</p>
<pre><code>In [33]:
df.loc[df['name'].str.split().str.len() == 2, 'last name'] = df['name'].str.split(... | python|pandas | 9 |
371,331 | 38,296,200 | InvalidArgumentError: You must feed a value for placeholder tensor Placeholder | <p>I have started learning tensorflow and have difficulties understanding the placeholders/variables issues.</p>
<p>I am trying to write a function for matrix multiplication. It works when using tf.constant but I have difficulties understanding how to use variables</p>
<p>here is my code</p>
<pre class="lang-py pretty... | <p>In order to meaningfully answer this question I have to go back to how tensorflow is designed to work</p>
<p><strong>Graphs</strong>
<br/>Graphs in Tensorflow are just a map / path that the computation will take. It does not hold any values and does not execute anything. </p>
<p><strong>Session</strong> <br/>
on t... | tensorflow | 4 |
371,332 | 38,448,193 | python array filtering out of bounds | <p>I tried doing this in python, but I get an error:</p>
<pre><code>import numpy as np
array_to_filter = np.array([1,2,3,4,5])
equal_array = np.array([1,2,5,5,5])
array_to_filter[equal_array]
</code></pre>
<p>and this results in:</p>
<pre><code>IndexError: index 5 is out of bounds for axis 0 with size 5
</code></pre... | <p>In the last statement the indices for your array are 1,2,5,5 and 5. Index 5 refers to 6th element in the array while you have only 5 elements. <code>array_to_filter[5]</code> does not exist.</p>
<p><code>[i for i in np.unique(equal_array) if i in array_to_filter]</code></p>
<p>would return the answer you want. ... | python|arrays|numpy | 0 |
371,333 | 38,278,603 | Use groupby in Pandas to count things in one column in comparison to another | <p>Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...</p>
<p>I want to group an event by it's outcome. Here is my DataFrame (df):</p>
<pre><code>Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
</code></pre>
<p>Here is my desired result:</p>
<pre><code>Event SUC... | <p>try this: </p>
<pre><code> pd.crosstab(df.Event, df.Status)
Status FAILED SUCCESS
Event
Run 0 2
Walk 1 1
len("df.groupby('Event').Status.value_counts().unstack().fillna(0)")
61
len("df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)")
... | python|pandas|dataframe | 9 |
371,334 | 38,251,906 | Pandas timestamp conversion | <p>I work with pandas. I have the following data:</p>
<pre><code>useradClick.head(n=5)
Out[291]:
timestamp userId adCategory adCount
0 2016-05-26 15:13:22 611 electronics 1
1 2016-05-26 15:17:24 1874 movies 1
2 2016-05-26 15:22:52 2139 computers 1
3 2016-0... | <p><strong>UPDATE:</strong></p>
<pre><code>cols = ['timestamp','userId','adCategory']
adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv',
uscols=cols,
parse_dates=['timestamp'],
skipinitialspace=True).assign(adCount=1)
#adclicksDF[... | python|pandas|timestamp|data-conversion | 1 |
371,335 | 38,194,270 | matlab convolution "same" to numpy.convolve | <p>I noticed that when I use conv(a, b, 'same') in matlab, it would return say M of length 200, but when I use numpy.convolve(a, b, 'same') it would return N of length 200, but shifted by one element compared to M (N[1:] would be the same as M[0:-1] and M[-1] would not be in N, N[0] not in M), how can I fix this?</p>
... | <p>My guess is that the length of the shorter input array is even. In this case, there is an ambiguity in how it should be handled when the method is "same". Apparently Matlab and numpy adopted different conventions.</p>
<p>There is an example of the use of the 'same' method on the Matlab documentation web ... | python|matlab|numpy | 13 |
371,336 | 38,368,490 | Pandas DataFrame select the specific columns with NaN values | <p>I have a two-column DataFrame, I want to select the rows with <code>NaN</code> in either column. </p>
<p>I used this method <code>df[ (df['a'] == np.NaN) | (df['b'] == np.NaN) ]</code><br>
However it returns an empty answer. I don't know what's the problem</p> | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="noreferrer"><code>isnull</code></a> for finding <code>NaN</code> values:</p>
<pre><code>df[ (df['a'].isnull()) | (df['b'].isnull()) ]
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/missing... | python|pandas|dataframe|nan | 13 |
371,337 | 38,218,063 | Pivoting Dataframe with Pandas | <p>I have the below table taken online through <code>pandas.read_html</code> </p>
<pre><code> Column0 Column1 Column2 Column3
0 Entry_1 0.685 Record_1 0.69-S$ 0.685
1 Entry_2 0.036 Record_2 0.685
2 Entry_3 05/Jul/2016 Record_3 0.72-S$ 0.4
3 Entry_4 ... | <p>This is probably the easiest way to solve this problem. The easiest way I could come up with anyway.</p>
<pre><code>Column0 Column1 Column2 Column3
0 Entry_1 0.685 Record_1 0.69-S$ 0.685
1 Entry_2 0.036 Record_2 0.685
2 Entry_3 05/Jul/2016 Record_3 0.72-S$ 0.4
3 Entr... | python|numpy|pandas | 2 |
371,338 | 38,277,336 | Read in year, DOY and microsecond data as datetime | <p>I have a data file formatted like this:</p>
<pre class="lang-none prettyprint-override"><code>year doy milliseconds data
2000 103 272220 1.123
2000 103 373058 1.342
2000 103 471764 0.743
2000 103 573509 1.666
2000 103 664624 1.736
2000 103 ... | <p>use <code>pandas</code>:</p>
<pre><code>import pandas as pd
f = r"df2dt.txt"
df = pd.read_csv(f, delim_whitespace=True)
td_ms = pd.to_timedelta(df['milliseconds'], unit='ms')
td_D = pd.to_timedelta(df['doy'] - 1, unit='D')
date_str = df['year'].astype(str)
date = pd.to_datetime(date_str, format="%Y", yearfirst=True... | python|datetime|numpy | 1 |
371,339 | 38,487,497 | Pandas find how many times a column value appears in dataset | <p>I am trying to sort data by the <code>Name</code> column, by popularity.</p>
<p>Right now, I'm doing this:</p>
<pre><code>df['Count'] = df.apply(lambda x: len(df[df['Name'] == x['Name']]), axis=1)
df[df['Count'] > 50][['Name', 'Description', 'Count']].drop_duplicates('Name').sort_values('Count', ascending=False... | <p>The solution I have been looking for is:</p>
<pre><code>df['Count'] = df.groupby('Name')['Name'].transform('count')
</code></pre>
<p>Big thanks to @Lynob for providing a link with an answer.</p> | python|pandas | 2 |
371,340 | 38,363,543 | How to convert a string to a float | <p>I have a Series of strings that represent cost data. I am attempting to convert the strings to floats</p>
<p><code>df['Line Total'].map(float)</code></p>
<p>which results in</p>
<p><code>ValueError: invalid literal for float(): 3,300.00</code></p>
<p>3,300.00 is the value from the first row of data. </p>
<p>I r... | <p>This had me stuck for awhile but thanks to this <a href="https://stackoverflow.com/questions/379906/parse-string-to-float-or-int">Parse String to Float or Int</a> I was able to figure out that commas in the string were the problem. </p>
<p>I ran <code>df['Line Total'] = df['Line Total'].str.replace(',', '')</code> ... | python|pandas | 0 |
371,341 | 38,496,418 | Fastest way to extract dictionary of sums in numpy in 1 I/O pass | <p>Let's say I have an array like:</p>
<pre><code>arr = np.array([[1,20,5],
[1,20,8],
[3,10,4],
[2,30,6],
[3,10,5]])
</code></pre>
<p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first c... | <p>numpy approach:</p>
<pre><code>u = np.unique(arr[:, 0])
s = ((arr[:, [0]] == u) * arr[:, [2]]).sum(0)
dict(np.stack([u, s]).T)
{1: 13, 2: 6, 3: 9}
</code></pre>
<p>pandas approach:</p>
<pre><code>import pandas as pd
import numpy as np
pd.DataFrame(arr, columns=list('ABC')).groupby('A').C.sum().to_dict()
{1: 1... | python|numpy|pandas|dictionary|vectorization | 3 |
371,342 | 38,326,578 | TensorFlow custom model optimizer returning NaN. Why? | <p>I want to learn optimal <code>weights</code> and <code>exponents</code> for a custom model I've created:</p>
<pre><code>weights = tf.Variable(tf.zeros([t.num_features, 1], dtype=tf.float64))
exponents = tf.Variable(tf.ones([t.num_features, 1], dtype=tf.float64))
# works fine:
pred = tf.matmul(x, weights)
# doesn'... | <p>This is correct behavior on TensorFlow's part, since the gradient is infinity there (and many computations that should mathematically be infinity end up NaN due to indeterminate limits).</p>
<p>If you want to work around the problem, a slightly generalized version of gradient clipping may work. You can get the gra... | machine-learning|neural-network|tensorflow | 0 |
371,343 | 66,140,105 | KeyError when installing tensorflow | <p>I tried installing <code>tensorflow</code> but I got this <code>KeyError</code>:</p>
<pre><code>>py -3.7-64 -m pip install tensorflow
Collecting tensorflow
Downloading tensorflow-2.4.1-cp37-cp37m-win_amd64.whl (370.7 MB)
|██ | 20.2 MB 3.3 MB/s eta 0:01:47ERROR: Exception:
Trac... | <p>Just use --default-timeout=100 parameter with the install. e.g</p>
<pre><code>py -3.7-64 -m pip install --default-timeout=100 tensorflow
</code></pre>
<p>I hope, this will help you.</p> | python|tensorflow|pip | 4 |
371,344 | 66,278,184 | Last Visited Interval for different people | <p>Given the following dataframe</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'visited': ['2015-3-4', '2015-3-5','2015-3-6','2016-3-4', '2016-3-6', '2016-3-8'],'name':['John','John','John','Mary','Mary','Mary']})
df['visited']=pd.to_datetime(df['visited'])
</code></pre>
<pre><code> visited name
0 2015... | <p>If check <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last.html" rel="nofollow noreferrer"><code>Series.last</code></a> it working different - it return last value of datetimes by DatetimeIndex, also it is not <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pand... | python-3.x|pandas|pandas-groupby | 0 |
371,345 | 66,091,613 | Pandas Col to dict with key, value pair where value is frequency of string occurrence | <p>so my df['data'] looks like this</p>
<pre class="lang-py prettyprint-override"><code>[[G, 37, T], [-, 447, A]]
[[G, 78, A], [-, 447, A], [A, 1023, -]]
[[-, 447, A], [C, 3049, T]]
[[-, 447, A]]
</code></pre>
<p>What I need is dictionary like this</p>
<pre class="lang-py prettyprint-override"><code>{'-447A':4,'G37T':1... | <p>Don't think there's a more optimized way to do this in pandas, just convert it to a list, transform and count it using <code>collections.Counter</code>:</p>
<pre><code>from collections import Counter
Counter((''.join(map(str, slst)) for lst in df.data.to_list() for slst in lst))
# Counter({'-447A': 4, 'G37T': 1, 'G7... | python|pandas|dataframe | 1 |
371,346 | 65,938,346 | Different Equation Applied to Specific Rows in DataFrame | <p>I'm trying to add a column for density to a dataframe, which is calculated by the equation shown. I need the reference density to change at a certain row (row 66). I've tried two for loops and a for/else loop and they each use one of the densities for every row, rather than switching as I intend. I have defined all ... | <pre><code>density_list = []
TR = <index of column TREF>
# get row count and loop through number of rows in dataframe
for i in range(0,tem80df.shape[0]):
if i<=66:
density80 = density_crust * (1-(alpha * tem80df.iloc[i:TR]))
density_list.append(density80)
else:
density80= den... | python|pandas|loops | 0 |
371,347 | 66,313,920 | Saving trainable weights Only - Tensorflow models | <p>I want to save the trainable weights of a custom VGG16 model.
I know that : custom_vgg_model.save_weights(fname) => saves all the weights even the untrainable weights of VGG16 .
How can I go and save only the trainable weights?</p> | <p>So generally, you would just save the entire model and then use <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#load_weights" rel="nofollow noreferrer"><code>model.load_weights(by_name=True)</code></a> to only load weights that you want to transfer. However, if you want to save a subset of the wei... | tensorflow|keras|tensorflow2.0|keras-layer | 0 |
371,348 | 65,947,993 | Python Dataframe Store name of the column with row max | <p>My dataframe has mulitple columns. I find max value in each row. Now I want to know the which column is max in each row and I want to store it. Finally, I would like to know how many times this row was max (top), etc.
My code:</p>
<pre><code>df=
Aple Bana Oran
0 10 20 30
1 2 5 1
2 8 9 ... | <p>You can use <code>idxmax</code>:</p>
<pre><code>df['max_val'], df['max_col'] = df.max(axis=1), df.idxmax(axis=1)
# also
df[cols].idxmax(axis=1)
</code></pre>
<p>Output:</p>
<pre><code> Aple Bana Oran max_val max_col
0 10 20 30 30 Oran
1 2 5 1 5 Bana
2 8 9 4 ... | python|pandas|dataframe | 2 |
371,349 | 66,019,738 | Add two dataframes without sorting index | <p>How can I add the values in 2 dataframes, by index value (0 for missing), without sorting the index.</p>
<pre><code>import pandas as pd
df1=pd.DataFrame([1,2,3],['Yes','Maybe','No'],['Num'])
df2=pd.DataFrame([4,5],['Yes','No'],['Num'])
df1.add(df2,fill_value=0)
Num
Maybe 2.0
No 8.0
Yes 5.0
</code></pr... | <p>This is due to index search when adding together, so we can fix <code>reindex</code></p>
<pre><code>out = df1.add(df2,fill_value=0).reindex(df1.index)
Out[281]:
Num
Yes 5.0
Maybe 2.0
No 8.0
</code></pre> | python|pandas|dataframe | 3 |
371,350 | 66,178,864 | Set values in pandas DataFrame group | <p>How can I assign values in a DataFrame group without triggering <code>SettingWithCopyWarning</code>?</p>
<p>I want to be able to get a reference to a DataFrame group and then be able to access and set column values in that group.</p>
<p>I can't use <code>.apply</code> or <code>.transform</code> because I will <a hre... | <p>This should work for you</p>
<pre><code>df.loc[df.index.get_level_values('Date') == '20210101', 'Dollars'] = 3
</code></pre>
<p>Outptut</p>
<pre><code>df
Dollars HaveMax
Name Date
A 20210101 3.000 False
B 20210101 3.000 False
C 20210101 3.000 True
A 20210102 0.000 ... | pandas|dataframe|pandas-groupby | 1 |
371,351 | 66,282,692 | Create SQL table from a pandas Dataframe with a lot of columns | <p>I am building a class that takes a pandas dataframe and dumps it into a SQL database, which is created by explicitly declaring all columns, like so:</p>
<pre><code>class BuildDB:
def __init__(self):
self.conn = sqlite3.connect('data/database.sqlite')
self.c = self.conn.cursor()
def ... | <p>doesn't <code>if_exists='replace'</code> take care of dropping the table and inserting these rows?</p> | sql|pandas|sqlite | -1 |
371,352 | 65,911,060 | How can I find the position of the outputs from pandas.Series.str.extractall()? | <p>For example, suppose I had the following <code>pd.Series</code>:</p>
<pre><code>>>> import pandas as pd
>>> series = pd.Series(['ASDFQWEFASDF', 'QEGGRGQFSAFAD'])
>>> series
0 ASDFQWEFASDF
1 QEGGRGQFSAFAD
</code></pre>
<p>and I wanted to find everything matching the regex <code>(.A)</... | <p>Pandas cannot return the index/span because it uses <a href="https://github.com/pandas-dev/pandas/blob/v0.25.1/pandas/core/strings.py#L2971-L2974" rel="nofollow noreferrer"><code>findall</code> under the hood</a> (<code>findall</code> returns strings and not <code>re.Match</code>-objects). As an alternative you coul... | python|regex|pandas | 0 |
371,353 | 66,019,116 | Variational Autoencoder - WARNING:tensorflow: Gradients do not exist for variables [] when minimizing the loss | <p>I'm trying to implement a <strong>Variational Autoencoder</strong>, using the last part of the official <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow noreferrer">keras page</a>, the input it's the mnist dataset normalized and flat:</p>
<pre><code>(x_train, y_train), (x_test, y_tes... | <p>The fact that does not recognise gradients for the decoder layers (dense_layer_4, etc.), suggests that the problem is with the reconstruction loss. In other words, it is recognising gradients for the encoder from the KL loss, and that is why it runs at all. I would say use the vae to get the outputs, such as:</p>
<p... | python|tensorflow|keras|deep-learning|autoencoder | 0 |
371,354 | 66,119,746 | Shorter way to create new column in groupby() based on previous n rows | <p>I have the following code that for a sorted Pandas data frame, groups by one column, and creates two new columns: one according to the previous 4 rows and current row in the group, and one based on the future row in the group.</p>
<pre><code>data_test = {'nr':[1,1,1,1,1,6,6,6,6,6,6,6],
'val':[11,12,13,14... | <p>Use custom function for create nested lists like:</p>
<pre><code>def f(x):
#list comprehension with shift by 4,3,2,1,0
L = [x['val'].shift(i).fillna(0) for i in range(4, -1, -1)]
#shifting to another column
x['future'] = x['val'].shift(-1).fillna(0).astype(int)
#column filled by lists
x['amou... | arrays|pandas|dataframe|group-by|shift | 3 |
371,355 | 66,108,323 | Using boolean_mask in custom loss function keras | <p>The issue and error:
<code> ValueError: Number of mask dimensions must be specified, even if some dimensions are None. E.g. shape=[None] is ok, but shape=None is not.</code></p>
<p>The story:</p>
<p>I was forced to implement a custom loss function is order to deal with the issue that I have "empty" lab... | <p>Without going into more detail than I can comprehend (and thus explain), the loss function exists in graph mode. In graph mode, batch doesn't have a dimension, since it hasn't been defined yet.</p>
<p>The solution is to use tf.py_function, which lets you call an explicitly non-graph function, (and thus you know the ... | python|tensorflow|keras | -1 |
371,356 | 65,983,514 | Keras Tensorflow multiple errors | <p>I was programming on CodeCademy and got stuck. I cant find the answer and the terminal is showing some strange stuff. The project is about classifing images of covid-19, Pneumonia and normal lungs. Hope you can help me.</p>
<p>Code:</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
from tensorflo... | <blockquote>
<p>The project is about classifing images of covid-19, Pneumonia and
normal lungs.</p>
</blockquote>
<p>As you stated, you have 3 classes, but in the last dense layer, your output layer has 4 neurons, which is incompatible, also having <code>'relu'</code> as activation, which is another mistake.</p>
<p>You... | python|python-3.x|tensorflow|keras | 1 |
371,357 | 66,093,715 | Tensorflow padding in map function | <p>I currently have a dataset of <code>n</code>x<code>m</code> tensors that I need to pad to <code>13</code>x<code>m</code> tensor (<code>n <= 13</code>); however, I cannot figure out how to do this without Tensorflow losing the shape of my tensor.</p>
<p>I am trying to apply the <code>map</code> function to these, ... | <p>PS: I'm not sure exactly what you mean by <em>apply the map function to these</em> and <em>because of map's requirement I cannot just use the numpy method</em>, if you still have problem after following example then please make the definition of the problem more clear</p>
<p>FWIW, add <code>.numpy()</code> and code ... | python|tensorflow | 0 |
371,358 | 66,166,349 | Extracting Data from non-Structured String in Python | <p>everyone. I´m working with a Job Board dataset and I intend to turn the "Salary Offered" column into something I can use to make calculations, comparisons and predictions. I have five different cases for the data in the column:</p>
<p>-Yearly Salaries within a range (YSWR)</p>
<p>IE:£15,000 - £17,000 per a... | <p>You can use <code>regular expression</code> to get the values and then implement the logic using <code>if=else</code></p>
<pre class="lang-py prettyprint-override"><code>import re
import pandas as pd
df = pd.DataFrame([['£16,000 per annum'],
['£25.0 per annum'],
['£19,000 per ... | python|pandas|dataframe|data-science|feature-engineering | 0 |
371,359 | 66,286,076 | How to sample M times from N different normal distributions in python? Is there a "faster" way in terms of processing time? | <p>I need to sample multiple (M) times from N different normal distributions. This repeated sampling will happen in turn several thousand times. I want to do this in the most efficient way, because I would like to not die of old age before this process ends. The code would look something like this:</p>
<pre><code>impor... | <p><code>np.random.normal</code> accepts means-var as an array directly and you can choose a size that covers all the sampling in one run without loops:</p>
<pre><code>myRESULT = np.random.normal(loc=myMEANS, scale=myVAR, size = (number_of_samples_per_process, number_of_repeated_processes,myMEANS.size))
</code></pre>
<... | python|numpy|random | 2 |
371,360 | 66,271,678 | Get word counts in strings of words in a list using python | <p>Starting with a pandas data frame where the first column is made up of comment strings with the other columns being features of single words. For each row I would like to get a count of how many times each word appears in that row's comments cell. I have the list of words (feature columns) as a list called, "wo... | <p>Convert your coment column into a list and explode.</p>
<p>Apply get dummies. That will tabulate frequency of occurrence</p>
<p>Reindex with the list of words you wish to check</p>
<p>Aggregate the frequency and join to the df.coments column</p>
<p>Code below:</p>
<pre><code>g=pd.get_dummies(pd.Series(df1.coments.st... | python|pandas|count|word | 2 |
371,361 | 66,117,949 | Neural network graph visualization | <p>I would like to generate visualization of my neural network (PyTorch or ONNX model) similar to <a href="https://www.graphcore.ai/posts/what-does-machine-learning-look-like" rel="nofollow noreferrer">this</a> using Graphcore Poplar.
I have looked in the <a href="https://docs.graphcore.ai/en/latest/" rel="nofollow nor... | <p>that visualization is not part of the Graphcore Poplar software. It is "data art" generated by the team at GraphCore.</p>
<p>It is a tough work and requires many hours to get to that fine quality, but if you are decided, I would suggest to start looking at graph visualization tools looking for "graph ... | pytorch | 2 |
371,362 | 66,265,116 | How to add a column to a dataframe and set all rows to a specific value | <p><strong>Attempt</strong></p>
<p>After reading a large json file and capturing only the <code>'text'</code> column, I would like to <strong>add a column to dataframe and set all rows to a specific value</strong>:</p>
<pre><code>df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text
df.replace(to_... | <p>The problem is that your <code>read_json(....).text</code> line returns a series, not a dataframe.</p>
<p>Adding a <code>.to_frame()</code> and referencing the column in the following line should fix it:</p>
<pre><code>df = pd.read_json('xl-1542M.train.jsonl', lines=True, encoding='utf8').text.to_frame()
df['text'].... | python|json|pandas|dataframe | 1 |
371,363 | 66,224,817 | how do I map tensor using dictionary | <p>im trying to map tensor using dictionary but envir_with_agent[1,2] return tensor(4) instead 4 and dictionary cannot map it correctly min code is below</p>
<pre><code> envir_with_agent = b.mountain.clone()
envir_with_agent[b.position_agent[0], b.position_agent[1]] = 4
print(envir_with_agent[1,2])
print(b.dict_map_dis... | <p>You would want to first convert the scalar tensor to type <code>int</code> before using it as an index; like this:</p>
<pre class="lang-py prettyprint-override"><code>envir_with_agent = b.mountain.clone()
envir_with_agent[int(b.position_agent[0]), int(b.position_agent[1])] = 4
</code></pre> | python|pytorch | 1 |
371,364 | 66,308,319 | Possible to directly feed SMILE structures stored in a pandas dataframe into RDKit to calculate molecular fingerprint and similarity? | <pre><code>ref_Molecule = Chem.MolFromSmiles('CC1=C(C(O)=O)C2=CC(=CC=C2N=C1C3=CC=C(C=C3)C4=CC=CC=C4F)F')
merged_data['Molecule_Tan'] = DataStructs.TanimotoSimilarity(Chem.RDKFingerprint(ref_Brequinar), Chem.RDKFingerprint(Chem.MolFromSmiles(merged_data.SMILES)))
</code></pre>
<p>I have roughly 1500 SMILES structures s... | <p>You are right, that pandas gives the whole series instead of individual objects, so you have to iterate.</p>
<p>But then the fingerprints can be compared at once with <code>BulkTanimotoSimilarity()</code>.</p>
<p>You could try this code:</p>
<pre><code>from rdkit import Chem
from rdkit import DataStructs
import pand... | python|pandas|dataframe|rdkit | 2 |
371,365 | 66,223,369 | I have a Data in DICOM images i want to convert dicom images in to png or jpg format . but how to convert Number of folders at once with for loop | <p>I have Data in DICOM images, and I want to convert dicom images into png or jpg format. However, I need to convert the images in multiple folders at once using a for-loop. Here what I've done so far:</p>
<pre class="lang-py prettyprint-override"><code>import pydicom as dicom
import cv2
# specify your image path
im... | <p>I've build a <a href="https://pypi.org/project/dicom2jpg/" rel="nofollow noreferrer">package</a> to convert dicom files to jpg/png/bmp, you just <code>pip install dicom2jpg</code> then use</p>
<pre><code>import dicom2jpg
dicom_dir = "/Users/user/Desktop/dir_a"
export_location = "/Users/user/Desktop/d... | python|pytorch | 0 |
371,366 | 66,209,988 | how to sample from a dataset and get the indices of samples in initial dataset | <p>I have a dataset A with a shape of (1000, 10).
I want to do sampling such that:</p>
<pre><code>B = pd.DataFrame(A).sample(frac = 0.2)
</code></pre>
<p>how I can get the indices of A that contain B? or how I can sort A based on B to have those 200 rows of B at the beginning of A?</p>
<p>I have tried this code but I d... | <ol>
<li>Make a boolean column in <code>A</code> that tells if row is in <code>B</code></li>
<li>We can get rows in <code>B</code> with index by <code>A.index.isin(B.index)</code></li>
<li>Sort with the new column and delete the column</li>
</ol>
<pre><code># after defining A and B
# step 1, 2
A["isinB"] = A.... | python|dataframe|numpy|sorting|sampling | 0 |
371,367 | 65,949,183 | How to plot multiple dataframes in a single catplot figure | <p>I have multiple data frames consist of three main columns: 1)the categories (c1, c2, c3), one includes the data values, and one includes different time-periods (AA, BB, CC, DD).</p>
<p>what I am trying to generate is to generate boxplots of the data for all dataframe, at once, and in one figure !
I did try with diff... | <p>One way is to stack your data frames and use the <code>row=</code> argument inside <code>catplot</code>. First to create something like your data:</p>
<pre><code>import pandas as pd
import numpy as np
import seaborn as sns
df1 = pd.DataFrame({'Cat':np.random.choice(['C1','C2','C3'],50),
'Data':n... | python|pandas|matplotlib|seaborn|catplot | 3 |
371,368 | 66,074,696 | Pytorch nn.Linear RuntimeError: mat1 dim 1 must match mat2 dim 0 | <pre><code>class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.max_pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(7*7*32, 128)
self.fc1 = nn.Linear(128, 10)
def fo... | <p>you have named this function <code>nn.Linear(128, 10)</code> as <code>self.fc1</code><br />
i.e <code>self.fc1 = nn.Linear(128, 10)</code><br />
Please change it to <code>self.fc2 = nn.Linear(128, 10)</code></p> | python|pytorch | 1 |
371,369 | 66,084,559 | How to get the index label for a series returned by groupby? | <p>I've read in a timecard CSV file consisting of daily entries: 'User','Hours'.
I want to know the list of Users who submitted a partial timecard (e.g., less than 40 hrs/week).</p>
<pre><code>summed_entries = df.groupby('User')['Hours'].sum()
# This returns me a Series of Users and their total hours logged.
for ite... | <p>I'm not sure why you'd want to implement a for loop in pandas, this seems to suffice for your purpose:</p>
<pre><code>summed_entries = df.groupby('User')['Hours'].sum()
summed_entries = summed_entries[summed_entries < 40]
</code></pre>
<p>To get the list of names:</p>
<pre><code>list(summed_entries.index.values)
... | python|pandas|dataframe|series | 0 |
371,370 | 66,029,807 | Logging state of AdamW optimizer at certain stage in training | <p>I'm using an AdamW optimizer to train a model (Tensorflow 2.0).
I need to log its state at certain steps during training, so to be able to reload the optimizer's state and resume training from there later on.
Do I need to log anything else, apart from the initial config (the output of <code>optimizer.get_config()</c... | <p>If you are using keras <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model" rel="nofollow noreferrer">Model</a>, you can directly use <code>model.save</code> and then later restore it with <a href="https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model" rel="nofollow noreferrer"><code>t... | tensorflow|machine-learning|keras | 0 |
371,371 | 65,921,294 | How to average over conditionally selected numpy array entries in a 4D array based on an index from a 3D array | <p>I want to average over conditionally selected elements in a 4D numpy array, based on an index using a 3D array.</p>
<p>In other words, my 4D array <strong>DATA</strong> has these dimensions: [ntime,nz,ny,nx]</p>
<p>where as my 3D array <strong>COND</strong> which I use to conditionally sample is only a function of [... | <h2>Using <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer"><code>zip</code></a> to get indices along each axis</h2>
<p>IIUC, you have done most of the work, i.e. <code>idx</code></p>
<pre><code>>>> [*zip(*idx)]
[(0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 1, 2, 2, 0, 0, 0, 1),
... | python|arrays|numpy|array-broadcasting | 1 |
371,372 | 66,052,785 | Python: Interpolate data to specific x values | <p>I have a problem, that should be typical in science but I couldn't find a solution yet.</p>
<p>I have a data set in a cvs file, e.g.:
<a href="https://i.stack.imgur.com/LvrqJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LvrqJ.png" alt="enter image description here" /></a></p>
<p>What I need is ... | <p>Numpy has a nice way of doing it:</p>
<pre><code>import numpy as np
x = [0, 0.53, 0.84, 1.25, 1.55]
y = [0.523, 0.723, 0.965, 1.251, 1.458]
new_x = [0, 0.5, 1.0, 1.5]
new_y = np.interp(new_x, x, y)
new_y
</code></pre> | python|pandas|dataframe|numpy|interpolation | 2 |
371,373 | 66,334,676 | Should data feed into Universal Sentence Encoder be normalized? | <p>I am currently working with Tensor Flow's Universal Sentence Encoder (<a href="https://arxiv.org/pdf/1803.11175.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1803.11175.pdf</a>) for my B.Sc. thesis where I study extractive summarisation techniques.
In the vast majority of techniques for this task (like <a hre... | <p>The choice really depends on the application of design.</p>
<p>Regarding stop word removal and lemmatization: these operations in general removes some contents from the text, hence, it can remove the information. However, if it doesn't make an impact, then you can remove. (It is always best to try out both. In gener... | python|tensorflow|nlp|artificial-intelligence | 1 |
371,374 | 66,226,747 | Pandas dataframe assignment by pair of (row,column) values | <p>I know that using pandas lookup I can choose particular dataframe cells using pairs of (row,column) values. For example</p>
<pre><code>frame = pd.DataFrame([[1,2,3],[4,5,6]])
frame.lookup([0,1],[1,2])
</code></pre>
<p>gives me</p>
<pre><code>array([2, 6], dtype=int64)
</code></pre>
<p>Is there a similar way to assig... | <p>I don't know about any Pandas solution for that.
But if I'll have to do it on my own - below code should work.</p>
<pre class="lang-py prettyprint-override"><code>frame = pd.DataFrame([[1,2,3],[4,5,6]])
# 0 1 2
# 0 1 2 3
# 1 4 5 6
frame.lookup([0,1],[1,2])
# array([2, 6])
def set_dataframe_values(datafr... | python|pandas|variable-assignment|lookup | 0 |
371,375 | 66,266,188 | How to stack/append all columns into one column in Pandas? | <p>I am working with a DF similar to this one:</p>
<pre><code> A B C
0 1 4 7
1 2 5 8
2 3 6 9
</code></pre>
<p>I want the values of all columns to be stacked into the first column</p>
<p>Desired Output:</p>
<pre><code> A
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
</code></pre> | <p>Very simply with <code>melt</code>:</p>
<pre><code>import pandas as pd
df.melt().drop('variable',axis=1).rename({'value':'A'},axis=1)
</code></pre>
<hr />
<pre><code> A
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
</code></pre> | python|pandas|dataframe | 3 |
371,376 | 65,982,756 | plot the data based the total count of two columns | <p>I have a dataset like this:</p>
<pre><code>df = pd.DataFrame({'name':["a"," b", "c","d", "e"],
'gender': ["m", "f", "f", "f", "m"],
'year':[ 2018, 2019, 2020, 2017, 2014],
'c... | <p>You can create a pivot table and plot directly. Below is an example with bar as result. Line is not good idea here as you have few years only:</p>
<pre><code>import matplotlib.pyplot as plt
pd.pivot_table(df, index='year', columns=['gender'], values='count', aggfunc='sum').plot.bar()
plt.show()
</code></pre>
<p>Outp... | python|pandas|plot|data-analysis | 1 |
371,377 | 66,308,822 | sqlite + pandas: database table is locked | <p>I'm getting an unexpected error when using sqlite3 in python with pandas. I'm using a sqlite database for an analysis I'm doing, so it's single-user, single-computer. I'm in Python 3.9.1, with sqlite 3.33.0 and pandas 1.2.1.</p>
<p>The short description is that I'm trying to loop over rows of <code>Table1</code>, an... | <p>When you make your connection, set <code>autocommit=True</code></p>
<pre class="lang-py prettyprint-override"><code>@contextlib.contextmanager
def database_connect():
db_conn = pyodbc.connect(
autocommit=True, # needed to prevent locks in DB with SPs
)
try:
yield db_conn
finally:
... | python|pandas|database|sqlite | 0 |
371,378 | 66,248,612 | How to read the table from this webpage using python/pandas? | <p>webpage link - <a href="http://www.atlasoftheuniverse.com/stars.html" rel="nofollow noreferrer">http://www.atlasoftheuniverse.com/stars.html</a></p>
<p>I tried using pandas read_html and web scraping libraries like bs4 but no luck as the data on the webpage is not wrapped inside a table tag.
Please help me out!</p> | <p>I did it like this:</p>
<ul>
<li>copy the table (spaces and everything!)</li>
<li>use text editor to get column width delimters</li>
<li>read in using pandas</li>
</ul>
<p>Note I have used a truncated data set here because of character limits:</p>
<pre><code>import pandas as pd
import io
data = """
... | python|pandas|web-scraping | 0 |
371,379 | 66,038,049 | Pandas To Add an Index to Sum the columns | <p>I have a dataframe that has transposed as below. Years heading are the index and {A,B,C,D, E} are the columns.</p>
<p>I like to know how can I add a SUM to add all the values in rows A, B, C, D, & E. Thank you very much.</p>
<p><a href="https://i.stack.imgur.com/5r9b0.png" rel="nofollow noreferrer"><img src="htt... | <p>This may work for you</p>
<pre><code>df = pd.DataFrame({'a':[1,2,4], 'b': [10,20,45], 'c': [1,2,5]})
df
df["sum"] = df.sum(axis=1)
df
</code></pre> | python|pandas|dataframe | 1 |
371,380 | 65,942,274 | How to shuffle batches with ImageDataGenerator? | <p>I'm using ImageDataGenerator with flow_from_dataframe to load a dataset.</p>
<p>Using <code>flow_from_dataframe</code> with <code>shuffle=True</code> shuffles the images in the dataset.</p>
<p>I want to shuffle the batches. If I have 12 images and <code>batch_size=3</code>, then I have 4 batches:</p>
<pre><code>batc... | <p>Consider using the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer"><code>tf.data.Dataset</code></a> API. You can perform the batching operation before the shuffling.</p>
<pre><code>import tensorflow as tf
file_names = [f'image_{i}' for i in range(1, 10)]
ds = tf.data.... | python|tensorflow|keras | 0 |
371,381 | 66,192,285 | Libtorch works with g++, but fails with Intel compiler | <p>I want to use a neural network developed in Python (PyTorch) in a Fortran program. My OS is Ubuntu 18.04.</p>
<p>What I am doing:</p>
<ol>
<li>save it as torchscript: TurbNN.pt</li>
<li>call it from c++ program: call_ts.cpp, call_ts.h</li>
<li>call c++ program from Fortran program (using bind©): main.f90</li>
</ol>
... | <p>Do you see <code>cxx11</code> in the linker errors? It looks like your <code>libcall_ts_cpp</code> is compiled in a way that expects the new C++11 ABI for std::string but perhaps the library where those functions are implemented was compiled with the old ABI. Here's a PyTorch forum post about the same problem: <a ... | c++|c++11|cmake|fortran|pytorch | 3 |
371,382 | 66,245,309 | Python MS-SQL query not returning a correct value for varbinary datatypa coulmn | <p>I can successfully connect to SQL server database with python script, execute the query and store the output in a dataframe, however, there are few columns with varbinary(max) datatype in the DB which do not return the column in the right format in the dataframe. Any pointers in the right direction will be appreciat... | <p>I have found the solution, in the sql query perform convert to varchar(max) in select query and it returns the expected output. Only downside is to specify all the columns instead of using "*".</p>
<pre><code>select CONVERT(varchar(max),col,1) FROM TableName
</code></pre>
<p>Thanks to those who took the ti... | python|sql-server|pandas|varbinarymax | 0 |
371,383 | 66,127,194 | Object tracking program does not show tracked points in the output image | <p>I need to track an object in a video frame but to do so I have to initialize good features to track my object.
So, I have a .mp4 file, I retained the blue channel of the first frame and I obtained the first frame. I then went on to create my binary mask by extracting my region of interest from the first frame and it... | <p>It creates small yellow dots in top left corner. They are similar to background color so you may not see them.</p>
<p>When I draw on RGB <code>frame</code> then I get red dots which you can see on image</p>
<p><a href="https://i.stack.imgur.com/9Cy0k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | python|numpy|cv2 | 0 |
371,384 | 65,972,002 | Create new column with a list of max frequency values for each row of a pandas dataframe | <p>Given this Dataframe:</p>
<pre><code>df2 = pd.DataFrame([[3,3,3,3,3,3,5,5,5,5],[2,2,2,2,8,8,8,8,6,6]], columns=list('ABCDEFGHIJ'))
A B C D E F G H I J
0 3 3 3 3 3 3 5 5 5 5
1 2 2 2 2 8 8 8 8 6 6
</code></pre>
<p>I created 2 news columns which give for each row the <strong>max_freq</s... | <p>Try this, it uses <code>mode()</code></p>
<pre><code>df2.assign(max_freq=pd.Series(df2.mode(axis=1).stack().groupby(level=0).agg(list)),
max_freq_value = df2.eq(df2.mode(axis=1)[0].squeeze(),axis=0).sum(axis=1))
</code></pre> | python-3.x|pandas|dataframe|max|frequency | 1 |
371,385 | 66,213,216 | import pandas as pd ModuleNotFoundError: No module named 'pandas' | <p>I receive this error in Python 3.9.1</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd ModuleNotFoundError: No module named 'pandas'
</code></pre>
<p>But when I install pandas in the terminal it.</p> | <p>Please check the interpreter your using while trying to <code>import pandas</code> and receiving this error. This is probably a multiple python versions problem. Type in terminal <code>which python3</code> or <code>which <what ever python you use></code> and then (it differs by the ide you use) check if both p... | python|pandas|apple-m1 | 1 |
371,386 | 66,059,223 | Update particular values in a pandas dataframe from another dataframe | <p>I have a dataframe consisting of a chat transcript:</p>
<pre><code>id time author text
a1 06:15:19 system aaaaa
a1 13:57:50 Agent(Human) ssfsd
a1 14:00:05 customer ddg
a1 14:06:08 Agent(Human) sdfg
a1 14:08:54 customer sdfg
a1 15:58:48 ... | <p>I think in your solution should be added <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.ffill.html" rel="nofollow noreferrer"><code>GroupBy.ffill</code></a> for forward missing values per <code>id</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/referenc... | python|pandas | 1 |
371,387 | 66,228,933 | Panda drop values in columns but keep columns | <p>Has the title say, I would like to find a way to drop the row (erase it) in a data frame from a column to the end of the data frame but I don't find any way to do so.</p>
<p>I would like to start with</p>
<pre><code>A B C
-----------
1 1 1
1 1 1
1 1 1
</code></pre>
<p>and get</p>
<pre><code>A... | <p>If you only know the column name that you want to keep:</p>
<pre><code>import pandas as pd
new_df = pd.DataFrame(df["A"])
</code></pre>
<p>If you only know the column names that you want to drop:</p>
<pre><code>new_df = df.drop(["B", "C"], axis=1)
</code></pre>
<p>For your case, to kee... | python|pandas|dataframe | 2 |
371,388 | 66,029,256 | Failed to convert a NumPy array to a Tensor (Unsupported object type int) | <p>I am doing a project for making classification of liver disease and it's csv type of dataset. I am facing an error to fit the model and please concern below codes.
<strong>Imported all needed libraries and sublibraries are,</strong></p>
<pre><code>import tensorflow as tf
import keras.backend as K
from keras.models i... | <p>Keras default type is float, but your input type seems like int. Please try by adding</p>
<pre><code>X = X.astype(np.float32)
</code></pre> | python|tensorflow|keras | 3 |
371,389 | 66,133,492 | PyTorch training with Batches of different lenghts? | <p>Is it possible to train model with batches that have unequal lenght during an epoch? I am new to pytorch.</p> | <p>If you take a look at the <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader" rel="nofollow noreferrer">dataloader documentation</a>, you'll see a <code>drop_last</code> parameter, which explains that sometimes when the dataset size is not divisible by the batch size, then you get a last... | pytorch | 1 |
371,390 | 66,265,289 | TypeError: '<' not supported between instances of 'numpy.ndarray' and 'int' with a csv file | <p>I am trying to find specific elements (those with a value less than 5) in a particular data column from an imported csv file. However I keep encountering this strange error. The code reads as follows:</p>
<pre><code>z = np.loadtxt('exoplanets_nasa_archive.csv', delimiter= ',', dtype=str )
zlabels = z[0]
#print(zla... | <p>Apparently you are doing:</p>
<pre><code>In [78]: mass = np.array([1.23, 123.3], dtype='U32')
In [79]: mass
Out[79]: array(['1.23', '123.3'], dtype='<U32')
In [80]: mass<5
Traceback (most recent call last):
File "<ipython-input-80-39e4c1351b25>", line 1, in <module>
mass<5
TypeEr... | python|numpy|csv | 0 |
371,391 | 65,976,605 | PyTorch - Creating Federated CIFAR-10 Dataset | <p>I'm training a neural network (doesn't matter which one) on CIFAR-10 dataset. I'm using Federated Learning:</p>
<ul>
<li>I have 10 models, each model having access to its own part of the dataset. At every time step, each model makes a step using its own data, and then the global model is an average of the model (thi... | <p>10% on CIFAR-10 is basically random - your model outputs labels at random and gets 10%.</p>
<p>I think the problem lies in your "federated training" strategy: you cannot expect your sub-models to learn anything meaningful when all they see is a single label. This is why training data <a href="https://stack... | python|neural-network|pytorch | 1 |
371,392 | 66,072,114 | How to use existing keras model in tensorflow.js | <p>I have Keras model which I have converted to tensorflow.js but could not load the model in javascript, what will be the steps for that?</p>
<pre><code>model.add(Embedding(vocabulary_size, seq_len, input_length=seq_len))
model.add(LSTM(256,return_sequences=True))
model.add(LSTM(128))
model.add(Dense(256,activation='r... | <pre><code>import tensorflowjs as tfjs
model.add(Embedding(vocabulary_size, seq_len, input_length=seq_len))
model.add(LSTM(256,return_sequences=True))
model.add(LSTM(128))
model.add(Dense(256,activation='relu'))
model.add(Dense(vocabulary_size, activation='softmax'))
# compiling the network
model.compile(loss='categor... | javascript|python|tensorflow|keras|tensorflow.js | 0 |
371,393 | 52,733,169 | Unsupported type for timedelta seconds component: numpy.int64 | <p>I am using the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timedelta.html" rel="nofollow noreferrer">timedelta function</a> from datetime package to convert seconds into hours and minutes format. </p>
<p>Here's an example: </p>
<pre><code>secs = timedelta(seconds = 30)
print(secs)
00:00... | <p><a href="https://stackoverflow.com/questions/24870953/does-iterrows-have-performance-issues/24871316#24871316">Dont use loops with <code>iterrows</code></a>, because exist vectorized solution.</p>
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow nore... | python|pandas|datetime|timedelta | 4 |
371,394 | 52,663,432 | Dealing with sparse categories in Pandas - replace everything not in top categories with "Other" | <p>I often come across the following common problem when cleaning the data
there are some more common categories (let's say top 10 movie genres) and lots and lots of others which are sparse. Usual practice here would be to combine sparse genres into "Other" for example.</p>
<p>Easily done when there are not many spars... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>pd.DataFrame.loc</code></a> with Boolean indexing:</p>
<pre><code>df.loc[~df['studio'].isin(top_8_list), 'studio'] = 'Other'
</code></pre>
<p>Note there's no need to construct your... | python|pandas|dataframe|counter|data-cleaning | 2 |
371,395 | 52,491,327 | Pandas Dataframe data are same or new? | <p>In Python, Pandas dataframes are used : <br><br>
dataframe_1 :</p>
<pre><code> id
0 AB17
1 AB18
2 AB19
3 AB20
4 AB10
</code></pre>
<p>dataframe_2 :</p>
<pre><code> id
0 AB20
1 AB10
2 AB17
3 AB21
4 AB09
</code></pre>
<p>Here, dataframe_2 contains <b>AB20</b>,<b> AB10</b> and <b>AB17</b> same as... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow noreferrer"><code>isin</code></a> as:</p>
<pre><code>df2.id.isin(df1.id)
0 True
1 True
2 True
3 False
4 False
Name: id, dtype: bool
</code></pre> | python|pandas|dataframe | 2 |
371,396 | 52,686,748 | Comparing today date with date in dataframe | <p>Comparing today date with date in dataframe
Sample Data</p>
<pre><code>id date
1 1/2/2018
2 1/5/2019
3 5/3/2018
4 23/11/2018
</code></pre>
<p>Desired output</p>
<pre><code>id date
2 1/5/2019
4 23/11/2018
</code></pre>
<p>My current code</p>
<pre><code>dfda... | <p>Pandas has native support for a large class of operations on datetimes, so one solution here would be to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a> to convert your dates from strings to pandas' representation ... | python|python-2.7|pandas|datetime|dataframe | 2 |
371,397 | 52,706,603 | Adding unique values in the output in Pandas | <pre><code>import pandas as pd
data = {'numbers' : [1, 2, 3, 1, 3, 2, 2, 3, 3, 1, 2, 1, 1, 2, 3],
'colors' : ['red', 'yellow', 'red', 'green', 'blue', 'purple', 'blue', 'blue', 'green', 'blue', 'purple', 'blue', 'blue', 'purple', 'red']}
df = pd.DataFrame(data)
temp = df.groupby('numbers').colors.apply(' --> '.join... | <p>Defining a custom function using <code>itertools.groupby</code>:</p>
<p><strong><em>Setup</em></strong></p>
<pre><code>import itertools
def foo(arr):
for i, g in itertools.groupby(arr):
l = len(list(g))
if l > 1:
yield f'{i} x{l}' # yield '{i} x{l}'.format(i=i, l=l)
el... | python|python-3.x|pandas|pandas-groupby | 4 |
371,398 | 52,819,066 | keras model evaluation with quantized weights post training | <p>I have a model trained in keras and is saved as a .h5 file. The model is trained with single precision floating point values with tensorflow backend. Now I want to implement an hardware accelerator which performs the convolution operation on an Xilinx FPGA. However, before I decide on the fixed point bit width to be... | <p>Sorry for that I'm not familiar to tensorflow, so I can't give you the code, but maybe my experience with quantizing a caffe model could make sense.</p>
<p>If I understand you correctly, you have a tensorflow model(float32) which you want to quantize it to int8 and save it in a <code>numpy.array</code>.</p>
<p>Fir... | python|tensorflow|keras|fpga|quantization | 0 |
371,399 | 52,465,389 | Adding up the values with the same index using numpy/python | <p>I am a newbie to python and numpy. I want to find the total rainfall days (ie. sum of column E for each year, attach the image herewith).
I am using <strong>numpy.unique</strong> to find the unique elements of array year.</p>
<p>following is my attempt;</p>
<pre><code>import numpy as np
data = np.genfromtxt("locat... | <p>For such tasks, Pandas (which builds on NumPy) is more easily adaptable.</p>
<p>Here, you can use <code>GroupBy</code> to create a series mapping. You can then use your input to query your series:</p>
<pre><code>import pandas as pd
# read file into dataframe
df = pd.read_excel('file.xlsx')
# create series mappin... | python|numpy|python-3.6 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.