Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
363,200 | 51,794,987 | calculate the weekday information based on date information | <p>In a dataframe created using Pandas, there is one column, i.e., 'date', storing the value of date, i.e., 2012-10-8, how can I create another column, each entry of which stores the weekdays for the corresponding date entry.</p>
<p>In other words, I would like to have two columns</p>
<pre><code>date weekday
... | <p>IIUC, use <code>.dt</code> accessor and <code>strftime</code> using <code>%A</code></p>
<pre><code>>>> df.date.dt.strftime('%A')
0 Monday
Name: date, dtype: object
</code></pre>
<p>ps: Note that <code>2012-10-08</code> was a <em>Monday</em>, and not <em>Tuesday</em></p> | python|python-3.x|pandas | 1 |
363,201 | 51,994,117 | Applying transformation and concatenating multiple columns from an existing dataframe to form a new dataframe in Pandas | <p>Suppose I have a dataframe like below:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({
'A' : ['foo ', 'b,ar', 'fo...o', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
})
</code></pre>
<p>I want to create a <strong>new dataframe</strong>, <cod... | <h2>Short version</h2>
<pre><code>list_o_cols = ['A', 'B']
df1[list_o_cols].sum(1).str.upper()
0 FOOONE
1 BARONE
2 FOOTWO
3 BARTHREE
4 FOOTWO
5 BARTWO
6 FOOONE
7 FOOTHREE
dtype: object
</code></pre>
<hr>
<pre><code>df2 = df1[list_o_cols].sum(1).str.upper().str.replace('O', '').t... | python|pandas|dataframe | 2 |
363,202 | 51,730,294 | Skorch training object from scratch | <p>I'm trying to use skorch class to execut GridSearch on a classifier.
I tried running with the vanilla <code>NeuralNetClassifier</code> object, but I haven't found a way to pass the Adam optimizer only the trainable weights (I'm using pre-trained embeddings and I would like to keep them frozen). It's doable if a mod... | <blockquote>
<p>but <code>module</code> needs an uninitialized model</p>
</blockquote>
<p>That is not correct, you can pass an initialized model as well. <a href="https://skorch.readthedocs.io/en/latest/user/neuralnet.html#module" rel="nofollow noreferrer">The documentation</a> of the model parameter states:</p>
<... | pytorch|skorch | 1 |
363,203 | 51,746,635 | All possible combinations of pandas data frame rows | <p>I have a pandas data frame having 4 rows:</p>
<p>df:</p>
<pre><code>col1 col2 col3 col4
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
D1 D2 D3 D4
</code></pre>
<p>How do i find all possible combinations of selecting two rows of this data frame. In this c... | <p>First, you need to find all the combinations using <code>itertools</code>and then use the output of <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="noreferrer"><code>combinations</code></a> as index to your dataframe. You will get all the possible dataframes of the given number... | python|pandas|combinations | 8 |
363,204 | 51,573,038 | Training a Neural Net using tensorflow, why doesthis always predict one class? | <p>Here is my code and below is the output:
I made the train sample have equal number of the two output classes. However, the model always predicts one class. [1 , 0]</p>
<p>I have also noticed that sometimes the output will be [0, 0] - which should be not allowed as the two classes are [1,0] and [0,1].</p>
<p>I did ... | <p>The final output needs to be unscaled "logits". But you use the output of the softmax function.</p>
<p>Try</p>
<pre><code>final_output = tf.add(tf.matmul(hidden_output_2, w2), b2)
</code></pre>
<p>instead. But this is all documented in the Tensorflow documentation and even the naming of the function suggest to us... | tensorflow|neural-network|classification|loss-function | 1 |
363,205 | 51,939,618 | What could cause a type error during the build process of Keras Layer? | <p>I was creating a custom layer based off the NALU paper, but when testing my code in Google Colab (tensorflow version 1.10.0) I got a type error. This did not hapen in my local Jupyter notebook(tensorflow cpu version 1.8.0).</p>
<p>The type error appears to occurring when adding a weight in the build function of Lay... | <p>The stacktrace indicates that somewhere in the code a <code>Dimension</code> value is given as n argument where you usually expect an <code>integer</code>/<code>float</code>. </p>
<p>I think that this might be caused by this line</p>
<pre><code>shape = tf.TensorShape((input_shape[1], self.num_outputs))
</code></pr... | python|tensorflow|keras|google-colaboratory | 2 |
363,206 | 51,654,037 | Ploting data points by omitting the lines Python Pandas | <p>how do I plot only the data points by omitting the lines with Python Python/matplotlib.</p>
<p>Here is my example code so far:</p>
<pre><code> import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'x': [1,2,-3,3,5,7,-1],
'y' : [2.6,3.4,3.25,2.8,1.75,1.34,-3.345]})
df.plo... | <p>You can use parameters <code>marker</code> and <code>linestyle</code> in <code>plt.plot</code>. You can experiment with marker, but if you want to omit lines, <code>linestyle='none'</code> is crucial here.</p>
<pre><code>plt.plot(df.x, df.y, marker='.', linestyle='none')
</code></pre> | python|pandas|matplotlib | 9 |
363,207 | 51,923,444 | Pandas groupby calculating percentage change column | <p>I'm new to pandas dataframes and I need help in understanding percentage changes.</p>
<p>I did generate a csv from a query in order to calculate mean values by assigning ranking to the columns.</p>
<pre><code>rank ds continent region device traffic
1 08/13 North ameri... | <p>Got this figured out. Used pct_change()</p> | python|python-2.7|pandas|pandas-groupby|percentage | 0 |
363,208 | 51,692,299 | How can I plot a bar chart showing total sales for different types of store types in Python? | <p>I have a dataset (not the one below, but of a similar kind) from which I am trying to plot a bar chart in Python so that I can visualize the 'Total Sales' made from different kind of 'Outlet Type'.</p>
<pre><code>ββββββββββββ¦βββββββββββββββββββββ¦ββββββββ
β Location β Outlet_Type β Sales β
β βββββββββββ¬βββββββ... | <p>You're really quite close. Just missing an <code>aggfunc</code> in your current approach, so <code>pivot_table</code> does not sum:</p>
<pre><code>import matplotlib.pyplot as plt
data.pivot_table(values = 'Sales', index = 'Outlet_Type', aggfunc='sum').plot(kind='bar')
plt.tight_layout()
plt.show()
</code></pre>
... | python|pandas|matplotlib|charts | 3 |
363,209 | 51,711,607 | Element-wise broadcasting for comparing two NumPy arrays? | <p>Let's say I have an array like this:</p>
<pre><code>import numpy as np
base_array = np.array([-13, -9, -11, -3, -3, -4, 2, 2,
2, 5, 7, 7, 8, 7, 12, 11])
</code></pre>
<p>Suppose I want to know: "how many elements in <code>base_array</code> are greater than 4?" This can be done s... | <p>You can simply add a dimension to the comparison array, so that the comparison is "stretched" across all values along the new dimension. </p>
<pre><code>>>> np.sum(comparison_array[:, None] < base_array)
228
</code></pre>
<p>This is the fundamental principle with <a href="https://docs.scipy.org/doc/num... | python|arrays|numpy|vectorization|array-broadcasting | 5 |
363,210 | 51,780,178 | non-uniform spacing with numpy.gradient | <p>I'm not sure how to specify non-uniform spacing when using numpy.gradient. </p>
<p>Here's some example code for y = x**2.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = [0.0, 2.0, 4.0, 8.0, 16.0]
y = [0.0, 4.0, 16.0, 64.0, 256.0]
dydx = [0.0, 4.0, 8.0, 16.0, 32.0] # analytical solution
spa... | <p>The API of the function is quite confusing. For non-uniformly spaced sample points, the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html" rel="nofollow noreferrer">gradient function</a> takes the <strong>coordinates of the point</strong> rather than the spacings:</p>
<blockquote>
... | python|numpy|derivative|differentiation | 4 |
363,211 | 51,715,082 | What is the running time (big "O" order) of pandas DataFrame.join? | <p>This problem is more conceptual/theoretical (has to do with run times for very large datasets), so I apologize for not having a minimial example to show. </p>
<p>I have a bunch of DataFrames from two different sensors that I need to eventually concatenate into two <em>very</em> large DataFrames from two different s... | <p>I think it depends on the options you pass to <code>join</code> (e.g. the type of join and whether to sort).</p>
<p>When using the default <strong><code>how='left'</code></strong>, it appears that the result is sorted, at least for single index (the doc only specifies the order of the output for some of the <code>ho... | python|pandas|dataframe|big-o|execution-time | 2 |
363,212 | 51,584,962 | Aggregating a pandas dataframe using groupby, then using apply.... but how to then add the output back into original dataframe? | <p>I have some data with 4 features of interest: <code>account_id</code>, <code>location_id</code>, <code>date_from</code> and <code>date_to</code>. Each entry corresponds to a period where a customer account was associated with a particular location.</p>
<p>There are some pairs of <code>account_id</code> and <code>lo... | <p>I think Mephy is right that this should probably go to StackOverflow. </p>
<p>You're going to have a shape incompatibility because there will be fewer entries in the grouped result than in the original table. You'll need to do the equivalent of an SQL left outer join with the original table and the results, and y... | python|pandas|aggregation | 1 |
363,213 | 51,996,518 | tf.nn.softmax_cross_entropy_with_logits how to use labels | <p>For an assignment, I'm supposed to write a single layer neural network for one part of it. I think I got most of the stuff right, however when I tried using the tf.nn.softmax_cross_entropy_with_logits method, I got an error saying "ValueError: Both labels and logits must be provided." Which obviously means I need to... | <p>In supervised learning you have to give labels along with the training data and softmax_cross_entropy_with_logits calculates the softmax cross entropy between logits and labels. It helps to give the probability of a data being in a particular class. You can read more about it here <a href="https://www.tensorflow.org... | python-3.x|tensorflow|machine-learning|neural-network|computer-science | 2 |
363,214 | 51,879,063 | How to get the maximum number of digits after the decimal point in a Pandas series | <p>I read a list of float values of varying precision from a csv file into a Pandas Series and need the number of digits after the decimal point. So, for 123.4567 I want to get 4.</p>
<p>I managed to get the number of digits for randomly generated numbers like this:</p>
<p><code>
df = pd.Series(np.random.rand(100)*10... | <p><code>pd.read_csv()</code> typically returns a <code>DataFrame</code> object. The <code>StringMethods</code> object returned by using <code>.str</code> is only defined for a <code>Series</code> object. Try using <code>pd.read_csv('your_data.csv' , squeeze=True)</code> to have it return a <code>Series</code> object... | python|pandas|dataframe | 1 |
363,215 | 51,711,170 | numpy: summing along all but last axis | <p>If I have an <code>ndarray</code> of arbitrary shape and I would like to compute the sum along all but the last axis I can, for instance, achieve it by doing</p>
<pre><code>all_but_last = tuple(range(arr.ndim - 1))
sum = arr.sum(axis=all_but_last)
</code></pre>
<p>Now, <code>tuple(range(arr.ndim - 1))</code> is no... | <p>You could reshape the array so that all axes except the last are flattened (e.g. shape <code>(k, l, m, n)</code> becomes <code>(k*l*m, n)</code>), and then sum over the first axis.</p>
<p>For example, here's your calculation:</p>
<pre><code>In [170]: arr.shape
Out[170]: (2, 3, 4)
In [171]: arr.sum(axis=tuple(rang... | python|numpy | 18 |
363,216 | 51,819,213 | Keras function api, setting weight manually to a layer | <p>In keras Sequential model, one can set weight directly using <code>set_weights</code> method.</p>
<pre><code>model.layers[n].set_weights([your_wight])
</code></pre>
<p>However I am facing problem if I am trying to set weight to a layer using functional API.</p>
<p>Here is the code snippet:</p>
<pre><code>emb = E... | <p>If you want to set the weights on Embedding layers you might add them to the constructor like this:</p>
<pre class="lang-py prettyprint-override"><code>from keras.layers import Embedding
embedding_layer = Embedding(len(word_index) + 1,
EMBEDDING_DIM,
weights=... | python|tensorflow|neural-network|keras | 5 |
363,217 | 51,810,364 | How to merge 2 series in pandas where nulls | <p>In a Dataframe/table I have data something like this</p>
<pre><code>+----+-------+--------+
| id | name1 | name2 |
+----+-------+--------+
| 0 | John | |
| 1 | | Nathan |
| 2 | Andy | |
+----+-------+--------+
</code></pre>
<p>I want to merge them to an another column where nulls or empti... | <p>If the empty cells are actually empty strings, you can do so:</p>
<pre><code>df['merged_names'] = df1['name1'] + df2['name2']
</code></pre>
<p>If the empty cells are <code>np.nan</code>, you can use <code>replace</code> in this way:</p>
<pre><code>df['merged_names'] = df1['name1'].replace(np.nan, '') + df2['name2... | python|python-3.x|pandas | 2 |
363,218 | 51,761,345 | Sorting arrays in NumPy by column wrong | <p>I have tested the following code</p>
<pre><code>a=np.array([[1,5],[2,4]])
a[a[:,1].argsort()]
print(a)
</code></pre>
<p>And i receive</p>
<pre><code>[[1,5],[2,4]]
</code></pre>
<p>I am supposed to obtain</p>
<pre><code>[[2,4],[1,5]]
</code></pre>
<p>Numpy is imported as np.
What is going on?</p> | <p>The expression will get evaluated at interpreter level. But the actual value of 'a' will get modified once the assignment happens to the variable. </p>
<pre><code>import numpy as np;
a=np.array([[1,5],[2,4]]);
a=a[a[:,1].argsort()];
print(a);
</code></pre> | python|arrays|numpy|columnsorting | 0 |
363,219 | 51,713,791 | loop to create output files with specific file names and content based on condition where name will be same as row content | <p>i have a file with n # of rows. I am reading the file and assigning it to a dataframe <code>df</code>. One of the columns name is <code>curr_state</code>. Based on the <code>curr_state</code>, I would like to create different output files for each specific <code>curr_state</code>. The output files have to follow a s... | <p>Dynamically named variables are not recommended. They are difficult to track, clutter the namespace, lead to errors. Instead, you can use a dictionary comprehension with <code>GroupBy</code>.</p>
<p>For example, utilising f-strings (Python 3.6+), and assuming you have specified strings <code>Client</code>, <code>Ch... | python|pandas|csv|dataframe | 0 |
363,220 | 51,762,962 | How to create a sub-tensor from a given tensor by selecting windows around some values of this tensor? | <p>My question is similar to the one asked <a href="https://stackoverflow.com/questions/41294064/tensorflow-getting-a-sub-tensor-from-a-tensor-using-indexing">here</a>. The difference is that I would like to have a new tensor <code>B</code> that's a concatenation of some selected windows from the initial tensor <code>A... | <pre><code>import tensorflow as tf
from tensorflow.contrib import autograph
# you can uncomment next line to enable eager execution to see what happens at each step, you'd better use the up-to-date tf-nightly to run this code
# tf.enable_eager_execution()
A = tf.constant([[1, 1, 1],
[2, 2, 2],
... | tensorflow|keras|slice|embedding | 1 |
363,221 | 51,711,750 | Read Relative Lines in a text document and convert to Pandas DF | <p>Working on a Python 3.6 read of a text file to extract <strong>relative</strong> lines to convert into a pandas dataframe.</p>
<p>What works: Searching for a phrase in a text document and converting the line into a pandas df.</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
list1 = []
list2 = []
with open(... | <p>This might do the trick, it does make the assumption that there are <em>always</em> four values before the 'Project' line.</p>
<pre><code>>>> a = []
>>> with open('test.txt') as f:
... prev_lines = []
... for line in f:
... prev_lines.append(line.strip('\n'))
... if 'Projec... | pandas|search|python-3.6 | 1 |
363,222 | 51,572,131 | Ignore zero values and continue with calculation in Python Pandas | <p>Is there a way I could continue with my calculation ignoring the Zero division error by ensuring Python returns a default zero for a Divide by Zero result.
Here is the block of code below:</p>
<pre><code>import pandas as pd
import numpy as np
data = {'Sales': [5000, 4000],
'COS': [0, 0],
'Inventory': [40... | <h3>try / except</h3>
<p>You can use <code>try</code> / <code>except</code>. You just need to include the inversion <code>1 / x</code> within the <code>try</code> part, and then multiply by the result instead of divide. One way is to define a function to do this for you:</p>
<pre><code>def inv_div_try(num, denom):
... | python|python-3.x|pandas|numpy | 5 |
363,223 | 51,808,573 | Running window of max-min in a numpy array. | <p>I'm trying to perform a "running max-min window" on a numpy array, such that for a given window size, the function returns the distance between the maximum and minimum values for this window.</p>
<p>I would also like to determine the length of each "skip" of the window. </p>
<p>For example:</p>
<p>if <code>x_arra... | <p>Here is a solution using the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.minimum_filter.html#scipy.ndimage.minimum_filter" rel="nofollow noreferrer">maximum and minimum filters from <code>ndimage</code></a>:</p>
<pre><code>import numpy as np
from scipy.ndimage import maximum_filter
... | python|numpy | 2 |
363,224 | 51,938,154 | Pandas read_csv drops first 2 digits from year | <p>In my .csv file I have a datetime column in a <code>05/20/1935 12:00:00 AM</code> format. Whenever I inject the data to pandas, the format changes to <code>5-20-35 12:00</code> and this would later on ruin my calculations as <code>pd.to_datetime()</code> would convert it to be <code>2035</code>.</p>
<p><strong>EDIT... | <p>It looks like you have a <code>|sv</code> file as opposed to a <code>csv</code> file. Try the following:</p>
<pre><code>df = pd.read_csv('your_file.csv', sep='|', index_col=0)
</code></pre> | pandas|python-datetime | 0 |
363,225 | 51,951,181 | Python Pandas if/else Statement | <p>I am trying to write a nested <code>if/else</code> statement using pandas, but not very great with if statements in pandas. Please find the sample CSV data being processed and the sample code snippet I've written so far.</p>
<p><code>df</code>:</p>
<pre><code>t1
8
1134
0
119
122
446
21
0
138
0
</code></pre>
<p... | <p>It is not efficient to use loops and <code>if</code> statements in pandas, unless absolutely necessary. Here is a completely vectorized, 100% pandas solution:</p>
<pre><code>import numpy as np # Needs numpy, too
x = df['t1'] // 720 * max_rate # Note the use of //!
y = df['t1'] % 720 * rate
df['cost'] = np.where(df... | python|pandas|if-statement | 4 |
363,226 | 51,579,868 | Compute the mean for each tensor's row in TensorFlow | <p>I am new in tensorflow and I want to compute the mean from each row from a tensor. Tensorflow has the tf.reduce_mean operation in order to do that. The problem is that when a row has a nan value the mean for this row is nan also. Except from that, I want to implement this on my own in order to understand better the ... | <pre><code>import tensorflow as tf
import numpy as np
ratings = np.array([[7, 6, 7, 4, 5, 4], [6, 7, np.NaN, 4, 3, 4], [np.NaN, 3, 3, 1, 1, np.NaN],
[1, 2, 2, 3, 3, 4], [1, np.NaN, 1, 2, 3, 3]], dtype = np.float16)
tRatings = tf.convert_to_tensor(ratings, dtype = np.float16)
means = tf.get_varia... | python|tensorflow | 1 |
363,227 | 51,957,231 | Spatial join in geopandas when overlapping polygons? | <p>I have two datasets, one with points (shops) and one with polygons (districts).</p>
<p>The districts dataset sometimes has overlapping polygons (as I have buffered them).</p>
<p>I want to know if each polygon has any matching points?</p>
<pre><code>joined = geopandas.sjoin(districts,shops, op='contains', how='inn... | <h1>TL/DR</h1>
<pre class="lang-py prettyprint-override"><code>gpd.sjoin(districts, shops, how="left", op="contains") \
.reset_index()\
.rename(columns={"index": "districts"})\
.groupby(["districts"])\
.agg(nshops=("index_right", "nunique"), lshops=(... | python|geopandas | 1 |
363,228 | 51,991,102 | How to get the same data batch multiple times using TensorFlow's `tf.data` API | <p>Is there a way to evaluate a tensor that depends on an tf.data iterator but temporarily pause the iterator so that it returns the previous batch? </p>
<p>Imagine snippet below:</p>
<pre><code>dataset = tf.data.Dataset.range(5)
iterator = dataset.make_one_shot_iterator()
next_batch = iterator.get_next()
train_op = ... | <p>Does not it work in following ways,</p>
<pre><code>dataset = tf.data.Dataset.range(5)
iterator = dataset.make_one_shot_iterator()
next_batch = iterator.get_next()
train_op = next_batch * 10
other_ops = do_other_stuff(next_batch)
num_train_batch = 50
for ep in range(num_train_batch):
if ep%N==0:
_, other_s... | tensorflow|tensorflow-datasets | -1 |
363,229 | 51,611,221 | Tensorflow Loss and accuracy error Neural Network | <p>Hope you are in good health. Actually I am facing a problem in my self built code. I am a beginner in Machine Learning and working on neural network. I build my own neural network and trying to train dataset with the help of tensorflow but getting alot of loss and having some problem with printing my accuracy Please... | <p>Your data Matrix is a 4D array of size (48000 * 28 * 28 * 1) which is > 784,500.
As a side note, 32,928,000 is actually 28 * 28 * 42000, probably X_train matrix has a different shape.
Could you add print(X_train.shape[0]) and double check your matrix?</p>
<p>To solve your problem with GraphDef, have a look at thi... | python-3.x|tensorflow|neural-network|deep-learning|mnist | 1 |
363,230 | 51,656,681 | set comprehension syntax error using numpy | <p>I'm trying to pick random zone in an image using numpy.</p>
<p>I'm using a python set to ensure that all my zones are unique, however, later when trying to generate a mask from this set, I'm getting an "SyntaxError: invalid syntax"</p>
<p>here is the code I'm using:</p>
<pre><code>def _get_positions(self):
sm... | <p>You can not the <a href="http://python-reference.readthedocs.io/en/latest/docs/comprehensions/set_comprehension.html" rel="nofollow noreferrer"><code>set comprehension</code></a> that you are using here</p>
<pre><code>{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
</code></pre>
<p>these comprehens... | python|numpy|set | 3 |
363,231 | 51,631,249 | How to check if a list of numpy arrays contains a given test array? | <p>I have a list of <code>numpy</code> arrays, say,</p>
<pre><code>a = [np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)]
</code></pre>
<p>and I have a test array, say </p>
<pre><code>b = np.random.rand(3, 3)
</code></pre>
<p>I want to check whether <code>a</code> contains <code>b</code> or not. How... | <p>You can just make one array of shape <code>(3, 3, 3)</code> out of <code>a</code>:</p>
<pre><code>a = np.asarray(a)
</code></pre>
<p>And then compare it with <code>b</code> (we're comparing floats here, so we should use <code>isclose()</code>)</p>
<pre><code>np.all(np.isclose(a, b), axis=(1, 2))
</code></pre>
<p... | python|numpy | 5 |
363,232 | 51,741,211 | Division by 0 within a map function | <p>I am wondering how to handle the division by 0 error inside a map function (under Python 2.7).</p>
<p>Without using <code>map</code>, I get</p>
<pre><code>def my_func(a, b):
return a / b
a = pandas.DataFrame([1, 1])
b = pandas.DataFrame([1, 0])
my_func(a, b)
Out[]:
0
0 1.000000
1 inf
</code... | <p>You could try in this way:</p>
<pre><code>def my_func(a, b):
if b != 0: return a / b
else: return np.inf
</code></pre>
<p>Or catching the warning with:</p>
<pre><code>import warnings
warnings.filterwarnings("error")
def my_func(a, b):
try:
return a / b
except:
return np.inf
</code... | python|pandas|numpy|divide-by-zero | 1 |
363,233 | 51,662,838 | Pandas Column based on values in other columns | <p>Basically, I would like to fill in column Discount_Sub_Dpt with 'Yes' or 'No' depending on if there is a Discount for that Sub_Dpt for that week EXCLUDING the product on which that row lands (for instance I don't want any of the A rows to consider whether there is a Discount for that week for A but rather only for t... | <p>Ok, the following is a bit crazy, but it works pretty nicely, so listen up.</p>
<p>First, we are going to build a <code>NetworkX</code> graph as follows.</p>
<pre><code>import networkx as nx
import numpy as np
import pandas as pd
G = nx.Graph()
Prods = df.Product.unique()
G.add_nodes_from(Prods)
</code></pre>
<p>... | python|pandas|csv|dataframe|pandas-groupby | 2 |
363,234 | 51,987,962 | can't install pandas in windows python 3.7? | <p>Due to some reasons I need to install pandas manually, I found this link: <a href="https://pandapower.readthedocs.io/en/v1.5.1/getting_started/installation_without_pip.html" rel="nofollow noreferrer">https://pandapower.readthedocs.io/en/v1.5.1/getting_started/installation_without_pip.html</a></p>
<p>FYI: since I am... | <p>Since it seems you are in a special circumstance where installing packages via <code>pip</code> and <code>conda</code> is not easy, I really recommend Anaconda. Anaconda Python offers python, environment control, and a few hundred commonly used packages (with dependencies) all located in a single tool.</p>
<p>This ... | python|pandas | 0 |
363,235 | 51,874,297 | Comparing two dataframes to return a new dataframe using pandas - Python | <p>Need your help please.</p>
<p>I have two dataframes created from csvs and I need to return a new dataframe which will be the difference between the two on a specific field/column. For example, if ID from df1 is not in df2, then df3 should give me all columns and rows from df1 that are not in df2. </p>
<p>Note df1 ... | <p>I would do:</p>
<pre><code>import pandas as pd
fileLocationDF1 = "BBG.csv"
fileLocationDF2 = "corp.csv"
createDf1 = pd.read_csv(fileLocationDF1, low_memory = False)
createDf2 = pd.read_csv(fileLocationDF2, engine='python')
# df3 will have createDf1 columns with ID's that are not in createDf2
# ~ means 'not' to t... | python|pandas|dataframe | 2 |
363,236 | 51,750,164 | How to loop through columns of a pandas DataFrame | <p>I have a CSV file with thousands of rows. The file has 3 columns Date, Time and Value. I want to first loop through the date column and then the time column then add the value between two particular time. Is there any function in Pandas to achieve this? Below is my sample CSV. The dates are not continuous but they a... | <p>You can achieve this through the use of the <code>resample</code> method.</p>
<p>First you need to merge your date column and time column to create a single date time index. Assuming your two columns are strings (if they are not you can call <code>as_type(str)</code> on them), you can concatenate the columns, conve... | python|pandas|dataframe|datetime|for-loop | 0 |
363,237 | 35,832,815 | Pandas : vectorized operations on maximum values per row | <p>I have the following pandas dataframe <code>df</code>:</p>
<pre><code>index A B C
1 1 2 3
2 9 5 4
3 7 12 8
... ... ... ...
</code></pre>
<p>I want the maximum value of each row to remain unchanged, and all the other values to become <code>-1... | <p>Consider using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow"><code>where</code></a>:</p>
<pre><code>>>> df.where(df.eq(df.max(1), 0), -1)
A B C
index
1 -1 -1 3
2 9 -1 -1
3 -1 12 -1
</code></pre>
<p>Here <code... | python|pandas|max|dataframe|vectorization | 6 |
363,238 | 36,028,932 | How to extract specific content in a pandas dataframe with a regex? | <p>Consider the following pandas dataframe:</p>
<pre><code>In [114]:
df['movie_title'].head()
β
Out[114]:
0 Toy Story (1995)
1 GoldenEye (1995)
2 Four Rooms (1995)
3 Get Shorty (1995)
4 Copycat (1995)
...
Name: movie_title, dtype: object
</code></pre>
<p><strong>Update:</strong>
I would like to... | <p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="noreferrer"><code>str.extract</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="noreferrer"><code>strip</code></a>, but better is use <a href=... | python|regex|string|python-2.7|pandas | 53 |
363,239 | 35,980,705 | Python Pandas: Index a value and boolean comparison | <p>Consider this dataframe:</p>
<pre><code>index = pd.Index(list(range(5)), name='rows')
columns = pd.Index(['A', 'B', 'C'], name='cols')
df = pd.DataFrame(np.random.randn(5, 3), index=index, columns=columns)
if df.A[-1:] < df.B[-1:] and df.B[-1:] > df.C[-1:] :
print True
</code></pre>
<p>Here, I'm trying t... | <p><code>df.A[-1:]</code> selects a range of the last item to the end, you want just <code>df.A[-1]</code>.</p> | python|pandas | 1 |
363,240 | 36,189,345 | Errors accessing MultiIndex in DataFrame from spreadsheet | <p>This is difficult to pin down, but it seems like I cannot use a multiindex in a dataframe read from a spreadsheet with <code>pandas.read_excel</code>. I've placed all files in a <a href="https://gist.github.com/cswarth/9b4c33d902e9752c66a4" rel="nofollow">Gist</a></p>
<pre><code>df = pd.read_excel('small.xlsx')
d... | <p>I think I know why this happens now. I printed out types being compared in <code>pandas.indexes.base.Index.is_type_compatible</code></p>
<pre><code>is_type_compatible: kind=string inferred_type=unicode
</code></pre>
<p>So apparently <code>pandas.read_excel()</code> is reading strings as unicode and those are typ... | python|python-2.7|pandas | 0 |
363,241 | 36,235,678 | Pandas use variable for column names part 2 | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
df
A B C D E F
0 1 ... | <p>I think you need add column <code>F</code> to <code>list</code>:</p>
<pre><code>allcols = cols + ['F'] + cols2
print df[allcols]
A B F C D
0 1 4 7 7 1
1 2 5 4 8 3
2 3 6 3 9 5
</code></pre>
<p>Or:</p>
<pre><code>print df[cols + ['F'] +cols2]
A B F C D
0 1 4 7 7 1
1 2 5 4 8 3
... | python-3.x|pandas | 2 |
363,242 | 36,139,283 | Python: turn single array of sorted, repeat values into an array of arrays? | <p>I have a sorted array with some repeated values. How can this array be turned into an array of arrays with the subarrays grouped by value (see below)? In actuality, my_first_array has ~8 million entries, so the solution would preferably be as time efficient as possible.</p>
<pre><code>my_first_array = [1,1,1,3,5,5... | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code> makes this trivial</a>:</p>
<pre><code>import itertools
wanted_array = [list(grp) for _, grp in itertools.groupby(my_first_array)]
</code></pre>
<p>With no <code>key</code> function, it just ... | python|arrays|numpy | 4 |
363,243 | 35,930,312 | how to combine two numpy arrays and form a new array of a new size | <p>I have two numpy arrays that have the same shape(4,1,2).
How can I combine them and get a new array of size(8,1,2) with minimum lines of python code? Not changing values just put them together with A on the top B at the bottom.</p>
<pre><code> A=numpy.array([[[1,1]],
[[2,2]],
... | <p><a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.concatenate.html" rel="nofollow"><code>numpy.concatenate()</code></a> should do what you want:</p>
<pre><code>numpy.concatenate((A, B))
</code></pre> | python|arrays|numpy | 1 |
363,244 | 35,947,561 | How to join two tables while merging column names | <p>I have two data frames df1 and df2. One looks like </p>
<pre><code> Surname Knownas TB
0 K S 79.3
1 H E 79.1
2 I S 78.3
3 P B 78.2
4 W A 78.1
</code></pre>
<p>The other ones looks like</p>
<pre><code> Mathemati... | <p>I would expand the <code>Name</code> column into two columns (<code>Surname</code> and <code>Knownas</code>) and merge using <code>Surname</code> and <code>Knownas</code> columns in both DFs:</p>
<pre><code>import six
import pandas as pd
data = """\
Surname Knownas TB
0 K S 79.3
1 T ... | python|pandas | 1 |
363,245 | 35,893,894 | how to implement logical and on array length? | <p>I need to translate the matlab code</p>
<pre><code>indexSelect0 = a.index1==0 & a.index2==wRange;
</code></pre>
<p>into a fast python style. My try is:</p>
<pre><code>idx1=np.array(np.where(a['index2'][:,0]==wIndex2))
idx=np.array(np.where(a['index1'][:,0]==wIndex1))
indexSelect0 = ma.masked_array(idx,mask=[n... | <p>For backup I found the answer. I thank Anton for having directed me to DataFrame</p>
<pre><code>import pandas as pd
d = {'index1': a['index1'][:,0].squeeze(), 'index2': a['index2'][:,0].squeeze(), 'data': x}
df= pd.DataFrame(data=d)
y = df[(df.index1==wIndex1) & (df.index2==wIndex2)]
</code></pre>
<p>So I use ... | python|arrays|matlab|numpy|logical-operators | 2 |
363,246 | 36,210,071 | Pandas Dataframe to_dict() with unique column values as keys | <pre><code>df = pd.DataFrame({'A': ['jars', 'used'], 'B': ['Phrase', 'Phrase']})
A B
0 jars Phrase
1 used Phrase
</code></pre>
<p>Desired Output:</p>
<pre><code>{'Phrase': ['jars', 'used']}
</code></pre>
<p>If column <code>B</code> has multiple unique values (say: Unique values were <code>Broad</cod... | <pre><code>In [11]: df.groupby('B').agg({'A': lambda x: x.tolist()})['A'].to_dict()
Out[11]: {'Phrase': ['jars', 'used']}
</code></pre> | python|pandas|dataframe | 3 |
363,247 | 35,950,319 | python plotting with pandas | <p>So, I have values that look like this. Now, with pandas plotting function, like
upperband.plot(), it shows broken line for the first few values like below:</p>
<pre><code>2015-03-12 NaN
2015-03-13 NaN
2015-03-16 NaN
2015-03-17 NaN
2015-03-18 NaN
2015-03-19 ... | <p>If you want to just ignore the data that is missing you can use</p>
<pre><code>df = df.dropna()
</code></pre> | python|python-3.x|pandas|matplotlib | 1 |
363,248 | 35,951,883 | Plot a histogram without the zero values in python? | <p>When I try to make a histogram without the zero values, I get an error: </p>
<blockquote>
<p>Traceback (most recent call last):. </p>
</blockquote>
<p>I have a list of <code>Beam_irradiance_DNI</code> values which include several zeroes. I can make histogram, but I don't want the zero values.</p>
<pre><code>imp... | <p>You can only perform logical indexing (<code>data[data != 0]</code>) on a <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array.html" rel="nofollow"><code>numpy.array</code></a> <em>not</em> a normal python list. If you want to remove values from a python list, you'll want to use a list com... | python|numpy|matplotlib|scipy | 4 |
363,249 | 36,107,180 | To_CSV unique values of a pandas column | <p>When I use the following:</p>
<pre><code>import pandas as pd
data = pd.read_csv('C:/Users/Z/OneDrive/Python/Exploratory Data/Aramark/ARMK.csv')
x = data.iloc[:,2]
y = pd.unique(x)
y.to_csv('yah.csv')
</code></pre>
<p>I get the following error:</p>
<pre><code>AttributeError: 'numpy.ndarray' object has no attribute... | <p>IIUC, starting from a dataframe:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,3,4,5,6],'b':['a','a','b','c','c','b']})
</code></pre>
<p>you can get the unique values of a column with:</p>
<pre><code>g = df['b'].unique()
</code></pre>
<p>that returns an array:</p>
<pre><code>array(['a', 'b', 'c'], dtype=object)
</... | python|pandas|csv|numpy | 19 |
363,250 | 35,961,972 | Broadcast function in Numpy similar to matrix multiplication | <p>So I am building a KNN for some larger datasets, and I am required to run Leave-one-out cross validation in order to choose the correct K, so speed is important. </p>
<p>I am trying to do the distance calculation via broadcasting. </p>
<hr>
<p>The situation is: <code>X</code> is my training matrix, a 2D matrix ... | <p>As Divakar already mentioned, the simplest option is probably <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a>:</p>
<pre><code>from scipy.spatial.distance import cdist
distances = cdist(y, x) ... | python|numpy|knn | 2 |
363,251 | 37,517,022 | Efficiently convert gmpy2.mpz to numpy boolean array | <p>I try to convert from gmpy2.mpz to a numpy boolean array, but can't quite get it right. (gmpy2: <a href="https://gmpy2.readthedocs.io" rel="nofollow">https://gmpy2.readthedocs.io</a>)</p>
<pre><code>import gmpy2
import numpy as np
x = gmpy2.mpz(int('1'*1000,2))
print("wrong conversion 1")
y = np.fromstring(gmpy2.... | <p>There are a couple of options. The function <code>gmpy2.bit_scan1(x, n)</code> will return the index of the first bit that is set that has an index >= n.</p>
<pre><code>>>> x = gmpy2.mpz(123456)
>>> bin(x)
'0b11110001001000000'
>>> n = 0
>>> while True:
... n = gmpy2.bit_scan... | python|numpy|gmpy | 1 |
363,252 | 37,573,996 | Tensorflow memory management -- chunking? | <p>I have a problem computing a reduction of a function of a network represented by a large (200000x200000) matrix generated as a distance matrix between pairs of points.</p>
<p>Minimal example, input X a 200000x2 numpy array of cartesian coordinates:</p>
<pre><code>x = tf.constant(X[:,0], shape=[X.shape[0],1])
y = t... | <p>What's really needed here (but not yet implemented) is cwise fusion. What's happening right now is that <code>2*sqrt(a+b)</code> will allocate new Tensor for <code>a+b</code>, then new tensor for <code>sqrt</code> and then another one for <code>2*sqrt</code>. PS, you can dig where the memory is going by examining me... | python|memory|tensorflow | 1 |
363,253 | 37,304,449 | Summing a column in Pandas Groupby | <p>I want to group by column A, and sum over column C and return the results immediately into the dataframe. I know that I need to use groupby, and I know that I need to use sum, but I cannot figure out how to get these functions to interact seamlessly and in one line of code.</p>
<p>Have</p>
<pre><code> A B ... | <p>call <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow"><code>transform</code></a> on the <code>groubpy</code> to add the aggregated column back to the original df:</p>
<pre><code>In [28]:
df['D'] = df.groupby('A')['C'].transform('sum')
df
Out[28]:
A B C D
0 ... | python|pandas|dataframe|group-by | 3 |
363,254 | 37,402,471 | Return groupby columns as new dataframe in Python Pandas | <p>Input: CSV with 5 columns.</p>
<p>Expected Output: Unique combinations of 'col1', 'col2', 'col3'. </p>
<p><strong>Sample Input:</strong></p>
<pre><code> col1 col2 col3 col4 col5
0 A B C 11 30
1 A B C 52 10
2 B C A 15 14
3 B C A 1 91
</code></pre>
<p><... | <pre><code>df[['col1', 'col2', 'col3']].drop_duplicates()
</code></pre> | python|pandas|dataframe | 3 |
363,255 | 37,508,659 | Group by and Count distinct words in Pandas DataFrame | <p>By year and name, I am hoping to count the occurrence of words in a dataframe from imported from Excel which results will also be exported to Excel.</p>
<p>This is the sample code:</p>
<pre><code>source = pd.DataFrame({'Name' : ['John', 'Mike', 'John','John'],
'Year' : ['1999', '2000', '2000','2... | <p>I think you can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> column <code>Message</code>, create <code>Serie</code> and add it to original <code>source</code>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generat... | python|pandas|dataframe|group-by|distinct-values | 2 |
363,256 | 37,550,248 | Adding a new column to the table in a database using sqlalchemy, pyodbc | <pre><code>cnx=sqlalchemy.create_engine("mssql+pyodbc://Omnius:MainBrain1@172.31.163.135:1433/Basis?driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0")
cnx1 = pyodbc.connect('driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0;server=SRVWUDEN0835;database=Basis;uid=Omnius; pwd=MainBrain1')
sqlquer... | <p>you have incorrectly built your <code>alter table ... add column ...</code> SQL.</p>
<p>It should look like as follows (for single column):</p>
<pre><code>ALTER TABLE table_name ADD COLUMN column_name data_type(precision);
</code></pre>
<p>or for multiple columns:</p>
<pre><code>ALTER TABLE table_name ADD COLUMN... | python|pandas|sqlalchemy|pyodbc | 3 |
363,257 | 37,348,328 | output multiple files based on multiple column values pandas python | <p>This question follows my previous question <a href="https://stackoverflow.com/questions/37216230/output-multiple-files-based-on-column-value-python-pandas">output multiple files based on column value python pandas</a>
but this time i want to go a bit further. </p>
<p>so this time i have a small sample data set: </... | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> by condition in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow noreferrer"><code>any</code></a> value in c... | python|pandas | 3 |
363,258 | 37,497,094 | Access the row number by its index | <p>I'm trying to access the row number with an index value corresponding to that row.</p>
<pre><code>mydata = [{'name': 'John', 'age': 75, 'height':1.78},
{'name': 'Paul', 'age': 22, 'height':1.71}]
df = pandas.DataFrame(mydata)
df = df.set_index('name')
</code></pre>
<p>Get index value of row number 1</p>
<p... | <p>You can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="noreferrer"><code>get_loc</code></a>:</p>
<pre><code>df.index.get_loc(index_value)
Out[67]: 1
</code></pre> | python|pandas | 7 |
363,259 | 37,422,487 | Is there a way to use the melt function in Python for multiple columns? | <p>I have a table in a cross-tab format, example below:</p>
<pre class="lang-html prettyprint-override"><code>State Item # x1 x2 x3 y1 y2 y3 z1 z2 z3
CA 1 6 4 3 7 5 3 11 5 1
CA 2 7 3 1 15 10 5 4 2 1
FL 3 3 2 1 5 3 ... | <p>I don't think so, but you could use two line solution:</p>
<pre><code>values = [['x1','x2','x3'], ['y1', 'y2', 'y3'], ['z1', 'z2', 'z3']]
df_m = pd.concat([pd.melt(df, id_vars=['State', 'Item_#'], value_vars=val, var_name='var', value_name='value') for val in values])
</code></pre>
<p>The <code>pd.concat</code> f... | python|pandas|melt | 1 |
363,260 | 37,194,862 | Tensorflow for 1D input vector | <p>I am a a beginner in machine learning and currently trying to learn about deep learning and convNets. I have been following the tutorials on tensorflow.org and have done the first two tutorials. But so far I have done examples of 2d input vectors (images). </p>
<p>My ultimate goal is to be able to train a CNN to be... | <p>There is no actual difference, simply your convolutional kernels will be rectangular instead of square, of size 1xK (as opposed to typical KxK). Besides that there is no much of the difference.</p> | machine-learning|tensorflow|deep-learning | 3 |
363,261 | 37,331,127 | How to randomly append "Yes/No" (ratio of 7:3) to a column in pandas dataframe? | <p>I have a dataframe , which consists of three columns. And i want to append "Yes" or "No" to one of the column using python-pandas. Also the ratio between Yes:No is 7:3.</p>
<p>Had anyone tried this??</p> | <p>With numpy's <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>random.choice</code></a>:</p>
<pre><code>df["new_column"] = np.random.choice(["Yes", "No"], len(df), p=[0.7, 0.3])
</code></pre>
<p>Note: np.random.choice consists of independent ... | python|pandas|dataframe | 9 |
363,262 | 37,545,626 | Python - Loop parallelisation with joblib | <p>I would like some help understanding exactly what I have done/ why my code isn't running as I would expect. </p>
<p>I have started to use joblib to try and speed up my code by running a (large) loop in parallel.</p>
<p>I am using it like so:</p>
<pre><code>from joblib import Parallel, delayed
def frame(indeces, i... | <p>Maybe your problem is caused because <code>image_pad</code> is a large array. In your code, you are using the default <code>multiprocessing</code> backend of <code>joblib</code>. This backend creates a pool of workers, each of which is a Python process. The input data to the function is then copied <code>n_jobs</cod... | python|numpy|parallel-processing|joblib | 3 |
363,263 | 37,284,083 | Apply custom cumulative function to pandas dataframe | <p>I have a dataframe sorted by <code>date</code>:</p>
<pre><code>df = pd.DataFrame({'idx': [1, 1, 1, 2, 2, 2],
'date': ['2016-04-30', '2016-05-31', '2016-06-31',
'2016-04-30', '2016-05-31', '2016-06-31'],
'val': [10, 0, 5, 10, 0, 0],
... | <p>I don't believe there is an easy way to accomplish your objective using vectorization. I would first try to get something working, and then optimize for speed if required.</p>
<pre><code>def cumulative_func(df):
results = []
for group in df.groupby('idx').groups.itervalues():
total = 0
resu... | python|pandas | 5 |
363,264 | 37,175,131 | Why will my network not learn? | <p>So I created a convolutional network in tensorflow but the accuracy will not change at all. I am trying to get it to tell the difference between triangles and circles. They are different colors and similar sizes. This is the code for the network. Also when I tried with a fully connected network the accuracy was almo... | <p>You cannot initialize all parameters to zeros(or any constant), which is almost a commonsense for almost all kinds of neural network. </p>
<p>Lets just imagine a simplest feed-forward network with all weight matrices initialized to the same constant(including but not just zero), what's gonna happen? No matter what ... | python|tensorflow | 3 |
363,265 | 42,041,522 | Appending a list to a column in Pandas while copying the rest of the values | <p>I have a Pandas dataframe read from a CSV file that is structured like this:</p>
<pre><code>x_column y_column number_column
--- ---- ----
--- ---- ----
xxx yyyy 1
xxx yyyy 2
xxx yyyy 35
xxx yyyy 42
</code></pre>
<p>Th... | <p>Don't call <code>data_df = data_df.append(...)</code> in a loop since that leads to <a href="https://stackoverflow.com/a/36489724/190597">quadratic copying</a>, which is very bad for performance. Instead, append to a list, build one DataFrame, then concatenate it to your original DataFrame:</p>
<pre><code>tmp = pd.... | python|csv|pandas | 2 |
363,266 | 41,946,106 | Pandas Read CSV file with variable rows to skip with special character at the beginning of row | <p>When reading a CSV file using pandas, read_csv method, how do I skip the lines if the number of lines are not known in advance ? </p>
<p>I have a CSV file which contains some meta-data at the beginning of the file and then contains the header and actual data.</p>
<ul>
<li>The meta data always start with a <strong>... | <p><code>comment</code> is what you're searching for:</p>
<pre><code>df = pd.read_csv('sample_file.csv', comment='#')
</code></pre>
<p>From the documentation:</p>
<blockquote>
<p>comment : str, default None </p>
<p>Indicates remainder of line should not be
parsed. If found at the beginning of a line, the li... | python|csv|pandas | 7 |
363,267 | 42,109,590 | Mixture of experts - Train best model only at each iteration | <p>I am trying to implement a crude method based on the Mixture-of-Experts paper in <strong>tensorflow</strong> - <code>https://arxiv.org/abs/1701.06538</code></p>
<p>There would be <code>n</code> models defined:</p>
<pre><code> model_1:
var_11
var_12
loss_1
optimizer_1
model_2... | <p>This seems to be doable with <code>tf.cond</code>:</p>
<pre><code>import tensorflow as tf
def make_conditional_train_op(
should_update, optimizers, variable_lists, losses):
"""Conditionally trains variables.
Each argument is a Python list of Tensors, and each list must have the same
length. Variables ar... | python|tensorflow | 4 |
363,268 | 41,807,959 | Reshapint ndarray from 2d to 3d | <p>I am currently having problems reshaping an numpy.ndarray from 2d to 3d.. </p>
<p>the current shape of my numpy.ndarray is (221286, 2050) and i need it to be
(221286 , 1, 2050)</p>
<p>I tried doing it like this: </p>
<pre><code>train_set_data_vstacked_normalized_reshaped = np.reshape(train_set_data_vstacked_norm... | <p><code>np.reshape</code>, when used as a function, takes the array to reshape as first argument, and the new shape as second. So this should do it:</p>
<pre><code>shape = your_long_named_array.shape
your_long_named_array_reshaped = np.reshape(your_long_named_array,
(shape[... | python|numpy | 1 |
363,269 | 42,034,480 | Efficient tensor contraction in python | <p>I have a list <code>L</code> of tensors (<code>ndarray</code> objects), with several indices each. I need to contract these indices according to a graph of connections. </p>
<p>The connections are encoded in a list of tuples in the form <code>((m,i),(n,j))</code> signifying "contract the <em>i</em>-th index of the ... | <p>Memory considerations aside, I believe you can do the contractions in a single call to <code>einsum</code>, although you'll need some preprocessing. I'm not entirely sure what you mean by "<em>as I contract a pair of indices, the result is a new tensor that does not belong to the list <code>L</code></em>", but I thi... | python|numpy|vectorization|numpy-einsum | 5 |
363,270 | 41,948,544 | Dataframe to dict python pandas | <p>I have the following dataframe, imported from a python dict:</p>
<p><code>perimeter risk vuls
0 External High 35
1 External Low 9
2 External Medium 76
3 Internal High 36
4 Internal Low 8
5 Internal Medium 41</code> </p>
<p>and I need to extract the following output:</... | <p>You want a list of dictionaries each of which comes from a single perimeter. You can loop through the grouped data frame with group variable of <code>perimeter</code> and construct the <code>perimeter</code> from the key and <code>risk</code> from the values with a list comprehension as follows: </p>
<pre><code>[{'... | python|list|pandas|dataframe|output | 1 |
363,271 | 41,760,608 | Add json elements to a pandas data frame | <p>I have a pandas df which I have created. The structure of the df is as follows :-</p>
<pre><code> A B C D
0 a b c NaN
2 x y z NaN
.
.
</code></pre>
<p>Now also have a list <strong>list1</strong> which has json as elements like</p>
<pre><code>[{a:1,b:2},{c:1,d:2},....]
</code></pre>
<p>I would like to... | <p>Solutions if <code>length</code> of <code>list1</code> is same as length of <code>DataFrame</code>:</p>
<p>You need create <code>Series</code> first with same index as <code>df</code> and then assign to new column:</p>
<pre><code>print (pd.Series(list1, index=df.index))
0 {'b': 2, 'a': 1}
2 {'d': 2, 'c': 1}
... | python|json|pandas | 2 |
363,272 | 41,842,310 | Does image size matter when training with TensorFlow? | <p>I was wondering if there is any benefit to training on high resolution images rather than low resolution. I understand that it will take longer to train on larger images and that the dimensions must be a multiple of 32. My current image set is 1440x1920. Would I be better off resizing to 480x640, or is bigger better... | <p>It's certainly not a requirement that your images be powers of two. There may be some cases where it speeds things up (e.g. GPU allocation) but it's not critical.</p>
<p>Smaller images will train significantly faster, and possibly even converge quicker (all other factors held constant) as you will be able to train ... | image-processing|machine-learning|tensorflow|computer-vision | 8 |
363,273 | 41,845,773 | pandas data frame read_excel: How to look for empty cells? | <p>I have a data frame that is constructed by pd.read_excel.
I want to create a second data frame by selecting all rows of the prior data frame where a column of the excel has a empty cell.</p>
<p>Something like </p>
<pre><code>A = df.loc[df["column"]==None]
</code></pre>
<p>did not work.</p> | <p>Use <code>isnull</code> instead</p>
<pre><code>A = df.loc[df["column"].isnull()]
</code></pre>
<p>Alternatively, you could use <code>query</code> because <code>None</code> is not equal to itself, this works</p>
<pre><code>A = df.query('column != column')
</code></pre> | python-3.x|pandas|dataframe | 9 |
363,274 | 41,791,327 | pandas groupby lteration does not work | <p>I have split my data into training set, validation set, and test set by grouping according to some different groups. The purpose is that the sets will have roughly equal shares of different classes.</p>
<p>After that, I'm trying to scale the data per column in the training set, and use the same transformation for t... | <p>I actually solved it the dirty way, i.e. just looping through features, classes, and types (3 for loops).</p>
<p>I'll post the code as soon as I'm in the cloud again.</p> | python|pandas | 0 |
363,275 | 41,963,839 | TensorFlow: Evaluating functions across a tensor | <p>Sci-Py lets me do the following with the norm.pdf function:</p>
<pre><code>x = 1;
mu = [1,2,3,4];
sigma = [1,1,1,1];
scipy.stats.norm.pdf(x,mu,sigma)
</code></pre>
<p>This will basically give me an array, where each element corresponds to the probability density of x given the corresponding mean and variance.</p... | <p>Using TensorFlow, you can do it in 2 steps with <a href="https://www.tensorflow.org/api_docs/python/contrib.distributions/univariate__scalar__distributions#Normal" rel="nofollow noreferrer"><code>tf.contrib.distributions.Normal</code></a> and <a href="https://www.tensorflow.org/api_docs/python/contrib.distributions/... | tensorflow | 0 |
363,276 | 42,014,062 | Pandas intersection of groups | <p>Hi I'm trying to find the unique <code>Player</code> which show up in every <code>Team</code>.</p>
<p>df = </p>
<pre><code>Team Player Number
A Joe 8
A Mike 10
A Steve 11
B Henry 9
B Steve 19
B Joe 4
C Mike 18
C Joe 6
C ... | <p>You can use a <code>GroupBy.transform</code> to get a count of unique teams that each player is a member of, and compare this to the overall count of unique teams. This will give you a Boolean array, which you can use to filter your DataFrame:</p>
<pre><code>df = df[df.groupby('Player')['Team'].transform('nunique'... | python|pandas|group-by|intersection | 10 |
363,277 | 41,773,540 | How to install numpy to Python 3.5? | <p>I'm attempting to install numpy on python3.5 via :</p>
<pre><code>python3.5 -m pip install numpy
</code></pre>
<p>but receive error :</p>
<pre><code>/usr/local/bin/python3.5: No module named pip
</code></pre>
<p>Same error for pip3 :</p>
<pre><code>python3.5 -m pip3 install numpy
/usr/local/bin/python3.5: No mo... | <p>Although using virtual environment is advisable in many use-cases, it is not strictly required. You can have a system <code>python3.5</code> and a <code>pip</code> installation associated with it.</p>
<p>Note that <a href="https://www.python.org/downloads/release/python-3510/" rel="nofollow noreferrer">Python 3.5 is... | python|numpy|pip | 9 |
363,278 | 42,001,566 | TensorFlow: How to merge multiple 'collections'? | <p>I have some <code>collections</code> that I would like to track with TensorBoard using a supervisor. In the Supervisor initializer I would like something to the effect</p>
<pre><code>summary_op = tf.summary.merge_all(['test', 'valid'])
</code></pre>
<p>But I get the error <code>TypeError: unhashable type: 'list'</co... | <p>Try <code>tf.summary.merge()</code>, e.g. like so:</p>
<pre><code>summary_op = tf.summary.merge([
tf.summary.merge_all('test'),
tf.summary.merge_all('train')],
collections='merged')
</code></pre>
<p>This would merge all summaries from the <code>test</code> and <code>train</code> collections and... | python|tensorflow|deep-learning|tensorboard | 2 |
363,279 | 41,791,171 | Bazel build for TensorFlow inception model | <p>I am following tutorial for inception model build for TensorFlow at url (<a href="https://www.tensorflow.org/how_tos/image_retraining/" rel="nofollow noreferrer">https://www.tensorflow.org/how_tos/image_retraining/</a>). When I am running command <code>bazel build tensorflow/examples/image_retraining:retrain</code>,... | <p>First run <code>touch WORKSPACE</code>, and then run the <code>bazel build</code> command.</p> | macos|python-3.x|tensorflow|bazel | 10 |
363,280 | 41,949,633 | Tensorflow: how to swap variables between scopes and set variables in scope from another | <p>I have different scopes and they have variables with same names but with different values. I want to swap values of these variables between scopes.
Example: </p>
<pre><code>with tf.variable_scope('sc1'):
a1 = tf.Variable(0, name='test_var1')
b1 = tf.Variable(1, name='test_var2')
with tf.variable_scope('sc2'):... | <p>I want to swap relatively small scopes, so it's not a problem have temporary scope for swapping. I made working prototype. It doesn't look cool and actually ugly but works.</p>
<pre><code>def swap_tf_collections(col1, col2, tmp_col):
col2_dict = {}
for i in xrange(len(col1)):
curr_var_name = col2[i]... | python|scope|tensorflow | 0 |
363,281 | 41,986,357 | Sampling Sequences in Pandas | <p>I've got a bunch sequential data, and I want to sample, with replacement, random <strong>sequences</strong> of items (e.g. 50 days at a time).</p>
<p>If I do something like <code>df.sample(50,replace=True)</code>, it just pulls 50 random rows out of a hat.</p>
<p>I've written code that does the trick, but it's not... | <p>Assuming Python2.7, index your dataframe on dates, sort and then you can select rows very nicely like so:</p>
<pre><code>my_df.iloc(xrange(10, 60))
</code></pre>
<p>Obviously ensure the 2nd argument to <code>xrange < my_df.shape[0]</code>. It's easy to randomise the selected range.</p> | python|pandas | 1 |
363,282 | 42,075,408 | Trying to convert pandas df series of floats to one of four categorical values based on there respective locations in the series quartiles | <p>I'm trying to write a function that goes through a pandas df series full of floats and converts them into one of four string categorical variables based on where they are in the series range. So all values in the ranges quartiles would be converted to either low, low_mid, high_mid, or high. I've done it a number of ... | <p>I'd use vectorized <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="noreferrer">pd.cut()</a> method:</p>
<pre><code>In [51]: df = pd.DataFrame(np.random.randint(0, 332801, 10), columns=['val'])
In [52]: df
Out[52]:
val
0 230852
1 140030
2 231657
3 73146
4 240890
5 3... | python|pandas | 6 |
363,283 | 41,841,526 | Inserting/Adding/Updating elements in matrix | <p>Let's say I've initialized a matrix/array that has 400 rows, 3 columns:</p>
<pre><code>distances = np.zeros([400, 3], dtype=np.float64)
</code></pre>
<p>Now, I have a for loop that returns 1200 objects (float values) and I want to "append" each element into <code>distances</code> (row by row) or assign those float... | <p>Gather you items in a list, convert this list into NumPy array and reshape:</p>
<pre><code>distances = np.array([item1, item2, ... item1200], dtype=float).reshape((400, 3))
</code></pre> | python|python-3.x|numpy|matrix | 1 |
363,284 | 41,991,897 | How to add matrix and vector column-wise? | <p>Consider the following:</p>
<pre><code>>>> matrix = numpy.array([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]])
>>> vector = numpy.array([10, 20, 30])
>>> matrix + vector
array([[11, 22, 33],
[14, 25, 36],
[17, 28, 39]])
</code></pre>
... | <p>Make the vector a column:</p>
<pre><code>matrix + vector[:, None]
</code></pre> | python|numpy | 2 |
363,285 | 41,912,170 | Trying to generate random x,y coordinates within a ring in python | <p>I am trying to generate random x and y coordinates within a ring, which has an outer radius of 3.5 and an inner radius of 2. Therefor the following must be true for x and y:</p>
<pre><code>x**2 + y**2 < 12.25 and x**2 + y**2 > 4
</code></pre>
<p>I wrote the following function: </p>
<pre><code>def meteorites... | <p>To get uniform distribution of random point in the ring, one should take relative areas of thin circular regions into account. <a href="http://mathworld.wolfram.com/DiskPointPicking.html" rel="noreferrer">How it works for the circle</a>
<a href="https://i.stack.imgur.com/sPU0E.gif" rel="noreferrer"><img src="https:/... | python|python-2.7|numpy|math | 8 |
363,286 | 41,710,789 | Boolean Series key will be reindexed to match DataFrame index | <p>Here is how I encountered the warning:</p>
<pre><code>df.loc[a_list][df.a_col.isnull()]
</code></pre>
<p>The type of <code>a_list</code> is <code>Int64Index</code>οΌ it contains a list of row indexes. All of these row indexes belong to <code>df</code>.</p>
<p>The <code>df.a_col.isnull()</code> part is a condition I n... | <p>Your approach will work despite the warning, but it's best not to rely on implicit, unclear behavior.</p>
<p><strong>Solution 1</strong>, make the selection of indices in <code>a_list</code> a boolean mask:</p>
<pre><code>df[df.index.isin(a_list) & df.a_col.isnull()]
</code></pre>
<p><strong>Solution 2</stron... | python|pandas | 114 |
363,287 | 41,860,594 | Pythonic way of multiple for loops that create new lists on each iteration, and also clean data? | <p>I am pretty new to Python (using 3.5 with Anaconda)--with previous experience in MATLAB. Your help is much appreciated. If there's an easier way to do this, please let me know.</p>
<p>I have data that I read and cleaned from a pdf file from some experimental equipment and appended together into a list:</p>
<pre><c... | <p>You can use <code>nested list comprehension</code>, what seems faster as solution with <code>apply</code>:</p>
<pre><code>df = pd.DataFrame([[y[0] for y in x] for x in outputdata], columns=Molecule)
print (df)
H2 Ar Methane Ethane Ethylene Propane(C3H8) Propylene
0 2.37701 - - - - ... | python|python-3.x|pandas|numpy|list-comprehension | 2 |
363,288 | 41,846,972 | TensorFlow - How to read variable-length parts of data? | <p>I want to read variable_length parts of data of a single file using data reader in TensorFlow.
My file is as follows: [data_length_1, data_bytes_1, data_length_2, data_bytes_2, ...]
The first byte represents the number of bytes to be read, and then this process repeats.</p>
<p>The problem is that I want to read dat... | <p>I managed to solve my problem by adding a <a href="https://www.tensorflow.org/how_tos/new_data_formats/" rel="nofollow noreferrer">custom data reader</a> that reads the record length for each record from its first data byte, and it works.</p> | python|tensorflow | 0 |
363,289 | 41,753,318 | Replacing value in python numpy masked array | <p>I have the foll. numpy masked array:</p>
<pre><code>masked_array(data =
[[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
...,
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]],
mask =
[[ True True True ..., True True True]
[ True True... | <p>The mask is on where the <code>arr.mask</code> has value True.</p>
<p>All those values <code>-9999.</code> values are masked. </p>
<p>If you want it to apply to the masked values aswell, instead of using this:</p>
<pre><code>arr.data[arr == -9999.0] = 0.0
</code></pre>
<p>It should be this:</p>
<pre><code>arr.... | python|numpy | 3 |
363,290 | 41,694,460 | Python, Pandas: GroupBy attributes documentation | <p>On the Groupby documentation, at that level of the page:
<a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-object-attributes" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-object-attributes</a></p>
<p>If you scroll down a bit you can see their is a list of... | <p>I think you can check <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#groupby" rel="nofollow noreferrer">groupby docs</a>.</p>
<ol>
<li><a href="http://pandas.pydata.org/pandas-docs/stable/api.html#id34" rel="nofollow noreferrer">Indexing, iteration</a></li>
<li><a href="http://pandas.pydata.org/panda... | python|pandas|jupyter-notebook | 2 |
363,291 | 41,765,571 | Adding a new row in a matrix, every other row, whose elements are averages of the elements above and below it | <p>I have a matrix, say:</p>
<pre><code>A = [1, 2, 3]
[4, 5, 6]
[7, 8, 9]
</code></pre>
<p>and I want to construct another matrix, having two extra rows as such</p>
<pre><code>B = [1, 2, 3]
[2.5, 3.5, 4.5]
[4, 5, 6]
[5.5, 6.5, 7.5]
[7, 8, 9]
</code></pre>
<p>where every ele... | <p>Here's an approach making use of slicing -</p>
<pre><code>newvals = (A[1:] + A[:-1])/2.0
out = np.empty((A.shape[0]+newvals.shape[0],A.shape[1]))
out[::2] = A
out[1::2] = newvals
</code></pre>
<p>Here's another one with <code>np.insert</code> for a generic case -</p>
<pre><code>np.insert(A.astype(float),range(1,... | python|numpy|matrix|average | 4 |
363,292 | 42,049,448 | Why does copying a >= 16 GB Numpy array set all its elements to 0? | <p>On my Anaconda Python distribution, copying a Numpy array that is exactly 16 GB or larger (regardless of dtype) sets all elements of the copy to 0:</p>
<pre><code>>>> np.arange(2 ** 31 - 1).copy() # works fine
array([ 0, 1, 2, ..., 2147483644, 2147483645,
2147483646])
>... | <p>This is just a guess. I don't have any evidence supporting the following claims at the moment but my guess is that this is a simple overflow problem: </p>
<pre><code>>>> np.arange(2 ** 31 - 1).size
2147483647
</code></pre>
<p>Which just happens to be the largest <code>int32</code> value:</p>
<pre><code>&... | python|numpy|intel-mkl | 4 |
363,293 | 42,076,126 | vectorize percentile value of column B of column A (for groups) | <p>For every pair of <code>src</code> and <code>dest</code> airport cities I want to return a percentile of column <code>a</code> given a value of column <code>b</code>. </p>
<p>I can do this manually as such:</p>
<p>example df with only 2 pairs of src/dest (I have thousands in my actual df):</p>
<pre><code>dt src ... | <p><strong>Obtained a incredible saving of time!</strong><br></p>
<p><strong>Output:</strong><br>
Size of a_list: 49998 Randomized unique values<br>
<strong>percentile_1 (Your given df - scipy)</strong><br>
computed percentile 104 times - 104 records in 0:00:07.777022 </p>
<p><strong>percentile_9 (class PercentileOf... | python|pandas|scipy|apply|percentile | 6 |
363,294 | 7,930,803 | Inverse Filter of spatially convolved versus frequency convolved image | <p>My image processing class has been assigned a project on image restoration. I'm currently working on the Inverse Filter. image -> degrade -> inverse filter -> restore image. I'm using a simple 5x5 box filter for my degradation.</p>
<p>If I convolve the image in the spatial domain, move to frequency domain, then In... | <p>The problem is clearly that <code>F</code> and <code>F_HAT2</code> are not identical. The fact that you need to call <code>nan_to_num</code> is a clear indication that something is going wrong between the multiplication and division by <code>K</code>. A possible cause is integer overflow. Try converting <code>f</cod... | image-processing|numpy|scipy | 2 |
363,295 | 8,252,428 | How to solve the polynomial eigenvalue in python? | <p>In my python code, I would like to solve the polynomial eigenvalue problem:</p>
<pre><code>A0 + lambda*A1 + lambda^2*A2 + lambda^3*A3 + .... = 0
</code></pre>
<p>where <code>An</code> are dense matrices, and <code>lambda</code> is a constant. In matlab it is possible to solve this problem using the <a href="http:/... | <p><a href="http://octave.1599824.n4.nabble.com/Quadratic-Eigen-value-problems-td1626007.html" rel="nofollow">This discussion</a> points to a general method for turning a polynomial eigenvalue problem into a generalized eigenvalue problem, which can later be solved using <a href="http://docs.scipy.org/doc/scipy/referen... | python|matlab|numpy|scipy | 2 |
363,296 | 37,675,216 | What is the default learning rate for TensorFlowDNNRegressor with SGD or Adagrad? | <p>This is probably an easy question, but I just can't find it. But I'm also pretty new to all this, so maybe I'm just blind.</p>
<p>What is the default learning rate when using TensorFlowDNNRegressor with SGD or Adagrad?
The default when using Adam or Adadelta seems to be 0.001, but I cannot find a default for Adagra... | <p>AdaGrad doesn't need a learning rate as it adapts component-wise (thus the name). A pretty concise comment:
<a href="https://xcorr.net/2014/01/23/adagrad-eliminating-learning-rates-in-stochastic-gradient-descent/" rel="nofollow">https://xcorr.net/2014/01/23/adagrad-eliminating-learning-rates-in-stochastic-gradient-d... | tensorflow|skflow | 2 |
363,297 | 37,954,906 | Pandas applymap on multilevel dataframe | <p>I have a square matrix as a dataframe in pandas. It should be symmetric, and nearly is, except for a few missing values that I filled with 0. I want to use the fact that it should be symmetric to fill the missing values, by taking the max of the absolute value over df.ix[x,y] and df.ix[y,x]. I.e.:</p>
<pre><code>df... | <p>I think you can first convert <code>df</code> to <code>numpy array</code>, use <a href="https://stackoverflow.com/a/2573982/2901002"><code>numpy solution</code></a> and last create <code>DataFrame</code> with <code>constructor</code>:</p>
<pre><code>a = df.values
print (pd.DataFrame(data=a + a.T - np.diag(a.diagona... | python|pandas|multi-level | 2 |
363,298 | 37,951,219 | Inserting newaxis at variable position in NumPy arrays | <p>Normally, when we know where should we insert the newaxis, we can do <code>a[:, np.newaxis,...]</code>. Is there any good way to insert the newaxis at certain axis?</p>
<p>Here is how I do it now. I think there must be some much better ways than this:</p>
<pre><code>def addNewAxisAt(x, axis):
_s = list(x.shape... | <p>That singleton dimension <code>(dim length = 1)</code> could be added as a shape criteria to the original array shape with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html" rel="nofollow"><code>np.insert</code></a> and thus directly change its shape, like so -</p>
<pre><code>x.shape = ... | python|arrays|numpy | 3 |
363,299 | 37,697,195 | how to merge two data frames based on particular column in pandas python? | <p>I have to merge two dataframes:</p>
<p>df1</p>
<pre><code>company,standard
tata,A1
cts,A2
dell,A3
</code></pre>
<p>df2</p>
<pre><code>company,return
tata,71
dell,78
cts,27
hcl,23
</code></pre>
<p>I have to unify both dataframes to one dataframe. I need output like:</p>
<pre><code>company,standard,return
tata,A... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="noreferrer"><code>merge</code></a>:</p>
<pre><code>print (pd.merge(df1, df2, on='company'))
</code></pre>
<p>Sample:</p>
<pre><code>print (df1)
company standard
0 tata A1
1 cts A2
2 dell A3
pr... | python|pandas|python-2.7|merge | 149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.