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 |
|---|---|---|---|---|---|---|
14,500 | 49,893,143 | Tensorflow and Python Terminology and Language | <p>I am a statistician, so my relationship with Python and Tensorflow is relatively limited and English is not my native language, so I want to make sure I got the terminology right for this meme I'm making for a joint statisticians/computer scientists event. </p>
<ol>
<li>Which phrase sounds correct to you from CS/li... | <p>For points as,</p>
<ol>
<li><p>Training my neural network in Tensorflow is running in python consuming all my CPU</p></li>
<li><p>In my opinion issue happen more with CPU (if I consider it a normal CPU system) , and thats why they gave support for GPU (so Tenserflow execution could not load CPU more)</p></li>
<li><... | python|tensorflow|neural-network | 0 |
14,501 | 63,968,194 | How to generate a list of columns which have missing values in Pandas DataFrame | <p>This is what I have tried (and it works):</p>
<pre><code>req_col = []
for i in df.columns:
if df[i].isnull().sum()>0:
req_col.append(i)
print(req_col)
</code></pre>
<p>I tried to modify the above code to make it concise (and this works too):</p>
<pre><code>req_col1 = [i for i in df.columns if df[i].isnull(... | <p>You can use this</p>
<pre><code>df.columns[df.isna().any()]
</code></pre>
<p>To get it as a list:</p>
<pre><code>list(df.columns[df.isna().any()])
</code></pre>
<p>or</p>
<pre><code>df.columns[df.isna().any()].tolist()
</code></pre> | python|database|pandas|list|dataframe | 2 |
14,502 | 63,793,741 | Efficient way to count string values across multiple columns to create new total column | <p>I have a dataframe of survey responses with 'Yes/No' responses. I would like to create a new column/variable that is the total number of Yes responses.</p>
<p><a href="https://i.stack.imgur.com/trPYJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/trPYJ.png" alt="enter image description here" /></... | <p>Instead replacing compare by <code>Yes</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>DataFrame.eq</code></a> and then count <code>True</code>s by <code>sum</code>:</p>
<pre><code>df['total_variable'] = df.iloc[:, 16:22].eq('Yes'... | python|pandas|survey | 2 |
14,503 | 46,942,729 | Equivalent of theano.tensor.switch in Tensorflow | <p>Is there any function in Tensorflow which does the exact same thing as <code>theano.tensor.switch(cond, ift, iff)</code>?</p> | <p>In TensorFlow you can use <code>tf.cond</code>(<a href="https://www.tensorflow.org/api_docs/python/tf/cond" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/cond</a>). There are some examples in the documentation.</p>
<p>Edit: As you mentioned, this operation is not element wise, then it's eq... | numpy|tensorflow|theano | 0 |
14,504 | 46,993,965 | Pytorch RNN memory allocation error in DataLoader | <p>I am writing an RNN in Pytorch.
I have the following line of code:</p>
<pre><code>data_loader = torch.utils.data.DataLoader(
data,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
drop_last=True)
</code></pre>
<p>If I set num_workers to 0, I get a segmentation fault.
If... | <p>You are trying to load more data than your system can hold in its RAM.
You can either try to load only parts of your data or use/write a data loader which only loads the data that is needed for the current batch.</p> | pytorch | 1 |
14,505 | 63,059,060 | Sending message from pandas dataframe via telegram bot | <p>I have scraped a vacancy website and stored the data in csv (for now) and want to send it as a message to a user via telegram bot.</p>
<p>I managed to send one vacancy at each time but couldn't figure out how to send all the vacancies to user.</p>
<p>This is the sample data:</p>
<pre><code>df = pd.DataFrame({'positi... | <p>I assume you know how to write the function to send the message and you are looking only for the code to style the df to send it row by row.</p>
<p>Here is how I would do it:</p>
<pre><code>#Create the message
code_html='*Title of the message*'
if df.empty == False:
for i in range(len(df)):
code_html=... | python|pandas|telegram-bot | 1 |
14,506 | 62,909,212 | Labeling rows in pandas using multiple boolean conditions without chaining | <p>I'm trying to label data in the original dataframe, based on multiple boolean conditions. This is easy enough when labeling based on one or two conditions, but as I begin requiring multiple conditions the code becomes difficult to manage. The solution seems to break the code down into copies, but that causes chain e... | <p>I figured it out a solution that works for me.</p>
<p>The solution was to use <code>.index.value</code> to create an array of the index that passed the bool conditions. That array can be used to pass edit the original dataframe.</p>
<pre><code>##These two conditions can probably be combined
condition1=df[(df['Note']... | pandas | 0 |
14,507 | 68,002,381 | TensorFlow: how find out that tensor already created | <p>I'm trying to create big tensor with shape 42000x28x28, data comes as a ArrayBuffer, let's assume that I create tensor something like that:</p>
<pre><code>tf.tensor4d(new Uint8Array(xsTrainBuffer), [42000 * 0.9, 28, 28, 1]).div<Tensor<Rank.R4>>(255);
</code></pre>
<p>The question is - how find out that t... | <p>I believe a better approach would be the <a href="https://js.tensorflow.org/api/latest/#data.array" rel="nofollow noreferrer">tf.data.array()</a> function. This will create a <a href="https://js.tensorflow.org/api/latest/#class:data.Dataset" rel="nofollow noreferrer">DataSet</a> for you that is ideal for working wit... | tensorflow|tensorflow.js | 0 |
14,508 | 67,718,055 | convert .tflite to .pb model to test performance of tflite model on test tfrecords | <p>I am currently working on object detection task.
Till TF1.2 we could use toco to get .pb file get back again from .tflite model file. Is there any solution in tf2.4 or tf2.5?</p>
<p>If not, how can i test .tflite model performance on test tf records?</p>
<p>Thank you,
Anshu</p> | <p>You can read TFRecord file using some library such as tf.data or etc., and convert each data from there in np.float32 or np.something_array format so you can feed the data to tflite.interpreter.</p> | tensorflow|object-detection|tensorflow-lite|object-detection-api|tensorflow2.x | 0 |
14,509 | 61,514,047 | Plotting multiple density plots python | <p>I'm trying to plot multiple density plots from the same pandas df, but getting one plot with all the data on it. any suggestions how to make separate plots for every element of my List? </p>
<pre><code>for i in List:
ax = df[i].plot(kind='density', colormap="Set2", label='')
plt.axvline(point_of_interest,... | <p>Try</p>
<pre><code>for i in List:
ax = df[i].plot(kind='density', colormap="Set2", label='')
plt.axvline(point_of_interest, linestyle='dashed', linewidth=2, color='r', label="Current Price")
plt.title(i)
ax.legend(loc='lower center', bbox_to_anchor=(0.5, -0.25), ncol=2)
plt.figure()
</code></p... | python|pandas|density-plot | 0 |
14,510 | 61,284,230 | Why all weights become zeros in this code? | <p>I am trying to make a singer classification on TensorFlow 2. However, when I trained my model, I found all weights finally become to zero matrices. I am not sure why this problem occurs. Please let me know.</p>
<p>The following code is the simplest version of my problem. I tested this code on TF2.1, TF2.2rc0, TF2.2... | <p>Few things here:</p>
<ol>
<li><p>Given the shapes you want to feed into the model, the inputs should be:</p>
<pre><code>audios = tf.keras.layers.Input(
shape= [None, 1],
dtype= tf.float32
)
singers = tf.keras.layers.Input(
shape= [128],
dtype= tf.int32
)
</code></pre></li>
<li><p>In your training l... | tensorflow2.0 | 0 |
14,511 | 61,328,638 | how to solve size mismatch for this model? | <pre><code>data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(224),
transforms.CenterCr... | <p>With the provided debug information we can only tell that there is a size mismatch in one of the layers. </p>
<p>Looking at the error, it seems the error is in the first linear layer. You should change its size to 373248 instead of 256*6*6. </p>
<p>This should also be clear from the output of the print statement <... | pytorch | 0 |
14,512 | 68,627,132 | count number of rows in an hour using pandas excluding missing hours | <p>I have a dataframe like this :</p>
<pre><code> start_time end_time enter exit
0 2021-08-02 19:26:50.828000+00:00 2021-08-02 19:26:53.359000+00:00 271 271
1 2021-08-02 19:26:40.916000+00:00 2021-08-02 19:26:42.216000+00:... | <p>If I understand you correctly, your problem is solved if you remove the rows with value of 0? To do that you can use .loc, using conditionals:</p>
<pre><code># Keep rows where count column is larger than 0
clean_data = data.loc[data["count"]>0]
</code></pre> | python|pandas | 1 |
14,513 | 68,670,737 | Get IDs which don't have a specific value in other column | <p>I have a dataframe with columns : ID, value1, value2.
I want those IDs which don't have value1 equal to 'a' and 'b' at any point.</p>
<p>The dataframe df that I have :</p>
<pre><code>ID value1 value2
1 a 2
1 c 3
1 e 4
2 f 5
2 g 10
3 b 7
3 e 8
</code></pre>... | <p>Group by 'ID' and check if 'a' or 'b' is in group then invert selection (~) and select the right groups.</p>
<pre><code>>>> df[~df['value1'].isin(['a', 'b']).groupby(df['ID']).transform('any')]
ID value1 value2
3 2 f 5
4 2 g 10
</code></pre>
<p><strong>Optimized by @ALollz</str... | python-3.x|pandas|dataframe | 2 |
14,514 | 68,693,732 | Store ndarray as a blob in PostgreSQL with pandas | <p>I'm trying to store an ndarray from a pandas data frame
to postgres. Putting the ndarrays in an column and using <code>to_sql()</code> stores
them very inefficiently. Is there a more efficient way(memory wise) of doing this ?</p>
<p>Note: Of course normalizing the ndarrays into rows in a table would be much better f... | <p>Using <code>BytesIO</code> in combination with <code>numpy.save()</code> seems to do the trick. Also, explicit types in <code>to_sql</code> ensure <code>bytea</code> is used. Something like:</p>
<pre class="lang-py prettyprint-override"><code>import io
import numpy as np
import pandas as pd
from sqlalchemy import St... | pandas|postgresql|numpy | 0 |
14,515 | 68,574,611 | how to read specific columns from csv file using python in google collab | <pre class="lang-py prettyprint-override"><code>df = pd.read_csv(io.BytesIO(uploaded['data.csv']))
ParserError Traceback (most recent call last)
<ipython-input-22-a523fd2e8c08> in <module>()
1 import io
2
----> 3 df = pd.read_csv(io.BytesIO(uploaded['data.csv... | <pre><code>import pandas as pd #import pandas
fread = pd.read_csv('filepath/filename.csv') #make fread as object
freaddf = pd.DataFrame(fread, columns=['col1name', 'col2name', 'col3name'])
print(freaddf.to_string())
</code></pre> | python|pandas|dataframe|csv|data-analysis | 0 |
14,516 | 68,522,050 | Combine multiple dfs based on datetime index | <p>Say I have two dfs</p>
<pre><code>Date x y
2021-07-01 1 2
2021-07-02 2 4
2021-07-06 3 6
2021-07-07 4 8
2021-07-08 5 10
Date z n
2021-07-06 5 10
2021-07-07 6 12
2021-07-08 7 14
</code></pre>
<p>How Can I combine them based on the date so that I get. I have a fair few df... | <p>Use <code>merge</code>:</p>
<pre><code>>>> pd.merge(df1, df2, on='Date', how='outer')
Date x y z n
0 2021-07-01 1 2 NaN NaN
1 2021-07-02 2 4 NaN NaN
2 2021-07-06 3 6 5.0 10.0
3 2021-07-07 4 8 6.0 12.0
4 2021-07-08 5 10 7.0 14.0
</code></pre> | python|pandas | 2 |
14,517 | 52,993,640 | List of entries in header in text file using python | <p>I have a .txt file where I have text headers and numerical data. I am working with python 2.7, and am using pandas and numpy in my work. The structure of the file is like the picture shown below:</p>
<p><a href="https://i.stack.imgur.com/fWT45.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fWT45... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.get_level_values.html" rel="nofollow noreferrer"><code>get_level_values(1)</code></a> instead of <code>levels[1]</code>, then convert to list using <code>tolist()</code>:</p>
<pre><code>>>> df.columns.get_level_va... | python|pandas | 2 |
14,518 | 53,009,838 | Python: how to groupy and sum payments between people in Pandas? | <p>I have a dataframe <code>df</code> that contains the information of the payments from <code>Name1</code> to <code>Name2</code> contains the information of some users.</p>
<pre><code>df
Name1 Name2 amount
0 Tom Jack 554
1 Eva Laura 334
2 Eva Tom 45
3 Jack ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a> with aggregate <code>sum</code> and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unst... | python|pandas|group-by | 2 |
14,519 | 53,032,034 | Pandas & filtering | <p>I have an error </p>
<p><code>**'ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'**</code></p>
<p>when I am attempting to filter by my code : </p>
<p><code>(xls[xls['DisabilityFriendly'] == 'приспособлен ... | <p>Try this:</p>
<pre><code>xls[(xls['DisabilityFriendly'] == 'приспособлен для всех групп инвалидов') & (xls['Paid'] == 'бесплатно')]
</code></pre>
<p>Look at where the brackets <code>[]</code> and <code>()</code> are.</p>
<p>Differences:</p>
<pre><code>(xls[xls['DisabilityFriendly'] == 'приспособлен для всех ... | pandas|pandas-groupby | 0 |
14,520 | 53,114,494 | tensorflow calculating loss with GPU vs. CPU | <p>I'm a bit confused with the difference I'm getting in loss calculations when calculating loss with a GPU vs. CPU.</p>
<p>Model is a 6 layer CNN. </p>
<p>Loaded the model from checkpoints and ran it with the same data. Calculated the loss with a CPU and then a GPU.</p>
<p>CPU loss: 0.4687191
GPU loss: 0.46873742</... | <p>They might be different if you're shuffling the data you train the model on. Try fixing a <code>numpy.random.seed(123)</code> above your code (but after your imports) then disable shuffling and the losses should be identical.</p>
<p>For example, the <code>tensorlayers</code> mini-batch generator allows you to set t... | python|tensorflow | 0 |
14,521 | 63,605,446 | How to concatenate two tensors with different shape in 2d convolution in tensorflow? | <p>In my computational pipeline, I have used custom function which is going to create custom keras blocks, and I used this blocks multiple times with <code>Conv2D</code>. At the end, I got two different tensor which is features maps with different tensor shape: <code>TensorShape([None, 21, 21, 64])</code> and <code>Ten... | <p>To operate a concatenation you should provide layers with the same shapes except for the concat axis... in case of images, if you want to concatenate them on features dimensionality (axis -1) the layers must have the same batch_dim, width, and height.</p>
<p><strong>If you want to force the operation</strong> you ne... | python|tensorflow|keras | 2 |
14,522 | 53,521,753 | Groupby more than1 columns and then average over another column | <p>I have the follow dataset:</p>
<pre><code> cod date value
0 1O8 2015-01-01 00:00:00 2.1
1 1O8 2015-01-01 01:00:00 2.3
2 1O8 2015-01-01 02:00:00 3.5
3 1O8 2015-01-01 03:00:00 4.5
4 1O8 2015-01-01 04:00:00 4.4
5 1O8 2015-... | <p>using a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> </p>
<pre><code>df.groupby(["cod", pd.Grouper(key="date", freq="MS")]).mean()
</code></pre>
<p>Extra info on <a href="http://pbpython.com/pandas-grouper-agg.html" rel="nofo... | python-3.x|average|pandas-groupby | 1 |
14,523 | 53,578,019 | Pandas: Calculate percentage of column for each class | <p>I have a dataframe like this:</p>
<pre><code> Class Boolean Sum
0 1 0 10
1 1 1 20
2 2 0 15
3 2 1 25
4 3 0 52
5 3 1 48
</code></pre>
<p>I want to calculate percentage of 0/1's for each class, so for example the output cou... | <p>Divide column <code>Sum</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for return Series with same length as original DataFrame filled by aggregated values:</p>
<pre><code>df['%'] = d... | pandas | 5 |
14,524 | 72,104,302 | how to visualize network graph using python and pandas? | <p>I have the below dataframe that includes <strong>file number</strong> field and <strong>departements</strong>
where each file number is assign to one or more departments and the number <strong>(1-0-99)</strong> represent the status of the file like</p>
<ul>
<li>1: mean the task is done</li>
<li>0: the task is pendi... | <p>IIUC, you can use:</p>
<pre><code>import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
# df = pd.DataFrame(...)
COLORS = {0: 'red', 1: 'green'}
edges = df.melt('file', var_name='department', value_name='status').query('status != 99')
G = nx.from_pandas_edgelist(edges, source='department', tar... | python|pandas|networkx | 1 |
14,525 | 71,800,269 | Numpy applying a calculation to each element using the previous one | <p>I'm learning numpy and have this csv file:</p>
<pre><code>,August,September,October,November,December,January
Johney,84,81.3,82.8,80.1,77.4,75.2
Miki,79.6,75.2,75,74.3,72.8,71.4
Ali,67.5,66.5,65.3,65.9,65.6,64
Bob,110.7,108.2,104.1,101,98.3,95.5
</code></pre>
<p>That needs to change to a table that shows the weight ... | <p>With data:</p>
<pre><code>In [115]: data = np.genfromtxt(txt, delimiter=',', skip_header=1,)
In [116]: data
Out[116]:
array([[ nan, 84. , 81.3, 82.8, 80.1, 77.4, 75.2],
[ nan, 79.6, 75.2, 75. , 74.3, 72.8, 71.4],
[ nan, 67.5, 66.5, 65.3, 65.9, 65.6, 64. ],
[ nan, 110.7, 10... | python|numpy | 1 |
14,526 | 47,379,476 | How to convert bytes data into a python pandas dataframe? | <p>I would like to convert 'bytes' data into a Pandas dataframe. </p>
<p>The data looks like this (few first lines):</p>
<pre><code> (b'#Settlement Date,Settlement Period,CCGT,OIL,COAL,NUCLEAR,WIND,PS,NPSHYD,OCGT'
b',OTHER,INTFR,INTIRL,INTNED,INTEW,BIOMASS\n2017-01-01,1,7727,0,3815,7404,3'
b'923,0,944,0,2123,948... | <p>I had the same issue and found this library <a href="https://docs.python.org/2/library/stringio.html" rel="noreferrer">https://docs.python.org/2/library/stringio.html</a> from the answer here: <a href="https://stackoverflow.com/questions/22604564/how-to-create-a-pandas-dataframe-from-a-string">How to create a Pandas... | python-3.x|pandas | 56 |
14,527 | 68,148,077 | Load csv file that has a column with a numpy array written as string | <p>I have a CSV file with 3 columns, where the third one is an array but written as a string. The table format is the following:</p>
<p>int, int, array</p>
<pre><code>1, 4, [array([-3.98456901e-02, 1.11602008e-01, 6.12380356e-03, -4.49424982e-02,\n 7.13399425e-03, -4.11176607e-02, 8.72574970e-02, 9.94107723e... | <p>This is a common problem when reading/writing to .csv files.</p>
<p>If we have a string as such:</p>
<pre><code>>>> s = "[array([-3.98456901e-02, 1.11602008e-01, 6.12380356e-03, -4.49424982e-02,\n 7.13399425e-03, -4.11176607e-02, 8.72574970e-02, 9.94107723e-02])]"
</code></pre>
<p>We ca... | python|pandas|numpy | 2 |
14,528 | 68,326,144 | Attach values in a new column when a specific word is displayed | <p>I have a dataframe, df, where I would like to create a new column based on the 'id' column and attach a value whenever a certain string is present.</p>
<p><strong>Data</strong></p>
<pre><code>id place
aa ny
bb ny
ci ca
ci ca
</code></pre>
<p><strong>Desired</strong></p>
<pre><code>id place type
aa ny 1... | <p>From your DataFrame :</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
>>> df_1 = pd.DataFrame({'id': ['aa', 'bb', 'ci', 'ci'],
... 'place': ['ny', 'ny', 'ca', 'ca']},
... index = [0, 1, 2, 3])
>>> df_1
id place
0 aa ny
1 ... | python|pandas|numpy | 1 |
14,529 | 68,367,584 | how can i divide grouped masked id by a value that is in another df (the df contains a value for each masked id ) | <pre><code>df = pd.DataFrame([[1,'A', 4], [1,'B', 2], [2,'C', 5], [2,'A', 5], [3,'B', 2]],
columns=['maskedid ', 'test ', 'value'])
maskedid test value
1 A 4
1 B 2
2 C 5
2 A 5
3 B 2
</code></pre>
<p>I want to ... | <p>My understanding is that you want to generate the <code>.describe()</code> info and divide the data generated by the other dataframe (<code>df2</code>). You can acheive it this way:</p>
<pre><code>df.groupby(['maskedid', 'test']).describe()
value
count... | python|pandas|dataframe|pandas-groupby | 0 |
14,530 | 59,312,258 | create list of buckets of rows based on the value of N | <p>I have a pandas dataframe with say 11 rows. I want to create a list of column based on the value of N as below:</p>
<pre><code>import numpy as np
import pandas as pd
import math
import sys
df = pd.DataFrame({'group':[1,1,1,2,2,2,2,3,3,4,5]})
df
</code></pre>
<p>For example:</p>
<p>If N value is given as 2, then ... | <p>To ensure you get <code>N</code> groups that are as evenly split as possible you should use <code>pd.cut</code>. We use <code>rank</code> to ensure that groups are densely labeled, otherwise this will not work properly. This ensures an even splitting of the number of groups to each list +/-1, though will not ensure ... | python-3.x|pandas | 1 |
14,531 | 45,747,648 | convert csv column data type | <p>I have a csv sheet with 2 columns:</p>
<pre class="lang-none prettyprint-override"><code>Subject,Exam_Date
Maths,4/13/2017
Physics,4/15/2016
English,42936
</code></pre>
<p>In this example the <code>42936</code> is actually <code>7/20/2017</code>. Since the Excel cell data type was general the value got changed to ... | <p>You can use <code>xlrd.xldate_as_tuple</code> to convert the number to date tuple, then feed to <code>datetime</code> module:</p>
<pre><code>import datetime
import xlrd
df=pd.read_csv('test.csv')
converted_date = [ e if '/' in e else datetime.datetime(*xlrd.xldate_as_tuple(int(e),0)) for e in df["Exam_Date"] ]
df["... | python|pandas|csv|date|dataframe | 2 |
14,532 | 50,775,532 | Numpy replace specific rows and columns of one array with specific rows and columns of another array | <p>I am trying to replace specific rows and columns of a Numpy array as given below.</p>
<p>The values of array a and b are as below initially:</p>
<pre><code>a = [[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
b = [[2 3 4 5]
[6 7 8 9]
[0 2 3 4]]
</code></pre>
<p>Now, based on a certain probability, I need to p... | <p>With <strong>masking</strong>. We first generate a matrix with the same dimensions, of random numbers, and check if these are larger than <code>0.8</code>:</p>
<pre><code>mask = np.random.random(a.shape) > 0.8
</code></pre>
<p>Now we can assign the values of <code>b</code> where <code>mask</code> is <code>True<... | python|arrays|numpy|indexing|scipy | 5 |
14,533 | 66,599,084 | Getting Typerror trying to convert Object values to Integer or Datetime Value Year | <p>This is the dataframe</p>
<p><img src="https://i.stack.imgur.com/OOib4.png" alt="enter image description here" /></p>
<p>The column movie_df["year"] was created from extracting values from the title column:</p>
<pre><code>movie_df["year"] = movie_df["title"].str.extract("(\d+)"... | <p>In python <code>int</code> is a function that converts a string to an integer. So when you pass it you are actually passing a method as the error describes. From the documentation of pandas, it looks like <code>.astype</code> takes a string as an argument. For example:</p>
<pre class="lang-python prettyprint-overrid... | pandas|dataframe | 0 |
14,534 | 57,314,247 | Randomly shuffling a column in a list of DataFrames | <p>I have a list (called final_list) of pandas DataFrames (3 of them), each with 3 columns. A single dataframe looks like this</p>
<pre><code>x y T/F
2 0 False
2 1 False
3 2 False
5 3 True
6 4 False
6 5 False
6 6 False
4 7 False
2 8 False
2 9 True
3 10 True
</code></pre>
... | <p>IIUC, you need:
Taking the below as input:</p>
<pre><code>final_list=[df,df,df]
list_dfs=[i.assign(**{'T/F':np.random.choice(i['T/F'],len(i))}) for i in final_list]
</code></pre> | python|pandas | 1 |
14,535 | 57,594,075 | How to filter this type of data? | <p>If I have some numpy arrays like</p>
<ul>
<li><code>a = np.array([1,2,3,4,5])</code></li>
<li><code>b = np.array([4,5,7,8])</code></li>
<li><code>c = np.array([4,5])</code></li>
</ul>
<p>I need to combine these arrays without repeating a number. My expected output is <code>[1,2,3,4,5,7,8]</code>.</p>
<p>How do I ... | <p>You can use <code>numpy.concatenate</code> with <code>numpy.unique</code>:</p>
<pre><code>d = np.unique(np.concatenate((a,b,c)))
print(d)
</code></pre>
<p>Output:</p>
<pre><code>[1 2 3 4 5 7 8]
</code></pre> | python-3.x|numpy | 2 |
14,536 | 57,381,160 | opencv question enough values to unpack (expected 3,got 2) | <p>I am unable to understand following error in OpenCV.
I see some stack overflow solutions but I didn't get exact resolution please help me.</p>
<p>This is my error in my terminal.</p>
<p><code>Traceback (most recent call last):
File "capture.py", line 25, in <module>
fs.capture(frame, arg.debug)
File ... | <p><code>cv2.findContours</code> returns <code>3</code> objects in <code>opencv 3.x</code>, while <code>2</code> objects in <code>opencv 4.x</code> version.</p>
<p>So, change</p>
<p><code>_,img_contour, contours = cv.findContours(threshold,cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)</code></p>
<p>to <code>contours, hierar... | python-3.x|numpy|opencv | 0 |
14,537 | 57,720,089 | Creating a numpy array which contains list of arrays for .npz input file | <p>I am doing an analysis of food expenditures by 5 different members belonging to 5 different age group. I want to create a file in .npz format, which should have two variables, viz., 'age' and 'person'. I am trying to get an array containing a list of arrays.</p>
<p>I created a list of 5 members 'person' and a list ... | <p><code>savez</code> makes arrays of all list inputs; so that's what you'll see upon <code>load</code>:</p>
<pre><code>In [105]: np.array(person).shape
Out[105]: (5, 7)
In [106]: np.array(person).dtype ... | python|pandas|numpy | 1 |
14,538 | 70,421,520 | Find 2nd minimum along second axis in a 2-D numpy array | <p>I have a numpy array like this</p>
<pre><code>[[ 1, 5, 9, 7],
[ 5, 8, 9, 7],
[-9, 6, 2, 3]]
</code></pre>
<p>I want second minimum from every array present in the 2D array like this</p>
<pre><code>[5,7,2]
</code></pre> | <p>Actually, you want the second minimum from each <strong>row</strong> of the
source (<em>2-D</em>) array.</p>
<p>To get it, just sort the source array along <em>axis=1</em> and then take
the second column (numbering from 0, so the column number is actually <em>1</em>):</p>
<pre><code>result = np.sort(arr, axis=1)[:,1... | python-3.x|numpy|numpy-ndarray | 2 |
14,539 | 70,386,602 | TF OD API checkpointing and evaluation | <p>It seems that regardless of passing the default checkpoint in the <code>pipeline.config</code> file <strong>OR</strong> a saved checkpoint after fine-tuning, I always get metrics equal to zero on the first round of evaluation (see below). Is this intended behavior? It leads me to believe fine-tuning didn't do anythi... | <p>Found the answer here:
<a href="https://stackoverflow.com/questions/66673499/tensorflow-object-detection-api-train-from-exported-model-checkpoint?rq=1">Tensorflow Object Detection API: Train from exported model checkpoint</a></p>
<p>By setting fine_tune_checkpoint_type to "full", I got the correct mAP for ... | tensorflow|metrics|object-detection-api | 0 |
14,540 | 51,442,485 | Are tf.spectral.dct and scipy.fftpack.dct equivillant? | <p>I have compared tensorflow.spectral.dct with scipy.fftpack.dct using the following example: </p>
<p><strong>in scipy:</strong></p>
<pre><code>from scipy.fftpack import dct
import tensorflow as tf
xx=np.linspace(0,3,3)
x_dct=dct(xx,2,norm='ortho')
print(x_dct)
</code></pre>
<p>array([ 2.59807621e+00, -2.1213203... | <p>I'm the author of <code>tf.signal.dct</code>. It is designed to be equivalent to <code>scipy.fftpack.dct</code>, but there are minor numerical differences between them at the moment. I believe your example is computing the fftpack DCT in <code>float64</code>, while <code>tf.signal.dct</code> only supports <code>tf.f... | python-3.x|tensorflow | 1 |
14,541 | 51,397,097 | How to test for list equality in a column where cells are lists | <p>I want to be able to test if some cells that are lists are equal to <code>[0]</code> <strong>and</strong> <code>Var1==4</code>, and set a new column to <code>1</code> if this happens. Input and expected output are below.<br>
I had several tries but only managed with <code>apply</code> and <code>lambda</code> , and t... | <p>You can compare by <code>tuple</code> or <code>set</code>:</p>
<pre><code>df['ERR1'] = ((df['Id']==4) & (df['Var1'].apply(tuple)==(0, ))).astype(int)
df['ERR2'] = ((df['Id']==4) & ([tuple(x) ==(0, ) for x in df['Var1']])).astype(int)
df['ERR3'] = ((df['Id']==4) & (df['Var1'].apply(set)==set([0]))).ast... | pandas | 2 |
14,542 | 51,150,785 | How do I flat a Nested Json file in Python? | <p>I have a nested Json file with arrays.
I want to flat it so there won't be nested Jsons.</p>
<p>For example:</p>
<p><a href="https://i.stack.imgur.com/2mFT4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2mFT4.png" alt="enter image description here"></a></p>
<p>Code for Json:
<a href="https://... | <p>Try using <a href="https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10" rel="nofollow noreferrer">this</a>:</p>
<pre><code>import pandas as pd
import json
response = {u'total': 1245, u'limit': 2, u'results': [{u'customer': {u'lastName': u'rtyrtyrt', u'userAccountId': None, u'id': 637, u'f... | python|json|pandas | 2 |
14,543 | 70,740,108 | Create a python file with hardcoded array from a CSV file? | <p>I have a <code>CSV</code> and I would like to create a python <strong>file</strong> from it with array of <code>dics</code> inside.
Any search on how to do that bring me to using Pandas to create a dic <strong>in memory</strong>.</p>
<p>I need to create a <strong>physical</strong> file <code>name.py</code> in my pro... | <p><code>df.to_dict('records')</code> generates output in the format that you want, I think</p>
<p>so it could look like</p>
<pre><code>with open('name.py', 'w') as f:
records = df.to_dict('records')
print(f'data = {records}', file = f)
</code></pre>
<h2>Edit</h2>
<p>to print each record on a separate line you ... | python|pandas | 1 |
14,544 | 71,029,155 | How create dataframe from list of dictionary of multi level json | <p>So I have a json file that have multiple level,by using pandas I can read the first level and put it in a dataframe,but the problem is as you can see in the dataframe <a href="https://i.stack.imgur.com/Wgp1H.jpg" rel="nofollow noreferrer">Column Comments and hastags</a> the second level is inside a column have forma... | <p>Maybe this solves your problem:</p>
<p>Defined the following function which unnests any json:</p>
<pre><code>import json
import pandas as pd
def flatten_nested_json_df(df):
df = df.reset_index()
s = (df.applymap(type) == list).all()
list_columns = s[s].index.tolist()
s = (df.applymap(type) == ... | python|pandas|dataframe|dictionary | 0 |
14,545 | 71,021,932 | How to subtract columns of one dataframe to that of another in python and store the result and both columns in a new dataframe | <p>I’ve 2 data frames which have one common column ‘X’ having all the unique values. I want to subtract each column of data frame 1 to that of data frame 2 which have similar names.
dataframe 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">X</th>
<th style="text-... | <p>Yes you can merge on column "X" to create a single dataframe with all values, then iterate through the columns and append calculated dataframes to a list.</p>
<p>Something like:</p>
<pre><code>df = pd.merge(left=df1, right=df2, on='X', how='inner')
output_frames = []
letters = [i[-1] for i in df.columns if... | python|pandas|dataframe | 0 |
14,546 | 51,814,010 | Python auto docstring with sphinx new line | <p>I am wondering how can I have a new line when generating auto documentation using Sphinx. I am not using the default Sphinx docstring format reStructuredText, but I am using the Numpydoc format. I tried using '\n' yet it makes a line break, and I only need a new line. Here is an example of a Python module ...</p>
<... | <p>Simply add a blank line after the first line:</p>
<pre><code>def function1 (input):
""" this function docstring starts here
| this is not sentence number 2 at the vertical bar is not working
| this is not sentence number 3 at the vertical bar is not working
| this is not sentence number 4 at the ... | python|python-sphinx|docstring|numpydoc | 1 |
14,547 | 51,720,294 | Sorting pandas dataframe to get min value along diagonal | <p>I have a panda dataframe, it is used for a heatmap. I would like the minimal value of each column to be along the diagonal.</p>
<p>I've sorted the columsn using </p>
<pre><code>data = data.loc[:, data.min().sort_values().index]
</code></pre>
<p>This works. Now I just need to sort the values such that the index of... | <p><strong><em>Setup</em></strong></p>
<pre><code>data = pd.DataFrame([[5, 1, 9], [7, 8, 6], [5, 3, 2]])
</code></pre>
<p>You can accomplish this by using <code>argsort</code> of the diagonal elements of your sorted DataFrame, then indexing the DataFrame using these values.</p>
<p><strong><em>Step 1</em></strong><br... | python|pandas|dataframe | 2 |
14,548 | 37,423,546 | How to delete "weird" columns from pandas dataframe | <p>This code returns the name of the <code>dfESPCTC</code> column names</p>
<pre><code>print list(dfESPCTC.columns.values)
[('DateTime', ''), (u'bid', 'close'), (u'bid', 'high'), (u'bid', 'low'), (u'bid', 'open')]
</code></pre>
<p>How do I drop everything but the close from the dataframe? I tried this but it doesn't... | <p>Your DataFrame has a column <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex</a>. To drop all but the <code>close</code> column, just select the one column:</p>
<pre><code>dfESPCTC = dfESPCTC[[(u'bid', 'close')]]
</code></pre>
<p>If you index <code>dfESPCTC</code> using... | pandas | 1 |
14,549 | 42,059,487 | Tensorflow install on Windows with anaconda and no internet connection | <p>I can not install Tensorflow on Windows because there in no internet connection based on commpany's security policy. </p>
<p>I just installed anaconda and python by transmiting files with intranet. </p>
<p>Please let me know how to install that with no internet connection. </p>
<p>================================... | <p>If you can download the whl file and transfer it to your workstation, then you can run:</p>
<p><code>pip.exe install --upgrade --no-deps <tensorflow whl file name>
</code></p>
<p>This should avoid trying to connect to download tensorflow dependencies, as anaconda already has most of these.</p> | windows|tensorflow|installation|anaconda | 3 |
14,550 | 37,685,917 | Irregular binning of python pandas dataframe | <p>I am getting to grips with python pandas.</p>
<p>The toy problem below, illustrates an issue I am having in a related exercise.</p>
<p>I have sorted a data-frame so that it presents a column's values (in this case students' test scores) in ascending order:</p>
<pre><code>df_sorted =
variable test_score
... | <p>Just <code>groupby</code> a dummy variable that goes 0, 0, 0, 1, 1, 1, etc. This can be obtained with floor division:</p>
<pre><code>>>> d.groupby(np.arange(len(d))//3).mean()
variable test_score
0 2 53
1 6 64
2 10 73
3 4 77
</code></p... | python|pandas|dataframe|binning | 1 |
14,551 | 64,516,013 | How to change for loop print output to pandas dataframe | <p>I would like to print the output of the following for loop to a nice looking pandas dataframe:</p>
<pre><code>for i in range (1911, 2020):
bestmovie= movie.loc[movie['year'] == i]
bestmovie = bestmovie[['year','title', 'avg_vote', 'genre']].sort_values(['avg_vote'], ascending = False)
bestmovie = bestmov... | <p>I've had similar output in the past that turned out to be returning a list of one element. That one element happened to be a pandas dataframe. To check if the same is happening in your code, run the below.</p>
<pre><code>print(type(bestmovie))
print(type(bestmovie[0]))
</code></pre>
<p>If the above yields...</p>
<... | python|pandas|loops|printing | 0 |
14,552 | 64,437,516 | coverting false results to true if one came true | <p>I have a boolen series of true and false in a data frame.
what i need is how to covert the rest false results to true in case i found only one true. Thank you .
For example a coulmn
df["Test"]= [false,false,true,false ,true ,false]</p>
<p>I need to get it
df["Test"] = [false,false,true,true,true,... | <p>Use <code>idxmax</code>:</p>
<pre><code>df.loc[df.index>df['test'].idxmax(), 'test'] = True
</code></pre>
<p>EDIT</p>
<p>Because OP's original data is <code>String</code>, so convert it to <code>Boolean</code> firstly.</p>
<pre><code>import ast
df['test'] = df['test'].apply(ast.literal_eval)
df.loc[df.index>d... | pandas|datetime|boolean-operations | 0 |
14,553 | 64,199,335 | numpy get the blocks making an array in a matrix | <p>I have a numpy matrix such as the one below. What I'd like to do is get the arrays containing the blocks making each row/column here. How can this be efficiently done in numpy?</p>
<h2>Examples</h2>
<p>So if for example we have the array <code>[1 1 1 1 0 1 1 1 1 0]</code> (first row) then we would get <code>[4 4]</c... | <p>Here is some numpy magic:</p>
<pre><code>a = np.array([[1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 1, 0, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1, 1, 0, 0],
... | python|arrays|numpy|matrix | 2 |
14,554 | 47,604,047 | Merge axes before and after the i^{th} axis | <p>I want to reshape a numpy array <code>arr</code> to a shape of <code>(before, at, after)</code> for any one <code>axis</code> of <code>arr</code>. How to do this faster?</p>
<p>The axis has been normalized: <code>0 <= axis < arr.ndim</code></p>
<p>Program:</p>
<pre><code>import numpy as np
def f(arr, axis):... | <p><code>shape</code> is a tuple, and the desired result is also a tuple. Convert to/from arrays to use <code>np.prod</code> or some other array function will take time. So if we can do the same with plain Python code we might save time. </p>
<p>For example with <code>shape</code>:</p>
<pre><code>In [309]: shape
O... | python|numpy | 2 |
14,555 | 59,005,509 | Moving to numerically stable log-sum-exp leads to extremely large loss values | <p>I am working on a network that uses a LSTM along with MDNs to predict some distributions. The loss function I use for these MDNs involve trying to fit my target data to the predicted distributions. I am trying to compute the log-sum-exp for the log_probs of these target data to compute the loss. When I use standard ... | <p>Issue resolved. My targets had some large values which were leading to overflow calculations when log_probs was calculated for these values. Removed some outlandish data points and normalised the data, loss immediately came down.</p> | python|deep-learning|pytorch|gmm | 0 |
14,556 | 58,628,445 | Check if strings in column matches one of two formats, if not re-format the string | <p>I have a column of strings which are IDs that are suppose to follow the format of either: C-xxxxx-U-## or C-xxxxx-UX-## where x can be a digit or a uppercase letter. </p>
<p>I want to check that the ID follows either of these formats and if it doesn't I want to re-format the string so it does. </p>
<p>Some example... | <p>With specific regex replacement:</p>
<pre><code>In [51]: df['ID'].str.replace(r'^C([^-])', 'C-\\1').replace(r'-U[^A-Z0-9]+', '-U')
Out[51]:
0 C-20BV7-U-00
1 C-20BW5-U-00
2 C-1AWT4-UR-00
3 C-1B8V9-UR-00
4 C-20BX2-U-00
Name: ID, dtype: object
</code></pre> | python|python-3.x|pandas | 0 |
14,557 | 70,307,912 | Group list of dicts by two params and count grouped values | <p>I have list of dicts with id numbers, I need to group it by <code>main_id</code> and <code>second_id</code> and count values in each group. What is the best Python way to reach this?</p>
<p>I'm tried with Pandas, but don't get dict with groups and counts</p>
<pre><code>df = pd.DataFrame(data_list)
df2 = df.groupby('... | <p>You could use <code>collections</code> (from the standard library) instead of pandas. I assigned the list of dicts to <code>xs</code>:</p>
<pre><code>import collections
# create a list of tuples; each is (main_id, secondary_id)
ids = [ (x['main_id'], x['second_id']) for x in xs ]
# count occurrences of each tuple... | python|pandas|list|dataframe|group-by | 0 |
14,558 | 56,029,140 | How to display Summary statistics next to a plot using matplotlib or seaborn? | <p>I am trying to create a function that will iterate over the list of numerical features in a dataframe to display histogram and summary statistics next to it. I am using <code>plt.figtext()</code> to display the statistics but I am getting an error</p>
<pre><code>num_features=[n1,n2,n3]
for i in num_features:
f... | <p>You can "simplify" your code, by formatting the dataframe returned by <code>describe()</code> as a string using <code>to_string()</code>:</p>
<pre><code>df = pd.DataFrame(np.random.normal(size=(2000,)))
fig, ax = plt.subplots()
ax.hist(df[0])
plt.figtext(0.1,0.5, df.describe().to_string())
plt.figtext(0.75,0.5, df.... | pandas|matplotlib|seaborn | 8 |
14,559 | 55,666,648 | How can i split a dataframe into groups by its columns using a for loop, splitting df only by its columns, not rows | <p>i have a dataframe of with 2000 columns, and would like to write a fast code to split this dataframe into 10 groups of 200 columns. </p>
<pre><code>df_name = ['df1','df2','df3','df4','df5','df6','df7','df8','df9','df10']
for name in df_name:
for n in np.arange(0,2000,200):
name = df[df.columns[n:n+200]... | <p>Because you cannot dynamically build environment objects by string assignment with <code>name = ...</code>, consider building a dictionary of data frames using a dictionary comprehension that includes <code>zip</code> to iterate elementwise through <em>df_name</em> and 200 multiples:</p>
<pre><code>df_dict = {k:df[... | python|pandas|dataframe | 0 |
14,560 | 55,980,579 | How to normalize set of images between (-1,1) | <p>i have a dataset on images and i would like to normalize them betwwen (-1,1) before feeding them to NN how can i do that ? </p>
<pre><code>x=sample
#Normalized Data
normalized = (x-min(x))/(max(x)-min(x))
# Histogram of example data and normalized data
par(mfrow=c(1,2))
hist(x, breaks=10, xlab="Data", ... | <p>Assuming your image <code>img_array</code> is an <code>np.array</code> :</p>
<pre><code>normalized_input = (img_array - np.amin(img_array)) / (np.amax(img_array) - np.amin(img_array))
</code></pre>
<p>Will normalize your data between 0 and 1.</p>
<p>Then, <code>2*normalized_input-1</code> will shift it between -1... | python|matlab|tensorflow|pytorch | 3 |
14,561 | 55,984,345 | np.concatenate error...ValueError: all the input arrays must have same number of dimensions | <p>My code words fine until I try to load in my headers to the data frame. It appears to be an issue with np.concatenate.</p>
<p>I've tried transposing the array to see if it is in the incorrect direction.</p>
<pre><code>print("\n")
print("Prediction")
Y = vectorizer.transform(df['plot_keywords'].astype('U'))
predi... | <p>In </p>
<pre class="lang-py prettyprint-override"><code>np.concatenate([df.columns.values,'cluster_plot_keywords'])
</code></pre>
<p>you are trying to concatenate an array-like object (<code>df.columns.values</code>) with a string, <code>'cluster_plot_keywords'</code> (which is "interpreted" as 0-dimensional array... | python|numpy|dataframe | 0 |
14,562 | 64,931,112 | The result is empty when prediction of Faster RCNN model (Pytorch) | <ul>
<li>I'm trying to train Faster RCNN model. After training, I try to predict the result of image but the result is empty.</li>
<li>My data is w: 1600, h: 800, c: 3, classes: 7, bounding boxes:(x1, y1, x2, y2)</li>
<li>My model is below.</li>
</ul>
<p>My model</p>
<pre><code>import torchvision
from torchvision.model... | <p>You should change the number of classes to</p>
<pre><code> model = FasterRCNN(backbone,
num_classes=YOUR_CLASSES+1, # +1 is for the background
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
</code></pre>
<p>Remember that the class <code... | pytorch|detection|faster-rcnn | 3 |
14,563 | 64,670,940 | Percent Increase, groupby, over time (using Python) | <p>I have a dataset, df, where I am trying to calculate the percent increase of a particular group over a time period. Here is the dataset:</p>
<pre><code> date size type
1/1/2020 1 a
1/1/2020 1 a
1/1/2020 3 a
1/1/2020 1 b
1/1/2020 2 b... | <p>looks like a simple groupie aggregation function:</p>
<pre><code>df1 = df.groupby(['type','date'])['size'].agg(lambda x:(x.iloc[-1]/x.iloc[0]-1)*100).to_frame('increase')
df1['diff'] = df.groupby(['type','date']).agg(lambda x:x.iloc[-1]-x.iloc[0])
df1.reset_index()
</code></pre>
<p>output:</p>
<pre><code> type ... | python|pandas|numpy|time-series | 1 |
14,564 | 64,856,601 | Plotting two dataframes obtained from a loop in the same graph Python | <p>I would like to plot two <code>dfs</code> with two different colors. For each <code>df</code>, I would need to add two markers. Here is what I have tried:</p>
<pre><code>for stats_file in stats_files:
data = Graph(stats_file)
Graph.compute(data)
data.servers_df.plot(x="time", y="percentage... | <h1>TL;DR</h1>
<p>Your call to <code>data.servers_df.plot()</code> always creates a new plot, and <code>plt.plot()</code> plots on the latest plot that was created. The solution is to create dedicated axis for everything to plot onto.</p>
<h1>Preface</h1>
<p>I assumed your variables are the following</p>
<ul>
<li><code... | python|pandas|dataframe|matplotlib|plot | 5 |
14,565 | 40,285,296 | Modifying/Overwriting NumPy Array | <p>I have a series of binary NumPy arrays (which represent cloudy (1s) and clear (0s) sky pixels at a given time) and have added them together to find the total number of observations where cloud is present in each pixel.</p>
<p>I am now wanting to find out the percentage of cloud (number of cloud (1s)/total observati... | <p>The following code will create the arrays, add them together and divide each element by 100. For the percentage, you need to know the number of entries. You could work with a 3-D array and using numpy's sum/average etc. functions.</p>
<pre><code>import numpy as np
a = np.array([1,0,1])
b = np.array([0,0,1])
c = (a+... | python|arrays|numpy | 0 |
14,566 | 39,559,953 | My own data to tensorflow MNIST pipeline gives ValueError: input elements number isn't divisible by 65536 | <p>I'm using my own data with <a href="https://stackoverflow.com/questions/tags/tensorflow"><code>tensorflow</code></a> <a href="https://stackoverflow.com/questions/tagged/mnist"><code>MNIST</code></a> example pipeline but getting:</p>
<blockquote>
<p>ValueError: input has 16384 elements, which isn't divisible by 65... | <p>It's hard to tell without seeing more of your code exactly what's going wrong, but the summary is that TensorFlow thinks that the other dimensions of <code>input</code> result in a stride of 65536 elements, and so it's trying to infer the missing dimension by dividing the number of elements present by the known dime... | python|ubuntu|tensorflow|mnist | 0 |
14,567 | 44,222,949 | IndexError Can int be used as indices? | <p>I got an error,
IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices .
I am making sound recognition app.
My code is </p>
<pre><code>import numpy as np
import pandas as pd
import scipy as sp
import pickle
from scipy import fft
from time impo... | <p>The error message is saying that when indexing a numpy array</p>
<pre><code>only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
</code></pre>
<p><code>label</code> is a 2d array of floats, with current value of 0.:</p>
<pre><code>label = np.zeros([len(r... | python|numpy|scipy | 0 |
14,568 | 69,525,006 | Improve performance broadcast multiplication and 1 - broadcast | <p>How can I improve the last two "operations" of this code in terms of time? (minus1_power_x_t*x and 1-minus1_power_x). They are taking 1.73 and 1.47 seconds respectively. I asked for the last two operations because the others ones will be constants.</p>
<pre><code>import time
from multiprocessing import Poo... | <p>The problem with this code is that it creates many <strong>big temporary arrays</strong> for basic <strong>memory-bound</strong> operations. Big temporary arrays are slow to fill because of the speed of the RAM (unsurprisingly) and also because <strong>page fault</strong>.</p>
<p>Indeed, the operating system (OS) pe... | numpy | 1 |
14,569 | 69,406,431 | Inspect value of a tensor in Tensorflow 2.0 | <p>I struggle to apply answers to <a href="https://stackoverflow.com/questions/33633370/how-to-print-the-value-of-a-tensor-object-in-tensorflow">similar questions</a>, with Tensorflow 2.6.0.</p>
<p>I would like to inspect the values in my tensor during debugging. If I do a Python print</p>
<pre><code>predicted_ids=tf.r... | <p>It is fairly simple:</p>
<p>For example:</p>
<p><code>tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5).numpy()</code></p>
<p>Output:</p>
<p><code>array([[0, 1, 1, 0, 0]])</code></p>
<p>In your case:</p>
<p><code>predicted_ids.numpy()</code></p> | python|tensorflow|machine-learning | 0 |
14,570 | 69,532,970 | How to vectorize a numpy for loop that has a multiple indexed access | <p><code>unigram</code> is an array shape <code>(N, M, 100)</code></p>
<p>I would like to remove the <code>for</code> loop and perform all the calculations.</p>
<p><code>seq</code> is a 1D array of size <code>M</code>, and the size of <code>M</code> maybe up to 10000.</p>
<p>I would like to remove the for loop and vect... | <pre><code>In [129]: N,M = 5,3
In [130]: unigram=np.arange(N*M*4).reshape(N,M,4)
In [131]: seq = np.arange(M)
In [132]: b_seq = np.broadcast_to(seq, (N,M))
</code></pre>
<p>For a single <code>i</code>:</p>
<pre><code>In [133]: i=0; unigram[np.arange(N),i,b_seq[:,i]]
Out[133]: array([ 0, 12, 24, 36, 48])
</code></pre>
<... | python|numpy | 1 |
14,571 | 53,815,805 | converting 3D pandas dataframe to 2d | <p>I have a 3D dataframe with 2 levels of index and one column that looks like this:</p>
<pre><code> col1
0 0 67.23
0 1 7382
0 2 43
.
.
0 8002 54
0 8003 87
1 0 348
1 1 83
1 2 234
.
.
1 8002 23
1 8003 87
....
9 0 348
9 1 83... | <p>Try using <code>DataFrame.unstack</code> - bear in mind that this will not work if you have duplicate indices.</p>
<pre><code>df_2d = df.unstack(1)
</code></pre>
<p>Then fix column level using:</p>
<pre><code> df_2d.columns = df_2d.columns.droplevel(0)
</code></pre> | python|pandas|dataframe|pivot | 1 |
14,572 | 53,903,298 | How to convert a missing data to a NaN value | <p>I'm trying to convert missing data in an xls file to a dataframe of Nan values.</p>
<pre><code>New list=energy.where(energy['Energy Supply']>=0)
</code></pre>
<p>I got:</p>
<blockquote>
<p>the operator >= can't be used between strings and integer. </p>
</blockquote>
<p>My data type is numeric apart from the... | <p>You need to use <code>.loc</code> for indexing: </p>
<pre><code>energy.loc[energy['Energy Supply']>=0,:]
</code></pre>
<p>Use of <code>:</code> to show all columns is optional. Following should also work: </p>
<pre><code>energy.loc[energy['Energy Supply']>=0]
</code></pre>
<p>Above will not include any mis... | python|pandas | 0 |
14,573 | 38,235,922 | Pandas DataFrame to_dict fails after drop_duplicates | <p>I have a DataFrame, let's just call it <code>df</code>.</p>
<p><code>return df.to_dict(orient="records")</code> dutifully spits out a list of dicts.</p>
<p>But if I do</p>
<pre><code>df.drop_duplicates
return df.to_dict(orient="records")
</code></pre>
<p>it fails and says:</p>
<blockquote>
<p>'function' objec... | <p>I think you miss <code>()</code>, because without the <code>()</code> the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a> just refers to the function, so <code>df</code> becomes a copy of the function, no... | python|pandas|dictionary|dataframe | 4 |
14,574 | 38,409,586 | How to tell the hours elapsed in a csv file? | <p><strong>I want a column that tells me the time elapsed since he first row (5/1/2002 at 6:00AM), to the last (11/20/2006 at 2:00PM). How can I create an extra column that tells me the hours passed since the beginning of 5/1/2002?
Here is my dataframe:</strong></p>
<pre><code> Date Time (HHMM) Site ... | <p>Simple:</p>
<ul>
<li>read the file,</li>
<li>parse the date and time,</li>
<li>calculate the delta with the first date/time,</li>
<li>write the result.</li>
</ul>
<p>Here is an implementation using file-like objects for the demo:</p>
<pre><code>import datetime
import io
data = """\
Date Time (HHMM) ... | python|csv|datetime|pandas | 1 |
14,575 | 38,257,218 | Reshaping and grouping part of a dataframe | <p>I need help pivoting a dataframe</p>
<pre><code>data = [{'Start Date': '12/3/2016',
'End Date': '12/4/2016',
'Name':'John'},
{'Start Date':'12/3/2016',
'End Date': '12/4/2016',
'Name':'Karen'},
{'Start Date': '12/1/2016',
'End Date': '12/2/2016',
'Name':'John'},
{'Start Date':'12/1/... | <p>Consider a merge approach with data frame on itself (akin to SQL's self join) and then filter for non-matched names and first pairing with group count:</p>
<pre><code>mdf = pd.merge(df, df, on='End Date')
mdf['grp'] = mdf.groupby('End Date').cumcount()
# End Date Name_x Start Date_x Name_y Start Date_y gr... | python|pandas | 0 |
14,576 | 66,321,451 | find min and max index in numpy array column for a certain value | <p>I have a 2D numpy array which looks like this:</p>
<pre><code>['0.0002126159536893578' '0']
['0.000489237210943365' '0']
...
['6.998729658062154e-05' '3']
['7.956089498242174e-07' '3']
['9.178127570732645e-06' '3']]
</code></pre>
<p>Its sorted first by the second column and then by the first column, now i need to g... | <p>If your data is already sorted by second columns, you can try:</p>
<pre><code>uniques, idx = np.unique(arr[:,1], return_index=True)
</code></pre>
<p>Then <code>idx</code> contains the first occurences for each unique value in <code>uniques</code>.</p> | python|numpy|numpy-ndarray | 1 |
14,577 | 66,204,708 | Calculating R^2 value for the data that fall within 95% prediction interval | <p>I have data as follows.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
x = np.array([50,52,53,54,58,60,62,64,66,67,68,70,72,74,76,55,50,45,65])
y = np.array([25,50,55,75,80,85,50,65,85,55,45,45,50,75,95,65,50,40,45])
</code></pre>
<p>I can calculate overall <code>R^2</... | <p>Considering the following functions</p>
<pre><code>def calculate_limits(y_fitted, pred_interval):
"""Calculate upper and lower bound prediction interval."""
return (y_fitted - pi).min(), (y_fitted + pi).max()
def calculate_within_limits(x_val, y_val, lower_bound, upper_bound):... | python|numpy|scipy|statsmodels | 2 |
14,578 | 66,144,750 | Add counter as an additional column in Python pandas dataframe | <p>I have following dataframe as an output of my python script. I would like to add another column with count per pmid and add the counter to the first row, keeping the other rows.</p>
<p>The dataframe looks like this:</p>
<p>df</p>
<pre><code> PMID gene_symbol gene_label gene_mentions
0 33377242 MTHFR ... | <p>You can add count for each row with <code>groupby().transform</code>:</p>
<pre><code>df['count'] = df.groupby('PMID')['PMID'].transform('size')
</code></pre>
<p>Output:</p>
<pre><code> PMID gene_symbol gene_label gene_mentions count
0 33377242 MTHFR Matched Gene 2 1
1 33414971 ... | python|pandas | 1 |
14,579 | 66,073,806 | Pandas: Create 1 function to read json then create another function to create dataframe | <p>I would like to create a function to get data from an API, then create another function to create and clean the respective dataframe for use.</p>
<p>The first set of def looks like below and it works fine:</p>
<pre><code>def get_data():
print('start download the 1st set')
confirm_details = requests.get('htt... | <p>As per comment - structure your code so you know scope of variables. You have assumed everything is global which would be a very bad thing...</p>
<pre><code>def get_data():
ret = {}
print('start download the 1st set')
ret["confirm_details"] = requests.get('https://api.data.gov.hk/v2/filter?q=... | python|pandas|function|dataframe | 0 |
14,580 | 66,115,204 | Accessing to Weights and Layers in Tensorflow Hub | <p>When I try to get the model from tensorflow-hub resporitory.
I can see it as a Saved Model format, but I cant get access to model architecture as well as weights store for each layer.</p>
<pre><code>import tensorflow_hub as hub
model = hub.load("https://tfhub.dev/tensorflow/centernet/hourglass_512x512/1")
... | <p>With the CLI tool <code>saved_model_cli</code> provided by the package <a href="https://pypi.org/project/tensorflow-serving-api/" rel="nofollow noreferrer">tensorflow-serving-api</a> it's possible to inspect a saved model. In the first step I downloaded and cached the model:</p>
<pre class="lang-py prettyprint-overr... | tensorflow|keras|tf.keras|tensorflow-serving|tensorflow-hub | 1 |
14,581 | 66,135,099 | Collapse Numpy arrays to scalar when, e.g., multiplying by zero | <p>I'm a bit surprised that I couldn't find an easy when to collapse dimensions of a Numpy array containing identical values. Let me explain.</p>
<p>I might have to multiply to time series implemented as arrays, say <code>a * b</code>. In most cases, this is fine, but sometimes <code>a</code> or <code>b</code> are scal... | <p>The test case is your best bet. Numpy does not generally presume to know the contents of your data, so it only does what you tell it. Specifically, as you noted, the result of a broadcasted operation will be whatever the broadcasting comes out to. Anything short of that would voilate Python's principle of least surp... | python|numpy|scientific-computing | 1 |
14,582 | 52,657,865 | Trouble finding html object for scraper | <p>Hi I'm trying to create a dataset from a website. I found the dataset on kaggle and wanted to use the scraper the guy used to get an updated version but I'm having some issues with an error. It's giving me this error:</p>
<p>AttributeError:</p>
<pre><code> 'NoneType' object has no attribute 'find_all'
</code></pre... | <p>This site explicitly deny scrapping. Terms of use states:</p>
<p>'Unauthorized access to our sites is a breach of these Terms and a violation of the law. You agree not to access our sites by any means other than through the interface that is provided by VGChartz Ltd for use in accessing our sites. You agree not to ... | python|pandas | 0 |
14,583 | 52,768,061 | Why does set of a pandas dataframe return column names of the dataframe? | <p>I was just tinkering around and found this amusing:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> x = set(df)
>>> x
{'col2', 'col1'}
</code></pre>
<p>Why does pandas return column names as set values?</p> | <p>Because that's how <code>__iter__</code> is defined in the <a href="https://github.com/pandas-dev/pandas/blob/v0.23.4/pandas/core/generic.py#L1494" rel="nofollow noreferrer">source code</a> for <a href="https://github.com/pandas-dev/pandas/blob/v0.23.4/pandas/core/generic.py#L102" rel="nofollow noreferrer"><code>NDF... | python|pandas|set | 1 |
14,584 | 46,302,087 | How (with apply) to select and copy specific columns in a Dataframe according to index or another column | <p>I already asked my question but it was not enough accurate in its description.
Smart people in this forum already proposed solutions, but I forgot(sorry) to precise that if there were zeros in the relevant columns, they should be kept.</p>
<p>Hello I have a dataframe like below</p>
<pre><code> 2014 2... | <p>One of the ways would be</p>
<pre><code>In [1010]: def yearmove(x):
...: idx = x.index.astype(int)
...: idx = idx - x.name
...: mask = idx >= 0
...: idx = 'yearStart' + idx.astype(str)
...: return pd.Series(x.values[mask], index=idx[mask])
...:
In [1011]: ... | python|python-3.x|pandas|apply | 0 |
14,585 | 58,585,892 | Creating a Feed Forward NN Model in Pytorch with a dynamic number of hidden layers | <p>Why are these two code segments not equivalent:
Segment 1: Creating a model with 2 layers.</p>
<pre><code>class FNNModule(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim1, hidden_dim2, non_linear_function):
super().__init__()
self.hidden1 = nn.Linear(input_dim, hidden_dim1)
... | <p>Those modules are called as you would expect them to be called they are just not visible to the Module. In order to make them visible you can wrap them in a <code>nn.ModuleList</code> like this:</p>
<pre><code>class FNNModuleVar(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim_array = [], non_li... | pytorch | 1 |
14,586 | 58,184,563 | Converting timezones using pytz on Pandas Series | <p>I am trying to convert the timezone of a pandas Series. I am using the pytz package to do so, however I am getting a value that is off by a few minutes.
The code I am currently using can be found in the answer here: <a href="https://stackoverflow.com/questions/57062108/converting-items-from-pandas-series-to-date-ti... | <p>When I run the code from <a href="https://stackoverflow.com/questions/57062108/converting-items-from-pandas-series-to-date-time">the previous answer</a> it works just fine. Compare your code to IMCoins' and see where the difference is (you create a separate time series whereas IMCoins keeps everything within the da... | python|pandas|pytz | 0 |
14,587 | 58,527,983 | How to extract the first x digits out of a matrix? | <p>I would like to extract the first 5 digits out of a given nxm matrix.</p>
<p>For example the 3x3 Matrix A </p>
<pre><code>A = [[ 1. 2. 3. ]
[ 4. 5. 6.]
[ 8. 9. 10.]]
</code></pre>
<p>The first 5 digits would be 1,2,3,4,5, so the first row and the half of the second.</p>
<p>The big problem is to d... | <p>Reshape with shape of <code>(-1,)</code> then slice to <code>x</code>:</p>
<pre><code>import numpy as np
A = np.arange(9).reshape((3,3))
print (A)
x = 5
B = A.reshape((-1,))[:x]
print (B)
</code></pre>
<blockquote>
<pre><code>[[0 1 2]
[3 4 5]
[6 7 8]]
[0 1 2 3 4]
</code></pre>
</blockquote> | python|python-3.x|numpy|matrix | 0 |
14,588 | 58,531,235 | Is there a better way to manipulate column names in a pandas dataframe? | <p>I'm working with a large dataframe and need a way to dynamically rename column names. </p>
<p><em>Here's a slow method I'm working with:</em></p>
<pre><code># Create a sample dataframe
df = pd.DataFrame.from_records([
{'Name':'Jay','Favorite Color (BLAH)':'Green'},
{'Name':'Shay','Favorite Color (BLAH)':'B... | <p>You could define a <code>clean</code> function and just apply to all the columns using list comprehension.</p>
<pre><code>def clean(name):
name = name.split('(')[0] if ' (' in name else name
name = '_'.join(name.split())
return name
df.columns = [clean(col) for col in df.columns]
</code></pre>
<p>It's clea... | python|pandas | 1 |
14,589 | 58,258,139 | How to remove lines with a pattern if the next line matches the same pattern? | <p>I have a dataframe with a column containing logs for a ticket per row. Here is an example of the log:</p>
<pre><code>99645,
\Submitted',
'\Modifications made 2015/01/01',
'x_change0: --> info0',
'y_status1: --> info1',
'z_change2: --> info2',
'y_change3: --> info3',
'\Modifications mad... | <p>Solved with @Code Maniac's RegEx solution:
<code>(?sm)Modifications[^,]+,(?:(?!^\s*'\\Modifications).)*\b</code>.</p>
<p>Replace cell string with the following loop:</p>
<pre><code>pattern = r"(?sm)Modifications[^,]+,(?:(?!^\s*'\\Modifications).)*\b"
pattern = re.compile(pattern=pattern)
df['tickethist'] = ""
fo... | python|regex|pandas|text|text-mining | 1 |
14,590 | 69,146,243 | Share the output of one class to another class python | <p>I have two DNNs the first one returns two outputs. I want to use one of these outputs in a second class that represents another DNN as in the following example:</p>
<p>I want to pass the output (x) to the second class to be concatenated to another variable (v). I found a solution to make the variable (x) as a global... | <p>You should not have to rely on <em>global</em> variables, you need to solve this following common practices. You can pass both <code>v</code>, and <code>x</code> as parameters of the <code>forward</code> of <code>Net2</code>. Something like:</p>
<pre><code>class Net(nn.Module):
def forward(self, x):
z = ... | python|python-3.x|pytorch | 0 |
14,591 | 44,693,306 | How to remove tailing alphabet from dataframe column | <p>I have a dataframe :</p>
<p><code>A B
10.1 33.3
11.2 44.2s
12.3 11.3s
14.2s *
15.4s nan</code></p>
<p>i want output as </p>
<p><code>A B
10.1 33.3
11.2 44.2
12.3 11.3
14.2 0
15.4 0</code></p>
<p>How do I remove... | <p>You can extract <a href="https://stackoverflow.com/a/4703409/2901002">floats</a> first and for replace <code>NaN</code>s to <code>0</code> add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a>.</p>
<p>Solution is in <a href="h... | python|regex|csv|pandas|dataframe | 1 |
14,592 | 60,861,990 | I want to find the top 3 rank of customers based on value of cash in pandas | <p>For a customer i need to find out the rank value based on the cash value</p>
<p><strong>Input</strong></p>
<p>Id No prob<br>
1 0.000000<br>
1 0.000000<br>
1 0.000000<br>
1 0.000000<br>
1 0.000000<br>
1 0.000000<br>
3 0.000000<br>
3 0.000000<br>
2748 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.rank.html" rel="nofollow noreferrer"><code>GroupBy.rank</code></a> with <code>ascending=False</code> and casting to integers:</p>
<pre><code>df['rank'] = df.groupby('Cust_id')['cash'].rank(ascending=False).astype(int)... | python-3.x|pandas|dataframe | 3 |
14,593 | 71,641,666 | Hyperlink in Streamlit dataframe | <p>I am attempting to display a clickable hyperlink inside a dataframe containing filtered results on Streamlit. This is my code so far:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML
df = ... | <p>You can use <code>st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True)</code>:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML
df = pd.read_excel(
io='list.xlsx',
e... | python|pandas|hyperlink|streamlit | 2 |
14,594 | 71,683,457 | Pandas sorted groupby returning series data which is not able to access | <p><strong>Sample Data:</strong></p>
<pre><code> user_id content_id date
0 user_44289 cont_3375_16_10 2020-03-06
1 user_44289 cont_1195_1_8 2019-04-18
2 user_44289 cont_3470_2_15 2021-09-18
3 user_44289 cont_310_25_9 2020-09-08
4 user_44289 cont_4350_1_3 2021-06-25
5 user_40584 cont... | <p>Do you want something like:</p>
<pre><code>out = df.sort_values('date', ascending=False).groupby('user_id').agg(list)
print(out)
# Output
content_id date
user_id ... | python|pandas|pandas-groupby | 1 |
14,595 | 69,736,058 | AttributeError: 'DataFrame' object has no attribute 'assign' | <p>While assign a new column to my DataFrame I get this error here is my code</p>
<pre><code>def check_header(header, df):
print("Header : ",header)
for item in header:
if not item in df.columns:
df = df.assign(item) #here I'm getting error
return df[header]
</code></pre>
<p>I ... | <p>If need add new columns by <code>header</code> list with convert not matched values to new columns filled by <code>NaN</code>s use <a href="http://pandawheres.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>:</p>
<pre><code>df = p... | python|pandas | 1 |
14,596 | 43,238,279 | NumPy Histogram - ValueError range parameter must be finite - input array is okay | <p>I'm struggling to understand this error, since I'll give you an example that's working and the one I'm interested in that's <em>not</em>.</p>
<p>I have to analyse a set of data with hourly prices for an entire year in it, called <code>sys_prices</code>, which - after various transformations - is a <code>numpy.ndarr... | <p>I solved it, there was a single NaN in the dataset I couldn't spot.</p>
<p>For those wondering how to spot it, I just used this code to find the index of the item:</p>
<pre><code>nanlist=[]
for ii in range(len(array)):
if numpy.isnan(array[ii]):
nanlist.append(ii)
</code></pre>
<p>Where <code>array</c... | python|python-3.x|numpy|histogram|valueerror | 6 |
14,597 | 43,355,044 | Cumulative Explained Variance for PCA in Python | <p>I have a simple R script for running <a href="http://factominer.free.fr/classical-methods/principal-components-analysis.html" rel="nofollow noreferrer">FactoMineR's PCA</a> on a tiny dataframe in order to find the cumulative percentage of variance explained for each variable:</p>
<pre><code>library(FactoMineR)
a &l... | <p>Thanks to Vlo, I learned that the differences between the FactoMineR PCA function and the sklearn PCA function is that the FactoMineR one scales the data by default. By simply adding a scaling function to my python code, I was able to reproduce the results.</p>
<pre><code>import pandas as pd
from sklearn import dec... | python|r|pandas|scikit-learn|pca | 1 |
14,598 | 72,227,477 | How to calculate monthly changes in a time series using pandas dataframe | <p>As I am new to Python I am probably asking for something basic for most of you. However, I have a df where 'Date' is the index, another column that is returning the month related to the Date, and one Data column.</p>
<pre><code> Mnth TSData
Date
2012-01-05 1 192.6257
2012-01-12 1 194.2714
201... | <p>IIUC, starting from this as <code>df</code>:</p>
<pre><code> Date Mnth TSData
0 2012-01-05 1 192.6257
1 2012-01-12 1 194.2714
2 2012-01-19 1 192.0086
3 2012-01-26 1 186.9729
4 2012-02-02 2 183.7700
...
20 2012-05-24 5 179.1971
21 2012-05-31 5 183.7120
22 2... | python|pandas|dataframe | 0 |
14,599 | 72,183,882 | Bypassing and printing out the name of an Error in a Loop - Python | <p>Although I know it is not good practice to bypass an error, I'm trying to figure out in which of the data sets that I am working one, I get an error.</p>
<p>I am looping through all of the Data Sets, and everythime I get an error I flag it by using:</p>
<pre><code> try:
# block raising an exceptio... | <p>To print the type of error, you can use the following code</p>
<pre><code>try:
# Your code
except Exception as e:
print(type(e).__name__)
</code></pre>
<p>Example:</p>
<pre><code>try:
1/0
except Exception as e:
print(type(e).__name__)
# Output:
# ZeroDivisionError
</code></pre>
<p>Also see <a href="https... | python|pandas|debugging|error-handling | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.