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 |
|---|---|---|---|---|---|---|
363,000 | 29,566,603 | python pandas conditional count across columns | <p>I have a dataframe (called panel[xyz]) containing only 1, 0 and -1. The dimensions are: rows 0:10 and columns a:j. </p>
<p>I would like to create another dataframe (df) which has the same vertical axis, but only 3 columns:
col_1 = count all non-zero values (1s and -1s)
col_2 = count all 1s
col_3 = count... | <p>I'm just doing this with a flat dataframe but it's the same for panel. You can do one of two ways. The first way is what you did, just change the <code>count()</code> to <code>sum()</code>:</p>
<pre><code>( df > 0 ).sum(axis=1)
</code></pre>
<p>The underlying structure is boolean and True and False both get c... | python|pandas|conditional|dataframe|vectorization | 9 |
363,001 | 29,438,471 | how to prevent pandas psql.read_sql_query from fetching cache | <p>i use pandas 0.15.2 and read from a mysql storedproc into dataframe</p>
<pre><code>import pandas.io.sql as psql
cnx= pymysql.connect( .. connection string ...)
df=psql.read_sql_query('call storedproc', con=cnx)
</code></pre>
<p>the database is quite active with new data frequently, I realise whenever i rerun the a... | <p>after some testing, i added autocomit=True in the connection parameters and it stop fetching cached resultsets even if i am only doing a read. hope this help others.</p> | python|pandas | 4 |
363,002 | 29,428,539 | Boxplot and groupby: Issue with groups and sharex | <p>Here is my datasets:</p>
<pre><code>df
A B C
0 13 Yes False
1 12 No True
2 2 Yes True
3 12 No False
4 4 No True
5 1 Yes True
6 1 No False
7 5 No True
8 15 Yes False
</code></pre>
<p>and </p>
<pre><code>df2
A B C
0 13 Yes False
1 12 No False
... | <pre><code>import seaborn as sns
import pandas as pd
df = pd.DataFrame([[13, 'Yes', False],
[12, 'No', True],
[2, 'Yes', True],
[12, 'No', False],
[4, 'No', True],
[1, 'Yes', True],
[1, 'No', False],
[5, 'No', True],
[15, 'Yes', False]],
columns = list('ABC... | python|pandas|matplotlib | 2 |
363,003 | 29,685,386 | Pivot Table to Dictionary | <p>I have this pivot table:</p>
<pre><code>[in]:unit_d
[out]:
units
store_nbr item_nbr
1 9 27396
28 4893
40 254
47 2409
51 925
89 157
9... | <p>I'd use <a href="http://pandas.pydata.org/pandas-docs/version/0.16.0/groupby.html"><code>groupby</code></a> here, after resetting the index to make it into columns:</p>
<pre><code>>>> d = unit_d.reset_index()
>>> {k: v.tolist() for k, v in d.groupby("store_nbr")["item_nbr"]}
{1: [9, 28, 40, 47, 51... | python|dictionary|pandas|pivot-table | 6 |
363,004 | 29,518,817 | Extract Indices at Steps | <p>I have a numpy array as shown in figure consisting of red and yellow pixels. I wan to select only the red ones.
<img src="https://i.stack.imgur.com/pZYM6.gif" alt="enter image description here"></p>
<pre><code>import numpy as np
data = np.ones((10, 10))
</code></pre>
<p>How it is done, guys?</p> | <p>OK so it seems you want to mask your input with an alternation/checkerboard pattern:</p>
<pre><code>import numpy as np
def checkerboard(shape):
"A hacky way to generate a checkerboard"
return np.sum(np.indices(shape), axis=0) % 2 == 0
data = np.ones((10, 10), dtype=np.bool)
# equivalent ways of applying ... | numpy | 1 |
363,005 | 29,481,568 | Skipping 0xff byte when using pandas read_csv | <p>I am trying to read some log files from my boiler, but they are rather poorly formatted.</p>
<p>When I try to read the file(s) with</p>
<pre><code>import pandas
print(pandas.read_csv('./data/CM120102.CSV', delimiter=';'))
</code></pre>
<p>I get</p>
<p><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x... | <p>I would read it into a string. Then do some munging in python, before passing it off to pandas.read_csv. Example code follows.</p>
<pre><code># get the data as a python string
with open ("CM120102.CSV", "r") as myfile:
data=myfile.read()
# munge in python - get rid of the garbage in the input (lots of xff byte... | python|csv|python-3.x|pandas|null | 4 |
363,006 | 62,195,486 | Extract dictionary value from a list contained in Pandas dataframe column | <p>I'm trying to extract values from a dictionary contained within list in a Pandas dataframe .Objective is to split the id key into multiple columns. Sample data is like :</p>
<pre><code>Column_Header
[{'id': '498', 'relTypeId': 2'},{'id': '499', 'relTypeId': 3'}]
[{'id': '499', 'relTypeId': 3'},{'id': '500', 'relTyp... | <p>We can do <code>explode</code> first then create the additional key with <code>cumcount</code> , and pivot </p>
<pre><code>s=df.Column_Header.explode().str['id']
s=pd.crosstab(index=s.index,columns=s.groupby(level=0).cumcount(),values=s,aggfunc='sum')
Out[133]:
col_0 0 1 2
row_0
0 498 ... | pandas | 1 |
363,007 | 62,154,856 | Finding closest number index from a vector | <p>If there is a reference vector, for example:</p>
<pre><code>ref = np.array([1., 3., 5.])
</code></pre>
<p>And a random vector:</p>
<pre><code>r = np.array([3.1, 4.7, 0.1, 5.5])
</code></pre>
<p>Is there a fast way to find the index of the closes number in 'ref' for each number in 'r'?</p>
<p>Expected result is:... | <p>You can do a broadcasting:</p>
<pre><code>np.abs(r[:,None]-ref).argmin(-1)
</code></pre>
<p>Output (remember python is 0-indexed):</p>
<pre><code>array([1, 2, 0, 2])
</code></pre> | python|numpy | 1 |
363,008 | 62,296,989 | How to sequence rows based on another row? | <p>Pls check this : <a href="https://stackoverflow.com/questions/59976809/how-to-sequence-row-based-on-another-row">How to sequence row based on another row?</a>
input</p>
<pre><code>Column A
H
H
H
J
J
J
J
K
</code></pr... | <p>Use <code>shift</code> and <code>cumsum</code>:</p>
<pre><code>df["new"] = df["Column A"].ne(df["Column A"].shift(1)).cumsum()
print (df)
Column A Column B new
0 H 1 1
1 H 1 1
2 H 1 1
3 J 2 2
4 J 2 2
5 J 2... | python|pandas | 1 |
363,009 | 62,150,659 | How to convert a tensor of booleans to ints in PyTorch? | <p>Suppose, we have a tensor </p>
<pre><code>t = torch.tensor([True, False, True, False])
</code></pre>
<p>How do we convert it to an integer tensor with values <code>[1, 0, 1, 0]</code>?</p> | <p>The solution is just a single line of code.</p>
<p>To convert a tensor <code>t</code> with values <code>[True, False, True, False]</code> to an integer tensor, just do the following.</p>
<pre><code>t = torch.tensor([True, False, True, False])
t_integer = t.long()
print(t_integer)
[1, 0, 1, 0]
</code></pre> | int|boolean|pytorch|tensor | 14 |
363,010 | 62,099,121 | Is there a way to covert all columns with int to float | <p>I want to convert all the columns of dataframe with dtype as int to float. How can I achieve this? I dont know the name of the columns which are int so might need to use <code>if == int</code> or something.</p> | <p>try this, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer">select_dtypes</a></p>
<pre><code>columns = df.select_dtypes(include='int').columns
df[columns] = df[columns].astype(float)
</code></pre> | python|pandas | 0 |
363,011 | 62,299,991 | Convert pandas DataFrame to nested JSON array | <p>I have a df as follows:</p>
<pre><code> dates values
0 2020-01-01 00:15:00 25.7
1 2020-01-01 00:30:00 25.0
2 2020-01-01 00:45:00 24.6
3 2020-01-01 01:00:00 24.6
4 2020-01-01 01:15:00 25.0
5 2020-01-01 01:30:00 25.6
6 2020-01-01 01:45:00 26.2
7 2020-01-01 02:00:00 26.5
8 2020-... | <p>Try <code>orient="values"</code>:</p>
<pre><code>df.to_json(orient='values', date_unit='s')
</code></pre>
<p></p>
<pre><code>'[[1577837700,25.7],[1577838600,25.0],[1577839500,24.6],[1577840400,24.6],[1577841300,25.0],[1577842200,25.6],[1577843100,26.2],[1577844000,26.5],[1577844900,26.3],[1577845800,25.7]]'}
... | python|json|python-3.x|pandas|dataframe | 2 |
363,012 | 62,199,414 | Using Pandas to Filter String In Cell with Multiple Values | <p>I am using pandas to filter a data frame using str.contains() but my logic is dropping values that I might want to keep given the string. I don't know how to use Pandas to sort this out. </p>
<p>A sample cell in the excel sheet that I am working with would look like:</p>
<p>Case #1: Don't flag this because there i... | <p>You can create a Boolean Mask that indicates whether or not <code>all</code> separate words contain <code>'@work'</code>.</p>
<p>First, <code>split</code> so that each word is placed into a separate cell, and <code>explode</code> will turn this into one big Series, with the index duplicated and pointing back to the... | python-3.x|pandas|string|dataframe|conditional-statements | 5 |
363,013 | 62,350,781 | How do i compare two dataframe using between function on the other dataframe | <p>i have a dataframe that looks like this :</p>
<pre><code> Words Start_time(in sec) End_time(in secs) Total_Time_words
0 let 0.1 2.5 2.6
1 me 2.5 2.6 5.1
2 tell 2.6 2.9 ... | <p>You can use <code>pd.cut</code> and <code>groupby()</code>:</p>
<pre><code>bins = [df['Start_time(in sec)'].iloc[0]] + list(df['End_time(in secs)'])
s = pd.cut(df2.Time, bins=bins, labels=df.index)
df['Amplitudes'] = (df2.sort_values('Amplitudes', ascending=False)
.groupby(s)['Amplitudes']
... | python|pandas|dataframe|for-loop | 0 |
363,014 | 62,099,031 | confusion_matrix() library is giving ValueError | <p>When trying to get confusion matrix for a ConvNet constantly getting the same error. </p>
<pre><code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras impo... | <p>I am able to recreate your error using <code>Dogs_Vs_Cats</code> dataset. Where i have 2000 samples in train directory and 400 samples in validation directory.</p>
<p>Please change <code>model.predict_generator</code> from </p>
<pre><code>Y_pred = model.predict_generator(validation_generator, nb_validation_samples... | python|tensorflow|keras | 1 |
363,015 | 62,116,999 | Split pandas column with list of item and values, into separate columns with item as column header | <p>I have a column in a pandas DataFrame that looks like the below:</p>
<pre><code>[Apple X 1, Orange X 2, Watermelon X 1, Pineapple X 3]
</code></pre>
<p>There are 100k+ rows, and it represents things our customers have ordered.</p>
<p>I'd like to go through this column and split these into separate columns so that... | <p>IIUC, you can we can use <code>split</code> and <code>set_index</code>, then <code>T</code>, for transpose:</p>
<pre><code>import pandas as pd
s = pd.Series(['Apple X 1', 'Orange X 2', 'Watermelon X 1', 'Pineapple X 3'])
s.str.split(' ', expand=True).set_index(0).T.drop(1)
</code></pre>
<p>Output:</p>
<pre><code>... | python|pandas|split | 1 |
363,016 | 62,118,012 | Testing an implementation of an LSTM in Pytorch | <p>I'm trying to use the Pytorch implementation of an LSTM <a href="https://stackoverflow.com/questions/50168224/does-a-clean-and-extendable-lstm-implementation-exists-in-pytorch">here</a>. I'm including it here for reference. It consists of two classes, LSTMCell and LSTM, where LSTMCell is just a single unit and LSTM ... | <p>The first argument to <code>super()</code> should be class itself, not a different class.</p>
<pre class="lang-py prettyprint-override"><code>class LSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, bias=True):
super(LSTM, self).__init__()
# ^^^^ self is not an instance of LST... | python|pytorch|lstm | 1 |
363,017 | 62,453,871 | FutureWarning after setting epsg in Python with geopandas | <p>I get this error:
FutureWarning: '+init=:' syntax is deprecated. ':' is the preferred initialization method. When making the change, be mindful of axis order changes: <a href="https://pyproj4.github.io/pyproj/stable/gotchas.html#axis-order-changes-in-proj-6" rel="nofollow noreferrer">https://pyproj4.github.io/pypro... | <p>Your issue has two parts.</p>
<p>1) FutureWarning error tells you, that you should not use <code>{'init': 'epsg:3857'}</code> but some other way of CRS specification. It can be just <code>'epsg:3857'</code> or even <code>3857</code> would do.</p>
<p>2) The reason why your excel is empty if you do <code>to_crs</cod... | python|excel|geopandas|epsg | 1 |
363,018 | 62,299,221 | Color value of key 'CountMatch result' in dict obj | <pre><code> **testdict** = {'Dict_1': {'Start Time': '06-10-2020 13:08:58', 'Test Type': 'ERP_To_DBO','CountMatch Result': 'Failed', 'End Time': '06-10-2020 13:09:16'},
'Dict_2': {'Start Time': '06-10-2020 13:09:21', 'Test Type': 'ERP_To_DBO','CountMatch Result': 'Failed', 'End Time': '06-10-2020 13:11:53'},
'Dict_... | <p>Try operating on the entire column at a time inside your function:</p>
<pre><code>def color_mapper(values):
mapping = {'Failed': 'red', 'Passed': 'green'}
return [
'background-color: {}'.format(mapping.get(v, 'black') for v in values]
df.style.apply(color_mapper)
</code></pre> | python|pandas | 1 |
363,019 | 62,435,493 | Python Split output column with fixed & dynamic length | <p>I want to split the data frame from a single column to three columns <a href="https://pastebin.com/DYmn65V6" rel="nofollow noreferrer">Sample input and output</a>
[(Col1=fix length), (Col2=<em>dynamic length</em>),( Col3= remaining part)]</p>
<pre><code>import re
import pandas as pd
text='Raw Data'
out = re.finda... | <p>Is this working for you? </p>
<pre><code>df.RAW.str.extract(r"(.*)(\d\d\.\d+)(\d\d\.\d+)")
</code></pre>
<p>The output I get is: </p>
<pre><code> 0 1 2
0 RIY-OUHOMH-1002 24.534768 46.650127
1 RIY-OUHOHH-1017 24.51472 46.663988
2 RIY-OUHOMH-1004 24.532244 46.651758
3 RI... | python|regex|pandas|numpy | 0 |
363,020 | 62,156,920 | Difference between keras.backend.max and keras.backend.argmax | <p>I am a beginner in Deep Learning and while performing a practical assignment, came across the Keras documentation on keras.backend.</p>
<p>I went through the explanation a number of times. however, i cannot exactly understand the difference between max and argmax function.</p> | <p><code>argmax</code> is the index of maximum in an array and <code>max</code> is maximum value in that array. Please check the example given below</p>
<pre><code>import tensorflow as tf
x = tf.constant([1,10,2,4,15])
print(tf.keras.backend.argmax(x, axis=-1).numpy()) # output 4 (index of max value 15, which is 4)
pr... | keras|tensorflow2.0 | 0 |
363,021 | 62,264,017 | Object recognition with CNN, what is the best way to train my model : photos or videos? | <p>I aim to design an app that recognize a certain type of objects (let's say, a book) and that can say whether the input is effectively a book or not (binary classification).</p>
<p>For a better user experience, I would like the input to be a video rather than a picture: that way, the user won't have to deal with iss... | <p>Good question! The answer is: you should train your model on how you plan to use it. So if you ask the user to take photos, train it on photos. If you ask the user to film the object, train on frames extracted from video. </p>
<p>The images might seem blurry to you, but they won't be for a computer. It will just le... | python|tensorflow|deep-learning | 2 |
363,022 | 62,228,981 | What is freezing/unfreezing a layer in neural networks? | <p>I have been playing around with neural networks for quite a while now, and recently came across the terms "freezing" & "unfreezing" the layers before training a neural network while reading about transfer learning & am struggling with understanding their usage. </p>
<ul>
<li>When is one supposed to use f... | <p>I would just add to the other answer that this is most commonly used with CNNs and the amount of layers that you want to freeze (not train) is "given" by the amount of similarity between the task that you are solving and the original one (the one that the original network is solving). </p>
<p>If the tasks are very ... | tensorflow|machine-learning|deep-learning|neural-network|transfer-learning | 6 |
363,023 | 62,461,007 | Is it possible to train a NN in Keras with features that won't be available for prediction? | <p>I'm fairly new to this topic as a whole and struggle to wrap my head even the basics of neural networks in general. Not looking for a project plan, appreciate that you probably have better things to do.
Nonetheless, any idea or push in the right direction is appreciated.</p>
<p>Imaging a grey-box model of some kind... | <p>Yes, you can train your model like that. But you must feed all the features during prediction. For example, you have 30 mandatory features and 10 optional features. The total is 40. You must feed all the 40 features to get a prediction from your model. Input data shape must be the same always. But we asked for optio... | tensorflow|keras|neural-network | 0 |
363,024 | 62,465,877 | How to create multiple empty pd.DataFrame which are named like values from List | <p>I want to create multiple empty pd.DataFrame and I thought I can do it with a loop like this:</p>
<pre><code>for share in tickers:
share=pd.DataFrame()
</code></pre>
<p>with:</p>
<pre><code>tickers=['AAPL', 'MSFT', '^GSPC', 'VNA.DE', '^GDAXI', 'HJUE.HA', 'GYC.DE', '2B7K.DE']
</code></pre>
<p>But this creates a e... | <p>It is not <a href="https://stackoverflow.com/a/30638956">recommended</a>, better is create dictionary of <code>DataFrame</code>s:</p>
<pre><code>dfs = {x: pd.DataFrame() for x in tickers}
</code></pre>
<hr>
<pre><code>print (dfs)
{'AAPL': Empty DataFrame
Columns: []
Index: [], 'MSFT': Empty DataFrame
Columns: []
... | pandas|dataframe|for-loop | 1 |
363,025 | 62,347,069 | pandas: create column conditioned on row containing a string in list | <p>I have a dataframe with 20 columns, and 3 of those columns (always the same) may contain one or more of these strings ["fraction", "fractional", "1/x", "one fifth"].</p>
<p>I want to add a new column that says whether or not each row is "fractional" (in other words, contains one of those words). This column could ... | <p>Create a single pattern by joining all the words with <code>'|'</code>. Then we check the condition in each column separately using <code>Series.str.contains</code> and create a single mask using <code>np.logical_or.reduce</code>.</p>
<h3>Sample Data</h3>
<pre><code>import pandas as pd
import numpy as np
keywords... | python|pandas|numpy|dataframe | 2 |
363,026 | 62,354,005 | Easiest way to count distinct number of rows in Pandas dataframe? | <p>I just did:</p>
<pre><code>len(my_df.drop_duplicates())
</code></pre>
<p>Is there not a more elegant way to do this?
in R you can do:</p>
<pre><code>nrow(distinct(my_df))
</code></pre>
<p>Which to me is very readable, drop_duplicates() feels worrying, because as new Python user, I get lost with what operations ... | <p>In <code>pandas</code> you can do by another way <code>groupby</code> or <code>duplicated</code> with <code>sum</code></p>
<pre><code>df.groupby(list(df)).ngroup()
(~df.duplicated()).sum()
</code></pre>
<p>Also as a <code>R</code> and <code>python</code> user, I know that is hard to switch from <code>R</code> to... | python-3.x|pandas|dataframe | 1 |
363,027 | 62,133,139 | Using For Loop to create a List to then export with Pandas to Excel | <p>Good Morning,</p>
<p>I've been working on this for about 3 days now. I need some help.</p>
<p>I'm using BeautifulSoup to allow me to parse it. Everything I'm doing works all the way down to:</p>
<pre><code>df = pd.DataFrame({'Name':[Var1]})
df.append([Var1], ignore_index=False)
df.to_excel(writer, sheet_name='N... | <p>You need to put each <code>Var1</code> that you get in each iteration of the <code>for link in soup...</code> loop inside a structure (like a list) and <em>only after the loop is done</em> you transform that list into a DataFrame and write it to Excel. Otherwise, each call to <code>df.to_excel</code> simply overwrit... | python|python-3.x|pandas|for-loop | 0 |
363,028 | 62,386,150 | groupby by many columns in pandas and add it into one dataframe | <p>I have a dataframe that I made from stackoverflow survey 2018 and 2019. I have a column that is the salary for this specific respondent and I call it 'usd' and many columns of programming languages names - c,c++,c#, etc - 43 of them, so total 44 columns - 1 is salary and the others are programming languages.
Each ro... | <p>Here you go.. you have to group them by the language column value and take the mean of the 'usd' column</p>
<p>Sample dataset:</p>
<pre><code> usd java python c
0 10 1 0 1
1 20 0 1 1
2 30 1 1 0
3 40 0 0 1
4 50 1 1 0
</code></pre>
<p>Code</p>
<pr... | pandas | 0 |
363,029 | 62,178,252 | np.where error when trying to select two columns | <p>I am trying to perform a multiple regression on the 'Linnerud' dataset from sklearn.
I have an np array that is 20x3, but I only want to select two of the three columns.
I can add a single independent variable using:</p>
<pre><code>X_for_1D_LR = X[:,np.where(np.array([feature_names_X])[0] == 'Situps')[0]]
</code></... | <p>Restructure your code to make the logic more obvious. Python is a language that is generous with whitespace; use this to your advantage:</p>
<pre><code>X_for_2D_LR = X[:,
np.where(
np.array([feature_names_X])[0] == 'Situps',
np.array([feature_names_X])[0] == '... | python|numpy|scikit-learn|regression|valueerror | 0 |
363,030 | 62,166,479 | Keras ValueError: No data provided for "add". Need data for each key in: ['add'] using Model API | <p>I would like to use Keras for binary classification. Below is my code:</p>
<pre><code>input1 = tf.keras.Input(batch_size=batch_size, shape=(len1,))
output1 = tf.keras.layers.Dense(units=1, kernel_initializer='glorot_uniform')(input1)
input2 = tf.keras.Input(batch_size=batch_size, shape=(len2,))
output2 = tf.keras.l... | <p>I'm using tf.dataset here. It turns out I need to specify the correct input and output names for the tensors as tf.dataset is looking for these names while feeding the data to keras.</p>
<p>so <code>input1</code> and <code>input2</code> should have the corresponding name of the input features, and since the label i... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
363,031 | 62,284,838 | How to use regular expressions for making dummies? | <p>For instance, I have reviews column and I want to extract words and create dummy variables based on them.</p>
<p>I use that but can't use regular expressions here:</p>
<pre><code>df = df['reviews'].str.contains('good').astype(int)
</code></pre>
<p>How can I use regular expressions here for extracting good, goid, ... | <p>You can use the .map method after the .contains method. Here's a concise example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'id': [1,2,3],
'review': ['this is a good one',
'this is a bad one',
... | python|regex|pandas|dataframe|dummy-variable | 0 |
363,032 | 62,324,422 | version `GLIBC_2.28' not found | <p>I'm trying to install PyTorch on ARMv7(32-bit) architecture but PyTorch doesn’t have official ARMv7 builds so i tried <a href="https://discuss.pytorch.org/t/pytorch-1-3-wheels-for-raspberry-pi-python-3-7/58580" rel="noreferrer">this unofficial build</a>.</p>
<p>It installed successfully but when I import torch I ge... | <blockquote>
<p>So is it possible to install GLIBC_2.28 on my machine?</p>
</blockquote>
<p>It is possible, but the chances of you making a mistake and rendering your system un-bootable are quite high. It is also very likely that doing so will break something <em>else</em> on your system (this is the reason distribu... | pytorch|ubuntu-16.04|glibc|libc|armv7 | 28 |
363,033 | 62,067,131 | How to drop multiple columns (using column names) from a dataframe using pandas? | <p>I have a data frame <code>df</code> with around 200 columns. I want to drop the columns with an index position from 50 to 90 and 120 to 170 with its name rather than its index position. How to do that.</p>
<p>I cannot use: </p>
<pre><code>df.drop('column name', axis=1)
</code></pre>
<p>directly because there are ... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>np.r_</code></a> to do this:</p>
<pre><code>import numpy
idx = np.r_[50:90, 120:170]
df.drop(df.columns[idx], axis=1, inplace=True)
</code></pre>
<p>From the <code>np.r_</code> docs:</p>
<blockquo... | python|pandas | 6 |
363,034 | 62,271,807 | Create new columns according row values in pandas | <p>I have a pandas dataframe that looks like this:</p>
<pre><code> id name total cubierto no_cubierto escuela_id nivel_id
0 1 direccion 1 1 0 420000707 1
1 2 frente_a_alunos 4 4 0 420000707 1
2 3 ap... | <p>You need to use <code>pivot_table</code> here:</p>
<pre><code>df = df.pivot_table(index=['escuela_id', 'nivel_id'], columns='name', values=['total', 'cubierto']).reset_index()
df.columns = ['_'.join(col).strip() for col in df.columns.values]
print(df)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> es... | python|pandas|dataframe | 1 |
363,035 | 62,264,422 | How do I transpose an empty numpy array? | <p>I have an 'empty' 2D array in numpy as </p>
<p><code>arr = np.array([[[], [], []], [[], [], []]])</code>.</p>
<p>When I do <code>np.transpose(arr)</code>, I get the result: <code>[]</code>, instead of the expected:</p>
<p><code>[[[],[]],[[],[]],[[],[]]]</code>.</p> | <p>Look at what your expression produces:</p>
<pre><code>In [41]: arr = np.array([[[], [], []], [[], [], []]])
In [42]: arr
Out[42]: array([], shape=(2, 3, 0), dtype=float64)
In [43]: print(arr) ... | python|numpy|numpy-ndarray | 0 |
363,036 | 62,136,323 | How to convert PDF document to JSON Using Python script | <p>Trying to convert an PDF form to JSON data using python</p>
<p><strong>Sample PDF Format :</strong> </p>
<p><a href="https://i.stack.imgur.com/aOHzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aOHzu.png" alt="enter image description here"></a></p>
<p><strong>Code :</strong></p>
<pre><code>... | <p>He will get a string by this.You need to convert <code>page_content</code> into <code>dictionary</code> first</p> | python|json|pandas|dataframe|pypdf | -2 |
363,037 | 62,349,382 | How to parse this JSON which starts with two square brackets? | <p>I have a JSON File that starts with two square brackets. How do i parse the data from it?
The type of the JSON is class 'list'. I have gone though many Stackoverflow solutions but none of them helped. I am new to python and trying to use API extraction.</p>
<pre><code>[
[
{
"previous": null,
"stor... | <p>What you're looking at is a Dictionary with one entry. Before parsing instantiate a new Map like:</p>
<pre class="lang-js prettyprint-override"><code>const json_data = open('responsefile2.json')
const df1 = new Map(json.load(json_data));
json_data.close()
</code></pre>
<p>Then iterate over <code>df1</code> entries l... | python|json|pandas|dataframe | 0 |
363,038 | 62,094,274 | Tensorflow 2.0 (Keras) classification with restricted classes | <h1>Problem background</h1>
<p>I have a basic classification problem, classifying each row into one of 20 classes.</p>
<p>However, there is a twist. For every row, only some of those 20 classes are valid - and this is known upfront.</p>
<p>In tensorflow 1.0, I have been nullifying the logits of the impossible classes. ... | <p>Your loss function can be implemented exactly in the same way:</p>
<pre><code>def getLoss(logits, y, restrictions):
logits = tf.where(restrictions, -1000.0 * tf.ones_like(y, dtype=tf.float32), logits)
return tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)
</code></pre>
<p>The model can then ... | python|tensorflow|keras|tensorflow2.0|tf.keras | 1 |
363,039 | 62,135,685 | How do I select and print the : values and , values | <p>How do I select and print the <code>:</code> separated values and the<code>,</code> separated values in pandas. Example, I want, from ( Fridge:200:1,1,1,...1) the 200 values to be printed separately and the printed sum of the 1s after the final : from the"</p>
<pre><code>Fridge:200:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,... | <p>IIUC, This might help you:</p>
<pre><code>'''
Fridge:200:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Washer:500:0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0
Oven:2150:0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0
Microwave:1000:0,0,0,0,0,0,0,0,0.5,0,0,0,0,0,0,0,0,0.5,0,0,0.5,0,0,0
Aircon:2000:0,0,0,0,0,1,1... | python|python-3.x|pandas|csv | 0 |
363,040 | 62,046,817 | Masking and indexing pandas dataframe | <p>I have a pandas dataframe about crime statistics, where i want to mask and count the total number of crime values in my dataset: </p>
<pre class="lang-py prettyprint-override"><code>min = 0
max = 24
days = df[::24].count()['Year']
print(days)
df['daily_crime'] = np.NAN
for i in range(days):
#print(df.loc[df.i... | <p>You can use <code>groupby</code> and <code>transform</code>:</p>
<pre><code>df["Date2"] = pd.to_datetime(df["Date2"])
df["day_total"] = df.groupby(["Year","Month","Day"])["Personfarlig_krim"].transform(lambda d: sum(d.eq("Yes")))
print (df)
District Neighbourhood.x Year Month Day Hour Weekday Sun Person... | python|pandas|dataframe | 1 |
363,041 | 62,118,262 | Dask dataframe read parquet format fails from http | <p>I have been dealing with this problem for a week.
I use the command</p>
<pre><code>from dask import dataframe as ddf
ddf.read_parquet("http://IP:port/webhdfs/v1/user/...")
</code></pre>
<p>I got invalid parquet magic.
However ddf.read_parquet is Ok with "webhdfs://" </p>
<p>I would like the ddf.read_parquet work... | <p>Although the comments already partly answer this question, I thought I would add some information as an answer</p>
<ul>
<li>HTTP(S) is supported by dask (actually <code>fsspec</code>) as a backend filesystem; but to get partitioning within a file, you need to get the size of that file, and to resolve globs, you nee... | pandas|http|dask|parquet|fastparquet | 0 |
363,042 | 62,206,848 | Assign "points" based on column values and sum in new column using python | <p>I have this sample data frame:</p>
<pre><code>df_samp = pd.DataFrame({'Athlete': ['Bob', 'John', 'Ross'], 'Distance': [7.4, 6.01, 5], 'Under8': [1, 0, 1.2], 'Under745': [5.1, 0, 3], 'Under730': [0, 0, .8]})
</code></pre>
<p>We have an individual that ran a certain number of miles, in <code>Distance</code>, and the... | <p>Are you looking for something like this?</p>
<pre><code>df_samp['Points'] = df_samp.apply(lambda x: x['Distance']*1 + x['Under8']*1.25 + x['Under745']*1.5 + x['Under730']*1.75, axis=1)
</code></pre>
<p>Output</p>
<pre><code> Athlete Distance Under8 Under745 Under730 Points
0 Bob 7.40 1.0 ... | python|pandas | 1 |
363,043 | 62,111,128 | np.savetxt not appending even when file is still open | <p>Edit!!!
In the end I was able to write this with the while loop that I wanted and saved to correct output folder while it being appending. </p>
<p>Solution: </p>
<pre><code>tempfilename=keyname+'_trimmed.fastq'
TempSavelocation="./fastqs/"+tempfilename
f=open(TempSavelocation,'ab')
icounter=0
while icounter < ... | <p>When using <code>with open</code>, do that saving with the indented block.</p>
<pre><code>In [329]: atable=['a','b','b','a','b','b']
...: with open('abtest.csv','ab') as f:
...: for s in atable:
...: structuredArr=np.array([s,"+"])
...: np.savetxt(f, structuredArr, d... | python|numpy|append | 0 |
363,044 | 62,460,873 | subract every column from each other in dataframe | <p>We have a <code>df</code> as dataframe containing n number of columns. I want to subtract every column from each other such as(n is number of columns) :</p>
<ul>
<li><p>If n =3 then new column formed = 3</p>
</li>
<li><p>If n =4 then new column formed = 6</p>
</li>
<li><p>If n =5 then new column formed = 10</p>
<p>F... | <p>Assuming you are looking for something like this - get the difference of each pair of columns into new columns for each pair </p>
<p>Considering a <code>pd.DataFrame</code> with 5 rows and 4 columns - A, B, C, D - with all random values </p>
<pre><code>df = pd.DataFrame(np.random.randint(0, 5, size=(5, 4)), colum... | python|python-3.x|pandas | 1 |
363,045 | 62,462,171 | Pandas groupy by last 6 months from a reference date | <p>I need to sum a column "qtd" taking into account the last 6 months of a reference date.</p>
<pre><code>prod date qtd sum
proda 2018-01-01 2 2
proda 2018-02-01 2 4
proda 2018-04-01 1 5
proda 2018-05-01 4 9
proda 2018-06-01 2 11
proda 2018-07-01 1 11
</code></pre>
<p>I ... | <p>cumsum( ) function will bring you the cumulative sum for a given column. From numpy. </p>
<pre><code>df[‘sum’] = df[‘qtd’].cumsum()
</code></pre>
<p>Ok. In case you want to extract only the slice and calc cumsum(), you can use:</p>
<pre><code>start_date = '2018-01-01'
end_date = '2018-05-01'
between = (df['dat... | python|pandas | 0 |
363,046 | 62,165,524 | Getting error while installing `pandas-profiling` | <p>Need Help I want to install pandas-profiling in python 3.8.2 but when i try to install the package i am facing errors.</p>
<p><code>pip install pandas-profiling</code></p>
<p>I am getting this error</p>
<p><code>error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://... | <p>Visual Studio <a href="https://blogs.msdn.microsoft.com/vcblog/2016/11/16/introducing-the-visual-studio-build-tools/" rel="nofollow noreferrer">changed</a> the <a href="https://blogs.msdn.microsoft.com/vcblog/2017/11/02/visual-studio-build-tools-now-include-the-vs2017-and-vs2015-msvc-toolsets/" rel="nofollow norefer... | python|pandas|dataframe|pandas-profiling | 1 |
363,047 | 62,398,453 | Multiplying columns by values in a list | <p>I'm new to python and have the following code: </p>
<pre><code>T_0 = 288.15
def theta(OT, T_0):
return (273.15+OT)/(T_0)
Temp = []
for i in range (len(gp_data_list)):
temp = []
for ot in gp_data_list[i]["OAT"]:
temp.append(theta(ot, T_0))
Temp.append(temp)
Temptp = np.transpose(Temp)
Temptable =... | <p><code>a.multiply([2,3], axis='rows')</code> or <code>a.multiply([2,3], axis='columns')</code></p> | python|pandas|list|dataframe | 1 |
363,048 | 62,079,781 | Model gives great training and testing accuracy but not working well when doing prediction | <p>Hi there I am doing transfer learning with deep learning using VGG16 pre-trained model. I want to extract features from VGG16 to build my own model as I only have access to CPU. Here is my build and train setup.</p>
<pre><code>import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
fro... | <p>According to your code, your model receives a feature vector of size <code>1 x 7*7*512 = 1 x 25088</code>. This features is the encoding of an image in the <code>conv_base</code> model (implemented in your <code>extract_features</code> method).</p>
<p>However in your example at prediction time you just take an imag... | python|numpy|tensorflow|machine-learning|keras | 0 |
363,049 | 62,089,265 | Should I use numpy's Random Generator? | <p>I have a large Python code that I've been maintaining/updating/expanding since ~2014. Recently I came across <code>numpy</code>'s <a href="https://numpy.org/neps/nep-0019-rng-policy.html" rel="nofollow noreferrer">Random Number Generator Policy</a> (2018-05) and now I'm a bit confused.</p>
<p>I'm not sure what chan... | <p>1.In python2(old code) default_rng is not available.</p>
<p>2.In python3(new code) both first and second blocks you mentioned will runs without an error and executed.</p>
<p>3.In future they may drop the random.standard_normal from coming versions of python,that's why they mentioned to use of default_rng instead o... | python|numpy | -1 |
363,050 | 62,068,946 | Use NumPy cleverly to speed up this loop | <p>This is quite a theoretical question. It is about the for loop at the end of the code attached.</p>
<p>I have three compatible arrays, Z, Wt_1 and Wt_2.</p>
<p>I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still ta... | <p>This problem is quite hard to efficiently vectorize Numpy. In your version you have a vectorized command, which iterates over values which are not contiguously stored in memory <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order" rel="nofollow noreferrer">Numpy/C row-major, Fortran/Matlab/Julia is col... | python|arrays|numpy|scipy|vectorization | 1 |
363,051 | 51,179,793 | How to merge all columns in a DataFrame except the first into one column and drop empty rows? Python | <p>I have a large dataframe with multiple columns, and want to merge all values from all columns except the first one into one new column (<code>'New'</code>). Then drop rows for which <code>'New'</code> is empty. </p>
<p>The <code>DataFrame</code> looks something like this (row <code>'C'</code> is empty):</p>
<pre>... | <p>You can using <code>sum</code> </p>
<pre><code>df['New']=df.iloc[:,1:].sum(1)
</code></pre> | python|pandas|dataframe | 0 |
363,052 | 51,466,137 | Reconstructing numpy array after applying function to columns | <p>Say I have a numpy array</p>
<pre><code>import numpy as np
>>> a = np.array([[1, 2],
[3, 4]])
</code></pre>
<p>and I want to extract each column and apply a function to it like so</p>
<pre><code>>>> a_col_1 = a[:, 0]
array([1, 3])
>>> new_col_1 = tranform(a_col_1)
arr... | <p>This is actually super easy! Some quick experimentation with the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>numpy.concatenate</code></a> function found that I can achieve the results I need with <code>np.concatenate([new_col_1, new_col_2], ax... | python|arrays|numpy|concatenation | 0 |
363,053 | 51,491,732 | Dynamic Backfilling a Pandas DataFrame based on a Specified Depth | <p>say I have a data that tags the presence of water in terms of depth (meters):</p>
<pre><code>Depth Water
1.9
1.91
2
2.92
2.94
2.97
2.98
3 1
3.02
3.03
3.05
3.07
3.11
4.08
4.11 1
5.12
5.22
6.13
6.18
6.2
6.22 1
7.12
7.45
7.6
8.6 ... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> with <code>last</code> with helper <code>Series</code> and subtract column <code>Depth</code>, last set values by condition:</p>
<pre><code>s =... | python|pandas|dataframe | 1 |
363,054 | 51,257,583 | Categorical level to one hot encoding in python tensorflow | <p>If i have a categorical label like this</p>
<pre><code>labels = [cat,dog, bird, cow]
</code></pre>
<p>now i want to convert it like one hot encoding. Is it possible by using tensorflow.
like this</p>
<pre><code>output_label = [[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
<... | <p>First you need to transform your categorical data to numerical format. You could do that for example like this:</p>
<pre><code>def categorical_to_numerical(labels):
num_labels=[]
for k in labels:
if k == 'cat':
num_labels.append(0)
if k == 'dog':
num_labels.append(1)
... | python-3.x|tensorflow|machine-learning | 1 |
363,055 | 51,540,659 | How can I extract unique strings from a Dataframe column? | <p>I have a dataframe 'df_copy' which has a column 'genres'. In the column, each entry has single or multiple genres. Something like <a href="https://i.stack.imgur.com/sftTC.jpg" rel="nofollow noreferrer">this</a></p>
<p>I wish to extract all the unique genres that are present in the column.</p>
<p>How can I do this?... | <pre><code>new_df = df_copy['genres'].str.split(',',expand = True)
</code></pre> | python|pandas|numpy|jupyter | 1 |
363,056 | 51,118,675 | Inserting dictionary values in pandas column | <p>C is my column in pandas dataframe(df). And it consists of many lists.</p>
<pre><code> C
[ab ab bc abb]
[ll li lo ll]
</code></pre>
<p>D is my dictionary which is as follows.</p>
<pre><code>D={'ab':0, 'bc':1, 'abb':2, 'll':3, 'li':4, 'lo':5}
</code></pre>
<p>Now, I want to assign the values of my di... | <p>Looks like you have a list of <strong>space separated strings</strong>, so you'll need two loops, not one. Try this instead:</p>
<pre><code>df.C = [[D[j] for j in i.split()] for i df.C]
</code></pre>
<p>If you have to handle missing keys, use <code>dict.get</code> instead:</p>
<pre><code>df.C = [[D.get(j, -1) for... | python|pandas | 2 |
363,057 | 51,495,982 | Display totals and percentage in stacked bar chart using DataFrame.plot | <p>My data frame looks like below:</p>
<pre><code> Airport ATA Cost Destination Handling Custom Total Cost
0 PRG 599222 11095 20174 630491
1 LXU 364715 11598 11595 387908
2 AMS 401382 23562 16680 441623
3 PRG 599222 ... | <p>You can use <code>plt.text</code> to place the information at the positions according to your data.</p>
<p>However, if you have very small bars, it might need some tweaking to look perfect.</p>
<pre><code>df_total = df['Total Cost']
df = df.iloc[:, 0:4]
df.plot(x = 'Airport', kind='barh',stacked = True, title = 'B... | python|pandas|matplotlib | 20 |
363,058 | 51,163,582 | plotting dataframe elements is messy and unreadable | <p>Fairly new to this space and have spent several hours trying to find a solution to the following problem:</p>
<p>I have a dataframe with a column which lists some universities and a column which lists some values.</p>
<p>I wanted to show a clean line graph that shows all of the values for different unis, but the l... | <p>hope this helps, you can add <code>rot</code>and specify by how much labels should be rotated </p>
<pre><code>pedigree_df.plot(x="UNI", y=["worldcat_libcount"], rot=90);
</code></pre>
<p>edit: here is definition of <code>rot</code> from the documentation:</p>
<blockquote>
<p>rot : int, default None Rotation for... | pandas|matplotlib | 0 |
363,059 | 51,371,819 | Water year time series: resampling annually for custom non-calendar year dates | <p>I am writing my very first loop since resampling doesn't allow me to use custom start dates for annual sampling. My goal is to sum up each series of 12 consecutive months in a 30 years time series for a non-calendar year calculation (hydrologic water year Oct-Sept). The dataset begins in the month of October, so I f... | <p>Your function doesn't <code>return</code> anything, which is why it yields a NoneType when it finishes running. Create a variable before the for loop, add the different <code>new_value</code>s to it, and then return that variable after the for loop completes.</p> | python|pandas|dataframe|nonetype|resampling | 0 |
363,060 | 51,271,790 | Data Privacy with Tensorboard | <p>I've recently begun using Tensorflow via Keras and Python 3.5 to analyze company data, and I am by no means an expert and only recently built my first "real-world" model. </p>
<p>With my experimental data I used Tensorboard to visualiza how my neural network was working, and I would like to do the same with my real... | <p>No, Tensorboard does not upload the data to "the cloud" or anywhere outside the computer where it is running, it just interprets data produced by the model.</p> | python|tensorflow|keras|tensorboard|privacy | 0 |
363,061 | 51,212,744 | How can I save multiple images with labels in a numpy array? | <p>Previously this type of questions was asked. But my one is a little different. For example, I have 20 files ( 20 matrix ) in one folder, each of the matrix is 40*40 in dimension. Also, these 20 files represent 20 different categories. </p>
<p>Now I want to create one single Numpy array, where the length will be 20*... | <p>I would use a dictionary to store the mapping from keys to images.</p>
<pre><code>ind_to_image = {
0: numpy array with 40 x 40 shape,
...,
19: numpy array with 40 x 40 shape,
}
</code></pre>
<p>and save the indices(keys) to the first column of the 20 x 2 array
because I think you can't directly save a... | python|numpy|multidimensional-array|numpy-ndarray | 0 |
363,062 | 51,333,806 | pandas.errors.ParserError: Error tokenizing data | <p>I faced a problem when using pandas to read some txt files.</p>
<p>My file content would look like below.</p>
<pre><code>WNS 01.20
57039 108.8833 34.0833 445.8 LC 20150322120000
OOBS
00100 ///// ///// ////// /// /// ////////
00160 216.3 003.7 0006.5 100 100 -1.2E+02
00220 258.9 006.7 0006.6 100 100 -1.3E+02
002... | <p>I've come up with a couple solutions after saving a <code>test.txt</code> file just as the one you copied.</p>
<pre><code>import pandas as pd
import functools
def main():
data = pd.read_table( # this will not fail, but doesn't produce NaNs
'test.txt', delim_whitespace=True, skiprows=range(0,3), header=... | python|pandas|csv | 0 |
363,063 | 51,171,076 | How to feed input into one layer in a tensorflow pre-trained model? | <p>The pretrained model has many layers, I want to feed my input directly into one intermediate layer (and discard the result of the previous layers).
I only got the .pb file and the ckpt files of that model, so how to modify the computation flow without the source code?</p>
<p>This is the only code file that I got, b... | <p>Here is what you need to do :</p>
<ul>
<li>Load the model</li>
<li>Find the name of the layer or retrieve the tensor of the layer you want to feed values to (let's name it 'Z' for the sake of the explanation)</li>
<li>Find the name of the layer or retrieve the tensor of the layer you want to get results from ('Y')<... | tensorflow | 0 |
363,064 | 51,370,256 | Plot Category Percentages Over Time | <p>I have a DataFrame with a datetime index and a software version column:</p>
<pre><code>Date Version
2018-07-10 15:42:16 1.0
2018-07-10 16:38:18 1.0
2018-07-10 20:21:54 2.0
2018-07-11 08:28:56 1.0
2018-07-11 13:16:48 2.0
2018-07-13 15:25:56 2.0
</code></pre>
<p>I'd like to plot h... | <p>you could do something like:</p>
<pre><code>df.groupby('Version').resample('M').nunique()
</code></pre>
<p>or:</p>
<pre><code>df.resample('d')['Version'].unique()
</code></pre> | python|pandas|matplotlib | 0 |
363,065 | 51,483,386 | Pandas split /group dataframe by row values | <p>I have a dataframe of the following form</p>
<pre><code>In [1]: df
Out [1]:
A B C D
1 0 2 6 0
2 6 1 5 2
3 NaN NaN NaN NaN
4 9 3 2 2
...
15 2 12 5 23
16 NaN NaN NaN NaN
17 8 1 5 3
</code></pre>
<p>I'm interested in splitting the d... | <p>You could use the compare-cumsum-groupby pattern, where we find the all-null rows, cumulative sum those to get a group number for each subgroup, and then iterate over the groups:</p>
<pre><code>In [114]: breaks = df.isnull().all(axis=1)
In [115]: groups = [group.dropna(how='all') for _, group in df.groupby(breaks.... | python|pandas | 5 |
363,066 | 51,293,659 | More efficient way to put an image on top of another - OpenCV Python3 | <p>I have written a function that takes two images of equal size and returns a combined image of the same size such such that all <strong>black pixels</strong> (where the BGR value is [0, 0, 0]) of the first image will be replaced by <strong>pixels of the second image.</strong></p>
<p>My code looks like this:</p>
<pr... | <p>The following code does what you want with Numpy operations which should be a lot more efficient than Python loops:</p>
<pre class="lang-py prettyprint-override"><code>pixel_has_zero = np.any(img1 == 0, axis=2, keepdims=True)
retImage = np.where(pixel_has_zero, img2, img1)
</code></pre>
<p>This code is assumin... | python-3.x|numpy|opencv|image-processing | 2 |
363,067 | 51,493,462 | Get first value from series of dictionaries | <p>I have a Pandas series <code>orders['customer']</code> that looks like this:</p>
<pre><code>0 {'id': 454543543533, 'email': 'aaaaaa@gmail.com...
1 {'id': 437890767654, 'email': 'bbbbbbbb@mail.com...
2 {'id': 534764345453, 'email': 'ccccccccc@mail.com..
3 {'id': 345436564353, 'email': None, 'acce... | <p>Use <code>lambda</code> function with <a href="https://stackoverflow.com/a/11041421"><code>get</code></a> for match value if dictionary with key <code>id</code> else return default value, here <code>0</code>:</p>
<pre><code>orders_df = pd.DataFrame({'customer':[{'id': 454543543533, 'email': 'fdgr@gmail.com'},
... | pandas | 3 |
363,068 | 51,433,620 | In python, how to add new markers to boxplot? | <p>I have used pandas's boxplot function to create a boxplot, then I would like to add the mean/97.5%/2.5% quantiles of each column to the boxplot.</p>
<pre><code> df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
df.boxplot(return_type='axes')
</code></pre>
<p>In short, I want to have additional ... | <p>You can use <code>scatter</code> so as to make points:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
shape = (100,2)
df = pd.DataFrame(np.random.randn(*shape), columns=['x', 'y'])
df.boxplot(return_type='axes')
q975 = df.quantile(0.975)
q025 = df.quantile(0.025)
mean = df.... | python|pandas|matplotlib|boxplot | 1 |
363,069 | 51,417,970 | List of Dictionaries to DataFrame | <p>I have a data like this and I want the data to be written in a dataframe so that I can convert it directly into a csv file.</p>
<pre><code>Data =
[ {'event': 'User Clicked', 'properties': {'user_id': '123', 'page_visited': 'contact_us', etc},
{'event': 'User Clicked', 'properties': {'user_id': '456', 'page_visited... | <p>flatten the nested dictionaries & then just use the data frame constructor to create a data frame.</p>
<pre><code>data = [
{'event': 'User Clicked', 'properties': {'user_id': '123', 'page_visited': 'contact_us'}},
{'event': 'User Clicked', 'properties': {'user_id': '456', 'page_visited': 'homepage'}},
{'... | python|list|pandas|dictionary|dataframe | 2 |
363,070 | 51,506,229 | How to specify an absolute filepath in Python using Pandas | <p>When I run the specified code I get the specified Error message.</p>
<p>Code:</p>
<pre><code>import tkinter
import csv
import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfil... | <p>You can construct the full path using <code>os</code> path library.</p>
<pre><code>import os
target_filaname = os.path.join('c:', 'Errors.csv')
dferror.to_csv(target_filename, index=False)
</code></pre> | python|pandas|export-to-csv | 0 |
363,071 | 51,163,511 | Can we have a combination of embedding layers and regular layers in a neural network? | <p>I am trying to use neural networks for a binary classification problem using Keras. I am new to the whole neural network area. What I like to do is to have a network that has embedding layer for some features but regular input layer for the other features. For example, imagine I would like to use user ID as the inpu... | <p>Yes its possible, you have to use functioal API</p>
<p>Here is example, feel free to adapt for your needs:</p>
<pre><code>from keras.models import Model, Sequential
from keras.layers import Dense, Flatten, Concatenate, Reshape, Input, Dropout, Dense, BatchNormalization, Activation, concatenate
from keras.layers.... | tensorflow|neural-network|keras|deep-learning | 2 |
363,072 | 51,327,113 | Python, Pandas: Using isin() like functionality but do not ignore duplicates in input list | <p>I am trying to filter an input dataframe (<code>df_in</code>) against a list of indices. The indices list contains duplicates and I want my output df_out to contain all occurrences of a particular index. As expected, <code>isin()</code> gives me only a single entry for every index. </p>
<p>How do I try and not igno... | <p>Check <code>reindex</code></p>
<pre><code>df_out_desired = df_in.reindex(indices_needed_list)
df_out_desired
Out[177]:
A B
1 2 20
2 3 30
3 4 40
3 4 40
3 4 40
</code></pre> | python|pandas|numpy | 4 |
363,073 | 51,380,916 | counting each value in dataframe | <p>So I want to create a plot or graph. I have a time series data.
My dataframe looks like that:</p>
<p><a href="https://i.stack.imgur.com/lV6EB.png" rel="nofollow noreferrer">df.head()</a></p>
<p>I need to count values in <code>df['status']</code> (there are 4 different values) and <code>df['group_name']</code> (2 ... | <p>I used <code>spam.groupby('date')['column'].value_counts().unstack().fillna(0).astype(int)</code> and it working as it should. Thank you all for help</p> | pandas|plotly|python-3.6 | 0 |
363,074 | 51,468,957 | Python OR Operator Trouble | <p>I have a list of probabilities dictating whether an output is a 1 or a 0 in a numpy array. I'm trying to split these probabilities into two separate arrays based on a certainty level of 75%. If either probability is above 75% it goes into the 'certain' array, and if neither cross that threshold, it goes into the 'un... | <p><code>zero_val or one_val > 0.75</code> is more or less equivalent to <code>zero_val != 0 or one_val > 0.75</code> in this context, so <code>zero_val</code> is essentially treated as a boolean flag. You need to write <code>zero_val > 0.75 or one_val > 0.75</code>.</p> | python|arrays|numpy | 3 |
363,075 | 51,146,217 | Tensorflow conv2d_transpose: Size of out_backprop doesn't match computed | <p>When I build the FCN for segmentation, I want the images to keep the original size of input data, so I use the fully convolution layers. When I choose the fixed input size, such as (224, 224), the transpose conv works fine. However, when I changed the code of using (224, 224) to (h, w), I meet the following error. I... | <p>The conv Net and Deconv Net in FCN, which are built by different structures, are maybe not consistent with each other. In this case, the conv net use conv with <code>padding='VALID'</code>, while the deconv net uses all conv_transpose with <code>padding='SAME</code>. Thus the shapes are not the same, which causes th... | python|tensorflow|conv-neural-network|deconvolution | 2 |
363,076 | 51,415,395 | Replacing values in multiple specific columns of a Dataframe | <p>I have the following dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
raw_data = {
'Score1': [42, 52, -999, 24, 73],
'Score2': [-999, -999, -999, 2, 1],
'Score3': [2, 2, -999, 2, -999]}
df = pd.DataFrame(raw_data, columns = ['Score1', 'Score2', 'Score3'])
</code></pre>
<p>and I want t... | <p>Use</p>
<pre><code>In [282]: df.replace({'Score2': -999, 'Score3': -999}, np.nan)
Out[282]:
Score1 Score2 Score3
0 42 NaN 2.0
1 52 NaN 2.0
2 -999 NaN NaN
3 24 2.0 2.0
4 73 1.0 NaN
</code></pre> | python|pandas|dataframe | 6 |
363,077 | 51,387,944 | Vectorized dot product | <p>I have a pandas dataframe, and one of the columns has a list in each row. I have a separate numpy array, <code>query_ebd</code>, which I want to dot with every row in that column. The output I want is one number per row, representing the dot product of the list in that row with <code>query_ebd</code>. Currently, I a... | <p>IIUC</p>
<pre><code>df.col.transform(lambda k: query_ebd.dot(k))
</code></pre>
<hr>
<p>Just re-read your quesiton and now I understand what you want. </p>
<p>I believe this is a good solution, but I'm open to critics.</p>
<p>You can define your own type and overwrite <code>__mul__</code>, and let built-in imple... | python|pandas|vectorization|dot-product | 0 |
363,078 | 51,287,196 | Saving every rows of pandas dataframe to txt file | <p>So, I open a dataset from a HDF5 file like below:</p>
<pre><code>import pandas as pd
import numpy as np
data1 = pd.read_hdf('sport.hdf5', usecols=['category','title','images','link','date','desc'])
</code></pre>
<p>It will give me output like below:</p>
<pre><code>category ... | <p>After hours of working, here's the idea to solve the problem:</p>
<p>First, make iteration of rows for Data1 dataframe. Don't forget to add attribute iterrows that will return row selection. And don't forget to define index and rows.</p>
<p>To make file for every row, define the directory followed by (row[title]) ... | python|pandas|numpy|hdf5 | 0 |
363,079 | 51,301,688 | How to filter rows in Pandas based on specific value in 1 column | <p>I have a csv, like this (no headers):</p>
<pre><code>a1 b1 3
a2 b2 5
a3 b3 8
</code></pre>
<p>I want to get all rows, where values in last column is <code>>4</code>. How can I do that?</p>
<p>P.S. This is why this is not duplicated question - in the link above columns are named, my columns are unname... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> for select last ... | python|pandas | 1 |
363,080 | 51,220,131 | pandas query a grouping within a grouping | <p>Having trouble writing a query where I can get the top 10 of a top 10 based on a count</p>
<p>My starting table from this query: </p>
<pre><code>top_10_cars = 'CH', 'DA', 'AG', 'DC', 'LA', 'NY', 'SA', 'SE', 'DE', 'MI'
df = pd.read_sql("select\
count(*) as count\
,ID\
... | <p>This is probably not the correct way to do this but I just wrapped it some python:</p>
<pre><code>df = pd.DataFrame()
for x in top_NA_cars:
dftemp = pd.read_sql("select\
count(*) as count\
,ID\
,CAR\
... | mysql|pandas|dataframe | 0 |
363,081 | 51,463,838 | Pandas Group By producing a series; not a groupby object | <p>I have a Pandas DataFrame of transactions:</p>
<pre><code>transactions.head():
Amount Date of Transaction Description \
0 39.95 2017-03-30 Fake_Transaction_One
1 2.39 2017-04-01 Fake_Transaction_Two
2 8.03 2017-04-01 Fake_Transaction_Three... | <p>It is expected behaviour (if methods are chained like <code>groupby</code> with aggregate function) to get a <code>Series</code> or <code>DataFrame</code>.</p>
<p>If you need <code>groupby</code> object:</p>
<pre><code>g = transactions.groupby(['Purchase_Type','year_month'])
print (g)
<pandas.core.groupby.group... | python|pandas|dataframe|pandas-groupby | 3 |
363,082 | 51,370,211 | Pandas Dataframe - Row Iteration with Resetting Count-Value by Condition without loop | <p>I work with Pandas and I am trying to create a vector where the value is increased and especially reset by condition. Due to a big amount of data I need an alternative to loops. I couldn't find any case where the 'count'-value is reset and starts to count again by condition without using a loop. </p>
<p>Input data:... | <p>IIUC, </p>
<pre><code>mask = ((df.Force > -15) & (df.Force < -5))
df['count'] = mask.groupby((~mask).cumsum()).cumsum().astype(int)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Time Force count
0 1 -10 1
1 2 -8 2
2 3 -12 3
3 4 -30 0
4 ... | python|pandas|bigdata | 3 |
363,083 | 51,462,979 | How to get feature importance in logistic regression using weights? | <p>I have a dataset of reviews which has a class label of positive/negative. I am applying Logistic regression to that reviews dataset. Firstly, I am converting into <strong>Bag of words</strong>. Here <strong>sorted_data['Text']</strong> is <strong>reviews</strong> and <strong>final_counts</strong> is a <strong>sparse... | <p>One way to investigate the "<strong>influence</strong>" or "<strong>importance</strong>" of a given feature / parameter in a linear classification model is to consider the <strong>magnitude</strong> of the <strong>coefficients</strong>.</p>
<p><strong>This is the most basic approach</strong>. <strong>Other techniqu... | machine-learning|scikit-learn|logistic-regression|sklearn-pandas | 10 |
363,084 | 51,412,589 | edit values in a pandas column- my approach is not working | <p>I've been searching SO for the past couple hours and have tried several times with no joy to do something pretty simple. There is a column in my data frame that looks like this:</p>
<pre><code>Name
AEMULUS [S]
AIM
ANCOMLB [S]
APPASIA [S]
ASDION [S]
ASIAPLY [S]
</code></pre>
<p>I just want to remove the "[S]"</p>
... | <p>Your aproach is almost working. There is no need to wrap it into a function.</p>
<p>Assuming that you are just trying to remove anything after the space, you can just do this:</p>
<pre><code>df['Name'] = df['Name'].str.split(expand=True)[0]
</code></pre>
<p>Your result:</p>
<pre><code>>>> df['Name']
0 ... | python-3.x|pandas | 2 |
363,085 | 51,445,857 | Signal classification based on keras stateful LSTM | <p>This is my first time asking on StackOverflow. If there are any issues with my English, please forgive me. Thanks</p>
<p>I'm doing a project that uses LSTM to classify ECG sequences. I am using the <a href="https://physionet.org/physiobank/database/ptbdb/" rel="nofollow noreferrer">PTB database</a>. There are coupl... | <p>You will only need <code>True</code> if you're facing RAM issues. </p>
<p><strong>In a <code>stateful=False</code> case:</strong></p>
<p>Your <code>X_train</code> should be shaped like <code>(patients, 38000, variables)</code>. Or, in the downsampled case: <code>(patients, 9500, variables)</code>. </p>
<p>Your <c... | python|tensorflow|keras|lstm|rnn | 2 |
363,086 | 51,530,816 | In python pandas,How to use outer join using where condition? | <p>Table 1<br/></p>
<pre><code>S.No BusNo Timings People
1 1234 3:05 pm 55
2 3456 3:30 pm 45
3 8945 3:45 pm 50
Table 2
BusNo Model
1234 Leyland
3456 Viking
</code></pre>
<p>Join this table using pandas for condition: busno model people count for people between 50 and 55 and group by model</... | <p>You can do a simple merge on those two dataframes and do a simple condition check inside <code>loc</code> to get the desired output like shown below. </p>
<pre><code>df = pd.DataFrame()
df['S.No'] = [1, 2, 3]
df['BusNo'] = [1234, 3456, 8945]
df['Timings'] = ['3:05 pm', '3:30 pm', '3:45 pm']
df['People'] = [55, ... | python-3.x|pandas | 1 |
363,087 | 51,239,229 | generating a scatter plot using two different dataset in python pandas | <p>I have two datasets. Both have different numbers of observations. Is it possible to generate a scatter plot between features from different datasets?</p>
<p>For example, I want to generate a scatter plot between the submission_day column of dataset 1 and the score column of dataset 2.</p>
<p>I am not sure how to d... | <p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> for one <code>DataFrame</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.scatter.html" rel="nofollow noreferrer... | python|pandas|matplotlib|seaborn | 1 |
363,088 | 51,143,595 | How to create rolling window variables without skipping months when using a multiIndex? | <p>Currently I have a df with a location_key & year_month multiIndex. I want to create a sum using a rolling window for 3 months.</p>
<pre><code>(pd.DataFrame(df.groupby(['LOCATION_KEY','YEAR_MONTH'])['SALES'].count()).sort_index()).groupby(level=(0)).apply(lambda x: x.rolling(window=3).sum())
</code></pre>
<p>Th... | <p>Basically you have to get your index set up how you want so the rolling window has zeros to process.</p>
<pre><code>df
LOCATION_KE YEAR_MONTH SALES
0 A 2015-10-01 NaN
1 A 2015-11-01 NaN
2 A 2015-12-01 200.0
3 A 2016-01-01 220.0
4 A 2016-03-01 180.0
5 ... | python|pandas|datetime|dataframe | 1 |
363,089 | 51,287,821 | Python: KeyError whet trying to print the value of a pandas series element | <p>I want to run a machine learning classifier. It works well. But when I am trying to print the value of a test array , it says key error. Key error normally shows when the metadata is not present. But here you can see the y_test[index] exists.</p>
<pre><code>data = pd.read_csv("fakenews.csv")
#print(data)
text = da... | <p>If you mean to get the first element, try to use y_test.iloc[0]. If you use y_test[0] pandas will try to retrieve an element with the index value of 0 which may not exist in your set since your test set is only a part of the complete dataset.</p> | python-3.x|pandas|scikit-learn | 1 |
363,090 | 51,518,279 | How to config Spyder to work with a large file | <p>I have a large data frame in Pandas, python. How can I config and increase default value in Spyder to load this file into memory and processs. In Pycharm: we can open VMoption and change the default value to -xmx 4g. How can I do the same thing for Spyder?</p> | <p>(<em>Spyder maintainer here</em>) There's no such option in Spyder, sorry.</p> | python|pandas|spyder | 1 |
363,091 | 51,159,898 | Find numbers after a string "Quote" in a dataframe column | <p>I have a customer care call log in an excel sheet. Below is the format of the data i have</p>
<pre><code>So# Comments
1 sjhsh QUOTE 234566
1 sdsds customer call QUote 239876 Call back
2 adsdfh unknown call from customer QUOTE 189067 sdkjsd woieweio
3 QUOTE 657894 customer called for service
</code></pre... | <p><code>(?i)(?<=QUOTE )\d+</code> will capture the numbers you're looking for.</p>
<p><code>(?i)</code> means the rest of the pattern is case insensitive, so it will match "QUote" and any variation of the word.</p>
<p><code>(?<=QUOTE )</code> means the numbers will be preceded by the word quote and a space</p>... | python|regex|pandas | 2 |
363,092 | 51,176,661 | Keras seems to hang after call to fit_generator | <p>I am trying to fit the Keras implementation of the <a href="https://github.com/omni-us/squeezedet-keras" rel="noreferrer">SqueezeDet model</a> to a new dataset. After making the appropriate changes to my config file, I tried to run the train script, but it seems to hang after the call to <code>fit_generator()</code... | <p>Formatting conversation in comments to answer.</p>
<p>The culprit was <code>train_generator</code>.</p>
<p>I have looked into sources of <code>model.fit_generator</code> in Keras some time ago. It just retrieves some data from the generator and submits it to the backend, nothing magical :)</p>
<p>So, my hypothesi... | python|python-3.x|tensorflow|keras | 12 |
363,093 | 48,257,497 | Return all duplicates for pandas across multiple columns | <p>I have the following dataframe and would like to return all the duplicate rows</p>
<pre><code>| A | B |
---------
| 1 | 2 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 5 |
| 2 | 3 |
</code></pre>
<p>I would like the return data to show </p>
<pre><code>| A | B |
---------
| 1 | 2 |
| 2 | 3 |
</code></pre>
<p... | <p>You're looking for <code>keep='first'</code>:</p>
<pre><code>df[df.duplicated(keep='first')]
A B
1 1 2
6 2 3
</code></pre> | python|pandas|duplicates | 1 |
363,094 | 48,333,097 | Tensorflow - How to compute loss with policy gradient | <p>So I want to compute the loss, comparing my model's prediction with the validation output.</p>
<p>My code:</p>
<pre><code>def _build_net(self):
self.n_actions = 3
with tf.name_scope('inputs'):
self.tf_obs = tf.placeholder(tf.float32, shape=(None, MAX_NUM, NUM_FEATURES), name="observations")
self.tf_ac... | <p>From TensorFlow perspective, there is no workaround to specifying values for placeholders. You can't ask it to compute <code>a + b</code> without giving a value for <code>a</code>.</p> | python|tensorflow|reinforcement-learning | 0 |
363,095 | 48,216,128 | How to keep only the most recent revised order for each order in Pandas | <p>Say I have a data frame that tracks the order number, and the revision number for that order in two different columns like so:</p>
<pre><code>OrderNum RevNum TotalPrice
0AXL3 0 $5.00
0AXL3 1 $4.00
0AXL3 2 $7.00
0AXL3 3 $8.00
0BDF1 0 $3.00
0BDF1 1 $... | <p>One way is use drop_duplicates, note dataframe should be sorted on RevNum from smallest to largest or you can add sort_values:</p>
<pre><code>df1.drop_duplicates(subset='OrderNum', keep='last')
</code></pre>
<p>Output:</p>
<pre><code> OrderNum RevNum TotalPrice
3 0AXL3 3 $8.00
6 0BDF1 2 ... | python|python-2.7|pandas|dataframe | 1 |
363,096 | 48,237,012 | Adding Numpy Multi dimensional arrays together | <p>If I had two Numpy arrays: both with shape (50,5,5) how would I add both of them to get an array with (50,5,10)?</p> | <p>Use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.concatenate.html#numpy.concatenate" rel="nofollow noreferrer"><code>concatenate</code></a>:</p>
<pre><code>import numpy as np
n = 50 * 5 * 5
a = np.random.random(size=n).reshape(50,5,5)
b = np.random.random(size=n).reshape(50,5,5)
np.co... | python|numpy|multidimensional-array | 3 |
363,097 | 48,226,089 | scipy curve_fit doesn't like math module | <p>While trying to create an example with <code>scipy.optimize curve_fit</code> I found that scipy seems to be incompatible with Python's <code>math</code> module. While function <code>f1</code> works fine, <code>f2</code> throws an error message.</p>
<pre><code>from scipy.optimize import curve_fit
from math import si... | <p>Be careful with numpy-arrays, operations working on arrays and operations working on scalars!</p>
<p>Scipy optimize assumes the input (initial-point) to be a 1d-array and often things go wrong in other cases (a list for example becomes an array and if you assumed to work on lists, things go havoc; those kind of pro... | python|python-3.x|numpy|scipy|curve-fitting | 3 |
363,098 | 48,067,912 | pd.concat with multiindex | <p>I have a multi-indexed df and I want to perform an elementwise operation on it that differs depending on a string in the level 1 column and then combine them using the same index/column structure.</p>
<pre><code>dic = {'X':pd.DataFrame(np.random.randn(10, 2), columns = ['A','B']),
'Y':pd.DataFrame(np.random.... | <p>Add <code>sort_index</code></p>
<pre><code>pd.concat([a,b], axis = 1).sort_index(axis=1)
Out[162]:
X Y Z
A B A B A B
0 False True False True False False
1 False True False True False True
2 False True False True False Fa... | pandas|multi-index | 2 |
363,099 | 48,121,901 | How to print pandas.dataframe.head without cutting long parameters | <p>For example , how to avoid this:</p>
<pre><code> column1 column2
0 [4623,236236,2362,626226, ... 64662626
1 [6363,554644,6346,346363, ... 73473473
2 [9543,543674,9806,134736, ... 67457733
</code></pre> | <p>Set the <code>display.max_colwidth</code> option to <code>-1</code> , check <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas-set-option" rel="nofollow noreferrer">set_options</a> doc for details.</p>
<pre><code>pd.set_option('display.max_colwidth', -1)
</code></pre>
<p><st... | pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.