Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
371,600 | 44,389,480 | Optimize an algorithm which is executed a lot of times | <p>I have a couple of <code>for</code> loops and the innermost one will be executed a lot of times. This innermost loop contains some heavy calculations using numpy, so all of this is taking a lot of time. So I am trying to optimize the innermost loop.</p>
<h3>The most inner-loop contains the following logic:</h3>
<p... | <p>If you need to loop over your sequence and you care about performance you shouldn't use <code>numpy.array</code>s. NumPy arrays are great when NumPy can do the loop, but if you have to loop over it yourself it will be slow (I covered the details why iterations over arrays are quite slow in another answer recently, i... | python|performance|loops|numpy|optimization | 1 |
371,601 | 44,429,707 | Preserve order when indexing a multilevel with a list | <p>Using Pandas 0.20.2 with Python 3.6.1:</p>
<p>When you index a single-level DataFrame with a list, the returned DataFrame respects the order of the list, for example consider this DataFrame:</p>
<pre><code>df = pd.DataFrame({'col1': [0,1,2],
'col2': ['foo', 'bar', 'baz']},
inde... | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-reindexing-and-alignment" rel="nofollow noreferrer"><code>reindex</code></a> to force the order of the rows in the order you desire, it seems that using <code>loc</code> it's not possible to do this with multi-indexes as sorted... | python|pandas | 2 |
371,602 | 60,801,543 | Forward fill column on condition | <p>My dataframe looks like this;</p>
<pre><code>df = pd.DataFrame({'Col1':[0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0]
,'Col2':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]})
</code></pre>
<p>If col1 contains the value 1 in column 2 I want to forward fill with 1 n number of times. For example, if n = ... | <p><strong>Approach #1 :</strong> A NumPy based one with <code>1D convolution</code> -</p>
<pre><code>N = 4 # window size
K = np.ones(N,dtype=bool)
df['Col2'] = (np.convolve(df.Col1,K)[:-N+1]>0).view('i1')
</code></pre>
<p>A more compact one-liner -</p>
<pre><code>df['Col2'] = (np.convolve(df.Col1,[1]*N)[:-N+1]&g... | python|pandas|numpy|conditional-statements|fill | 4 |
371,603 | 61,007,925 | logical indexing in pandas dataframe with timestamp column and datetime.date-object | <p>I'm a little lost. I have a dataframe with a column names <code>dates</code>, that looks like this: </p>
<pre><code>>>> dates_df
product tile date
0 L30 34JDN 2019-01-01
1 L30 34JDN 2019-01-10
2 L30 34JDN 2019-01-17
3 L30 34JDN 2019-01-26
4 L30 34JDN 2019-02-0... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</code></a> for compare by scalar dates:</p>
<pre><code>dates_df[dates_df["date"].dt.date == date_np]
</code></pre>
<p>Or convert scalar to <a href="https://stackoverflow... | python|pandas|numpy|datetime | 1 |
371,604 | 60,801,282 | Check every row for each column values in a df in python | <p>I am new to pandas data frames. So, I need help in this
I have a df like below stated:</p>
<pre><code> Location A B C D
0 X GREEN RED GREEN AMBER
1 Y GREEN RED RED RED
2 Z GREEN GREEN GREEN GREEN
3 R GREEN GREEN GREEN GREEN
</code></pre>
<p>... | <p>Idea is create list of priority values, reshape values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a>, convert to categoricals, sorting and get first values by <a href="http://pandas.pydata.org/pandas-docs/... | python|pandas | 3 |
371,605 | 61,079,415 | Pandas:Conditionally combining multi-indexing dataframes | <p>I have two dataframes (df1 and df2) which are used pd.groupby from a same datafram.
I want to conditionally create another dataframe (df_result) based on the following logic:</p>
<ol>
<li>df_result's structure / cell is copied from df1</li>
<li>For count < 6 in df1, use the corresponding value in df2 instead.</l... | <p>Idea is add second level from <code>df1</code> to <code>df2</code> for <code>MultiIndex</code>, so possible repalce by condition in last step, only necessary matching first level of MultiIndex in both <code>DataFrame</code>s:</p>
<pre><code>m = df1[('diff','count')] < 6
mux = pd.MultiIndex.from_product([df2.ind... | python|pandas|dataframe|multi-index | 0 |
371,606 | 60,848,211 | Replacing a for loop related to a parameter inside function of two variables by numpy sum | <p>I am trying to speed up a function that can be minimally represented by:</p>
<pre><code>import numpy as np
def simple_function(x, y, a1, a2, a3):
return a1 + a2*x**2/(1 + a3*y**2)
def to_optimnize(x, y, a1, a2, a3, N):
Sigma = 0
for i in range(len(N)):
yn = N[i]*y
Sigma = Sigma + N[i]... | <p>This mostly seems to be a matter of getting the shapes for broadcasting correct. To understand what's going on here, note that given a 1-d array <code>a</code>, <code>a[None, :]</code> creates a 2-d array with a first dimension of length <code>1</code>. <code>a[:, None]</code> creates a 2-d array with a second dimen... | function|numpy|optimization|vectorization | 3 |
371,607 | 61,108,005 | Web-scraping: Empty dataset after collecting information | <p>I would like to create a dataset that includes information scraped from a website. I explain what I have done and the expected output below. I am getting empty arrays for rows and columns, then for the whole dataset, and I do not understand the reason. I hope you can help me.</p>
<p>1) Create an empty dataframe wit... | <p>Yon can do it using pandas only.Try the following code.</p>
<pre><code>urllist=[ 'bbc.co.uk','stackoverflow.com','who.int','cnn.com']
dffinal=pd.DataFrame()
for url in urllist:
df=pd.read_html("https://www.urlvoid.com/scan/" + url + "/")[0]
list = df.values.tolist()
rows = []
cols = []
for li i... | python|pandas|web-scraping|beautifulsoup | 1 |
371,608 | 61,148,574 | Get data array backing fortran ordered numpy array | <p>So I understand that "fortran ordering" of a numpy array means it's stored column major, but doesn't actually affect what the data represents. What I'm looking for is a way to take a column major numpy array, and return a 1 dimensional array that is stored in the same order as numpy's internal column major represent... | <p>Use <code>.flatten</code> with the argument <code>F</code>.</p>
<pre><code>a = np.array([[1, 2, 3],
[4, 5, 6]])
a.flatten('C') #row major
>>> [1, 2, 3, 4, 5, 6]
a.flatten('F') #column major
>>> [1, 4, 2, 5, 3, 6]
</code></pre>
<p>Transposing it and then making it flat is also anot... | python|arrays|numpy | 1 |
371,609 | 60,968,835 | Is there a way to filter a pandas dataframe row by arrays in the column? | <p>I have a dataframe for which the output is this:</p>
<pre><code> fruit season
0 apples [plant, plant, plant]
1 oranges [harvest, plant, plant]
2 bananas [harvest, plant, harvest]
</code></pre>
<p>I want to search for a pattern in the season column ...</p>
<pre><code>pattern = ... | <p>If I am not misinterpreting you want the rows with that exact value to be shown:
<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html</a></p>
<pre><code>pattern =... | python|pandas|dataframe|filter | 0 |
371,610 | 60,999,169 | Using Matplotlib, how to display Y-axis values ordered in HH24:MI format | <p>I am unable to sort the job finish time (Y-Axis). Currently it is displaying what each Y-axis has. I am going to have more Y-axis added in future.</p>
<p>Is there any way of sorting the Y-Axis values? My sample code is pasted below and a screenshot of the issue is attached. <a href="https://i.stack.imgur.com/gqkrQ.... | <p>Your problem is that you're converting to string, so the y-axis is presented in the given order by default, not sorted. It's better to work with datetime objects, and let matplotlib figure out the y-axis order for you. In order to do that, you need to convert the datetimes into matplotlib's datetime floats using <a ... | python|pandas|matplotlib | 0 |
371,611 | 61,108,578 | model.evaluate() changes results depending on batch size, when fed by generator | <p>Working in colab, with default tensorflow and keras versions (which print tensorflow 2.2.0-rc2, keras 2.3.0-tf )</p>
<p>I've got a superweird error. Basically, the results of model.evaluate() depend on the batch size I'm using and they change after I shuffle the data. Which makes no sense. I've been able to reprodu... | <p>You made a small mistake inside the <code>__getitem__</code> function. </p>
<pre><code>curPat = (patStart+patIdx)
</code></pre>
<p>should be changed to</p>
<pre><code>curPat = (patStart*batchS+patIdx)
</code></pre>
<p><code>patStart</code> is equal to <code>idx</code>, the current batch number. If your data set ... | python|tensorflow|keras|deep-learning | 2 |
371,612 | 61,017,605 | How to redirect tensorboard to my server? | <p>I have a distant computer (A) with a training on tensorflow. I run locally tensorboard on port 30080.</p>
<p>I redirect the port 30080 to my server B so in my computer A I run that command:</p>
<pre><code> ssh -R 30080:localhost:30080 user@mydomain.net
</code></pre>
<p>When I try to reach with my other computer C... | <p>Try adding the option <code>--bind_all</code> while launching the tensorboard.</p> | tensorflow|ssh|tensorboard | 0 |
371,613 | 61,149,788 | Split a cell data into multiple rows in using python | <p>I want to split the data contained in a cell into multiple rows in using python. Such an example is given below:</p>
<p>This is my data:</p>
<pre><code>fuel cert_region veh_class air_pollution city_mpg hwy_mpg cmb_mpg smartway
ethanol/gas FC SUV 6/8 9... | <p>my suggestion is to step out of pandas, do ur computation and put the result back into a dataframe. in my opinion, it is much easier to manipulate, and I'd like to believe faster : </p>
<pre><code>from itertools import chain
</code></pre>
<p><br> Step 1: convert to dict : </p>
<pre><code>M = df.to_dict('records')... | python|pandas|data-analysis | 3 |
371,614 | 61,165,349 | pandas dataframe split values in one row by weights | <p>this seems like a basic question, but an elegant solution is escaping me. </p>
<p>I have a pandas dataframe where all the values have been assigned into one row. However, I need to split values across multiple rows by weights. Example here:</p>
<p>Input dataframe:</p>
<pre><code>import pandas as pd
# starting... | <p>A pure-pandas solution:</p>
<pre><code>df_output = df_input.copy()
df_output.loc[:, 'X1':] = df_output.loc[:, 'X1':].apply(lambda col: col[0] * df_output['W'])
</code></pre>
<p>Or using numpy broadcasting:</p>
<pre><code>df_output = df_input.copy()
df_output.loc[:, 'X1':] = df_output.loc[0, 'X1':].values[None, :]... | python|pandas|dataframe|split|weighted | 2 |
371,615 | 61,063,367 | Does `tf.distribute.MirroredStrategy` have an impact on training outcome? | <p>I don't understand if the <code>MirroredStrategy</code> has any impact on training outcome.</p>
<p>By that, I mean: Is the model trained on a single device the same as a model trained on multiple devices?</p>
<p>I think it should be the same model, because it's just a distributed calculation of the gradients, isn'... | <p>Yes, the model trained on a single GPU and multiple GPUS (on a single machine) is the same. That is, the variables in the model are <a href="https://www.tensorflow.org/guide/distributed_training#mirroredstrategy" rel="nofollow noreferrer">replicated and in sync</a> on all GPU's, as per the documentation.</p> | python|tensorflow|distributed-training | 1 |
371,616 | 60,900,346 | LSTM in PyTorch Classifying Names | <p>I am trying the example presented in <a href="https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html</a> but I am using a LSTM model instead of a RNN. The dataset is composed by diffe... | <p>Lets dig into the solution step by step</p>
<h2>Frame the problem</h2>
<p>Given your problem statement, you will have to use LSTM for making a classification rather then its typical use of tagging. The LSTM is unrolled for certain timestep and this is the reason why input and ouput dimensions of a recurrent models... | python|pytorch|lstm | 5 |
371,617 | 60,940,355 | Is there a Python method for creating a custom convolution? | <p>I'm trying to create an efficient implementation of a totalistic cellular automaton with three possible colors for each cell as in this image from Stephen Wolfram's book, <em>A New Kind of Science</em>:</p>
<p><a href="https://i.stack.imgur.com/pQwnp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co... | <pre><code> a = self.array
i = self.next
window = [1, 1, 1]
row = self.array[i - 1]
correlated_row = np.correlate(row, window, mode="same")
next_row = np.array([self.table[7 - total - 1] for total in correlated_row])
a[i] = next_row
self.next += 1
</code></pre> | python|numpy|cellular-automata | 0 |
371,618 | 60,999,601 | Getting Open, High, Low, Close for 5 min stock data python | <p>I have a DataFrame that contains stock data with the following columns:</p>
<pre><code> time ticker price
0 2020-04-02 09:30:35 EV 33.860
1 2020-04-02 09:00:00 AMG 60.430
2 2020-04-02 09:30:35 AMG 60.750
3 2020-04-02 09:00:00 BLK 455.350
4 2020-04-02 09:30:35 BLK 451.514
... ... ... ...
50... | <p>IIUC, in the <code>groupby</code> you can do it by 'ticker' but also using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="noreferrer"><code>pd.Grouper</code></a> on 'time' with a frequence of 5 minutes. In the <code>agg</code> method, you can use since pandas>0.25 <a hr... | python|pandas|dataframe|finance|stock | 6 |
371,619 | 61,166,318 | Dataframe to PowerBI's json format | <p>I am trying to convert Dataframe data into PowerBI's JSON format. But no luck so far.</p>
<p><strong>DataFrame:</strong></p>
<pre><code> ProductID Name Category IsCompete ManufacturedOn
0 1 Adjustable Race Components true 07/30/2014
1 2 LL Crankarm ... | <p>use pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">to_dict</a> method : </p>
<pre><code>json = {'rows':df.to_dict('records')}
print(json)
{'rows': [{'ProductID': 1,
'Name': 'Adjustable Race',
'Category': 'Components',
'I... | python|json|pandas | 2 |
371,620 | 60,975,174 | how to use different dataframes on train/test split | <p>I have 6 different datasets in 6 different data frames</p>
<p>what I want is to use different datasets each time for the train/ test split. after that, I gonna fit this in an lstm network</p>
<p>so lets df1, df2, df3,df4, df5 in the train set and df6 in the test set</p>
<p>then df1, df2, df3, df4, df6 in the trai... | <p>You can just solve this simple way.</p>
<pre><code>df_list = [df1, df2, df3, df4, df5, df6]
for i in range(6):
train = pd.concat(df_list[0:i] + df_list[i+1:])
test = df_list[i]
# do your training.
</code></pre> | python|pandas|dataframe|machine-learning | 1 |
371,621 | 61,028,834 | Pandas Plot: How to change xlim in datatime format? | <p>The range of date is from 2020-01-30 to 2020-03-31. The format of Date is datetime64[ns].
I want to change the xlim range to (2020-01-30, 2020-03-31), but not working. </p>
<p>My code is as follows:</p>
<pre><code>#Plot left Y
fig, ax1 = plt.subplots()
fig.autofmt_xdate()
x_lim = (datetime.date(2020, 1, 30), dat... | <p>You do set the x-range in your code with <code>xlim=...</code>, and it works fine. But the ticks that matplotlib places on the x-axis by default do not necessarily include the min and max values. To change that, you have to change the ticks, not the range. Pandas' <code>df.plot()</code> wrapper takes an <code>xticks... | python|pandas|matplotlib | 1 |
371,622 | 60,945,485 | Simulate stock price based on a given equation in Python | <p>How can I generate a price time series using the following equation:</p>
<p><strong>p(t) = p0(1+A * sin(ωt +0.5η(t)))</strong></p>
<p>where <strong>t</strong> ranges from <strong>0</strong> to <strong>1</strong> in <strong>1000</strong> time steps, <strong>p0 = 100</strong>, <strong>A = 0.1</strong>, and <strong>ω... | <p>Assuming I haven't missed anything, this should do the trick</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
n_t = np.random.normal(0, 1, 1000)
t = np.arange(0, 1, 1/1000)
p_0, A, w = 100, 0.1, 100
ts = p_0 * (1 + A * np.sin(w * t + 0.5 * n_t))
plt.plot(t, ts)
plt.xlabel("Day")
plt.ylabel("Pric... | python-3.x|numpy|scipy|simulation|scipy.stats | 2 |
371,623 | 60,974,556 | Databricks Koalas fails importing parquet file | <p>I ran into an error when importing parquet file from Azure data lake to databricks.
<a href="https://i.stack.imgur.com/r0frz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0frz.png" alt="enter image description here"></a></p>
<p>I tried other ways like importing parquet as Spark DataFrame succe... | <p>I just found that a column was named like '.<em>_index_.</em>' which caused the confusion for converting. I removed that column and it worked correctly.</p> | python|pandas|pyspark|databricks|spark-koalas | 1 |
371,624 | 61,007,279 | How do I load weighted split tensorflow dataset | <p>I do the weighted split by this code:</p>
<pre><code>half, quarter, quarter2 = tfds.Split.TRAIN.subsplit(weighted = [2, 1, 1])
</code></pre>
<p>After that I try to load the split data by:</p>
<pre><code>dataset = tfds.load('mnist', split=half)
</code></pre>
<p>But I get the error:</p>
<pre><code>AssertionError:... | <p>Alternate solution to your problem was using this type of slicing</p>
<pre><code>import tensorflow_datasets as tfds
s1,s2,s3 = "train[:50]","train[:25]","train[:25]"
dataset= tfds.load('mnist', split=s1)
</code></pre> | python|tensorflow|tensorflow-datasets | 1 |
371,625 | 60,838,718 | Pytorch crashes on input in eval mode | <p>My model trains perfectly fine, but when I switch it to evaluation mode it does not like the data types of the input samples:</p>
<pre><code>Traceback (most recent call last):
File "model.py", line 558, in <module>
main_function(train_sequicity=args.train)
File "model.py", line 542, in main_function
... | <p>The errors seems to be clear: <code>tgt</code> is <code>Float</code>, but it was expecting it to be <code>Long</code>. Why?</p>
<p>In your code, you define that <code>go_tokens</code> is <code>torch.int64</code> (i.e., <code>Long</code>):</p>
<pre class="lang-py prettyprint-override"><code>def forward(self, tgt, m... | python|deep-learning|neural-network|pytorch|transformer-model | 1 |
371,626 | 60,913,479 | DQN Model ValueError: setting an array element with a sequence | <p>(All references to code can be found at <a href="https://github.com/EXJUSTICE/Doom_DQN_GC/blob/master/TF2_Doom_GC_CNN.ipynb" rel="nofollow noreferrer">https://github.com/EXJUSTICE/Doom_DQN_GC/blob/master/TF2_Doom_GC_CNN.ipynb</a>) </p>
<p><strong>Background</strong></p>
<p>I apologize for the length of this post, ... | <p>it's because of the length of lists and it can't have a shape
for example:</p>
<pre><code>np.array( [ [1,2,3],[1,2,3,4],[1,2,3],[1,2] ] ) #this just returns an np array object without shape and this may be your problem. if you print the shape you'll get (4,)
np.array( [ [1,2,3],[1,2,3,4],[1,2,3],[1,2] ], dtype='flo... | python|tensorflow|reinforcement-learning|openai-gym|q-learning | 0 |
371,627 | 60,823,154 | How to combine multiple columns into one long column using python and pandas | <p>Hi everyone I am currently working on data like the following:
<a href="https://i.stack.imgur.com/KHnMg.png" rel="nofollow noreferrer">Example of original data file</a></p>
<p>There are a total of 51 files, each with more than 800 oscillating columns, e.g. (Time, ID, x1, x2, ID, x1, x2,...), the columns are all unl... | <pre><code> with open(os.path.join(working_folder, file_name)) as f:
student_data = []
for line in f:
row = line.strip().split(",")
number_of_results = round(len(row[1:]) / 4) # if we do not count time column, data repeats every 4 times
time_column = row[0]
results = row[1:]
... | python|pandas | 0 |
371,628 | 60,909,478 | FileNotFoundError: [Errno 2] when adding a csv to Jupyter notebook | <p>I just started learning python from linked learning and already stuck. I wanted to import my csv file from my desktop to Jupiter notebook. This is what I had: </p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import os
print(os.getcwd())
pd.read_csv(r"C:\Users\QQM2\Desktop\us_baby_names.cs... | <p>i believe you should assign the file path in a variable like this</p>
<pre><code>file1 = "C:\Users\QQM2\Desktop\us_baby_names.csv"
# then while calling the file you should assign it in a variable as well:
df = pd.read_csv(file1)
# then print it:
print(df.head())
</code></pre> | python|pandas | 0 |
371,629 | 60,995,243 | Multiplying single level dataframe to multilevel dataframe | <p>I have a dataframe <code>df</code> as:</p>
<pre><code>node date_ A1 A2
bkt B1 B2 B1 B2
0 1/1/2015 0.9 1 2 1
1 1/2/2015 0.7 0.6 5 6
2 1/3/2015 0.9 1 9 23
df.columns
Mul... | <p>Yes, you can:</p>
<pre><code>df_out = df.copy()
df_out.loc[:,['A1','A2']] = df.mul(df2, level=1, axis='columns')
</code></pre>
<p>Output:</p>
<pre><code>node date_ A1 A2
bkt B1 B2 B1 B2
0
0 1/1/2015 1.8 1.0 4 1
1 1/2/2015 1.4 1.2 10 ... | pandas|python-3.8 | 3 |
371,630 | 61,144,720 | Add column in a multindex panda dataframe | <p>I have a multi-index data frame and a dictionary. Some keys of this dictionary and some values of the first subcolumn coincide. I want to add a new column with the values of my dictionary In accordance with the query_name values. </p>
<p>Here my dataframe</p>
<pre><code>
S... | <p>You can convert the MultiIndex to a DataFrame with <code>to_frame</code>, select the first level by its label (<code>query_name</code>), and use the dictionary to translate each value via a list comprehension:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
# example data frame, simplified
... | python|pandas | 1 |
371,631 | 61,091,820 | Want to make a for loop for the same data set for different restrictions | <p>I have a data set where I am restricting what rows the data set reads:</p>
<pre><code># Use pandas to read in csv file
data_df_0 = pd.read_csv('data_set.csv')
#create data subsets based on specific buoy coordinates
data_df_1 = pd.read_csv('data_set.csv', skiprows=range(9,114))
data_df_2 = pd.read_csv('data_set.csv'... | <p>Your issue is that Python interprets "data_df_x" as a separate variable--not as "data_df_0" and "data_df_1" like you're wanting it to. </p>
<p>Instead, you can iterate through the dataframes, themselves:</p>
<pre><code>longitudes = []
latitudes = []
for df in [data_df_0, data_df_1]:
lon_x = df['longitude']
... | python|pandas | 1 |
371,632 | 60,795,096 | Are these 2 keras deep learning code the same for multiple outputs? | <p>I've a problem involving airfoil velocity and pressure prediction, given the AOA,x,y. I'm using keras with MLP. I have 3 inputs (AOA,x,y) and I have to predict 3 outputs (u,v,p). I initially have a code which outputs the MSE loss as a single value. However, I modified the code so that I have MSE for each output. How... | <p>I think the difference comes from the optimization objective.</p>
<p>In your old code, the objective was:</p>
<p>sqrt( (u_true - u_pred)^2 + (v_true - v_pred)^2 + (p_true - p_pred)^2 )</p>
<p>which minimizes the 2-norm of the [u_pred,v_pred,p_pred] vector with respect to its target.</p>
<hr>
<p>But in the new o... | python|tensorflow|keras|deep-learning | 0 |
371,633 | 61,079,227 | DataFrame object has no attribute insert | <p>While running this command
<code>dupedWithColsDF = dupedDF.insert(loc=len(dupedDF.columns),
column='lcFirstName',
value=lower(firstName))</code></p>
<p>I get the error: 'DataFrame' object has no attribute 'insert'</p>
<p>Also, I try to insert a... | <p>to add a column to a dataframe you should use withColumn:</p>
<pre><code>df.withColumn('age2', df.age + 2).collect()
[Row(age=2, name='Alice', age2=4), Row(age=5, name='Bob', age2=7)]
</code></pre>
<p>basically you can just do this for the example you posted:</p>
<pre><code>dupedWithColsDF = dupedDF.withColumn("l... | pandas|apache-spark|pyspark | 0 |
371,634 | 60,775,636 | Python: Repeat a 2d array K number of times and transform | <p>I have the 2d array <code>XTM</code> below.</p>
<pre><code>array([[-0.49349673, -0.16749763, 1.09365913, 0.91916602, 0.5942118 ],
[-1.1357679 , -1.06851897, -0.72537699, 0.06350472, 0.1747241 ],
[-0.29972989, -0.3321334 , -1.52296231, -1.41765091, -0.53735561]])
</code></pre>
<p>I have the follo... | <p>One way is using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html" rel="nofollow noreferrer"><code>np.broadcast_to</code></a>, specifying the final shape (<code>a</code> being the input array):</p>
<pre><code>k = 2
out = np.broadcast_to(a, (k, *a.shape))
</code></pre>
<hr>
<pr... | python|numpy | 1 |
371,635 | 60,806,045 | Load only rows into Dataframe Based on searching for sub-string in the row from unstructured format | <p>I have unstructured datasets that use a legacy Java program which are currently loaded based on a specific string within the row that is comma delimited. For example if the row contains "PAT" in one of the columns, then every row that has that string is loaded into a column within a SQL database. This happens for se... | <p>The "in" keyword is great for testing if something is in a data set. Here's an example using the built-in CSV module.</p>
<pre class="lang-py prettyprint-override"><code>import pandas
import csv
with open("data.csv") as csv_file:
reader = csv.reader(csv_file)
keyword = "PAT"
keyword_dataframes = panda... | python|pandas|dataframe | 0 |
371,636 | 60,930,305 | How constant is tf.constant? | <p>According to other StackOverFlow questions, you cannot change <code>tf.constant</code>, but when I do this it runs perfectly:</p>
<pre><code>>>>c = tf.constant([2])
>>>c += 1
>>>print(c)
[3]
</code></pre>
<p>Why is that?</p> | <p>The original <code>c</code> is constant and remains unchanged. You loose reference to it by creating a new tensor with the same name <code>c</code> that equals to the old value of <code>c</code> plus <code>1</code>.</p> | python|tensorflow|tensorflow2.0 | 2 |
371,637 | 61,007,668 | Convert list of xmls into DataFrame | <p>I have a list of xmls, suppose that:</p>
<pre><code> xmls = [
'<note>
<to>John</to>
<from>Janet</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>',
'<note>
<to>Tom</to>... | <p>You can use <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree" rel="nofollow noreferrer"><code>xml.etree.ElementTree</code></a> module. First, Iterate through the XML list and Parse the required fields. Then, construct a dictionary with keys as column name and values ... | python|xml|pandas | 1 |
371,638 | 61,174,349 | Casting a string tensor to a list of string | <p>How could someone cast the following string tensorflow tensor:</p>
<pre class="lang-py prettyprint-override"><code><tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'example string 1',
b'example string 2',
b'example string 3',
...
b'example string 63',
b'example string 64... | <p>Just use <code>list(tensor.numpy())</code>. Example:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
n_strings = 8
t = tf.convert_to_tensor(['example string ' + str(i) for i in range(n_strings)])
t
# <tf.Tensor: shape=(8,), dtype=string, numpy=
# array([b'example string 0', b'example... | python|tensorflow | 3 |
371,639 | 61,063,980 | How skip to another loop in python if no data returned by the API? | <p>I have a python code that loops through multiple location and pulls data from a third part API. Below is the code <code>sublocation_ids</code>are location id coming from a directory. </p>
<p>As you can see from the code the data gets converted to a data frame and then saved to a Excel file. The current issue I am f... | <p>Change this bit of code:</p>
<pre><code>df = articles_list_normalized
if 'publication_timestamp' in df.columns:
df['publication_timestamp'] = pd.to_datetime(df['publication_timestamp'])
df['publication_timestamp'] = df['publication_timestamp'].apply(lambda x: x.now().strftime('%Y-%m-%d'))
df.to_excel(wr... | python|python-3.x|pandas|api|dataframe | 3 |
371,640 | 60,825,554 | How to generate a sequence of numbers when encountered a value in python pandas dataframe | <p><a href="https://i.stack.imgur.com/f92mo.jpg" rel="nofollow noreferrer">sample and expected data</a></p>
<p>The block one is current data and block 2 is the expected data that is, when i encounter 1 i need the next row to be incremented by one and for next country b same should happen</p> | <p>First replace all another values after first <code>1</code> to <code>1</code>, so is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum</code></a>:</p>
<pre><code>df = pd.DataFrame({'c':['a']*3 + ['b... | python|pandas|dataframe | 0 |
371,641 | 61,014,208 | Tensorflow audio features extraction process won't run | <p>I am trying to build my own audio TF dataset using some documentation from <a href="https://github.com/devicehive/devicehive-audio-analysis" rel="nofollow noreferrer">devicehive</a> project. I have two PC machines, the same exact project works on one, but it doesn't work on the other! It gives a warning about TF th... | <p>I solved it!
It turned out that I missed placing "/" the slash at the end of my wav folder path!
That's all!</p> | python-3.x|tensorflow|feature-extraction|tf.keras | 0 |
371,642 | 61,178,230 | Nested json object column into dataframe | <p>I have a dataframe(df1) containing two columns.</p>
<pre><code>id information
00100 {'DriversList': {'ProblematicDrivers': [], 'In...
00200 {'DriversList': {'ProblematicDrivers': [], 'In...
</code></pre>
<p>The information column contains nested json object, which needs to be converted int... | <p>IIUC, this is a possible approach:</p>
<pre><code>import json
import pandas as pd
# setup
d = """{"DriversList": {
"ProblematicDrivers": [],
"InstalledDrivers": [
{"DriverName": "FaxMachine", "DisplayName": "Fax", "Version": "10", "Date": "06-21-2006"},
{"DriverName": "FaxMachine", "Display... | python|json|pandas|dataframe | 2 |
371,643 | 60,859,324 | How to avoid empty set in pandas's concate and to_csv function? | <p>I have a dictionary to be stored in csv through pandas:</p>
<pre><code>df = pd.concat([pd.Series(node_dict[k], name=k) for k in HEADERS], 1)
df.to_csv(os.path.join(abspath, outputfile), sep='\t', index=False)
</code></pre>
<p>The keys correspond to the columns in the CSV or pandas frame, and the values are a list ... | <p>I think you can do something like:</p>
<p><code>node_dict = {k: [x if x else "invisible" for x in v] for k,v in node_dict.items()}</code></p>
<p>prior to doing <code>[pd.Series(node_dict[k], name=k) for k in HEADERS]
</code> </p> | python|pandas | 0 |
371,644 | 60,767,730 | How to parse guess_language to read 30000 tweets? | <p>I am using <a href="https://bitbucket.org/spirit/guess_language/src/default/" rel="nofollow noreferrer">guess_language</a> to detect the language of the tweets for a school project. I used pandas to read the .csv file. I have around 30000 rows.</p>
<p>However, my problem is that the guess language can only read one... | <p>You can fetch every and process them basically like this</p>
<pre><code>resdf = newdf[ newdf['text'].apply(guess_language) == 'en' ]
</code></pre>
<p>the resdf should contain the rows of the original that had a classification of english for its tweets.</p>
<p>The function <code>apply</code> should apply your f... | python|pandas|nltk | 0 |
371,645 | 60,981,589 | Trying to run TensorBoard for the First Time | <p>I did some research on TensorFlow today and hacked together the code below. Basically, I'm trying to run TensorFlow from Spyder (not from the cmd line in Anaconda). I think that's possible, right. So, I ran the code below (select all code and hit F9 key) and it runs fine in Spyder, but when I try to view some/any... | <p>You need to run the TensorBoard callback as follows: </p>
<pre><code>tensorboard_cb = tf.keras.callbacks.TensorBoard(
os.path.join(args.job_dir, 'keras_tensorboard'),
histogram_freq=1)
keras_model.fit(
...
callbacks=[tensorboard_cb])
export_path = os.path.join('/tmp/', 'keras_expor... | python|python-3.x|tensorflow|tensorflow2.0 | 1 |
371,646 | 61,037,986 | Trouble with the output of a for loop? | <p>I'm trying to write a piece of code that proves that two anonymized columns do not show the same information. My original hypothesis was that where <code>A4</code>== 'u' that <code>A5</code> would then equal 'g'.</p>
<p>After running this for loop, the output gave me heaps of pairs of other variables i.e. 'u' paire... | <p><em>IIUC: You can use <code>np.where</code> to generate the mask to filter the columns where <code>A4</code> is <code>u</code> and <code>A5</code> is other than <code>g</code>.
You can use this:</em></p>
<pre><code>import numpy as np
mask = np.where((crx_data["A4"] == "u") & (crx_data["A5"] != "g"), True, Fals... | python|pandas | 2 |
371,647 | 60,947,708 | Iterate and update pandas dataframe simultaneously | <p>I have a dataframe containing <code>Level, Product ID and Cost</code>.
Here <code>Level 1</code> indicates it is a main product and <code>Level 2</code> indicates it is a sub-product and further increase in Level indicates multiple sub-products of a sub-product.</p>
<pre><code> Level Product ID Cost
0 1 ... | <p>Here are the directions for something like this. Take the product ID and turn it into a string. Put character 1 of the product ID into it's own column "pid1" do the same for the 2nd character "pid2" and "pid3" for the 3rd, as well as "pid4" (N-1 columns)</p>
<pre><code>df.groupby(['pid1','pid2','pid3','pid4']).a... | python|python-3.x|pandas|dataframe | 0 |
371,648 | 61,065,853 | Python: Using Imported Tables (.txt files) and Editing For Certain Values to be Omitted | <p>I have a .txt file with a table as such:</p>
<p>Object Size Quantity</p>
<p>1 2 3</p>
<p>2 10 3</p>
<p>3 4 1</p>
<p>4 5 2</p>
<p>5 12 1</p>
<p>6 6 2</p>
<p>7 17 4</p>
<p>8 19 2</p>
<p>9 9 3</p>
<p>10 14 2</p>
... | <p>Besides @Mark Meyer's comment/answer, this is my approach in Python. </p>
<pre><code>with open('sample.txt','r') as f:
c = f.readlines()
c = [ x.strip('\n').split() for x in c[2:] if x.strip('\n') !='']
# Assign elements to a list [['1', '2', '3'], ['2', '10', '3'] ...
min_number = 10 # ciriteria
c =... | python|numpy | 0 |
371,649 | 61,049,245 | Python datetime problem converting time format | <p>I would like to convert the following time format which is located in a panda dataframe column </p>
<pre><code>100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
</code></pre>
<p>I would like to transform the previous time format into a standard time form... | <p>This will give you a df with a datetime64[ns] and object dtype column for your data:</p>
<pre><code>import pandas as pd
df = pd.read_csv('hm.txt', sep=r"[ ]{2,}", engine='python', header=None, names=['pre'])
df['pre_1'] = df['pre'].astype(str).str.replace('00', '')
df['datetime_dtype'] = pd.to_datetime(df['pre_1... | python|pandas|datetime | 0 |
371,650 | 61,009,092 | AttributeError: partially initialized module 'pandas' has no attribute 'DataFrame' | <p>i want to run this code but i can't and received this error.
also i downloaded pandas package.</p>
<pre class="lang-py prettyprint-override"><code>import pandas
data = {
"Day": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Visitors": [18, 26, 18, 18, 9, 9, 20, 30, 16, 24],
"Bounce_Rate": [77.27, 74.07, 73.68, 65, ... | <p>Have you have saved your file as <code>pandas.py</code>? It will confuse the <a href="https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces" rel="noreferrer">namespace</a> if the file is named <code>pandas.py</code>
Otherwise check if there is any file named pandas and delete it. So that you c... | python|pandas|attributeerror | 18 |
371,651 | 60,919,087 | Filtering in pandas by index - Keyerror | <p>I am trying to filter in Pandas for a selected period. (picture added) The start and the end date is to be entered in an input box. </p>
<p>"Day" is found in the index column, however the third line gives an error message. </p>
<pre><code>df = pd.read_excel('prices.xlsx', index_col=0)
df.iloc[::-1]
filtered_date =... | <p>Look at the picture of your DataFrame:</p>
<ul>
<li>All names of "regular" columns are located a bit higher.</li>
<li>"Day" is located a bit lower and it indicates that it is the name of
the <strong>index</strong> column.</li>
</ul>
<p>Your code contains <em>df['Day']</em>, so you attempt to reference a <strong>re... | python|pandas|keyerror | 2 |
371,652 | 60,994,780 | How can I combine the Index in the python dataframe? | <p>in the following, can I make a single index for all the entries with common index.</p>
<pre><code>cric = pd.Series(['India', 'Pakistan', 'South Africa', 'England', 'New Zealand'],
index = ['Cricket', 'Cricket', 'Cricket', 'Cricket', 'Cricket'])
ftbl = pd.Series(['England', 'South Africa', 'Austral... | <p>If, by single index, you mean an index made of autoincrementing numbers, there is nothing special you have to do. That is the default index for a DataFrame, so using the <code>reset_index()</code> method will get what you want. The next step will probably be to rename your index column. You can chain that method wit... | python|pandas | 1 |
371,653 | 60,787,563 | TypeError: can't convert expression to float, with symbolic x, polynomial interpolation | <p>I'm trying to run the following code but an error appears at the line with <code>S[i][0]</code>.</p>
<blockquote>
<p>TypeError: can't convert expression to float</p>
</blockquote>
<p>I'm am sure that my variables <code>D[][]</code>, <code>h[]</code>, <code>age[]</code>, <code>A[]</code>, <code>B[]</code> and <co... | <p>The problem is that while most of your variables are floats, <code>x</code> is symbolic, which causes all of those calculations in the end to be a symbolic object. Such objects are handled at python-level with classes, while numpy requires numbers, so it tries to apply <code>float()</code> to it. For example,</p>
<... | python|numpy|sympy | 0 |
371,654 | 60,973,164 | Pandas to_datetime ignore the format | <p>I was trying to convert a date stored in my dataframe to DateTime format. The column i'm trying to convert has dates stored in <strong>mm/dd/yy</strong> format.</p>
<p>This is the script i used to convert:</p>
<pre><code>df['dt'] = pd.to_datetime(df['dt'], format = '%d-%m-%Y')
</code></pre>
<p>The script runs wit... | <p>Consider the date <code>1-2-2020</code>. Now just by looking at the date can you say exactly what date it is? The answer is no, because, unless you know how the date is formatted or how the date was created i.e whether Day-Month-Year or Month-Day-Year, you can't really say whether the above date is <code>1st Februar... | python|pandas|string-to-datetime | 0 |
371,655 | 60,768,583 | Pytorch w/ GPU on Docker Container Error - no CUDA-capable device is detected | <p>I am trying to use Pytorch with a GPU on my Docker Container.</p>
<p><strong>1. On the Host -</strong>
I have nvidia-docker installed, CUDA Driver etc</p>
<p>Here is the nvidia-smi output from host:</p>
<pre><code> Fri Mar 20 04:29:49 2020
+--------------------------------------------------------------... | <p>It needs <code>runtime</code> options, but well, the runtime option is not available at compose file format 3. So there's some options</p>
<ol>
<li>Downgrade your compose file version to 2, so something like this :</li>
</ol>
<pre><code>version: 2
backend:
build: ./app
ports:
- "5000:5000"
volum... | python|docker|pytorch | 1 |
371,656 | 60,887,128 | How to convert SQL Oracle Database into a Pandas DataFrame? | <p>I am trying to get a Oracle SQL database into python so I can aggregate/analyze the data. Pandas would be really useful for this task. But anytime I try to use my code, it just hangs and does not output anything. I am not sure its because I am using the cx oracle package and then using the pandas package? </p>
<pre... | <p>To convert a cx_Oracle cursor to dataframe you can use de following code.</p>
<pre><code>with conn.cursor() as cursor:
cursor.execute("SELECT * FROM data WHERE date like '%20%'")
from pandas import DataFrame
df = DataFrame(cursor.fetchall())
df.columns = [x[0] for x in cursor.description]
print(... | python|sql|pandas|oracle|performance | 1 |
371,657 | 60,896,619 | Problem with concatenating a series to a DataFrame along axis=1 (Pandas) | <p>I am having a little problem with <code>pandas.concat</code></p>
<p>Namely, I am concatenating a dataframe with 3 series. The 1 dataframe and 2 of the series are concatenating as expected. One series, however is being attached to the bottom of my new data frame instead of as a column.</p>
<p>Here is my minimal wor... | <p>Check <a href="https://stackoverflow.com/questions/38256104/differences-between-merge-and-concat-in-pandas">this</a> out. Did you try to change from <code>concat</code> to <code>merge</code>?</p> | python|pandas | 0 |
371,658 | 60,917,823 | Finding product count respect to old history with pandas | <p>Good Evening there, hope everyone is fine and safe from Corona.
I have two Csv files. history.csv --> contain products and customerId, other CSV customers.csv contain all customerId present in history.csv. I want to find how many times a product is bought by each customer? For example:</p>
<pre><code>product 3344 i... | <p><strong>Sample df</strong></p>
<pre><code>print(df)
products customerId
0 27845 22986
1 39275 142175
2 43251 200540
3 42900 69496
4 21472 178294
5 37067 150285
6 4945 205945
7 17333 47461
8 38739 123967
9 46979 ... | python-3.x|pandas | 0 |
371,659 | 71,764,848 | Pandas Create dataframe from Key Value pair dictionary | <p>Assume I have a dictionary in the following format:</p>
<pre><code>{
"model1": 0.5,
"model2": 0.6,
"model3": 0.7
}
</code></pre>
<p>How would I load it into a pandas dataframe such that it has the following structure:</p>
<div class="s-table-container">
<table class="s-table">
... | <p>Check the doc of <code>from_dict</code> <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer">here</a></p> | pandas | 0 |
371,660 | 71,661,932 | I want to find the time-displacement curve through inverse fast Fourier transform | <pre><code>import numpy as np
import matplotlib.pyplot as plt
N=1000; T=10; dt=T/N
t=np.arange(0,N*dt,dt)
#system properties
wn = 4 * np.pi
w=0.2*wn
Tn = 2*np.pi/wn
fn = 1/Tn
m = 1
Z = 0.05
k = wn*wn * m
c = 2*m*wn*Z
######################################################
P = np.sin(wn * t)
#Frequency response
L = l... | <p>The <code>plt.plot()</code> function is just complaining that <code>t</code> and <code>ut</code> do not have the same length.</p>
<p>This line <code>Pf = Pf[range(int(L/2))]</code> takes <code>Pf</code> from an array of length <code>N</code> to <code>N/2</code>. This affects <code>Uf</code> and consequently <code>ut... | python|numpy|fft | 0 |
371,661 | 71,503,683 | Pytorch loss is nan | <p>I'm trying to write my first neural network with pytorch.
Unfortunately, I encounter a problem when I want to get the loss.
The following error message:</p>
<pre><code>RuntimeError: Function 'LogSoftmaxBackward0' returned nan values in its 0th output.
</code></pre>
<p>So I tried debugging and found something strange... | <p>Sorry, my reputation is not enough for me to comment directly. This may be caused by the exploding gradient due to the excessive learning rate. It is recommended that you reduce the learning rate or use weight_decay.</p> | python|pytorch | 2 |
371,662 | 71,733,808 | generating continuous 'id' field in a column for all dataframes where I have a list of data frames | <p>I have a list of 4/5 data frames with a blank column 'id', I want to generate a cumulative sequence across these data frames.</p>
<p>I tried something like this but its not working.
f is my list of data frames</p>
<pre><code>for i in range(1,len(f)):
print(f[1]['id'])
for row in f[i]['id']:
f[i]=f[... | <p>A simple loop approach could be:</p>
<pre><code>dfs = [df1, df2]
start = 0
for d in dfs:
stop = start + len(d)
d['id'] = range(start, stop)
start = stop
</code></pre> | python|pandas|list|dataframe|sequence | 0 |
371,663 | 71,540,594 | Transform list in a dataframe (breaking elements by interval of rows) | <p>I'm trying to append a list to a dataframe in Python
I want to put the first 6 numbers on the same line and then add it line by line, until complete the dataframe.
<em>I tried to generate the data to make it easier:</em></p>
<pre><code>import pandas as pd
import random
randomlist = []
for i in range(0,30):
n = ... | <p>You need to firstly reshape your list and afterwards give the arguments to the dataFrame. This should work:</p>
<pre><code>import pandas as pd
import numpy as np
randomlist = [30, 11, 18, 11, 28, 18, 22, 18, 20, 10, 11, 6, 29, 1, 11, 15, 3, 4, 17, 11, 17, 18, 27, 25, 11, 10, 7, 4, 18, 27]
lista_colunas = ['Carro',... | python|pandas|dataframe | 0 |
371,664 | 71,758,525 | How to group same words in dictionary in Pandas? | <p>I have a German to English dictionary with multiple entries for some words. I want to group those entries such that the English translations for the same german word are separated by a comma.</p>
<p>I have the following dataframe:</p>
<pre><code>Deutsch Englisch
spindeldürr spindly
Garn {n}... | <p>Try <code>groupby</code>:</p>
<pre><code># Old versions of Pandas
>>> df.groupby('Deutsch', sort=False)['Englisch'].agg(', '.join).reset_index()
# Newer versions
>>> df.groupby('Deutsch', sort=False, as_index=False)['Englisch'].agg(', '.join)
Deutsch ... | python|pandas | 1 |
371,665 | 71,769,444 | Python Pandas replace NaN with data from another row | <p>I have two dataframes. Dataframe A contains course information, including the ISBN number for required textbooks:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Course Abbreviation</th>
<th>Course Number</th>
<th>Section Number</th>
<th>Course Name</th>
<th>Course Instructor</th>
<th>Co... | <p>Sorting by <code>ISBN No</code> will push the nulls to the bottom, then you can groupby title and ffill the data.</p>
<pre><code>df.sort_values(by='ISBN No').groupby('Title').ffill()
</code></pre> | python|pandas|dataframe|merge | 0 |
371,666 | 71,735,232 | Cumulative Value summed up with first entry of a column with groupby | <p>I have got the following dataframe:</p>
<pre><code>lst=[['01012021','A',100,'NaN'],['01012021','B',120,'NaN'],['01022021','A',140,5],['01022021','B',160,12],['01032021','A',180,20],['01032021','B',200,25]]
df1=pd.DataFrame(lst,columns=['Date','FN','AuM','NNA'])
</code></pre>
<p>I would like to generate a new column ... | <p>Sum values from <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum</code></a> and first values per groups by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy... | python|pandas|jupyter|point|addition | 1 |
371,667 | 71,777,675 | use Pandas to drop values from csv | <p>I have a csv that I want to use to search an api for data, but the row which stores the data used for the api search can contain a second value separated by <code>;</code>
like this:</p>
<pre><code>2 Jan Rohls Kunst und Religion zwischen Mittelalter und Barock : von Dante bis Bach -
3 Karl-Markus Ritter Der Dom z... | <p>Try this, split by seperator and keep wanted split:</p>
<pre><code>data['ISBN'] = [x.split(' ')[0] for x in data['ISBN']] #keeps first portion of split.
</code></pre> | python|python-3.x|pandas|csv | 1 |
371,668 | 71,689,793 | Efficient way to create np array based on values in data frame | <p>I have a data frame with N rows containing certain information. Depending on the values in the data frame, I want to create a numpy array with the same number of rows but with M columns.</p>
<p>I have a solution where I iterate through the rows of the data frame and apply a function, which outputs me a row for the a... | <p>See Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby()</a> to group depending on M and than extract.</p> | python|pandas|numpy | 0 |
371,669 | 71,479,852 | How to expand a numpy vector n times into an 2d array with its own values | <p>With numpy, say you have a vector like:</p>
<pre><code>array([1, 2, 3])
</code></pre>
<p>How do you extend it n times with its own values? E.g.:</p>
<pre><code>array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre> | <p>You can use <code>numpy.tile</code>:</p>
<pre><code>a = np.array([1, 2, 3])
N = 3
b = np.tile(a, (N,1))
</code></pre>
<p>or <code>numpy.vstack</code>:</p>
<pre><code>N = 3
b = np.vstack([a]*N)
</code></pre>
<p>output:</p>
<pre><code>array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre> | numpy | 2 |
371,670 | 71,683,375 | how to append columns in dataframe | <p>I have a dataframe like this,</p>
<pre><code>data = {'first_column': ['first_sentence', 'second_sentence'], 'second_column': ['A', 'B'], 'third_column' : ['C', 'D'] }
</code></pre>
<p>The original structure like this</p>
<blockquote>
<p>first_column second_column third_column</p>
<p>first_sentence ... | <p>Use <code>set_index</code> before <code>stack</code>:</p>
<pre><code>out= df.set_index('first_column').stack().droplevel(1).rename('column').reset_index()
print(out)
# Output
first_column column
0 first_sentence A
1 first_sentence C
2 second_sentence B
3 second_sentence D
</code></pr... | python-3.x|pandas|dataframe | 0 |
371,671 | 71,570,653 | styleframe.ExcelWriter's date_format and datetime_format is not work~ | <p>Today I use styleframe to help beautify my Excel.</p>
<p>While I add the date_format or datetime_format, it's not work.</p>
<pre class="lang-py prettyprint-override"><code>def _write_xlsx(self, filename, data, columns):
print(f'Writing {filename} length: {len(data)}')
data_frame = pandas.DataFrame(data, col... | <p><code>styleframe</code> uses <a href="https://styleframe.readthedocs.io/en/latest/styler.html" rel="nofollow noreferrer"><code>Styler</code></a> objects to represent and apply styles. It can specify different formats for <code>date</code>, <code>time</code> and <code>datetime</code> objects.</p>
<p>See this example:... | python|pandas|styleframe | 0 |
371,672 | 71,700,439 | How do I return the column title of a cell, combine it with another value and store it in a new dataframe? | <p>I have a dataframe with which if a cell has a value other than "." then I need python to return the cell's column title and the campus number.
<img src="https://i.stack.imgur.com/Vtc77.png" alt="Here is an example of the dataframe" /></p>
<p>The end result should be a new dataframe or list that contains th... | <p>Reducing the dimensionality of the problem by stacking makes it easier as you can then simply query the index.</p>
<pre><code>temp = df.set_index('Campus').stack()
result_list = temp.loc[temp!='.'].index.values
</code></pre> | python|pandas | 0 |
371,673 | 71,555,321 | sklearn.preprocessing.OneHotEncoder and the way to read it | <p>I have been using one-hot encoding for a while now in all pre-processing data pipelines that I have had.</p>
<p>But I have run into an issue now that I am trying to pre-process new data automatically with flask server running a model.</p>
<p>TLDR of what I am trying to do is to search new data for a specific Date, r... | <p>IIUC, use <code>get_feature_names_out()</code>:</p>
<pre><code>import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 1, 0],
'C': [0, 2, 2], 'D': [0, 1, 1]})
ohe = OneHotEncoder()
data = ohe.fit_transform(df)
df1 = pd.DataFrame(data.toarra... | python|pandas|scikit-learn | 1 |
371,674 | 71,465,186 | Why the output from `__call__` and `predict` of transformers's BERT model are different? | <p>When playing with huggingface's transformers with tensorflow, I got different results from <code>__call__</code>, <code>call()</code> and 'predict', but I think they should be the same.</p>
<p>With transformers, Which one gives me the right result during training/inferencing?</p>
<p>I am using transformers 4.17.0 wi... | <p>I post the same question on GitHub and got a great response from transformers team.</p>
<p>Generally, while training=True, the output should be different since there are dynamics in it(dropout).
when calling with <code>model.predict</code>,<code>encoded_input.values()</code> will give a wrong sequence, the correct o... | tensorflow|huggingface-transformers|bert-language-model | 0 |
371,675 | 71,503,428 | Fixing TypeError: unsupported format string passed to numpy.ndarray.__format__ | <p><a href="https://i.stack.imgur.com/8s1dr.png" rel="nofollow noreferrer">trying to print a loop over x for values of q, but keep getting this syntax error. Can anyone help with this?</a></p> | <p>Because it's a vector/array, not a single value. You may try the following:</p>
<pre class="lang-py prettyprint-override"><code>np.set_printoptions(precision=2)
print(f'x = {x} -> q = {q}')
</code></pre>
<p>You could also take a look at <a href="https://numpy.org/devdocs/reference/generated/numpy.array2string.htm... | for-loop|numpy-ndarray | 1 |
371,676 | 71,732,854 | Where does Pandas store metadata info? | <p>Where does pandas store its metadata information?
For eg. if pandas.dataframe.info() is executed, it returns the metadata information.</p>
<p>Where is this metadata getting stored? or do Pandas generate it dynamically without storing anywhere?
Also, if it is getting stored, how to find the memory usage the metadata ... | <p>It is not stored, it is computed on demand.</p>
<p>This is done by <code>DataFrameInfo</code>, you can check the source of <a href="https://github.com/pandas-dev/pandas/blob/v1.4.2/pandas/io/formats/info.py" rel="nofollow noreferrer">pandas.io.formats.info</a></p> | pandas|metadata | 1 |
371,677 | 71,604,868 | How to get the unscaled regression coefficients errors using statsmodels? | <p>I'm trying to compute the coefficient errors of a regression using statsmodels. Also known as the standard errors of the parameter estimates. But I need to compute their "unscaled" version. I've only managed to do so with NumPy.</p>
<p>You can see the meaning of "unscaled" in the docs: <a href="h... | <p>statsmodels documentation is not well organized in some parts.
Here is a notebook with an example for the following
<a href="https://www.statsmodels.org/devel/examples/notebooks/generated/chi2_fitting.html" rel="nofollow noreferrer">https://www.statsmodels.org/devel/examples/notebooks/generated/chi2_fitting.html</a>... | python|numpy|regression|statsmodels | 0 |
371,678 | 71,764,027 | Numpy installation fails when installing with Poetry on M1 and macOS | <p>I have a Numpy as a dependency in Poetry <code>pyproject.toml</code> file and it fails to install.</p>
<pre><code> error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly
error: Command "clang -Wno-unused-result -Wsign-compare -Wunreachable-cod... | <p>Make sure you have OpenBLAS installed from Homebrew:</p>
<pre><code>brew install openblas
</code></pre>
<p>Then before running any installation script, make sure you tell your shell environment to use Homebrew OpenBLAS installation</p>
<pre class="lang-sh prettyprint-override"><code>export OPENBLAS="$(brew --pr... | python|numpy|python-poetry | 10 |
371,679 | 71,723,214 | Trying to Generate an NFT Using .CSV Metadata and Pandas | <p>I have been scratching my head at generating my actual NFT's from a .csv file for a long time and looking for resources has been challenging at the very least for my Hardcoding Method (Following a Guide) If Anyone could Look through what I have and Offer some Help Figuring out what's going on I would be FOREVER End... | <p>Change:</p>
<pre><code>index_list = aData[(aData['Background'] == checkRow[2])] & (aData['Accessories'] == checkRow[3]) & (aData['Head'] == checkRow[4]) & (aData['Hat'] == checkRow[5]) & (aData['Body'] == checkRow[6]) &(aData['Chest'] ==checkRow[7]) & (aData['Arms'] ==checkRow[7]) & (aDat... | python|python-3.x|pandas | 0 |
371,680 | 71,477,766 | PyTorch normalization in onnx model | <p>I am doing image classification in pytorch, in that, I used this transforms</p>
<p><code>transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])</code></p>
<p>and completed the training. After, I converted the .pth model file to .onnx file</p>
<p>Now, in inference, how should I apply this transforms in nu... | <p>You can apply the same <code>transforms</code> to np.array, for <a href="https://pytorch.org/tutorials/intermediate/realtime_rpi.html#image-preprocessing" rel="nofollow noreferrer">example</a>.</p> | python|neural-network|pytorch|onnx|onnxruntime | 0 |
371,681 | 71,727,655 | Ordinal Encoder with Specific order include NAN | <p>Let say that I have this example dataset</p>
<pre><code>test = {'Education': ['High School', 'Uneducated', 'Graduate', 'College', np.nan, 'High School'],
'Gender': ['M', 'F', 'M', 'F', 'M', 'F']}
</code></pre>
<p>and the outcome will be like this, right</p>
<pre><code> Education Gender
High School M... | <p>Never mind, I got it by myself</p>
<pre><code>edu = ['Uneducated','High School', 'College', 'Graduate']
oe_edu = OrdinalEncoder(categories=[edu], handle_unknown='use_encoded_value', unknown_value=np.nan)
test['Education'] = oe_edu.fit_transform(test[['Education']])
</code></pre> | python|pandas|scikit-learn|nan|ordinal | 1 |
371,682 | 71,543,473 | Linear sum assignment (SciPy) and balancing the costs | <p>I am having difficulty using <code>scipy.optimize.linear_sum_assignment</code> to evenly distribute tasks (costs) to workers, where each worker can be assigned multiple tasks. The cost matrix represents the workload of each task for each worker.</p>
<p>We want to minimize the total costs of all workers, while evenly... | <p>The <code>linear_sum_assignment</code> method doesn't support constraints or a custom objective, so I don't think this is possible.</p>
<p>However, you could formulate your problem as a mixed-integer linear programming problem (MILP) and solve it by means of <a href="https://coin-or.github.io/pulp/" rel="nofollow no... | python|numpy|optimization|scipy|assignment-problem | 2 |
371,683 | 71,714,857 | Input and Output to the lstms in pytorch | <p>I want to implement lstms with CNN in pytorch as my data is a time series data i.e. frames of video for heart rate detection, I am struggling with the input and output dimensions for lstms what and how i should properly configure the dimensions/parameters/arguments at input of lstms in pytorch as its quite confusing... | <p>Generally, the input shape of sequential data takes the form <code>(batch_size, seq_len, num_features)</code>. Based on your explanation, I assume your input is of the form <code>(2, 256)</code>, where 2 is the batch size and 256 is the sequence length of scalars (1-dimensional tensor). Therefore, you should reshape... | deep-learning|pytorch|lstm|recurrent-neural-network | 1 |
371,684 | 71,689,876 | sliding window on a tensor | <p>I'm trying to build a simple word generator. However, I encounter some difficulty with the sliding windows.</p>
<p>here is my actual code:</p>
<pre><code>files = glob("transfdata/*")# a list of text files
dataset = tf.data.TextLineDataset(files) # all files are one line
dataset = dataset.map(lambda x: tf.... | <p>Try using <code>tensorflow-text</code>, it has a decent sliding window <a href="https://www.tensorflow.org/text/api_docs/python/text/sliding_window" rel="nofollow noreferrer">function</a>:</p>
<pre><code>import tensorflow as tf
import tensorflow_text as tft
with open('data.txt', 'w') as f:
f.write('How are we goi... | python|tensorflow|tensorflow2.0|tensor|tensorflow-datasets | 2 |
371,685 | 71,746,996 | Convert columns into rows with Pandas for daily data | <p>So my dataset CSV looks like</p>
<p><a href="https://i.stack.imgur.com/JSiKs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JSiKs.png" alt="enter image description here" /></a></p>
<p>What I would like is for it to look like</p>
<p><a href="https://i.stack.imgur.com/NJSHd.jpg" rel="nofollow noref... | <p>You can first remove unnecessary column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a> and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.set_index.html" rel="nofo... | pandas | 0 |
371,686 | 71,766,006 | I have 12 pd dataframes , i want to extract one column from each and pass as new df and rename based on source df | <p>**I need to extract "adj close" from all into a new DF and rename based on source and map based on Date</p>
<p>new_DF = date AAL AAPL ALK .....(containing adj close)
please help**</p>
<p>AAL = pd.read_csv("AAL.csv")</p>
<p>AAPL = pd.read_csv("AAPL.csv")</p>
<p>ALK = pd.read_csv("A... | <p>Try this:</p>
<pre><code># load csv data
# define relative path to folder containing csv data
files_folder = '/path/to/csv/'
# load all csv files in one dataframe
df_list = []
for file in glob.glob(os.path.join(files_folder, '*.csv')):
df = pd.read_csv(file)
# write here column you want to select
df_col... | python|pandas|dataframe|csv | 1 |
371,687 | 71,574,066 | 2 different specified elements from 2 numpy arrays | <p>I have two numpy arrays with 0s and 1s in them. How can I find the indexes with 1 in the first array and 0 in the second?</p>
<p>I tried np.logical_and</p>
<p>But got error message (builtin_function_or_method' object is not subscriptable)</p> | <p>Use <code>np.where(arr1==1)</code> and <code>np.where(arr2==0)</code></p> | python|numpy | 3 |
371,688 | 71,773,515 | Importing Keras for a CNN | <p>I am getting a TypeErrir due to the added layer, BatchNormalization, not being the same as the class layer. I'm unsure why, I've tried to correctly import the layers, and have tried multiple different ways.</p>
<p>My imports are currently:</p>
<pre><code>import copy
import numpy as np
import pandas as pd
from sklear... | <p>You are almost there. Batchnorm is a class so you need to instantiate it by adding <code>()</code></p>
<pre><code>model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(BatchNormalization())
</code></pre> | python|python-3.x|tensorflow|keras|deep-learning | 1 |
371,689 | 71,567,484 | Pandas - compare index and column between excel and dataframe to enter value | <p>I have a dataframe like as given below</p>
<pre><code>ID,DIV,APP1,APP2,APP3,Col1,Col4
1,A,AB1,ABC1,ABCD1,20,40
2,A,AB1,ABC2,ABCD2,60,
3,B,BC1,BCD1,BCDE1,10,20
region_1 = pd.read_clipboard(sep=',')
region_1.set_index(['ID','DIV','APP1','APP2','APP3'],inplace=True)
</code></pre>
<p>And I have an excel file like as b... | <p><strong><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>DataFrame.fillna</code></a></strong> can accept an entire DataFrame of filler values, in which case it fills missing values by matching the row/column labels.</p>
<p>So, create an empty DataFra... | python|excel|pandas|dataframe|xlwings | 2 |
371,690 | 71,546,493 | TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid I got this error | <p>giving a unique code by seeing the first column string and the second columns string and whenever the first column string change it starts from 1</p>
<p>Example
<a href="https://i.stack.imgur.com/RMdfm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RMdfm.png" alt="enter image description here" />... | <p>It is not very clear what you expect, but when you write <code>df[1] for df in dfs</code>, then your <code>df</code> is a key (for example <em>Kebele 1</em>) and <code>df[1]</code> is a character (for example <em>e</em> - second character of the string).</p>
<p>That is why you get this error, because your array <cod... | python|pandas|dataframe|numpy | 1 |
371,691 | 71,557,228 | Folium-ChoropletMap issues with key_on: does not overlay the choroplet map | <p>I have a strange issue with the following piece of code:</p>
<pre><code> m10=folium.Map(location=[41.9027835,12.4963655],tiles='openstreetmap',zoom_start=5)
df.reset_index(inplace = True)
folium.Choropleth(
geo_data = df.to_json(),
data = df,
columns=['TERRITORIO', var],
key_on='feature... | <ul>
<li>I can't find any geometry for Nord, Centro, Mezzogiorno Italy, so have sythesized by dissolving regions geometry</li>
<li>have setup functions and variables used by your code to make this a MWE</li>
<li>can switch between geometries by <code># regions==False, north/central/south==True if True:</code> <strong>b... | geojson|geopandas|folium|choropleth | 1 |
371,692 | 71,480,856 | Count the number of occurrences of each word in a file and load into pandas | <p>How do I count the number of occurrences of each word in a .txt file and also load it into the pandas dataframe with columns name and count, also sort the dataframe on column count?</p> | <p>Use <code>nltk</code>:</p>
<pre><code># pip install nltk
from nltk.tokenize import RegexpTokenizer
from nltk import FreqDist
import pandas as pd
text = """How do I count the number of occurrences of each word in a .txt file and also load it into the pandas dataframe with columns name and count, also ... | python|pandas|dataframe|nlp | 0 |
371,693 | 71,741,444 | reading logfiles with pandas (tab/ newline separated, each row contains a column and value) | <p>I am processing log files with pandas with the following structure, all log files have the same structure and contain data about one machine that should be reducable to 1 row:</p>
<pre><code>Column1 Value1
Column2 Value2
Column3 Value3
Column4 Value4
Column5 Value5
</code></pre>
<p>I am using the... | <p>I think you are concatenating along rows, like this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
appended_data = [
pd.DataFrame({"Column1": ["1"],}),
pd.DataFrame({"Column2": ["2"],}),
pd.DataFrame({"Column3": ["3"],... | pandas|dataframe|logging|stringio | 0 |
371,694 | 71,519,327 | Get indices from np.array under condition from another array | <p>Suppose I have a NumPy array (5×5) with distances between points.
The matrix is square and symmetrical.</p>
<pre class="lang-py prettyprint-override"><code>distances = np.array([
[0, 3, 2, 1, 4],
[3, 0, 1, 3, 5],
[2, 1, 0, 7, 6],
[1, 3, 7, 0, 9],
[4, 5, 6, 9, 0],
])
</code></pre>
<p>I also ha... | <p>Something like this?</p>
<pre class="lang-py prettyprint-override"><code>In [152]: import numpy as np
In [153]: points = np.array(['A', 'D', 'A', 'D', 'F'], dtype='str')
In [154]: distances = np.array(
...: [[0, 3, 2, 1, 4],
...: [3, 0, 1, 3, 5],
...: [2, 1, 0, 7, 6],
...: [1... | python|numpy | 1 |
371,695 | 71,528,623 | Optimizer zero_grad() and optimize() - how to use when each sample split into patches? | <p>I have a dataset consisting of small RGB images. Each image is then split into a specific number of patches, each then being resized and blurred (Gaussian). The input of my model (see Thermal Image Enhancement using CNN (10.1109/IROS.2016.7759059), shallow 3-layers network for increasing the resolution and handling ... | <p>You should pass all patches as a batch. performing a gradient step on a sole patch consitutes pure stochastic gradient descent, which is generally not preferred because it yeilds a very noisy estimate of the desired gradient. Furthermore looping over each patch from the image is computationally inefficient.</p>
<p>A... | python|neural-network|pytorch|conv-neural-network | 0 |
371,696 | 71,742,030 | Efficient reverse order comparison of huge growing list in Python | <p>In Python, my goal is to maintain a unique list of points (complex scalars, rounded), while steadily creating new ones with a function, like in this pseudo code</p>
<pre class="lang-py prettyprint-override"><code>list_of_points = []
while True
# generate new point according to some rule
z = generate()
# ... | <p>Your best bet might to be to use a set instead of a list, python sets use hashing to insert items, so it is very fast. And, you can skip the step of checking if an item is already in the list by simply trying to add it, if it is already in the set it wont be added since duplicates are not allowed.</p>
<p>Stealing yo... | python|numpy|performance|unique|fifo | 3 |
371,697 | 71,514,712 | argument must be a string or a number, not 'datetime.datetime', but i have a string (Pandas + Matplotlib) | <p>I have a pandas dataframe</p>
<pre><code>published | sentiment
2022-01-31 10:00:00 | 0
2021-12-29 00:30:00 | 5
2021-12-20 | -5
</code></pre>
<p>Since some rows don't have hours, minutes and seconds I delete them:</p>
<pre><code>df_dominant_topic2['published']=df_dominant_topic2['published'].as... | <p>Try like this:</p>
<pre><code>import pandas as pd
from matplotlib import pyplot as plt
values=[('2022-01-31 10:00:00',0),('2021-12-29 00:30:00',5),('2021-12-20',-5)]
cols=['published','sentiment']
df_dominant_topic2 = pd.DataFrame.from_records(values, columns=cols)
df_dominant_topic2['published']=df_dominant_topic... | pandas|datetime|matplotlib | 0 |
371,698 | 71,698,295 | Take average of rows with the same value with pandas | <p>I have a .csv formatted as following:</p>
<pre><code>Year Number
2001 5
2001 10
2003 15
</code></pre>
<p>My goal is to take a user input (year) and take the average of all the numbers that share the same year using python's pandas.</p>
<p>For example, If I chose the year "2001" I should get 7.5.</p> | <p>I would take the input data, convert it to "int", then filter your dataframe accordingly and take the mean value from ['Number'] column.</p>
<p>So it would look like this:</p>
<pre><code>#Preparing the data
import pandas as pd
df=pd.DataFrame()
df['Year']=pd.Series([2001,2001,2003])
df['Number']=pd.Series(... | python|pandas|csv | 0 |
371,699 | 71,603,636 | How to Predict Future values Using LSTM? | <p>I am kind of new in time series forecasting and deep learning. I have a dataset regarding Solar Irradiation and I am using Jupyter Notebook. I have divided data into 3 parts train, val and test. Trained the model and got the predictions on the test dataset. The dataset is from 2010 to 2020 consisting of each hour. I... | <p>I don't know how you extended the dataset, but I think it should be like this: in the existing data, suppose the solar irradiation data of the previous 24 hours is used to predict the solar irradiation data of the next hour. Your data is from 2010 to 2020. Then you can use the data of the last day of 2020 to predict... | tensorflow|deep-learning|neural-network|conv-neural-network|lstm | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.