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 |
|---|---|---|---|---|---|---|
354,000 | 64,132,358 | Numpy find maximum tuple in array of windows | <p>I'm starting our with list of tuples (each tuple is an (X,Y)). My end result is I want to find the maximum Y-value within EACH window/bin of length 4 using numpy.</p>
<pre><code># List of tuples
[(0.05807200929152149, 9.9720125), (0.34843205574912894, 1.1142874), (0.6387921022067363, 2.0234027), (0.9291521486643438,... | <p>this should solve your issue.</p>
<p>Input: list of tuples</p>
<p>Ouput: list of tuples, taking the the tuple with the maximum y-value in each block
of 4 elements
import numpy as np</p>
<pre><code># List of tuples
listTuples = [(1,1),(120,1000),(12,90),(1,1),(0.05807200929152149, 9.9720125),
(0.34843205574912894, 1... | python|numpy | 1 |
354,001 | 64,158,202 | Is there an opposite of np.take for multi-dimensional case in NumPy? | <p>If I have <code>N</code>-D array <code>a</code> and 1-D array <code>indexes</code> and <code>axis</code>, what is the shortest/easiest way to assign values to sub-array of <code>a</code> indexed with these indexes along given axis?</p>
<p>If <code>N</code> and <code>axis</code> are known/fixed at code writing time t... | <p>One way would be to permute axes to bring that <code>axis</code> to the front and simply index -</p>
<pre><code>np.moveaxis(a,axis,0)[indexes] = np.moveaxis(b,axis,0)
</code></pre>
<p>Another with <code>np.put_along_axis</code> if you are looking for something built around a bultin -</p>
<pre><code>i = [None]*b.ndim... | python|arrays|numpy|multidimensional-array | 1 |
354,002 | 63,829,209 | Read rows and columns from excel in Python and put them in array | <p>My aim is to read excel data and then classify each first name as first name, second name as second name and domain as domain variables respectively.</p> | <p>You can iterate over rows with <code>pandas</code>, update data and then save it to excel with <code>pandas</code> again:</p>
<pre><code>import pandas as pd
df = pd.read_excel('input.xlsx', index_col=None)
output = {'0': [], '1': [], '2': [], '3': [], '4': []}
for index, row in df.iterrows():
output['0'].appen... | python|arrays|pandas|export-to-csv|xlrd | 1 |
354,003 | 63,979,928 | ranking similarity of one vector with a very large dataframe of vectors in panda | <p>Objective: I'm trying to create an ordered list of items that are ranked based on how close they are with a test item. <br></p>
<p>I have 1 test item with 10 attributes and 250,000 items with 10 attributes. I want a list that ranks the 250,000 items. For example, if the resulting list came back [10,50,21,11,10000...... | <p>If you call cosine_similarity with a second argument it will only compute the distance against the second array.<br />
An example with random vectors</p>
<pre><code>x = np.random.rand(5,2)
</code></pre>
<p>With one argument</p>
<pre><code>cosine_similarity(x)
array([[1. , 0.95278802, 0.93496787, 0.45860786, 0... | python|pandas|numpy|sklearn-pandas|cosine-similarity | 1 |
354,004 | 63,830,848 | HParams in Tensorboard, Run IDs and naming | <p>I'm using <code>SummaryWriter.add_hparams(params, values)</code> to log hyperparameters during training of my Seq2Seq model. My runs are named with a timestamp like <code>2020-09-10 14-50-27</code>. In the HParams tab in Tensorboard, everything looks fine, but the HParam Trial IDs are different; they have another st... | <p>As Aniket mentioned there is not enough in your issue description to be entirely sure what the issue is.</p>
<p>However, if you are using Pytorch, I suspect you may be referring to the behaviour also reported in <a href="https://github.com/pytorch/pytorch/issues/32651" rel="nofollow noreferrer">this issue</a>. The <... | python|tensorflow|pytorch|tensorboard | 2 |
354,005 | 64,054,554 | np.where with list element selection | <p>I have a data sample look like this (real dataset has more columns):</p>
<pre><code>data = {'stringID':['AB CD Efdadasfd','RFDS EDSfdsadf dsa','FDSADFDSADFFDSA'],'IDct':[1,2,3]}
data = pd.DataFrame(data)
data['Index1'] = [[3],[7,9],[5,6,8]]
data['Index2'] = [[4],[10,13],[8,9,10]]
</code></pre>
<p><a href="https://i.... | <p>You can try to use loc to assign the columns.</p>
<pre><code>data.loc[data['IDct'] > 1, 'pos'] = data.loc[data['IDct'] > 1]['Index1'].apply(lambda x: x[1])
data.loc[data['IDct'] > 1, 'pos1'] = data.loc[data['IDct'] > 1]['Index2'].apply(lambda x: x[1])
</code></pre> | python|list|numpy | 1 |
354,006 | 63,816,713 | Filter cells in pandas dataframe with arrays in it | <p>You can see my code <a href="https://i.stack.imgur.com/1b1c7.jpg" rel="nofollow noreferrer">here</a>.</p>
<p>How can I filter this column (<code>childGTalleles</code>) if I have there cells like: [0, 0], [0, 1], or similar?</p>
<p>I have three columns <code>(fatherGTalleles, motherGTalleles and childGTalleles)</code... | <p>The reason is that data type of <code>childGTalleles</code> numpy array. You have to take double quotes from your code and use <code>np.array_equal</code>:</p>
<pre class="lang-py prettyprint-override"><code>newdff = newdf[np.array_equal(newdf.childGTalleles, [0, 0])]
</code></pre>
<p>For your second question, you c... | python|pandas|dataframe|filter | 1 |
354,007 | 63,757,209 | Python: inconsistent handling of IF statement in loop | <p>I have a dataframe <code>df</code> containing conditions and values.</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'COND':['X','X','X','Y','Y','Y'], 'VALUE':[1,2,3,1,2,3]})
</code></pre>
<p>Therefore <code>df</code> looks like:</p>
<pre><code> COND VALUE
X 1
X 2
X 3
Y ... | <p>The problem you are encountering arises because you are overwriting <code>df</code> inside the loop.</p>
<pre class="lang-py prettyprint-override"><code>conditions = {'X','Y'}
for condition in conditions:
if condition == 'X':
df = df[df['VALUE'] < 3] # <-- HERE'S YOUR ISSUE
df2 = df[df['COND'... | python|pandas|loops|if-statement | 7 |
354,008 | 64,088,616 | Rearranging unique groups in csv | <p>I have a huge dataset that's arranged like this. Each ID corresponds to a unique set of groups.</p>
<pre><code>0
0 0
NUMBER 22 ADD_FLD 5 15 &11111
ID 382 START_TIME 2001052306
POINT 63
2010052306 119.464119 15.870264 1.682708e+00 & 1.213053
2010052312 119.910667 15.874892 1.934127e+00 & 1.22... | <p>I spent some time with that, i hope it helps :)</p>
<pre><code>t=open('your_file.txt').read() #or your_file.csv'
l=t.split('\n')
l=l[3:]
l=[i for i in l if i[:5] not in ('POINT', '')]
d={}
current_key=0
for i in range(len(l)):
if l[i][:2]=='ID':
current_key=l[i].split(' ')[2]
d[current_key]=[]
else:
... | python|python-3.x|pandas|csv | 3 |
354,009 | 63,807,212 | How to transform a column value into new columns in python? | <p>My dataframe is similar to:</p>
<pre><code>accident_type office A office B office C information
1 0 0 0 number
1 0 2 2 fatality
1 0 0 0 frequency ... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFram... | python|pandas | 0 |
354,010 | 63,857,586 | How do I fix a value error when using scipy.integrate odeint function? | <p>I'm an engineering student and I'm trying to figure out how to use the odeint function from the scipy.integrate module (I've only ever used ode45 in MATLAB). I'm attempting to numerically solve a simple second order mass, spring, dashpot system. Below is the code I've written (specifically I'm using Jupyter Notebook... | <p><code>f</code> is an array of numbers, and therefore so is <code>f -b/m*x[1] - k/m*x[0]</code>, so the return value of your function <code>translational</code> is not correct.</p>
<p>Instead of attempting to precompute the values of <code>f</code>, what you should do is use the expression for the function in <code>t... | python|numpy|scipy | 0 |
354,011 | 63,903,807 | VGG19 .h5 file modfiying | <p>I'm using pretrained VGG19 in my modified neural transfer code (Gatys algorithm), but my PC doesn't allow me to use input image in original size (original height is 2499 pix, but with 20GB RAM I can use it only 1000 pix maximum)</p>
<p>As I read, the solution for me will be decreasing batch_size. So, my question is ... | <p>Assuming the pretrained model is defined on ImageNet, the maximum input data size for a single sample is 224*224.</p>
<p>If you try and pass a large input, it's possible your deep learning framework will reshape it into many images to be classified at once.</p>
<p>Resizing your input data to 224*224, you will run wi... | tensorflow|keras | 0 |
354,012 | 63,845,808 | Python ValueError: time data '02-01-2020' does not match format '%d/%m/%y' (match) | <p>I am working on a dataset for machine learning but I have an error for the date that not matching. I am tried both times with different strings in format <code>"%d-%m-%y"</code>, <code>"%d/%m/%y"</code> but it is not worked for me. What can I do so that problem will solve. What can I do as datase... | <p>I've had some success using the infer_datetime_format argument of to_datetime in a small example:</p>
<pre><code>>>> df = pd.DataFrame({'a': ['02-01-2020', '03-02-20', '03/02/2020', '04/05/2020']})
>>> pd.to_datetime(df['a'], infer_datetime_format=True)
0 2020-02-01
1 2020-03-02
2 2020-03-02
... | python|pandas|datetime | 4 |
354,013 | 64,036,438 | Add pandas Dataframe to MySQL | <p>I am trying to add a section of dataframe to mySQL database and I am getting an error on my syntax</p>
<pre><code>#connection to database
conn = mysql.connector.connect(host='localhost', user='root', passwd='passed')
cur = conn.cursor() #create cursor
# Insert DataFrame records one by one.
for index, row in final_d... | <p>MySQL does not use square brackets, <code>[...]</code> for column identifiers but backticks. Consider also using <code>executemany</code> converting all rows to list of values avoiding the <code>iterrows</code> loop. Below <code>reindex</code> ensures column subset and order.</p>
<pre class="lang-py prettyprint-over... | mysql|python-3.x|pandas | 1 |
354,014 | 63,972,881 | How to extract hour, day of the week from categorical data? | <p>I have data like this (it's a time series problem):</p>
<pre><code>Time y
2017-01-01 00:00:00 34002
2017-01-01 01:00:00 37947
2017-01-01 02:00:00 41517
2017-01-01 03:00:00 44476
2017-01-01 04:00:00 46234
</code></pre>
<p>I want to extract the hour, day of the week and day off as categori... | <p>Elaborating on the answer included in @MrFruppes comment:</p>
<p>The problem here is that we were trying to convert the DataFrame data to <code>datetime</code> objects, rather than convert the index of the DataFrame to <code>datetime</code> objects.</p>
<p>It is possible to access a DataFrame's index using the <code... | python|pandas|dataframe|datetime|time-series | 0 |
354,015 | 63,934,767 | Cumulative monthly sum with reset to zero at the beginning of each new month in pandas | <p>I have a pandas dataframe with daily data</p>
<pre><code>Date Value
2020-01-01 1780.2
2020-01-02 1783.3
2020-01-05 1781.5
...
2020-02-01 1816.0
2020-02-02 1810.4
...
</code></pre>
<p>There is not always a value for every day of the month, so some days could be missing, therefore the timedelta... | <p>Solution if multiple years is grouping by month periods by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.to_period.html" rel="nofollow noreferrer"><code>Series.dt.to_period</code></a>:</p>
<pre><code>df['Cumulative Value'] = df.groupby(df['Date'].dt.to_period('m'))['Value'].cums... | python|pandas|time-series|cumulative-sum | 3 |
354,016 | 64,159,777 | Stateful LSTM Tensorflow Invalid Input_h Shape Error | <p>I am experimenting with stateful LSTM on a time-series regression problem by using TensorFlow. I apologize that I cannot share the dataset.
Below is my code.</p>
<pre><code>train_feature = train_feature.reshape((train_feature.shape[0], 1, train_feature.shape[1]))
val_feature = val_feature.reshape((val_feature.shape[... | <p>The fix is to <strong>ensure batch size never changes between batches</strong>. They must all be the same size.</p>
<h2>Method 1</h2>
<p>One way is to use a <strong>batch size that perfectly divides your dataset into equal-sized batches</strong>. For example, if total size of data is 1500 examples, then use a batch ... | tensorflow|keras|neural-network|lstm|lstm-stateful | 7 |
354,017 | 63,783,909 | Methods to improve neural network distinguish red from blue? | <p>I have a lot of data for red and blue where I'm trying to distinguish red data from blue, but they all look like this basically (see Imgur). Overlapping a lot, but having peaked in different places</p>
<p><a href="https://i.stack.imgur.com/zsYVc.png" rel="nofollow noreferrer">https://i.stack.imgur.com/zsYVc.png</a><... | <p>Based on your description it's not clear why you believe there should be a better score. Instead of changing the model you should focus on features. Based on what red and blue represent why do you believe they are different? Can you tell that story using the features before you attempt to estimate parameters for a c... | python|tensorflow|machine-learning|scikit-learn|deep-learning | 0 |
354,018 | 63,744,229 | Reindexing rows by reversed column values | <p>I have this <code>df</code>, where inverted column values are far apart from each other, like so:</p>
<pre><code> Team Adversary Home
0 Internacional Bahia Home
1 Flamengo Grêmio Home
...
18 Grêmio Flamengo Away
19 Bahia Internac... | <p>Use <code>np.sort</code> to sort the values of <code>Team</code> and <code>Adversary</code> along <code>axis=1</code>, then using <code>sort_values</code> sort the dataframe based on this sorted columns <code>x</code> and <code>y</code>:</p>
<pre><code>df['x'], df['y'] = np.sort(df[['Team', 'Adversary']], axis=1).T
... | python|pandas|dataframe | 1 |
354,019 | 63,750,419 | Problems with visualization classification_report | <p>I have trying plot classification report, but in my problem have a only 2 classes (0 and 1) and when I called the classification report, his output is it:</p>
<p><a href="https://i.stack.imgur.com/E9ZPR.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>My model is a LSTM with Glove embedding for... | <p>You can define your output from the <code>classification_report</code> to be a <code>dict()</code>, so that you can then read it as a pandas DataFrame via <code>pandas.DataFrame.from_dict()</code> like this:</p>
<pre><code>import pandas as pd
display(pd.DataFrame.from_dict(classification_report(y_true, y_pred, outp... | tensorflow|machine-learning|scikit-learn | 0 |
354,020 | 63,741,650 | when i add grouping function for creating a new column in DF, it's not working as expected | <p>Group by result</p>
<p>empdf.groupby('deptno')['sal'].max()
deptno
10 5000.0
20 3000.0
30 2850.0</p>
<p>I joined this result to my DF empdf, but the result is not coming. Below is query and result.</p>
<p>empdf.assign(maxsal_dept = empdf.groupby('deptno')['sal'].max())</p>
<p>empno</p>
<p>ename</p>
<p>job</... | <p>You have to use <code>transform</code></p>
<p>Try the below snippet</p>
<p><code>empdf['maxsal_deptl']= empdf.groupby('deptno')['sal'].transform('max')</code></p> | python|pandas|dataframe | 0 |
354,021 | 64,101,667 | Reading JSON in a format that can be plotted | <p>I want to read a JSON file generated from a <code>dict()</code> such that I can then make a pie chart. My code so far:</p>
<pre><code>import json
import pandas as pd
openJson = open("path")
jsonFile = json.load(openJson)
df = pd.DataFrame.from_dict(jsonFile)
</code></pre>
<p>The problem I have is that I... | <p>Read JSON file like this</p>
<pre><code>df = pd.read_json (r'C:\Users\XXX\Desktop\data.json')
</code></pre>
<p>This will work if your file is already in JSON format.</p> | python|pandas|matplotlib | 1 |
354,022 | 63,817,766 | Python: how to create a smoothed version of a 2D binned "color map"? | <p>I would like to create a version of this 2D binned "color map" with smoothed colors.</p>
<p>I am not even sure this would be the correct nomenclature for the plot, but, essentially, I want my figure to be color coded by the median values of a third variable for points that reside in each defined bin of my ... | <p>Thanks to everyone who viewed this issue and tried to help!</p>
<p>I ended up being able to solve my own problem. In the end, it was all about image smoothing with Gaussian Kernel.</p>
<p>This link: <a href="https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python">Gaussian filterin... | python-3.x|numpy|matplotlib|plot|smoothing | 1 |
354,023 | 63,823,926 | Dataframe to Dictionary including List of dictionaries | <p>I am trying to convert below dataframe to dictionary.
I want to group via column A and take a list of common sequence. for e.g.</p>
<p><strong>Example 1:</strong></p>
<pre><code> n1 v1 v2
2 A C 3
3 A D 4
4 A C 5
5 A D 6
</code></pre>
<p><strong>Expected output:</strong></p>
<pre><code>{'... | <p>Lets create a function <code>dictify</code> which create a dictionary with top level keys from <code>name</code> column and club's the repeating occurrences of values in column <code>v1</code> into different sub dictionaries:</p>
<pre><code>from collections import defaultdict
def dictify(df):
dct = defaultdict(... | python|pandas|list|dataframe|dictionary | 4 |
354,024 | 63,898,176 | Soap API data to Google Sheets | <p>Good morning,</p>
<p>I have been having troubles getting soap API data into google sheets. When i run the Soap request I get the data as shown in the image .
[output data][1]</p>
<p>Then i tried getting this data into a google sheets using different methods, unfortunately no solution so far has worked.
The solutions... | <p>The <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow noreferrer">decimal</a> values in the response you're getting cannot be serialized to JSON.</p>
<p>Because of this, you should transform this decimal values to another type which can be serialized. For example, float. So you can do the follow... | python|json|pandas|google-sheets|soap | 0 |
354,025 | 63,836,839 | Finding eigenfrequencies for a matrix | <p>I have a square matrix of size 8*8. Some of terms are a function of frequency(omega). I want to write a function which searches for eigenfrequencies in a given range like (0 - 1kHz).</p>
<p>I have included the function below. Here the terms 'tx', 'ki1', 'ki2' are function of omega. For finding eigenfrequencies, the ... | <p>You don't say which project you are looking at the documentation for but sympy can do this:</p>
<pre><code>In [1]: omega = Symbol('omega')
In [2]: M = Matrix([[1, omega], [omega, 1]])
In [3]: M
Out[3]:
⎡1 ω⎤
⎢ ⎥
⎣ω 1⎦
In [4]: M.eigenvals()
Out[4]: {1 - ω: 1, ω + 1: 1}
</code></pre>
<p>However you need to be... | python|numpy|sympy | 0 |
354,026 | 63,911,439 | How to apply a function by grouping by specific locations in pandas? | <pre><code>logged_at type name values
2020-08-17 00:02:22 weak AA 55
2020-08-17 00:12:20 weak AA 54
2020-08-17 00:22:24 weak AA 53
2020-08-17 00:32:25 weak AA 50
2020-08-17 00:42:28 strong AA 44
2020-08-17 00:52:22 strong AA 33
2020-08-17 01:02:20 strong AA ... | <p>You can break it in stages :</p>
<pre><code># get the first values :
top = df.loc[df["type"].ne(df["type"].shift())]
# get the last values
bottom = df.loc[df["type"].ne(df["type"].shift(-1))]
#get the difference in values and generate the rank :
top.assign(values=top["... | python|pandas | 1 |
354,027 | 63,748,666 | Pandas Merging rows with column values within a range of each other | <p>I have an example dataframe as shown below</p>
<pre><code> x y dx
0 1 6.0 1.1
1 2 6.0 1.5
2 2 6.5 1.2
3 3 7.2 4.3
4 4 7.5 4.5
5 4 8.0 4.7
6 5 1.1 7.0
</code></pre>
<p>I would like to merge the rows if the values in column dx are within a range of 1 of each other. There will be no overlapp... | <p>You can have the first option with the following:</p>
<pre><code>import pandas as pd
new_df=df[0:1]
for i in range(1,len(df)):
if df.dx.iloc[i]-new_df.dx.iloc[-1]>1:
new_df=pd.concat([new_df, df.iloc[i:i+1,:]], ignore_index=True)
</code></pre> | python|pandas | 1 |
354,028 | 63,801,619 | Pandas - Calculate which dates another date is between | <p>I have a dataset where each record has 5 date values, and then another date variable. I want to pull either the smallest of the 5 dates that's greater than the other variable, or else the largest of the 5 dates that's smaller. Example:</p>
<pre><code>date1 date2 date3 date4 date5 date_var result1 result2
jan1 feb1 ... | <p>Here is my understanding of the question.</p>
<ul>
<li>We are given 5 dates such that d1 < d2 < d3 < d4 < d5.</li>
<li>We are also given a target date.</li>
<li>Find i such that d_i <= target < d_i+1</li>
<li>result1 is d_i, and result2 is d_i+1</li>
</ul>
<p>Here is my approach:</p>
<pre><code>fro... | python|pandas|date | 1 |
354,029 | 64,113,723 | I want to run a function with an iteration of rows as parameters, python | <p>I have a function that takes the argument home and away as two soccer teams, then applys the poisson distribution (with previous historical information), and makes a prediction of the home and away expected goals. The code is the following:</p>
<pre><code> def predictMatchScore(home, away):
if home in eplTeamStre... | <p>I figured it out:</p>
<pre><code> H_R=[]
A_R=[]
for index, row in season_16_17.iterrows():
home, away = row['HomeTeam'], row['AwayTeam']
sH, sA = predictMatchScore(home, away)
H_R.append(round(sH,2))
A_R.append(round(sA,2))
</code></pre> | python|pandas|distribution|prediction|poisson | 0 |
354,030 | 63,817,717 | How do I decipher this Tensorflow error message? | <p>Unfortunately, I can't post the code that produced this, but I'm having trouble deciphering the following error message (TensorFlow / Keras):</p>
<pre><code>2020-09-09 11:20:35.700555: W tensorflow/core/framework/op_kernel.cc:1753] OP_REQUIRES failed at conv_ops_fused_impl.h:716 : Invalid argument: input must be 4-d... | <p>you need to diminish the size of your input from 5D to 4D</p> | python|tensorflow|keras | 0 |
354,031 | 64,048,508 | Pytorch weighted Tensor | <p>I'm porting a little bit complex TF2 code to Pytorch. Since TF2 does not distinguish Tensor and numpy array, it was straightforward on it. However, I feel like I came back to the TF1 era when I encountered several errors saying 'you cannot mix Tensor and numpy array here in Pytorch!'. Here is the original TF2 code:<... | <p>Perhaps this will help you, but I'm not sure about your final multiplication between weights and weighted_imgs since they don't have the same shape, even after reshaping as you probably wanted. I am not sure I understood correctly your logic:</p>
<pre><code>import torch
def get_weighted_imgs(points, centers, imgs):
... | tensorflow|pytorch|tensor | 2 |
354,032 | 63,890,267 | How do I capture a matrix from a user input and print it out as the user input it? | <p>I'm messing around with numpy trying to create a 3x3 matrix. I want to capture the matrix input via user input and then print the matrix out as the user entered it.</p>
<p>Here's what I have now, it throws a</p>
<pre><code>ValueError: invalid literal for int() with base 10:
</code></pre>
<p>when I run it and I have... | <p>Right now, your code asks for each element seperately. If you enter numbers until it ends itself like</p>
<pre><code>111
222
333
444
555
666
777
888
999
</code></pre>
<p>the program will return</p>
<pre><code>[[111, 222, 333], [444, 555, 666], [777, 888, 999]]
</code></pre>
<p>This happens because the <code>input()<... | python|numpy | 3 |
354,033 | 64,015,946 | Filter pandas Data Frame Based on other Dataframe Column Values | <p>df1:</p>
<pre><code>Id Country Product
1 india cotton
2 germany shoes
3 algeria bags
</code></pre>
<p>df2:</p>
<pre><code>id Country Product Qty Sales
1 India cotton 25 635
2 India cotton 65 335
3 India cotton 96 455
4 India cotton 78 255
5 german... | <p>You can create a dictionary and save all dataframes in it.
Check the code below:</p>
<pre><code>d={}
for i in range(len(df1)):
name=df1.Country.iloc[i]+'_'+df1.Product.iloc[i]
d[name]=df2[(df2.Country==df1.Country.iloc[i]) & (df2.Product==df1.Product.iloc[i])]
</code></pre>
<p>And you can call each dataf... | python|pandas|dataframe | 1 |
354,034 | 63,908,129 | extracting individual element from pandas data frame | <p>I have saved the following panda file into CSV now how do I get it back as a panda file(dataframe) in another program.And is it possible to get single element from the dataframe like for example I want the element of 10th row 3rd column specifically like how it can be done in numpy</p>
<pre><code> df = af.merge(df... | <p>Others have suggested how to extract specific elements above but retrieving the file in the first place should be as simple as</p>
<pre><code> import pandas as pd
df=pd.read_csv("my_csvfilename.csv")
</code></pre>
<p>If you aren't in the same directory you may need to amend to be</p>
<pre><code> df=pd.... | python|pandas|dataframe | 0 |
354,035 | 64,010,102 | timestamp error while importing datat from csv to postgresql | <pre><code>import uuid
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://postgres:xxx@localhost:5432/xxxxa')
df=pd.read_csv("uplauds_corp_financial.csv")
li=[]
for _ in range(len(df)):
ud = uuid.uuid1()
print(ud)
li.append(ud)
df['uuid_']=li
df... | <p>The error is telling you the problem:</p>
<pre><code>select '23:37.2'::timestamp;
ERROR: invalid input syntax for type timestamp: "23:37.2"
LINE 1: select '23:37.2'::timestamp;
#Reformatting won't help
select '23:37:00.2'::timestamp;
ERROR: invalid input syntax for type timestamp: "23:37:00.2"... | python|pandas|postgresql|csv|sqlalchemy | 1 |
354,036 | 64,139,079 | Removing duplicate sets of items in a sequence | <p>I have a list, for example <code>data = [0, 4, 4, 2, 5, 8, 5, 8, 7, 1, 5, 6, 1, 5, 6]</code>, and I need to remove sets of items from it (max. lenght of set <code>k = 3</code>), but only when the sets follow each other. <code>data</code> includes three such cases: <code>[4, 4]</code>, <code>[5, 8, 5, 8]</code>, and ... | <p>You added a numpy tag, so let's use that to our advantage. Start with an array:</p>
<pre><code>data = np.array([0, 4, 4, 2, 5, 8, 5, 8, 7, 1, 5, 6, 1, 5, 6])
</code></pre>
<p>It's easy to make a mask of elements up to length <code>n</code> that follow each other:</p>
<pre><code>mask_1 = data[1:] == data[:-1]
mask_2 ... | python|list|algorithm|numpy | 2 |
354,037 | 63,801,848 | Numpy: Conserving sum in average over two arrays of integers | <p>I have two arrays of positive integers A and B that each sum to 10:</p>
<ul>
<li>A = [1,4,5]</li>
<li>B = [5,5,0]</li>
</ul>
<p>I want to write a code (<em>that will work for a general size of the array and the sum</em>) to calculate the array C who is <strong>also a array of positive integers</strong> that <strong>... | <p>You can ceil/floor every other non-int element. This works for any shape/size and any sum value (in fact you do not need to know the sum at all. It is enough if <code>A</code> and <code>B</code> have same sum):</p>
<pre><code>C = (A + B) / 2
C_c = np.ceil(C)
C_c[np.flatnonzero([C!=C.astype(int)])[::2]] -= 1
print(C... | python|arrays|numpy | 2 |
354,038 | 47,008,099 | How to convert weeks,months into days in python pandas? | <p>The dataset is of hotel and there is a column name "calender updated".Below are the values in this column.Can Anybody help to convert months into days?</p>
<pre><code>array(['2 months ago', '12 months ago', 'yesterday', 'today',
'5 weeks ago', 'a week ago', '3 days ago', '3 months ago',
'4 months ago'... | <p>Welcome to Stack Overflow. When you have a chance, take a look at the help pages to see how to format your question to increase the chances that someone will be able to help you.</p>
<blockquote>
<p>How to convert weeks,months into days in python pandas?</p>
</blockquote>
<p>Take a look at the <a href="https://... | python|pandas | 0 |
354,039 | 46,675,856 | If column A value in dict key, set column B to dict value in pandas dataframe | <p>Say I have a dataframe that looks like:</p>
<pre><code>df=pd.DataFrame({'a':['A','A','B','C'],'b':[1,2,3,4]})
a b
0 A 1
1 A 2
2 B 3
3 C 4
</code></pre>
<p>and a dictionary that looks like this: </p>
<pre><code>convert={'A':9,'C':8}
</code></pre>
<p>If column <code>a</code> has a value in <code>conver... | <p>You can use <code>map</code> with <code>fillna</code>; <code>df.a.map(convert)</code> maps values in column <em>a</em> to corresponding values in the dict if key exists otherwise <code>NaN</code>, then use <code>fillna(df.b)</code> to fill missing values with values from column <em>b</em>:</p>
<pre><code>df['b'] = ... | python|pandas | 3 |
354,040 | 46,653,668 | tensorflow - assign name to optimizer for future restoration | <p>
I create model in tensorflow and one of last lines in it is </p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
...
train_step = tf.train.AdagradOptimizer(LEARNING_RATE).minimize(some_loss_function)
</code></pre>
<p>I wonder if I can give this tensor/operation a name, so that that I can r... | <p>
According to <a href="https://www.tensorflow.org/api_docs/python/tf/train/Optimizer#minimize" rel="nofollow noreferrer">the docs for <code>tf.train.Optimizer</code></a> yes, yes you can.</p>
<pre class="lang-py prettyprint-override"><code>train_step = tf.train.AdamOptimizer().minimize(loss, name='my_training_step'... | tensorflow|save|restore | 3 |
354,041 | 46,916,521 | How to get float matrix from string type matrix in Python 3? String matrix is a part of tuple as a column | <p>I have MySQL data that I am using for some calculations using python 3. <code>result</code>, having fetched MySQL data, is a tuple. When I check <code>result[0][8]</code>, that represents the <code>column</code> represented below in form of a <code>matrix</code> and have type <code>str</code>. I need to replace all... | <p>You can convert the string into a list of lists with <code>eval</code>, then to an <code>array</code> (of type <code>float</code> by default) with:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# untitled.py
#
# Copyright 2017 John Coppens <john@jcoppens.com>
#
# This program is free soft... | python|mysql|python-3.x|numpy | 1 |
354,042 | 46,840,790 | Calculate pandas DataFrame column by custom routine which accepts dictionary as input | <p>There is pandas DataFrame with numeric columns A1 and A2. </p>
<p>Task: create new column in DataFrame which is the result of the following logical steps:</p>
<p><strong>Step #1.</strong> Create the python dictionary for every row in DataFrame. For example for the 1st row it may look like
{‘A1’:5, ‘A2’: 20}<... | <p>Step 1:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(5,2))
dicts = []
for row in df.itertuples():
dicts.append({df.columns[0]: row._1, df.columns[1]: row._2})
</code></pre>
<p>You now have a list of dicts.</p>
<p>Step 2:</p>
<pre><code>packed_blobs = [pack(x) for x... | python|pandas | 0 |
354,043 | 47,053,061 | What's a good way to create multiple dataframes of different row length from one dataframe? | <p>I have a dataframe like the following:</p>
<pre><code>df
Index Fruit
1 Apple
2 Banana
3 Peach
4 Watermelon
5 Apricot
</code></pre>
<p>I want to create 3 dataframes from this, using the indexes =<code>[[1,4],[1,3,5],[1,2,4]]</code>. I want to be able to call these dataframes by the... | <p>Use a <em>dict comprehension</em>:</p>
<pre><code>df = df.set_index('Index')
df
Fruit
Index
1 Apple
2 Banana
3 Peach
4 Watermelon
5 Apricot
idx
[[1, 4], [1, 3, 5], [1, 2, 4]]
d = {'df_{}'.format(i) : df.loc[x] for i, x in enumerate(idx, 1)}
d.key... | python|pandas | 2 |
354,044 | 46,834,421 | python pandas add arguments to function | <p>I want to do a pivot_table but in some cases i have to add the margins,
so my code looks like</p>
<pre><code>if ytd:
datak = direct.pivot_table(index='Code', columns='Period',
values=agg, aggfunc=sum,
margins=True,
marg... | <p>perhaps with <code>eval</code>:</p>
<pre><code>exp = 'direct.pivot_table(index=\'Code\', columns=\'Period\', values=agg, aggfunc=sum'
marg = 'margins=True, margins_name=\'Year to date\')'
datak = eval(exp + ', ' + marg) if ytd is not None else eval(exp + ')')
</code></pre> | python|pandas|pivot-table | 1 |
354,045 | 46,833,527 | Why is TensorFlow while_loop node required? | <p>Why does the basic static, compiled computation graph structure of TF (as opposed to a dynamic graph) necessitate a dedicated while loop node and doesn't enable the use "regular" Python control flow expressions?</p>
<p>Thanks.</p> | <p>TensorFlow builds the computational graph and makes it static (unchangeable) for efficiency. Once it's finalized, telling the TensorFlow graph to do something is like sending some input to a separate program which you can no longer change besides passing in different inputs. So the TensorFlow graph at that point has... | tensorflow|symbolic-math | 1 |
354,046 | 46,631,972 | Conditioned index in numpy array | <p>I've been going through an online tutorial </p>
<pre><code>from sklearn.decomposition import *
from sklearn import datasets
import matplotlib.pyplot as plt
import time
digits=datasets.load_digits()
randomized_pca = PCA(n_components=2,svd_solver='randomized')
# a numpy array with shape= (1800,2)
reduced_data_... | <p>Your first loop (commented out) loops over a 1800-element array. The second one uses the indexing methods of numpy for the "inner loop" and only has to a regular <code>for</code> loop through your 10 colors. Numpy arrays are faster than regular lists and loops.</p>
<p>But what does <code>digits.target == i</code> d... | python|numpy | 1 |
354,047 | 46,702,755 | Pandas Value_Counts Selection | <p>Below is the output of the -</p>
<pre><code>df['x'].value_counts()
-1 266551
1 172667
0 155994
</code></pre>
<p>I would like to calculate the maximum of the counts except of the value -1.</p>
<p>In this case, answer would be 172667.</p>
<p>How can i remove the value of -1 from it and select the max o... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.drop.html" rel="nofollow noreferrer"><code>drop</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.max.html" rel="nofollow noreferrer"><code>max</code></a>:</p>
<pre><code>df['x'].value_counts().d... | python|pandas | 4 |
354,048 | 46,809,615 | User defined function on pandas dataframe | <p>Here is my Code:</p>
<pre><code>dfnew=pd.DataFrame({ 'year': [2015,2016],
'month': [10, 12],
'day': [25,31]})
print(dfnew)
def calc(yy,n):
if yy==2016:
return yy*2*n
else:
return yy
dfnew['nv']=map(calc, dfnew['year'],2)
print(dfnew['nv'])... | <p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="noreferrer"><code>apply</code></a> for custom function:</p>
<pre><code>dfnew['nv']= dfnew['year'].apply(lambda x: calc(x, 2))
print (dfnew)
day month year nv
0 25 10 2015 2015
1 31 12 2016 8064... | python|function|pandas | 5 |
354,049 | 46,874,209 | LSTM cells after convolution | <p>I need to implement an LSTM layer after a two convolutional layers. Here is my code after the first convolution:</p>
<pre><code>convo_2 = convolutional_layer(convo_1_pooling, shape=[5, 5, 32, 64])
convo_2_pooling = max_pool_2by2(convo_2)
convo_2_flat = tf.reshape(convo_2_pooling, shape=[-1, 64 * 50 * 25])
cell = rn... | <p>According to Tensorflow documentation (<a href="https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn</a>)</p>
<p>Input should be in the following shape (I use the default here),
<a href="https://i.stack.imgur.com/fGXtv.p... | python|tensorflow|lstm|convolution | 3 |
354,050 | 46,721,714 | customizing heatmap using data stored in pandas dataframe | <p>I have a dataframe <code>z1</code> with entries as follows:</p>
<pre><code>z1.ix[1:10,1:3]
2017-04-01 2017-05-01
2017-01-04 NaN 0.993549
2017-01-05 NaN NaN
2017-01-06 0.830973 0.978463
2017-01-09 0.926456 NaN
2017-01-10 0.998371 0.997590
2017-01-11 0... | <p>For your first question, you need to use the "cmap" parameter.</p>
<p>For your second question, you need to use set_xticklabels() with the rotation parameter or the set_yticklabels() depending on what axis you want.</p>
<p>For your third question you need to do z1.index.strftime('%Y-%m-%d')</p>
<pre><code>from io... | python-2.7|pandas | 1 |
354,051 | 46,985,411 | Tensorflow, read tfrecord without a graph | <p>I tried to write a good structured Neural network model with Tensorflow. But I met a problem about feed the data from tfrecord into the graph. The code is as below, it hangs on at the following function, how can I make it work?</p>
<p>images, labels = network.load_tfrecord_data(1)</p>
<p>this function can not get... | <p>You need to start the queue before using <code>images, labels</code> in your model. </p>
<pre><code>with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
images, labels = network.load_tfrecord_data(1)
...
coord.request_stop()
coord.join... | tensorflow|tensorflow-datasets|tfrecord | 0 |
354,052 | 46,655,712 | remove rows and ValueError Arrays were different lengths | <p>My dataframe has subcategory, under each category (<code>cat</code>, <code>dog</code>, <code>bird</code>), stats information is presented. I need to remove the rows if they contain info in <code>count</code> and <code>freq</code>, and only keep rows with <code>sd</code> and <code>mean</code> values. Some values are ... | <p><code>!=</code> will not work here. Use <code>pd.Series.isin</code> to obtain a mask you'll then use to filter your dataframe. </p>
<pre><code>m = ~df.stats.isin(['count', 'freq'])
print(m)
0 True
1 True
2 False
3 False
4 True
5 True
6 False
7 False
8 True
9 True
10 ... | python|pandas|numpy|dataframe|valueerror | 7 |
354,053 | 46,899,399 | Lists to columns of dataframe | <pre><code>df1 = pd.DataFrame(np.column_stack([CIK, period, data]), columns=['CIK','Period','Text'])
</code></pre>
<p>I have 3 lists which I want to be columns of my dataframe. Above code worked fine when my data was small. Now this gives me memory error. Am I missing something?
Is there a different way to do this?</p... | <p>You could build a dataframe by passing a <code>dict</code> to it. </p>
<pre><code>i = ['CIK','Period','Text']
j = [CIK, period, data]
df = pd.DataFrame(dict(zip(i, j))
</code></pre>
<p>This is cheap as it doesn't result in creating copies of your data. The <code>dict</code> simply generates key-value pairs around... | python|pandas|dataframe | 2 |
354,054 | 46,752,071 | Feed a Tensor of SparseTensors to estimators | <p>To get started with TF, I wanted to learn a predictor of match outcomes for a game. There are three features: the 5 heros on team 0, the 5 heroes on team 1, and the map. The winner is the label, 0 or 1. I want to represent the teams and the maps as SparseTensors. Out of a possible 71 heroes, five will be selected. ... | <p>Ultimately it wasn't necessary to convert my text representation into sparse vectors in my <code>input_fn</code>. Instead I had to tell the model to expect an input of an array of strings, which it understands how to convert into a "bag of words" or n-hot vector and how to embed as dense vectors.</p>
<pre><code>imp... | tensorflow | 2 |
354,055 | 46,647,805 | building a tf.estimator input_fn: feature is not in features dictionary | <p>I have a corpus of records that represent matchups in a video game. I want to feed this to a <code>tf.estimator.DNNClassifier</code>. </p>
<p>The records contain text representations of the 5 heroes on team 0 and the 5 heroes on team 1, the map the game was played on, and the winner of the game. I want to represent... | <p>I think you should check your data and make sure the field you are missing (team_0) is showing up correctly. It could be many things like ill formed data or the field name might be incorrectly spelt in the training data source.</p> | tensorflow | 0 |
354,056 | 47,039,214 | Python Matplotlib wont show rolling averages over existing subplot | <p>I've created subplots which contain 2 bars sitting side-by-side.
I now want to add 7 day rolling averages as lines over the top of the bars.</p>
<p>I can't get the plot to work, whichever I define last seems to occupy the figure. I'd like all 4 of these plots to be on the same figure. How can I achieve this?</p>
<... | <p>Usually the datetimes utilities of pandas and matplotlib are incompatible. If you use a <code>matplotlib.dates</code> object on a date axis created with pandas then this will in most cases fail.</p>
<p>Here is a solution where pandas is used for plotting and matplotlib for formatting (see comments):</p>
<pre><code... | python|pandas|matplotlib|subplot | 0 |
354,057 | 47,048,843 | finding the length of a numpy array | <p>I am trying to find the length of a numpy array. But when i use the len() function it is giving an error like "TypeError: len() of unsized object"
also when i used the ".size" method the value i am getting is '1'. </p>
<p>my code is as follows</p>
<p><code>for dt in daterange(start_dt, end_dt):
dateComplet... | <p>What exactly are you trying to achieve with your loop? If you want to have an array of dates and check its length, there's no need to iterate through it. I don't know what type of object <code>daterange</code> returns, but if its a numpy array (like with <code>pandas.date_range()</code>, you can get your desired arr... | python|numpy | 0 |
354,058 | 46,696,105 | set a name for pandas dataframe that created from dict | <p>I have created a dataframe form dictionary:</p>
<pre><code>df = pandas.DataFrame.from_dict(my_dict['data'], orient='index')
</code></pre>
<p>I have a dataframe like this:</p>
<pre><code> value
10.1.1.1 aa
10.1.1.2 bb
10.1.1.3 cc
</code></pre>
<p>I want a data frame like this</p>
<pre><code> ... | <p>Use this:</p>
<pre><code>df.index.name = 'ip'
</code></pre>
<p>or</p>
<pre><code>df = df.rename_axis('ip')
</code></pre>
<p>Then, you may want to <code>reset_index</code>:</p>
<pre><code>df = df.reset_index()
</code></pre>
<p>Output:</p>
<pre><code> ip value
0 10.1.1.1 aa
1 10.1.1.2 bb
2 10.1... | python|pandas|dictionary | 2 |
354,059 | 46,982,652 | Keras: Rename Metrics for Same Tensorboard Graph Viewing | <p>Use Case:
I have multiple models each with a slightly different architecture. Model A with one output and Model B with two outputs (call them <code>output_1</code> and <code>output_2</code>). <code>output_1</code> of Model B corresponds to the same information as the single output of Model A. I would like plot th... | <p>I'm not sur I understand well your situation.</p>
<p>For me you just have to make a correct tree directory structure with your log output to to do it and then launch Tensorboard from root folder.</p>
<p>Example: consider \ as root, if you log you loss data from Model A on a folder named model_A and loss from model... | python|tensorflow|keras|metrics|tensorboard | 0 |
354,060 | 47,066,212 | Returning more than one object in Flask | <p>I am trying to return two items to an html file in Flask and am having trouble figuring out the best way to do it.</p>
<p>The two operative lines Flask is pulling from in a separate file are:</p>
<pre><code> # trader_db = Blotter(1000000, collection)
cash = self.cash + df... | <p>The general idea is to separate "logic" from "presentation". Using python function you calculate values. And using template system you structure it in a presentable html view.</p>
<p>I wrote simple example that might be helpful for you:</p>
<p>First, we calculate data (I have a stub here) and pass them to the temp... | python|pandas|flask|flask-sqlalchemy | 1 |
354,061 | 46,899,904 | Conversion of list to sets in pandas dataframe | <p>I would like to search for substrings in each row of a dataframe column. I read somewhere that it is faster to search if the column can be converted into a set. I am trying to use the approaches suggested here: <a href="https://stackoverflow.com/questions/33125611/how-to-convert-list-into-set-in-pandas">How to conve... | <p>Your data is not in a format that makes it easy to work with. I'd recommend an extension of Andy's code that results in each entry getting its own row, so you can then filter your data much more efficiently. </p>
<p>Start with <code>str.split</code>, and then extract key-value pairs using <code>str.extract</code>.... | python|pandas|set | 2 |
354,062 | 46,810,120 | Predicting values in time series for future periods using RNN in Tensorflow | <p>I'm kindly new to deep learning and its approach to time series predicting. Recently I found one article about <a href="https://github.com/JustinBurg/TensorFlow_TimeSeries_RNN_MapR/blob/master/RNN_Timeseries_Demo.ipynb" rel="nofollow noreferrer">time series predicting using Recurrent Neural Networks (RNN) in Tensorf... | <p>In first step you should use real values. Then using predict value to replace last value as you want.
Hope the following code could help you. </p>
<pre><code>with tf.Session() as sess:
saver.restore(sess, './model_saved')
preds = []
X_batch = last_n_steps_value
X_batch = X_batch.reshape(-1, n_steps... | python|tensorflow|deep-learning|time-series|rnn | 1 |
354,063 | 46,974,877 | pandas conditional replacement of cell values with mean / median over rows | <p>I am new to python and have 2 (big) unstacked pandas dataframes with dates as rows and columns as ids. The first dataframe contains certain values while the second contains the (row) rank of each value. I would like to replace rank values with their row median when a condition on the value itself is met. </p>
<p>He... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a>:</p>
<pre><code>np.random.seed(100)
dfval = pd.DataFrame(np.random.rand(5,5), columns=list('ABCDE'))
print (dfval)
A B C D ... | python|pandas | 1 |
354,064 | 46,669,314 | How to set the column name for first column in python pandas? Weird error | <p>I have an xls with the title row as : </p>
<pre> AZ-Phoenix CA-Los Angeles CA-San Diego
YEAR PHXR LXXR SDXR
January 1987 59.33 54.67 77
February 1987 59.65 54.89 78
March 1987 59.99 55.16 79
</pre>
<p>Note : the firs... | <p>YEAR is not a column, it's an index here.<br>
try:</p>
<pre><code>df.index.name = 'foobar'
</code></pre>
<p>or:</p>
<pre><code>df = df.reset_index()
</code></pre>
<p>in this case, YEAR will become a normal column and you can rename it.</p> | python|pandas|csv|dataframe | 6 |
354,065 | 46,733,767 | calculate a 2d array in python using numpy | <p>I want to create a 2d array in python using numpy.
In the following, I just create the 2d array with numbers 1,2,3,...
I should calculate an expression to produce each element of it.
Thank you</p>
<pre><code>import numpy as np
my_2darray = np.array([[1,2,3],[4,5,6]])
</code></pre> | <p>you can create a 2d array of size 2 x 3 using numpy in that way:</p>
<pre><code>x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
</code></pre> | python|numpy | 0 |
354,066 | 47,013,052 | Issue with pyarrow when loading parquet file where index has redundant column | <p>I am using pandas/dask to do computations an I am storing my data inside a parquet file on disk. The issue is, that I have a column 'time' and also an index that is called time. I want to keep both. When I store the data and then load it later, I get the following errors:</p>
<pre><code>import pyarrow as pa
import ... | <p>Looks a bit buggy to me. I opened a bug report <a href="https://issues.apache.org/jira/browse/ARROW-1754" rel="nofollow noreferrer">https://issues.apache.org/jira/browse/ARROW-1754</a>, let's continue discussing there.</p> | python|pandas|parquet|pyarrow | 2 |
354,067 | 46,779,264 | Python nested loop, break if conditions not satisfied | <p>I have been trying to use a nested loop to iterate through the rows of a pandas DataFrame, the outer loop, and for each row check if the conditions of a rule, a list of tuples:[(Attribute,Value),(Att,Val)], match those Att,Val pairs in the row of the DataFrame, the inner loop. If all conditions in the rule are satis... | <p>I'd do something like this:</p>
<p>Let <code>s</code> be a <code>pandas.Series</code> that represents the <code>rule</code> </p>
<pre><code>s = pd.Series(dict(rule))
</code></pre>
<p>Reassign the dataframe to be aligned with <code>s</code> </p>
<pre><code>d, s = self.data.align(s, 'inner', 1)
</code></pre>
<p... | python|pandas|loops|break | 1 |
354,068 | 32,899,621 | Numpy/CAPI error with import_array() when compiling multiple modules | <p>I am trying to compile a C++ module to use in <code>scipy.weave</code> that is composed of several headers and source C++ files. These files contain classes and methods that extensively use the Numpy/C-API interface. But I am failing to figure out how to include <code>import_array()</code> successfully. I have been ... | <p>I had a similar problem, as the link you've posted points out, the root of all evil is that the <code>PyArray_API</code> is defined static, which means that each translation unit has it's own <code>PyArray_API</code> which is initialized with <code>PyArray_API = NULL</code> by default. Thus <code>import_array()</cod... | python|c++|c|numpy|python-c-api | 7 |
354,069 | 33,032,840 | Python Sine function error | <p>I have worked for a while in matlab but want now also learn some python. but after a few days i run in some trouble...</p>
<p>I have similar functions. one matplotlib example and one own based on some examples (probably also the matplotlib one)</p>
<p>The trouble is that one function is working one not...</p>
<p>... | <p>When using <code>numpy</code> arrays, you shouldn't use <code>math</code> functions. Try use <code>numpy</code> functions:</p>
<pre><code>sine = numpy.sin(2*numpy.pi*f0*t))
</code></pre>
<p>As for the <code>getShape()</code> issue, as the error message says there is no attribute with that name. Try:</p>
<pre><cod... | python-3.x|numpy|matplotlib | 3 |
354,070 | 32,945,506 | How can I test if two objects are equal in python? | <p>I have made a function that connects to a twitter api.
This function returns an twitter object. I want to create a testing function that checks if the returned object is really a twitter object.
So this is my function:</p>
<pre><code>def authenticate_twitter_api():
"""Make connection with twitters REST api"""
... | <p>classes are objects themselves in Python. So you can assign your desired variable like this:</p>
<pre><code>import twitter
# (...)
desired = twitter.api.Twitter
</code></pre> | python|object|testing|numpy | 2 |
354,071 | 32,854,677 | How to deal with multiple date string formats in a python series | <p>I have a csv file which I am trying to complete operations on. I have created a dataframe with one column titled "start_date" which has the date of warranty start. The problem I have encountered is that the format of the date is not consistent. I would like to know the number of days passed from today's calendar dat... | <p>Unfortunately you just have to try each format it might be. If you give an example format, <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="noreferrer">strptime</a> will attempt to parse it for you as discussed <a href="https://stackoverflow.com/questions/14245029/parsing-a-d... | python|python-2.7|date|pandas | 13 |
354,072 | 32,989,124 | I have a SAP generated file with many columns and some unwanted rows. How should I read directly into Pandas? | <p>My table:</p>
<pre><code>Table To Be Searched MSEG
Number of hits 273208
Maximum No. of Entri 0
Runtime 00:24:17
----------------------------------------------------------------------... | <p>You could use <a href="https://docs.python.org/2/library/itertools.html#itertools.ifilter" rel="nofollow"><code>itertools.ifilter</code></a> to filter only the table data and a <code>csv.reader</code> to parse the important rows as follows:</p>
<pre><code>import csv
import itertools
import StringIO
with open('inpu... | python|string|csv|pandas | 2 |
354,073 | 38,650,895 | How do I add multiple markers to a stripplot in seaborn? | <p>I would like to know how I could get multiple markers in the same strip plot.</p>
<pre><code>tips = sns.load_dataset("tips")
coldict={'Sun':'red','Thur':'blue','Sat':'yellow','Fri':'green'}
markdict={'Sun':'x','Thur':'o','Sat':'o','Fri':'o'}
tips['color']=tips.day.apply(lambda x: coldict[x])
tips['marker']=tips.d... | <p>Caution it's a little hacky but here ya go:</p>
<pre><code>import sns
tips = sns.load_dataset("tips")
plt.clf()
thu_fri_sat = tips[(tips['day']=='Thur') | (tips['day']=='Fri') | (tips['day']=='Sat')]
colors = ['blue','yellow','green','red']
m = sns.stripplot('size','total_bill',hue='day',
marker... | python|pandas|matplotlib|seaborn | 5 |
354,074 | 38,608,881 | Linear interpolation of the 4D array in Python/NumPy | <p>I have a question about the linear interpolation in python\numpy.
I have a 4D array with the data (all data in binary files) that arrange in this way:
t- time (lets say each hour for a month = 720)
Z-levels (lets say Z'=7)
Y-data1 (one for each t and Z)
X-data2 (one for each t and Z)</p>
<p>So, I want to obtain a ... | <p>You can create different interpolation formulas for different combinations of z' and t. </p>
<p>For example, for <code>z=7</code>, and a specific value of <code>t</code>, you can create an interpolation formula:</p>
<pre><code>formula = scipy.interp1d(x,y)
</code></pre>
<p>Another one for say <code>z=25</code> an... | python|arrays|numpy|4d | 0 |
354,075 | 38,537,461 | apply groupby rules to timeseries? | <p>I have a sample DataFrame as follows:</p>
<pre><code> value=DataFrame({'A':[0,-1,0],
'B':[1,1,-1],
'C':[0,0,1],
'D':[-1,1,1]})
value.index=pd.date_range('1/1/2016',periods=len(value),freq='M')
</code></pre>
<p>And I want to have the answer as fo... | <pre><code>import pandas as pd
value = pd.DataFrame({'A':[0,-1,0],
'B':[1,1,-1],
'C':[0,0,1],
'D':[-1,1,1]})
value.index = pd.date_range('1/1/2016',periods=len(value),freq='M')
pos = (value > 0)
neg = (value < 0)
result = ((value*pos).divide(pos.sum(axis=1), ax... | pandas|group-by | 1 |
354,076 | 38,929,737 | Pandas: Rolling sum with multiple indexes (i.e. panel data) | <p>I have a dataframe with multiple index and would like to create a rolling sum of some data, but for each id in the index.</p>
<p>For instance, let us say I have two indexes (<em>Firm</em> and <em>Year</em>) and I have some data with name <em>zdata</em>. The working example is the following:</p>
<pre><code>import p... | <p><strong><em>Option 1</em></strong></p>
<pre><code>mydf.unstack(0).rolling(2).sum().stack().swaplevel(0, 1).sort_index()
</code></pre>
<p><a href="https://i.stack.imgur.com/9yYCq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9yYCq.png" alt="enter image description here"></a></p>
<p><strong><em... | python|pandas|panel|multi-index|rolling-sum | 4 |
354,077 | 38,567,693 | Produce new data frame from extracted grouped data | <p>I'm a Python novice. I'm trying to extract trip duration from a series of GPS fixes. There are multiple different tracks that I am trying to get information from and put the results into seperate data frame. The data looks like this (latitude and longitude columns excluded): </p>
<pre><code> track_id DateTime ... | <p>You were nearly there, basically you can call <code>reset_index</code> with <code>name</code> param to to restore the 'track_id' column and name the aggregated column:</p>
<pre><code>In [44]:
(df.groupby('track_id')['DateTime'].max() - df.groupby('track_id')['DateTime'].min()).reset_index(name='trip_dur')
Out[44]:... | python|datetime|pandas|dataframe | 1 |
354,078 | 38,517,124 | How to minimize two loss using TensorFlow? | <p>I am working on a project which is to localize object in a image. The method I am going to adopt is based on the localization algorithm in <a href="https://cs231n.stanford.edu/slides/winter1516_lecture8.pdf" rel="nofollow">CS231n-8</a>.</p>
<p>The network structure has two optimization heads, classification head an... | <p>It depends on your network status.</p>
<p>If your network is just able to extract features [you're using weights kept from some other net], you can set this weights to be constants and then train separately the two classification heads, since the gradient will not flow trough the constants.</p>
<p>If you're not us... | tensorflow | 2 |
354,079 | 38,557,827 | TypeError: __init__() got an unexpected keyword argument 'syntax' | <h3>Environment info</h3>
<p>Operating System: OS X El Capitan Version 10.11.1</p>
<h3>Steps to reproduce</h3>
<ol>
<li>run `import tensorflow as tf'</li>
</ol>
<h3>Logs or other output that would be helpful</h3>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File... | <p>You might have not installed it correctly. Try:</p>
<pre><code>$ virtualenv tensorflow
$ source tensorflow/bin/activate
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
$ pip install --upgrade $TF_BINARY_URL
$ python
>>>
</code></pre>
<p>Then:</p>
<pr... | python|tensorflow | 1 |
354,080 | 38,695,811 | Can't find efficient way to replicate original code after refactoring of pandas .resample() | <p>I am passing a dictionary of pandas DataFrames (or a pandas panel) into the function below in order convert from daily to monthly data. Each DataFrame represents a field (eg Open, High, Low or Close) in datetime v stock code space. The function works fine but I am getting deprecation warnings. I can't find an eff... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.tseries.resample.Resampler.aggregate.html" rel="nofollow"><code>Resampler.aggregate</code></a> and pass a dict of the Column names as keys with it's respective intended operation as the values.</p>
<pre><code>dict_ohlcv = {'Op... | python|pandas|resampling|deprecation-warning | 0 |
354,081 | 38,848,222 | Python remove customized stop words from pandas dataframe | <p>I was following the next question: <a href="https://stackoverflow.com/questions/29523254/python-remove-stop-words-from-pandas-dataframe/38846564">Python remove stop words from pandas dataframe</a></p>
<p>but it doesnt work for me for a customized stop words list, check out this code:</p>
<pre><code> pos_tweets = [... | <p>You need assign output back to column <code>tweet</code>:</p>
<pre><code>test['tweet'] = test['tweet'].apply(lambda x: [item for item in x if item not in stop])
print (test)
tweet col2
0 [i, this] positive
1 [th... | python|pandas|dataframe | 1 |
354,082 | 38,894,418 | How to name a dataframe column filled by numpy array? | <p>I am filling a DataFrame by transposing some numpy array :</p>
<pre><code> for symbol in syms[:5]:
price_p = Share(symbol)
closes_p = [c['Close'] for c in price_p.get_historical(startdate_s, enddate_s)]
dump = np.array(closes_p)
na_price_ar.append(dump)
print symbol
df = pd.DataFrame(na_pric... | <p>Instead of using a list of arrays and transposing, you could build the DataFrame from a dict whose keys are symbols and whose values are arrays of <em>column</em> values:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(2016)
syms = 'abcde'
na_price_ar = {}
for symbol in syms[:5]:
# price_p ... | python|arrays|pandas|numpy|dataframe | 4 |
354,083 | 38,676,418 | Pandas DatetimeIndex indexing dtype: datetime64 vs Timestamp | <p>Indexing a pandas DatetimeIndex (with dtype numpy datetime64[ns]) returns either:</p>
<ul>
<li>another DatetimeIndex for multiple indices</li>
<li>a pandas Timestamp for single index</li>
</ul>
<p>The confusing part is that Timestamps do not equal np.datetime64, so that:</p>
<pre><code>import numpy as np
import p... | <p>You are using numpy functions to manipulate pandas types. They are not always compatible. </p>
<p>The function <code>np.in1d</code> first converts its both arguments to ndarrays. A <code>DatetimeIndex</code> has a built-in conversion and an array of dtype <code>np.datetime64</code> is returned (it's <code>DatetimIn... | python|pandas|datetimeindex | 2 |
354,084 | 38,626,039 | Trying to convert a CSV into JSON in python for posting to REST API | <p>I've got the following data in a CSV file (a few hundred lines) that I'm trying to massage into sensible JSON to post into a rest api
I've gone with the bare minimum fields required, but here's what I've got:</p>
<pre><code>dateAsked,author,title,body,answers.author,answers.body,topics.name,answers.accepted
13-Jan... | <p>You can use a <code>csv.DictReader</code> to process the CSV file as a dictionary for each row. Using the field names as keys, a new dictionary can be constructed that groups common keys into a nested dictionary keyed by the part of the field name after the <code>.</code>. The nested dictionary is held within a list... | python|json|csv|pandas | 2 |
354,085 | 38,837,860 | Numpy Uniform Distribution With Decay | <p>I'm trying to construct a matrix of uniform distributions decaying to 0 at the same rate in each row. The distributions should be between -1 and 1. What I'm looking at is to construct something that resembles:</p>
<pre><code>[[0.454/exp(0) -0.032/exp(1) 0.641/exp(2)...]
[-0.234/exp(0) 0.921/exp(1) 0.049/exp(2)...]... | <p>You can use numpy's broadcasting feature to do this:</p>
<pre><code>w = np.random.uniform(-1, 1, size=(10, 10))
weights = np.exp(np.arange(10))
w /= weights
</code></pre> | python|numpy | 6 |
354,086 | 38,555,120 | Hardware requirements to deal with a big matrix - python | <p>I am working on a python project where I will need to work with a matrix whose size is around 10000X10000X10000.</p>
<p>Considering that:</p>
<ul>
<li>The matrix will be dense, and should be stored in the RAM.</li>
<li>I will need to perform linear algebra (with numpy, I think) on that matrix, with around O(n^3) w... | <p>Well, the first question is, wich type of value will you store in your matrix?
Suposing it will be of integers (and suposing that every bytes uses the ISO specification for size, 4 bytes), you will have 4*10^12 bytes to store. That's a large amount of information (4 TB), so, in first place, I don't know from where y... | python|numpy|matrix | 4 |
354,087 | 38,668,788 | Nested "ifs" on pandas df columns | <p>I have a pandas df called data.</p>
<p>I want to do something like:</p>
<pre><code>for i in range(data["col1"].count()):
if data["col1"][i] > 25:
count1 += 1
if data["col2"][i] > 35:
count2 += 1
</code></pre>
<p>and possibly with more columns so that I can keep track of when several conditio... | <p>This is a better way to go:</p>
<pre><code>cond1 = data.col1 > 25
cond2 = data.col2 > 35
count1 = cond1.sum()
count2 = (cond1 & cond2).sum()
</code></pre> | python|pandas | 3 |
354,088 | 38,673,305 | Bazel Errors on creating .so file with tensorflow and cuda | <p>Im able to create a .so file with tensorflow / bazel but without cuda. If i try bazel build -c opts --config=cuda :lib.so i get an undefined reference to main(..). Would there be a way to get rid of the errors referring to main (...) ?</p>
<p>Here is my BUILD file</p>
<pre><code>cc_binary(
name = "lib.so",
... | <p>Turns out you just need to set linkshared = 1 onto the BUILD</p>
<pre><code> cc_binary(
name = "lib.so",
srcs = [
"lib.cc",
"jni.h",
"jni_md.h",
"lib.h",
"jni_utils.h", "jni_utils.cc"
],
copts = tf_copts(),
linkshared = 1,
deps = [
"//tens... | c++|cuda|java-native-interface|tensorflow | 0 |
354,089 | 38,646,996 | tf.nn.dynamic_rnn() returning error when used in Google Cloud Datalab | <p>I'm trying to run an RNN on Google Cloud Datalab. The same network runs correctly on my computer, but when I run it on Datalab, I get the following error:</p>
<p>TypeError: dynamic_rnn() takes at least 3 arguments (3 given)</p>
<p>The use of dynamic_rnn() is as follows:</p>
<p>rnn_outputs, state = tf.nn.dynamic_r... | <p><code>dynamic_rnn</code> does not appear to be listed in the <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/nn.html" rel="nofollow noreferrer">api docs</a> of tensorflow 0.7.</p>
<p>As a next step, you could try one of the following options:</p>
<ul>
<li>Deploy a newer version of Datalab. This i... | tensorflow|google-cloud-datalab | 1 |
354,090 | 38,814,873 | Python & Pandas: Will using many df.copy affect code's performance? | <p>I'm doing some data analysis, and the data are in pandas <code>DataFrame</code>, <code>df</code>.</p>
<p>There are several function that I defined to do process on the <code>df</code>.</p>
<p>For encapsulation purpose, I define the functions like this:</p>
<pre><code>def df_process(df):
df=df.copy()
# do ... | <p>Far better would be:</p>
<pre><code>def df_process(df):
# do some process work on df
def df_another(df):
# other processing
def df_more(df):
# yet more processing
def process_many(df):
for frame_function in (df_process, df_another, df_more):
df_copy = df.copy()
frame_function(df_c... | python|pandas | 1 |
354,091 | 38,921,558 | Numpy choose shape mismatch | <p>I have a numpy problem with choose. I would like to choose certain indices as decribed in array a from array b.</p>
<pre><code>a
Out[54]:
array([[3, 2, 2],
[0, 0, 2]], dtype=int64)
b
Out[55]:
array([[[ 6., 1., 8., 9., 3., 8., 5.],
[ 6., 1., 5., 8., 2., 2., 10.],
[ ... | <p>It looks you want to use <code>choose</code> to select values from the dimension of length 7 in <code>b</code> (which is sized (2,3,7)). Your choosing array <code>a</code> will work for this, but only if the sequence dimension is the outermost dimension (as you quoted). The outermost dimension in Numpy is the <em>... | python|numpy | 2 |
354,092 | 38,790,852 | Unable to properly install or load Tensorflow on Ubuntu 12.04 LTS with resultant ImportError | <p>I attempted the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation" rel="nofollow noreferrer">Anaconda installation</a> for TensorFlow on my Ubuntu 12.04 LTS system, which went through, but while importing the library in Python, I came across an ImportError shown below... | <p>This error probably relates to you glibc version. There are some topics regarding this:<a href="https://stackoverflow.com/questions/16605623/where-can-i-get-a-copy-of-the-file-libstdc-so-6-0-15">Where can I get a copy of the file libstdc++.so.6.0.15</a></p>
<p>First check whether the required version is on your sys... | python|ubuntu|tensorflow|anaconda | 0 |
354,093 | 38,574,596 | Flatten nested pandas dataframe | <p>I'm wondering how to flatten the nested pandas dataframe as demonstrated in the picture attached. <a href="https://i.stack.imgur.com/7UR1f.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UR1f.jpg" alt="enter image description here"></a></p>
<p>The nested attribute is given by 'data' field. In sh... | <p>Try this:</p>
<pre><code>pd.concat([df.data.apply(pd.Series), df.drop('data', axis=1)], axis=1)
</code></pre> | python|pandas|dataframe | 7 |
354,094 | 38,646,009 | MemoryError while reading and writing a 40GB CSV... where is my leak? | <p>I have a 40GB CSV file which I have to output with different column subsets as CSVs once again, with a check that there are no <code>NaN</code>s in the data. I opted to use Pandas, and a minimal example of my implementation looks like this (inside a function <code>output_different_formats</code>):</p>
<pre><code># ... | <p>The solution for now has been to manually call the garbage collector with <code>gc.collect()</code></p>
<pre><code>while scen_cnt < 10000:
scenario = scen_iter.get_chunk(CHUNKSIZE)
if scenario.isnull().values.any():
# some error handling (has yet to ever occur)
for item in output_names:
... | python|python-3.x|pandas|memory | 2 |
354,095 | 38,927,077 | Format to cleanly save and restore DataFrame? | <p>I want to save pandas table in a file, so I can read it from that file later. My requirements:</p>
<ul>
<li><p>the file format should be decently portable (good library support on Windows/Linux in major languages)</p></li>
<li><p>the DataFrame I read should be absolutely identical to the one I saved</p></li>
</ul>
... | <p><code>pd.DataFrame.to_pickle</code> / <code>pd.read_pickle</code> hold columns data types. Let's check it out:</p>
<pre><code>df_in.to_pickle('input_5')
df_out = pd.read_pickle('/input_5')
</code></pre> | python-3.x|pandas|dataframe | -1 |
354,096 | 38,546,881 | Pandas MultiIndex get all rows with label value | <p>Assume you have a Panda DataFrame with a MultiIndex. You want to get all the rows that have a label with a particular value. How do you do this?</p>
<p>My first thought was a boolean mask...</p>
<p><code>df[df.index.labels == 1].head()</code></p>
<p>but this does not work.</p>
<p>Thanks!</p> | <p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow"><code>xs</code> (cross-section)</a>:</p>
<pre><code>In [11]: df = pd.DataFrame([[1, 2, 3], [3, 4, 5]], columns=list("ABC")).set_index(["A", "B"])
In [12]: df
Out[12]:
C
A B
1 2 3
3 4 5
</code>... | python|pandas|multi-index | 3 |
354,097 | 38,706,932 | Pandas Dataframe and Converting DateTime Objects | <p>I have multiple datettime columns in my dataframe and when I export the datetime to csv, I need to convert the datetime from Month/Day/Year to Month/Year. Is it possible to do this?</p>
<p>I was trying this:</p>
<pre><code>if date_mask == "MMM":
df[name].apply(lambda x: x.strftime('%b %Y'))
else:
df[name]... | <p>Solution</p>
<pre><code>def modify_date(x):
try:
if pd.isnull(x) == False:
return x.strftime('%b %Y')
else:
print pd.NaT
except:
return pd.NaT
df = pd.DateFrame.from_records(<some list from database>)
df[name] = df[name].apply(modify_date)
</code></pre... | python|csv|datetime|pandas | 0 |
354,098 | 63,242,900 | In pandas, how to convert a column of float32 values to float16 values? | <p>I have a pandas column of float32 numbers, I would like to convert them to float16 to save memory.</p>
<p>I tried looking "pandas convert column of float32 to float16" but most of my results were mostly about numpy.</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a>:</p>
<pre><code>df = pd.DataFrame({'col':[1.456, 53.2368]})
print (df)
col
0 1.4560
1 53.2368
df['col'] = df['col'].astype(np.float16)
</code></pre>
<p... | python|pandas|memory-management | 4 |
354,099 | 63,254,783 | Pandas subset rows according to string-match | <p>I have used the <code>string_grouper</code> package in Python to generate a list of the common names between two databases of company info. The resulting data-frame <code>matches</code> shows the company names from DB1 (<code>left_side</code>) and DB2 (<code>right_side</code>) above a certain string-similarity thres... | <p>The error happens because <code>DB1['names']</code> is series while <code>in</code> operator expects single element on the left.</p>
<p>Try using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer">pandas.Series.isin() function</a>:</p>
<pre><code>rs... | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.