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 |
|---|---|---|---|---|---|---|
368,600 | 37,102,403 | How do I log or view the cost used in training a TensorFlow neural network with dropout? | <p>How do I see the accuracy and cost for the dropouts actually used in training a <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/nn.html#dropout" rel="nofollow">TensorFlow</a> neural network with <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/nn.html#dropout" rel="nofollow">dropou... | <p>And where is the problem? You <strong>should</strong> get three different values if you call three times a stochastic network. When you are logging your losses from network you are logging the ones that are actually used during training. Basically you can just read out value from your computed graph, like:</p>
<pre... | machine-learning|neural-network|tensorflow | 2 |
368,601 | 37,017,191 | Python/Pandas subtracting numbers in a column | <p>Sorry if this is a dumb question,</p>
<p>I have a pandas data frame that looks kind of like this:</p>
<pre><code>Col1 Col2
0 217
287 130
</code></pre>
<p>I'm trying to subtract the two numbers inside column 2</p> | <p>If you are trying to do subtraction between all of the elements in Col2, you can do:</p>
<pre><code>sub = df['Col2'].diff()
</code></pre>
<p>sub will be a Series where:</p>
<pre><code>Col2
NaN
-87
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="no... | python|pandas | 3 |
368,602 | 36,925,354 | how to concat two data frames with different column names in pandas? - python | <pre><code>df1 = pd.DataFrame({'a':[1,2,3],'x':[4,5,6],'y':[7,8,9]})
df2 = pd.DataFrame({'b':[10,11,12],'x':[13,14,15],'y':[16,17,18]})
</code></pre>
<p>I'm trying to merge the two data frames using the keys from the <code>df1</code>. I think I should use <code>pd.merge</code> for this, but I how can I tell pandas to ... | <p>Just use <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.concat.html#pandas.concat" rel="noreferrer"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.rename.html" rel="noreferrer"><code>rename</code></a> the column for <... | python|pandas|merge | 49 |
368,603 | 36,904,051 | Numpy generation of subsets of global array based on mask | <p>I am interested in generating a list (or np.array) of np.arrays from a global 2D array, based on a matching boolean mask using numpy, for a particular axis. I was wondering if np.ma.mask() or similar could be employed...</p>
<p>An example is probably better:</p>
<pre><code>number= 10
x = np.linspace(0,number,num=n... | <p>Here are the steps I would follow to solve the case in a vectorized manner -</p>
<ol>
<li>Use <code>boolean indexing</code> to select the valid elements from <code>X</code>.</li>
<li>Get the indices at which we see column indices shifting for the input mask. This would be achieved after transposing the mask, using ... | python|numpy|where|mask | 1 |
368,604 | 37,063,577 | How to print the value of a tensor in tensorflow mnist_softmax.py | <p>I just tried to run <code>mnist_softmax.py</code> in TensorFlow 0.8.
I want to observe the value of <code>y</code> and <code>y_</code> just before the model test step.</p>
<p>Below is the code:</p>
<pre><code>print(y) # added by me
print(y_) # added by me
# Test trained model
correct_prediction = tf.equal(tf.ar... | <p><strong>TL;DR:</strong> Both the <code>y</code> and <code>y_</code> tensors depend on <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/io_ops.html#placeholder" rel="nofollow"><code>tf.placeholder()</code></a> operations, and so they require you to <em>feed</em> an input value when you evaluated them... | python|tensorflow | 4 |
368,605 | 36,700,404 | TensorFlow: Opening log data written by SummaryWriter | <p>After following this tutorial on <a href="https://www.tensorflow.org/versions/r0.8/how_tos/summaries_and_tensorboard/index.html" rel="noreferrer">summaries and TensorBoard</a>, I've been able to successfully save and look at data with TensorBoard. Is it possible to open this data with something other than TensorBoar... | <p>As of March 2017, the EventAccumulator tool <a href="https://github.com/tensorflow/tensorflow/issues/9532" rel="noreferrer">has been moved</a> from Tensorflow core to the Tensorboard Backend. You can still use it to extract data from Tensorboard log files as follows:</p>
<pre class="lang-py prettyprint-override"><c... | tensorflow|tensorboard | 47 |
368,606 | 37,079,640 | numpy ndarray indexing - retrieving indexes from tuple | <p>I have asked a similar question before, but I'm still not completely sure how numpy organises its indices. </p>
<p>I am working with many 3D arrays, all of which are the same size. due to later operations (view as window with scipy and others) I need to slice the arrays which I am doing with a series of operations ... | <p>Consider storing slice objects instead of the fragements themselves</p>
<pre><code>your_slice = np.s_[:100, :100, :100]
</code></pre>
<p>To get the image just</p>
<pre><code>Padded[your_slice]
</code></pre>
<p>To get the indices you used to create the slice</p>
<pre><code>your_slice[0].start
your_slice[0].step
... | python|arrays|numpy | 1 |
368,607 | 37,049,837 | Add legend to scatter plot to differentiate colours? | <p>I am using Pandas 0.18. I have a dataframe like this:</p>
<pre><code>code proportion percent_highcost total_quantity
A81 0.7 76 1002
A81 0.0 73 1400
</code></pre>
<p>And I am drawing a scatter plot like this:</p>
<pre><code>colours = np.where(... | <h1>Plot unique <code>DataFrame</code>s on the same axis</h1>
<p>Plotting multiple <em>series</em> (not <code>pandas</code> <code>Series</code>) in a scatter can be accomplished by separating the <code>DataFrame</code>s by a condition and then plotting them as separate scatters with unique colors on the same axis. Th... | python|pandas|matplotlib | 0 |
368,608 | 36,816,038 | A way to reformat and write one pandas dataframe to another | <p>I have two dataframes which I would like to join together.</p>
<p>The first data frame (stockData) has more than one stock (the below is just for illustrative purposes) and has the following structure:</p>
<pre><code> BBG.XLON.VOD.S_LAST BBG.XLON.VOD.S_VOLUME BBG.XLON.VOD.S_MKTCAP
date ... | <p>you can do it this way:</p>
<pre><code>In [316]: df1.join(df2['reporting_type'].groupby(level=0).first())
Out[316]:
BBG.XLON.VOD.S_LAST BBG.XLON.VOD.S_VOLUME BBG.XLON.VOD.S_MKTCAP \
2001-01-02 NaN NaN NaN
2001-01-03 225.00 ... | python|python-3.x|pandas | 1 |
368,609 | 36,756,427 | Distance of an array of vector from it's own element | <p>I've got an array of vector and I want to build a matrix that shows me the distance between its own vector. For example I've got that matrix with those 2 vectors:</p>
<pre><code>[[a, b , c]
[d, e , f]]
</code></pre>
<p>and I want to get that where <code>dist</code> is an euclidian distance for example:</p>
<pre><co... | <p>The functions <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer"><code>pdist</code></a> and <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html" rel="nofollow noreferrer"><code>squareform</code></... | python|numpy|matrix|vector|scikit-learn | 2 |
368,610 | 36,905,288 | How would you reshape a collection of images from numpy arrays into one big image? | <p>I'm having some trouble reshaping a 4D numpy array to a 2D numpy array. Currently the numpy array is follows, (35280L, 1L, 32L, 32L). The format is number of images, channel, width, height. Basically, I have 35280 image blocks that are 32x32 and I want to combine the image blocks (keeping the indices) to create one ... | <p>Reshaping is not sufficient, you must carefully rearrange your data with <code>swapaxes</code>. </p>
<p>Sample data :</p>
<pre><code>dims=nbim,_,h,w=np.array([6,1,7,6])
data=arange(dims.prod()).reshape(dims)%256
</code></pre>
<p>The images : </p>
<pre><code>figure()
for i in range(nbim):
subplot(1,nbim,i+... | python|arrays|numpy | 2 |
368,611 | 37,110,879 | Simplest way to make a polynomial regression with sklearn? | <p>I have some data that doesn't fit a linear regression:</p>
<p><a href="https://i.stack.imgur.com/pV5EA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pV5EA.png" alt="enter image description here" /></a></p>
<p>In fact should fit a quadratic function 'exactly':</p>
<pre><code>P = R*I**2
</code></... | <p>You can use numpy's <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.polyfit.html" rel="noreferrer">polyfit</a>.</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
X = np.linspace(0, 100, 50)
Y = 23.24 + 2.2*X + 0.24*(X**2) + 10*np.random.randn(50) #added some noise
coef... | python|pandas|scikit-learn|polynomials|non-linear-regression | 5 |
368,612 | 36,872,851 | How to save a list of dataframes to csv | <p>I have a list of data frames which I reshuffle and then I want to save the output as a csv. To do this I'm trying to append this list to an empty data frame:</p>
<pre><code>l1=[year1, year2,..., year30]
shuffle (l1)
columns=['year', 'day', 'tmin', 'tmax', 'pcp']
index=np.arange(10957)
df2=pd.DataFrame(columns=colum... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="noreferrer"><code>to_csv</code></a> if <code>l1</code> is <code>list</cod... | python|list|pandas|dataframe|export-to-csv | 10 |
368,613 | 37,039,865 | Load many files into one array - Python | <p>So, I have to load many .mat files with some features to plot it. </p>
<p>Each array to be plotted is loaded into a dictionary:</p>
<pre><code>import numpy as np
import scipy.io as io
dict1 = io.loadmat('file1.MAT')
dict2 = io.loadmat('file2.MAT') # type = dict
dict3 = io.loadmat('file3.MAT')
...
</code></pre>
... | <p>Given that you are talking about dealing with many matrices, you should manage them as a collection. First, let's define your set of files. It could be a tuple, or a list:</p>
<pre><code>Matrix_files = [ 'fileA.MAT', 'file1.MAT', 'no pattern to these names.MAT' ]
</code></pre>
<p>If they happen to have a pattern, ... | python|numpy | 4 |
368,614 | 36,850,702 | Python multiprocessing: Shared memory (numpy) Array not being modified as expected | <p>I have written a small multiprocessing program in Python which reads an array of values and runs multiple processes asynchronously to operate on parts of the data array. Each separate process should its own 1-D section of the 2-D array, with no overlap between processes. Once all the processes have completed the sha... | <p>I have now successfully implemented a solution although it is still exhibiting unexpected behaviors: 1) it runs on all CPUs on a Windows environment but the total elapsed time for the process is no faster than running a single processor job (i.e. the same code without any of the multiprocessing.* usages), and 2) whe... | python|arrays|numpy|multiprocessing|ctypes | 1 |
368,615 | 36,705,264 | Convert dataframe column to datetime for re-mapping | <p>I have a bunch of weather data that I need to remap with Pandas.
I'm struggling to convert the first column 'Time' to a datetime index.
I've been scanning forums, and have not been able to fix the problem.</p>
<p>Here is a sample of the data:</p>
<pre><code>Time TemperatureF DewpointF
1/1/2015 0:01 31.7 ... | <p>Try using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime()</code></a> instead of <code>df.index.to_datetime()</code>, and use the result as your <code>index</code>. </p>
<p>If the format does not convert correctly, you'll need to add a <c... | python|datetime|pandas | 1 |
368,616 | 55,023,691 | (Casting) errors using extract_(relevant_)features from tsfresh | <p>Trying out Python package tsfresh I run into issues in the first steps. Given a series how to (automatically) make features for it? This snippet produces different errors based on which part I try.</p>
<pre><code>import tsfresh
import pandas as pd
import numpy as np
#tfX, tfy = tsfresh.utilities.dataframe_functions... | <p>Fixed it. Either the version on conda(-forge) or one of the dependencies was the issue. So using "conda uninstall tsfresh", "conda install patsy future six tqdm" and "pip install tsfresh" combined did the trick.</p> | python|python-3.x|numpy|casting | 2 |
368,617 | 55,011,390 | Numpy n-diagonal matrix broadcasting decomposition | <p>I would like to know if there is a better way of taking advantage of python numpy array broadcasting to avoid the use of the two inner <code>for</code> loops of the following minimal example :</p>
<pre><code>import numpy as np
# Parameters
n_t = 10
n_ddl = 3
# Typical dummy M n_ddl-diagonal matrix
x = np.arange(1... | <p>Simply slice with appropriate step-sizes and starts and hence remove the inner two loops -</p>
<pre><code>for i in range(0,n_t):
M_i = M[i::n_t,i::n_t]
</code></pre> | python|python-3.x|numpy|array-broadcasting | 4 |
368,618 | 54,708,668 | Convert A Column and Column B In Pandas to One Long String (Python 3) | <p><a href="https://i.stack.imgur.com/qKyrp.png" rel="nofollow noreferrer">enter image description here</a>How can I convert a pandas columns into one long string?</p>
<p>For example, convert the following DF:</p>
<pre><code>column1 column2
John Noun
Went Verb
To DT[enter image description here][2]
Fetch ... | <p>Join columns together with separator and call <code>join</code>:</p>
<pre><code>s = ' '.join(df['Keyword'] + '/' + df['Tag'])
</code></pre>
<p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel="nofollow noreferrer"><code>str.cat</code></a>:</p>
<pre><code>s = ' ... | python|python-3.x|string|pandas | 1 |
368,619 | 55,102,525 | numpy: linspace calculation generating nan. How to remove point pair from both arrays? | <p>I'm curious if there's an elegant way to solve the problem below, preferably using as few lines of code as possible and is easy to remember, possibly a built-in numpy function?</p>
<p>Let's say I have a function f(x) and I want to be lazy and generate a np.linspace over an x range that purposely generates values of... | <p>There isn't really any need to filter out the <code>nan</code>, they are simply not plotted. </p>
<p><a href="https://i.stack.imgur.com/LlcwK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LlcwK.png" alt="enter image description here"></a></p>
<p>If you want to filter them out, the line gets co... | python|numpy|matplotlib | 3 |
368,620 | 55,029,608 | I am trying to apply a function to a column of a DataFrame but get error of a loop with signature matching | <p>Hello I am trying to run the following code: </p>
<pre><code>def f(df):
new = pd.Series(df)
i = new.str.lower() \
.str.replace('[^a-z\s]', '') \
.str.split(expand=True) \
.stack()
# generate bigrams by concatenating unigram columns
j = i + ' ' + i.shift(-1)
digrams = []... | <p>That error emerges when your code is expecting an integer type but receives a string or something else instead. Try adding a str() type conversion to variable s when you append it to the digrams. Also ensure the data type of "abstract_text_x" is string and not an object or an array. Basically, just iterate through y... | python|python-3.x|pandas | 0 |
368,621 | 54,771,128 | combine_first with ffill for baseDf AND fillna for additionalDf | <p>I need to combine_first a baseDf and an additionalDf with pandas.
How can I use ffill() for the baseDf and fillna(-1) for the second?</p>
<hr>
<p>for instance:
baseDf:</p>
<pre><code> qty total
1 10 10
2 5 15
4 4 19
6 8 27
8 2 29
</code></pre>
<p>additionalDf:</p>
<pre><code> ... | <p>Just need change the position of <code>fillna</code> and <code>fffill</code></p>
<pre><code>baseDf.combine_first(additionalDf).fillna({'val':-1}).ffill()
Out[360]:
qty total val
1 10.0 10.0 -1.0
2 5.0 15.0 -1.0
3 5.0 15.0 400.0
4 4.0 19.0 -1.0
5 4.0 19.0 150.0
6 8.0 27.0 -1... | python|pandas | 3 |
368,622 | 54,719,742 | tf.Estimator.predict() issue when using a Tensorflow Hub module as the basis of a custom tf.Estimator | <p>I am trying to create a custom tensorflow tf.Estimator. In the model_fn passed to the tf.Estimator, I am importing the Inception_V3 module from Tensorflow Hub. </p>
<p>Problem: After fine-tuning the model (using tf.Estimator.train), the results obtained using tf.Estimator.predict are not as good as expected based... | <p>There's a few things that seem to be missing from the code snippet. How is <code>final_output</code> computed from <code>iv3_module</code>? Also, mean squared error is an unusual choice of loss function for a classification problem; the common approach is to pass image features from the module into a a linear output... | tensorflow|tensorflow-hub | 0 |
368,623 | 55,093,651 | Loop only takes last value | <p>I have a dataFrame with country-specific population for each year and a pandas Series with the world population for each year.
This is the Series I am using:</p>
<pre><code>pop_tot = df3.groupby('Year')['population'].sum()
Year
1990 4.575442e+09
1991 4.659075e+09
1992 4.699921e+09
1993 4.795129e+09... | <p>You don't need loop, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" rel="nofollow noreferrer"><code>groupby.transform</code></a> to create the column <code>pop_tot</code> in <code>df3</code> directly. then for the column <code>weighted</code> just do column ... | python|pandas|loops | 3 |
368,624 | 55,138,991 | Remove all the words except in list | <p>I have a pandas dataframe like below, It contains sentence of words, and I have one more list called vocab, I want to remove all the words from sentence except the words are in vocab list.</p>
<p>Example df:</p>
<pre><code> sentence
0 packag come differ what about tomorrow
1 ... | <p>Use nested list comprehension with split by whitespace:</p>
<pre><code>df['res'] = [' '.join(y for y in x.split() if y in vocab_lis) for x in df['sentence']]
print (df)
sentence res
0 packag come differ what about tomorrow packag differ tomorrow
1 Hello ... | python|pandas | 2 |
368,625 | 55,103,428 | Apply function to dataframe column of lists | <p>I have a set of text strings (A). I can break them down into tokens (B). I would like to drop some of the tokens so that I end up with only words (C). I tried:</p>
<pre><code>from nltk.tokenize import word_tokenize
df = pd.DataFrame({'A': ["potato soup, 99", "2 tomato"]})
# Tokenise
df['B'] = df['A'] .apply(word_... | <p>Use a list comprehension:</p>
<pre><code>df['C'] = df['B'].apply(lambda x: [y for y in x if y.isalpha()])
</code></pre> | pandas|natural-language-processing | 2 |
368,626 | 54,961,860 | Divide ndarray by maximums along given axis | <p>Say I have an array like this</p>
<pre><code>import numpy as np
a = np.array([[2]*9 + [3]*9 + [4]*9])
a = a.reshape((-1,3, 3))
print(a)
</code></pre>
<p>Which is </p>
<pre><code>[[[2 2 2]
[2 2 2]
[2 2 2]]
[[3 3 3]
[3 3 3]
[3 3 3]]
[[4 4 4]
[4 4 4]
[4 4 4]]]
</code></pre>
<p>So for example, if I ... | <p>You could find the maximum value in each <code>ndarray</code> in the first axis by taking the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html" rel="nofollow noreferrer"><code>np.max</code></a> along their rows and columns, setting <code>keepdims=True</code> so <code>a</code> is divided ... | python|numpy|multidimensional-array|tensor | 1 |
368,627 | 54,763,414 | How can I make a dictionary from a pandas data frame where the values are data types? | <p>I have a dataframe called "Lookup" that looks something like this:</p>
<pre><code> | Variable | Type
0 | Var1 | object
1 | Var2 | np.uint16
</code></pre>
<p>I want to use this to create a dictionary to import a large csv to keep the memory size low.</p>
<p>The large csv is too large to use the low_mem... | <p>If this is your file <code>test.csv</code></p>
<pre><code>Name1;Number1;Number2;Name2
a;2;3.0;b
</code></pre>
<p>then you can define a type series</p>
<pre><code>types = pd.Series(data=['object', 'float', 'float', 'object'], index=['Name1', 'Number1', 'Number2', 'Name2'])
types = types.apply(eval)
</code></pre>
... | python-3.x|pandas|dataframe|dictionary|types | 2 |
368,628 | 54,776,916 | Inverse of Pandas json_normalize | <p>I just discovered the json_normalize function which works great in taking a JSON object and giving me a pandas Dataframe. Now I want the reverse operation which takes that same Dataframe and gives me a json (or json-like dictionary which I can easily turn to json) with the same structure as the original json.</p>
<... | <p>I implemented it with a couple functions</p>
<pre><code>def set_for_keys(my_dict, key_arr, val):
"""
Set val at path in my_dict defined by the string (or serializable object) array key_arr
"""
current = my_dict
for i in range(len(key_arr)):
key = key_arr[i]
if key not in current:... | json|python-3.x|pandas|normalize | 12 |
368,629 | 54,825,098 | Datetime, pandas, and timezone woes: AttributeError: 'datetime.timezone' object has no attribute '_utcoffset' | <p>Here is a toy example of what I am trying to do:</p>
<pre><code>import pandas as pd
import datetime
import matplotlib
matplotlib.use('agg') # noqa
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from time import sleep
lst = []
for x in range(0, 10):
lst.append((datetime.datetime.now(datetime... | <p>Mostly scraped this from @AndyHayden <a href="https://stackoverflow.com/a/13703721/2864250">answer</a>, but one option is to convert <code>datetime.datetime</code> to <code>str</code> and convert back to "timezone aware" timestamp using <code>pd.to_datetime</code></p>
<pre><code>df = pd.DataFrame(lst, columns=['Tim... | python-3.x|pandas|datetime|matplotlib|timezone | 6 |
368,630 | 54,852,820 | 'Tensor' object is not callable using Keras and seq2seq model | <p>I was following this <a href="https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html" rel="nofollow noreferrer">tutorial</a>, and I can compile and train my model like this:</p>
<pre><code>encoder_inputs = Input(shape=(None,))
encoder_embedding = Embedding(max_words, latent_d... | <p>Mentioning the Solution in this Section (even it is mentioned by Matias Aravena Gamboa in Question), for the benefit of the community.</p>
<p>Issue is resolved using the code mentioned below:</p>
<pre><code>encoder_model = Model(encoder_inputs, encoder_states)
decoder_hidden_state_inputs = Input(shape=(latent_dim... | python|tensorflow|keras | 0 |
368,631 | 55,051,707 | How to get cumulative sum of unique IDs with group by? | <p>I am very new to python and pandas working on a pandas dataframe which looks like</p>
<pre><code>Date Time ID Weight
Jul-1 12:00 A 10
Jul-1 12:00 B 20
Jul-1 12:00 C 100
Jul-1 12:10 C 100
Jul-1 12:10 D 30
Jul-1 ... | <p>The code below uses <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">pandas.duplicate()</a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pandas.merge()</a>, <a... | python|pandas|data-processing | 3 |
368,632 | 54,800,231 | Assigning dataframe to dataframe in Pandas Python | <p>When i assign dataframe to another dataframe, making changes to one dataframe affects another dataframe</p>
<p>Code:</p>
<pre><code>interest_margin_data = initial_margin_data
interest_margin_data['spanReq'] = (interest_margin_data['spanReq']*interest_margin_data['currency'].map(interestrate_dict))/(360*100*interes... | <p>Use <code>.copy</code> to create a separate dataframe in memory:</p>
<pre><code>interest_margin_data = initial_margin_data.copy()
</code></pre>
<p>It creates a different object in memory, rather than just pointing to the same place.</p>
<p>This is done so if you create a "view" of the dataframe it does not requir... | python|pandas | 1 |
368,633 | 54,854,145 | Panda objects and plotting | <p>I have a panda data frame called 'cone'
I labeled the 11 columns in that frame
then I did <code>cone[["No experience"]].plot()</code> to show all the columns with that label
But then when I try to do </p>
<pre><code>noExperience = pd.DataFrame(cone[["No experience"]])
cone[["No experience"]].rolling(2).mean.plot()
... | <p>mean is a callable function so add'()' wherever you use it.
replace 'mean' in your code with 'mean()'</p> | python-3.x|pandas | 1 |
368,634 | 54,986,376 | Same category from different lists | <p>I originally had a Dataframe like</p>
<pre><code>datax = {'col1' : [['apple','pear','peach'],['kiwi','pear','apple','watermelon']]}
db = pd.DataFrame(columns = ['col1'], data = datax))
</code></pre>
<p>Every rows of the column 'col1' is a list of strings and every element of the string should be a category.
What I... | <p>okay, so you can use , explanation is added as comments:</p>
<pre><code>import itertools
a=list(itertools.chain.from_iterable(db.col1)) #flatten the lists
d=dict(zip(a,pd.factorize(a)[0])) #create a dictionary mapping
#output->{'apple': 0, 'pear': 1, 'peach': 2, 'kiwi': 3, 'watermelon': 4}
#next line replaces t... | python|pandas|dictionary | 0 |
368,635 | 55,123,366 | Does "from tensorflow.python.keras.models import load_model" give you the model.predict function? | <p>I just successfully finished training a tf.keras sequential model and wrote a separate "Flask" script where I load the saved model to an app I uploaded to Heroku. Everything worked. But, when I was playing, I realized for my requirements I only had to import Flask, request from flask as well as pandas, numpy and f... | <p>The saved model to disk has both the model architecture and the weights. load_model API deserializes this file, builds and returns a Keras Model object. So, you're essentially invoking predict() on the Keras Model object. You can inspect the model object by invoking the following methods:</p>
<pre><code>type(flask_... | tensorflow|keras | 0 |
368,636 | 54,972,359 | Using np.min with list input in a numba function | <p>What is the problem with the use of <code>np.min</code> here? Why doesn't numba like using a list in that function, is there some other way to get <code>np.min</code> to work?</p>
<pre><code>from numba import njit
import numpy as np
@njit
def availarray(length):
out=np.ones(14)
if length>0:
out[... | <p>The problem is that the numba version of <code>np.min</code> requires an <code>array</code> as input.</p>
<pre><code>from numba import njit
import numpy as np
@njit
def test_numba_version_of_numpy_min(inp):
return np.min(inp)
>>> test_numba_version_of_numpy_min(np.array([1, 2])) # works
1
>>&... | python|list|numpy|numba | 3 |
368,637 | 54,876,452 | Run Parallel Request session in python | <p>I am trying to open a multiple web session and save the data into CSV, Have written my code using for loop & requests.get options, But it's taking so long to access 90 number of Web location. Can anyone let me know how the whole process run in parallel for loc_var:</p>
<p>The code is working fine, only the issu... | <p>There are multiple approaches that you can take to make concurrent HTTP requests. Two that I've used are (1) multiple threads with <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" rel="noreferrer"><code>concurrent.futures.ThreadPoolExecutor</code></a> or (2) s... | python|multithreading|pandas|asynchronous|python-requests | 18 |
368,638 | 54,772,758 | Softmax Regression - validation and test predictions shows no improvement | <p>I'm currently learning how to use Tensorflow and I'm having some issues to implement this Softmax Regression aplication.</p>
<p>There's no error when compiling but, for some reasson text validation and test predictions shows no improvement, only the train prediction is showing improvement.</p>
<p>I'm using Stocast... | <p>It sounds like overfitting, which isn't surprising since this model is basically a linear regression model.<br>
There are few options you can try:<br>
1. add hidden layers + activation functions(<a href="https://arxiv.org/abs/1511.07289" rel="nofollow noreferrer">https://arxiv.org/abs/1511.07289</a>: elu paper works... | python|tensorflow | 0 |
368,639 | 55,081,171 | Import data separated by strings to numpy array | <p>I am trying to import data to python numpy.array from data file like this:</p>
<pre><code>VARIABLES = Y Z V W
ZONE
T="1"
0 1 2 3
4 5 6 7
8 9 10 11
ZONE
T="2"
12 13 14 15
16 17 18 19
20 21 22 23
24 25 26 27
</code></pre>
<p>My expected result is:</p>
<pre><code>[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[... | <p>Iterate over the file; for each line strip whitespace from end; split on whitespace; check for numbers; keep line if it only contains numbers after <em>turning them into</em> floats (or mayb ints?); make an array of the result.</p>
<pre><code>import io
import numpy as np
f = io.StringIO('''VARIABLES = Y Z V W
ZONE... | python|numpy | 0 |
368,640 | 55,052,731 | concatenate pandas rows if next row has NaN in specific column | <p>I have csv file parsed from pdf file and it is not correctly parsed as the table in pdf file has multiple rows.
importing it into pd DataFrame looks like this. </p>
<pre><code> Record Operational Address BIC
2 2007-03-03 Omladinskih Brigada 90V 11070 BEOGRAD SERBIA, AAAA... | <p>Use <code>cumsum</code> to form groups and specify a dictionary for aggregation for each column.</p>
<pre><code>agg_d = {'Record': 'first',
'Operational Address': lambda x: ' '.join(x.dropna()),
'BIC': 'first'}
df.groupby(df.Record.notnull().cumsum().rename(None)).agg(agg_d)
Record ... | python|pandas|dataframe | 2 |
368,641 | 55,093,027 | While Loop in Python - Array Manipulation | <p>I am working on the following Python codes.</p>
<p>I am hoping to accomplish the following:</p>
<ol>
<li>Create a <code>total_fold_array</code> which will hold 5 items (folds)</li>
<li>For each fold, create an array of data from a larger dataset based off of the logic (which I know is correct) inside of my <code>f... | <p>Just before <code>for a_class,a_class_weight in zip(classes, class_weights):</code>, you're initializing total_fold_array to <code>[]</code>.</p>
<p>That loop executes for <strong>exactly as many times as there are elements in <code>classes</code></strong>.</p>
<p>Each iteration of that loop appends a <code>curr_f... | python|python-3.x|numpy|for-loop | 1 |
368,642 | 54,893,547 | Edit data in a python pandas filter and apply it to the original data frame | <p>I am trying to figure out how to filter data in pandas then assign a value to all of the rows in a column for the items that meet the filter criteria and have it affect the original data frame.
Here is the closest attempt I have so far but it is throwing a lot of informational warnings:</p>
<pre class="lang-py pret... | <p>IIUC, are you trying to do something like this:</p>
<pre><code>zone1 = (df['Latitude'] > 0) & (df['Longitude'] > 0)
zone2 = (df['Latitude'] < 0) & (df['Longitude'] > 0)
zone3 = (df['Latitude'] > 0) & (df['Longitude'] < 0)
zone4 = (df['Latitude'] < 0) & (df['Longitude'] < 0)
... | python|pandas|filter | 2 |
368,643 | 54,892,001 | KeyError when creating new column in python pandas | <p>I am trying to create a new column in python pandas, and I keep getting an (unsteady) reoccurring KeyError. The section of the script is very straightforward so I am not sure what could be causing the error since none of the columns in the dataset have the same name.</p>
<p>My goal is to created a new column and ap... | <p>I agree with the comments that you shouldn't be iterating through the dataframe. You should compute all of the values into a list, array, or Series, and assign them all at once.</p>
<p>However your error comes from this line:</p>
<pre><code>test_data['translated_descriptions'].copy = translated_description
</code>... | python|pandas|keyerror | 1 |
368,644 | 54,963,814 | How can I find the value with the minimum MSE with a numpy array? | <p>My possible values are:</p>
<pre><code>0: [0 0 0 0]
1: [1 0 0 0]
2: [1 1 0 0]
3: [1 1 1 0]
4: [1 1 1 1]
</code></pre>
<p>I have some values:</p>
<pre><code>[[0.9539342 0.84090066 0.46451256 0.09715253],
[0.9923432 0.01231235 0.19491441 0.09715253]
....
</code></pre>
<p>I want to figure out which of my possib... | <p>You can use <code>np.argmin</code> to get the lowest index of the rmse value which can be calculated using <code>np.linalg.norm</code></p>
<pre><code>import numpy as np
a = np.array([[0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0],[1, 1, 1, 0], [1, 1, 1, 1]])
b = np.array([0.9539342, 0.84090066, 0.46451256, 0.09715253])
n... | python|numpy|mean-square-error | 1 |
368,645 | 54,960,828 | Accelerating a screenshot function - Python | <p>I need my screenshot function to be as fast as possible, and now every call to the function takes about 0.2sec.</p>
<p>This is the function:</p>
<pre><code>def get_screenshot(self, width, height):
image = self.screen_capture.grab(self.monitor)
image = Image.frombuffer('RGB', image.size, image.bgra, 'raw', ... | <p>As your code is incomplete, I can only guess what might help, so here are a few thoughts...</p>
<p>I started with a 1200x1200 image, because I don't know how big yours is, and reduced it by a factor of 0.8x to 960x960 because of a comment in your code.</p>
<p>My ideas for speeding it up are based on either using a... | python|numpy|python-imaging-library|python-mss | 3 |
368,646 | 55,038,173 | Extracting any 2 rows from a df that satisfy conditions - Pandas | <p>I am trying to use a df ( sampled with 7 rows below) to extract any two rows that satisfy 3 conditions:</p>
<ol>
<li>Distance between 1st location less than x miles Using Haversine</li>
<li>Distance between 2nd location less than x miles Using Haversine</li>
<li>Difference between created time less than x minutes</... | <p>The general syntax is: </p>
<pre><code>answerdf = df.loc[df[<cond1> & <cond2> & <cond3>]]
</code></pre>
<p>Come up with your own conditions to replace in the above and you'll get your answer because your question is not providing a clear explanation of what your conditions are</p>
<p>Ex... | python|pandas|filter|difference|haversine | -1 |
368,647 | 54,780,189 | Comparing rows in 2 dataframes and counting number of similar columns | <p>I have two dataframes </p>
<pre><code>>> df1
ID Hair Legs Feathers
1 1 0 0
2 1 2 1
3 0 2 1
>> df2
ID Hair Legs Feathers
21 1 2 0
22 1 0 1
</code></pre>
<p>I want to compare each row in <code>df2</code> with all the rows in <code>df1</c... | <p>I believe you need:</p>
<pre><code>#cross join between both DataFrames
df = df2.assign(A=1).merge(df1.assign(A=1), on='A', suffixes=('','_')).drop('A', axis=1)
#join ID columns and set index
df.index = df.pop('ID_').astype(str) + '_' + df.pop('ID').astype(str)
df.index.name='ID'
print (df)
Hair Legs Feather... | python|pandas|dataframe | 2 |
368,648 | 55,024,604 | How to combine tf.map_fn and tf.split | <p>So the pseucode of thing i want is:</p>
<pre><code>splitted_outputs = [tf.split(output, rate, axis=0) for output in outputs]
</code></pre>
<p>where outputs is Tensor of shape (512, ?, 128), and splitted_outputs is list of lists of Tensors or Tensor with 3 dimensions. So i can iterate such tensor tensorflow.</p>
<... | <p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/usntack" rel="nofollow noreferrer"><code>tf.unstack</code></a> on <code>outputs</code> to get a list of "subtensors", then use <a href="https://www.tensorflow.org/api_docs/python/tf/split" rel="nofollow noreferrer"><code>tf.split</code></a> on each o... | python|tensorflow | 1 |
368,649 | 54,946,237 | How to get a 7x7 matrix numpy | <p>I want to get a 7x7 matrix from my numpy array.</p>
<pre><code>np.shape(y)
</code></pre>
<blockquote>
<p>(1, 7, 7, 32)</p>
</blockquote>
<pre><code>np.shape(y[0][:][:][:])
</code></pre>
<blockquote>
<p>(7, 7, 32)</p>
</blockquote>
<pre><code>np.shape(y[0][:][:][0])
</code></pre>
<blockquote>
<p>(7, 32)</... | <p>You were probably thinking by analogy: "To get element <code>i, j, k, l</code> I can do</p>
<pre><code>y[i][j][k][l]
</code></pre>
<p>if these indices are scalars, so why not for more general things like slices?"</p>
<p>The difference and reason why scalars work while slices don't is that scalar indexing removes ... | python|numpy | 1 |
368,650 | 55,136,865 | Value not found in data frame in python | <p>Original data frame has all 3 columns i.e. <code>name</code>, <code>description</code> and <code>specialties</code> columns in it. </p>
<p>I want to input a company name, compare its specialties with all other companies' specialties and during comparison whenever I found a match I want to print and save all the det... | <p>The data you've provided is not very clean or replicable, so I've created sample data here.</p>
<p>Assuming you can split specialties by <code>','</code>, it's simpler to work with lists and sets than with strings for this kind on analysis.</p>
<pre><code># Sample Data
df = pd.DataFrame({'description': ['d1', 'd2'... | python-3.x|pandas|dataframe | 1 |
368,651 | 54,994,219 | Dask - How to concatenate Series into a DataFrame with apply? | <p>How do I return multiple values from a function applied on a Dask Series?
I am trying to return a series from each iteration of <code>dask.Series.apply</code> and for the final result to be a <code>dask.DataFrame</code>.</p>
<p>The following code tells me that the meta is wrong. The all-pandas version however works... | <p>You're right, the problem is you're not specifying the meta correctly; more specifically and as the error message says, the metadata columns (<code>"name", "action", "comments"</code>) do not match the columns in the computed data (<code>0, 1, 2</code>). You should either:</p>
<ol>
<li>Change the metadata columns t... | python|pandas|dataframe|dask|dask-distributed | 3 |
368,652 | 55,106,400 | AttributeError: module 'numpy' has no attribute 'testing' | <p>Last week I was able to run programs in Python 3.7.2 just fine.</p>
<p>This morning I come in, run the same program and get error</p>
<p><code>AttributeError: module 'numpy' has no attribute 'testing'</code></p>
<p>I did fresh uninstall and install of python 3.7.2</p>
<p>Then I did <code>pip3 install -U scikit-l... | <p>run an additional import code, example:</p>
<pre><code>import np.testing as npt
npt.assert_array_almost_equal(answer1, answer2 )
</code></pre> | python|numpy|scikit-learn | -1 |
368,653 | 54,859,139 | Matching rows in pandas based on values is different columns | <p><strong>Input</strong></p>
<p>Assume I have a dataframe with the following structure:</p>
<pre><code> transaction_code transaction_time amount reversed_transaction_code
0 TX051 2019-01-01 13:00:00 150
1 TX002 2019-01-01 14:00:00 250 TX004
2 TX113 2019-01-0... | <p>I've modified your original data to make it little more complex. </p>
<hr>
<h3>Solution-</h3>
<pre><code>eg = {'transaction_code': ['TX051','TX002','TX113','TX004','TX805'],
'transaction_time': pd.to_datetime(['1 Jan 2019 1pm','1 Jan 2019 2pm','1 Jan 2019 3pm','1 Jan 2019 4pm','1 Jan 2019 5pm']),
... | python|python-3.x|pandas | 1 |
368,654 | 54,832,021 | How can I Access a Column by Name as a Variable to use the isin() Method | <p>I have two dataframes as df1 and df2.<br>Both have the same column name as 'Accounts'.<br><br>
I can currently access this data for comparison using the following code:<br>
<code>df1.account.isin(df2.account.values)</code></p>
<p>I would like 'account' to be accessed as a variable something like this.<br><code>df1.... | <p>Give this a try.. using the set functionality</p>
<pre><code>Usercol ='Account' #user entry
Common =
list(set(df1.loc[:Usercol]).intersect(set(df2.loc[:Usercol])))
#fetch index of each data frame using
df1[df1[Usercol].isin(Common)].index
df2[df2[Usercol].isin(Common)].index
</code></pre> | python|pandas|data-science | 2 |
368,655 | 54,811,481 | Numpy Vectorization - Weird issue | <p>I am performing some vectorized calculation using numpy. I was investigating a bug I am having and I ended with this line:</p>
<pre><code>(vertices[:,:,:,0]+vertices[:,:,:,1]*256)*4
</code></pre>
<p>The result was expected to be <code>100728</code> for the index <code>vertices[0,0,17]</code>, however, I am getting... | <p>The issue here is that you are using too small integers, and the number overflows and wraps around because numpy uses fixed width integers rather than infinite precision like python <code>int</code>'s. Numpy will <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.result_type.html" rel="nofoll... | python|numpy|numpy-ndarray | 2 |
368,656 | 54,867,896 | TypeError: Batching of padded sparse tensors is not currently supported on padding a TF dataset object | <p>I am trying to train a model for detecting an object from a drawing. I am using tensorflow. I have made a function using the input_fn provided by Google for the QuickDraw dataset. But I am getting the mentioned error on running the function. The code for the function is:</p>
<pre><code>def input_func():
"""... | <p>The problem was in the parse_tfexample function. In it, there is a dictionary with an element keyed "drawing" which is a sparse tensor. So I just converted it to dense using <code>tf.sparse.to_dense()</code>. Here is the code of the parse_tfexample:</p>
<pre><code>def parse_tfexample(example,mode):
"""Parse... | python|tensorflow|deep-learning | 0 |
368,657 | 49,624,124 | python last working day of month (with CustomBusinessDay)? | <p>I like to calculate last working day before or after a specific date(includes holidays, not just weekends)?</p>
<pre><code>import datetime as dt
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \
USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \
USLabo... | <p>I was able to reproduce the problem and after some testing I've narrowed it down to using a <code>DatetimeIndex</code> as the input of the calendar parameter in <code>CustomBusinessDay</code>.</p>
<p>You can skip that and use the calendar instance directly:</p>
<pre><code>import datetime as dt
import pandas as pd
... | python|pandas|datetime | 2 |
368,658 | 49,346,876 | Large Numpy array handler, numpy data procession, memmap funciton mapping | <p>Large numpy array (over 4GB) with nyp file and memmap function</p>
<p>I was using numpy package for array calculation where I read <a href="https://docs.scipy.org/doc/numpy/neps/npy-format.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/neps/npy-format.html</a> </p>
<p>In "Format Specification: Ve... | <p>The previous header size field was 16 bits wide, allowing headers smaller than 64KiB. Because the header describes the structure of the data, and doesn't contain the data itself, this is not a huge concern for most people. Quoting the notes, "This can be exceeded by structured arrays with a large number of columns."... | python|file|numpy | 1 |
368,659 | 49,424,089 | Python: Group output of Column based on a condition | <pre><code>#code source
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=50,
n_features=6,
n_informative=3,
n_classes=2,
random_state=... | <p>I think need <code>Series</code>, get differences by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a>, compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.gt.html" rel="nofollow noreferrer"><cod... | python|pandas|numpy | 0 |
368,660 | 49,386,165 | Creating a matrix where each element is equal to the minimum of its row and column index | <p>I want to create a matrix C where each element is equal to the minimum of its corresponding row and column index. For example: the element corresponding to the first row and second column should have a value of 1, the element corresponding to the eighth row and the third columns should have a value of 3, etc. </p>
... | <p><strong>Option 1</strong><br>
<code>np.mgrid</code></p>
<pre><code>np.mgrid[1:33, 1:33].min(axis=0)
</code></pre>
<p></p>
<pre><code>array([[ 1, 1, 1, ..., 1, 1, 1],
[ 1, 2, 2, ..., 2, 2, 2],
[ 1, 2, 3, ..., 3, 3, 3],
...,
[ 1, 2, 3, ..., 30, 30, 30],
[ 1, 2, ... | python|arrays|numpy | 0 |
368,661 | 49,604,218 | Unable to install Statsmodel | <p>I am getting error when i try to install statsmodel.
I have installed all dependencies required for statsmodel.
<a href="https://i.stack.imgur.com/DoDuq.png" rel="nofollow noreferrer">Error message when using CMD</a></p>
<p><a href="https://i.stack.imgur.com/D0t44.png" rel="nofollow noreferrer">Unable to find the r... | <p>I was also facing issues in installing statsmodel .
you can use Anaconda navigator and follow the following steps.</p>
<ul>
<li><p>Clone the statsmodels repository using
"git clone git://github.com/statsmodels/statsmodels.git"</p></li>
<li><p>Inside statsmodel build the setup file using "python setup.py build" </... | python|tensorflow|data-science|statsmodels | 1 |
368,662 | 49,662,807 | importing txt file with dictionary script and applying it to dataframe to replace words | <p>I am trying to replace certain strings within a column in a dataframe using a txt file.</p>
<p>I have a dataframe that looks like the following (this is a very small version of a massive dataframe that i have).</p>
<pre><code>coffee_directions_df
Utterance Frequency
Directions to Starb... | <p>You almost had it! Here's a solution that reuses the regex object and lambda function in your current code.</p>
<p>Instead of your last line (<code>rep = pattern.sub(...</code>), run this:</p>
<pre><code>coffee_directions_df['Utterance'] = \
coffee_directions_df['Utterance'].str.replace(pattern, lambda m: rep[m.gr... | python|pandas|dataframe|replace | 1 |
368,663 | 49,711,324 | tf.contrib.summary.generic or tf.summary.text in eager mode | <p>It looks like only tf.contrib.summary.scalar is supported when using eager mode. Is there a workaround to use tf.contrib.summary.generic or tf.summary.text?</p> | <p>I believe you are mistaken. <strong>All</strong> the summary methods in <code>tf.contrib.summary</code> are supported for both eager execution and graph construction. For example, something like this seems to work:</p>
<pre><code>import tensorflow as tf
tf.enable_eager_execution()
with tf.contrib.summary.create_f... | tensorflow | 2 |
368,664 | 49,429,888 | Use tf.shape(tensor) as a bound for a loop | <p>Using Tensorflow in Python, I want to use the shape of a placeholder for the bound of a for-loop. However, when I try to do this, I get the error: 'Tensor' object cannot be interpreted as an integer. This shape is not a constant value across the data so we cannot use a tf.constant. How can we solve this problem? </p... | <p><em>EDIT:</em></p>
<p>Seems I didn't understand the question correctly in first instance. I'll leave the original answer because it's related and just in case someone finds it useful.</p>
<p>In any case, if you want to use a dimension of a tensor as the number of iterations in a loop, then the value of the dimensi... | python|tensorflow|deep-learning|tensor | 1 |
368,665 | 49,559,770 | How do you resolve 'hidden imports not found!' warnings in pyinstaller for scipy? | <p>I'm working on using pyinstaller to create an .exe for a python program that uses pandas and sklearn. The pyinstaller process completes and produces the dist folder with the executable as expected. However, when I run the .exe I get module import errors related to sklearn and scipy.</p>
<p>I created a test script (... | <p>You need to go into the hook-scipy.py (or create one) and have it look like this:</p>
<pre><code>from PyInstaller.utils.hooks import collect_submodules
from PyInstaller.utils.hooks import collect_data_files
hiddenimports = collect_submodules('scipy')
datas = collect_data_files('scipy')
</code></pre>
<p>then go in... | python|pandas|scipy|scikit-learn|pyinstaller | 7 |
368,666 | 49,764,463 | Return Pandas dataframe rows where more than N columns have the same value | <p>Let's say I have the following dataframe <code>df</code>. How can I take in a value N and return only rows where N columns have the same value? For example if N=3, it would return rows 0,2,3,4. If N=4, then only row 3. </p>
<pre><code> 'A' 'B' 'C' 'D' 'E'
0 1 1 1 3 5
1 5 4 ... | <p>We can using <code>value_counts</code>, ge mean >=, you can change number 3 in it to what you need </p>
<pre><code>df[df.apply(pd.value_counts,1).ge(3).any(1)]
Out[257]:
'A' 'B' 'C' 'D' 'E'
0 1 1 1 3 5
2 3 4 3 2 3
3 5 5 5 4 5
4 1 2 1 2 1
</code></p... | python|pandas|row|subset | 1 |
368,667 | 49,627,687 | Extracting the max consecutive missing values between the first and last value within a dataframe | <p>I have a dataset that has columns which start on different dates:</p>
<pre><code>| Date | Hour | A | B | C | D |
--------------------------------------
| 01/01/2012 | 01:00 | | 1 | 2 | |
| 01/01/2012 | 03:00 | | | | 1 |
| 01/01/2012 | 07:00 | | 5 | | |
| 15/04/2012 | 01:00 | 1 | | 2 | 3 |
|... | <p>I think need:</p>
<pre><code>print (df)
Date Hour A B C D
0 01/01/2012 01:00 NaN 1.0 2.0 NaN
1 01/01/2012 03:00 NaN NaN NaN 1.0
2 01/01/2012 07:00 NaN 5.0 NaN NaN
3 15/04/2012 01:00 1.0 NaN 2.0 3.0
4 16/01/2013 05:00 1.0 1.0 NaN NaN
5 01/01/2012 01:00 NaN 1.0... | python|pandas|dataframe | 3 |
368,668 | 49,768,187 | Python/Pandas - How to make pandas automatically convert numeric type when needed | <p>When doing some simple calculation from dataframe object (python 3.5, pandas 0.20.1), pandas is not behaving consistently when the calculated result doesn't fit the current numeric type. Why?</p>
<p>Please see code below, creating a dataframe with numeric type-int16 :</p>
<pre><code>import pandas as pd
import nump... | <p>The answer is that np.int16 has a negative range: <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html</a>.</p>
<blockquote>
<p>int16 Integer (-32768 to 32767) which means 65535 integers</p>
</blockquote>... | python|pandas | 0 |
368,669 | 49,371,489 | Python output formatting issues | <p>Not sure about the syntax of the output I am receving. Any help would be appreciated.
Here is my code: </p>
<pre><code>import numpy
def g(): #generate random complex values
return numpy.random.random(1) + numpy.random.random(1) *1j
p = numpy.poly1d(numpy.squeeze([g(),g(),g()])) # test function p
pprime = nu... | <p>The <code>2</code> is the exponent on the first <code>x</code>, misaligned because you put text before it on the same line.</p>
<p>If we take your output:</p>
<pre><code>Our p(x) is 2
(0.6957 + 0.683j) x + (0.3198 + 0.5655j) x + (0.9578 + 0.1899j)
</code></pre>
<p>and remove the text you prepen... | python|numpy|format|output | 4 |
368,670 | 49,683,143 | Python Pandas Group By Consecutive Multiple Columns | <p>I need to do a consecutive group-by involving multiple columns in a pandas dataframe. I've found answers on how to do a consecutive group-by with a single column, but I'm not sure how to extend it to multiple columns.</p>
<p>For exmaple, my data looks like:</p>
<pre><code> Time Object Status ... | <p>To add the "consecutiveness" condition, compare each row with its succeeding row.
When they are not equal, we wish to start a new group:</p>
<pre><code>mask = (df[['Object','Status']] != df[['Object','Status']].shift(1)).any(axis=1)
# 0 True
# 1 True
# 2 True
# 3 True
# 4 False
# dtype: bool
gro... | python|pandas|group-by|pandas-groupby | 3 |
368,671 | 49,717,720 | How to append multiple columns into two? | <p>The data I am working with is in a large set of columns, with related values - for example:</p>
<pre><code>| YearQ | Area A | Area B | Area C |
+--------+--------+--------+--------+
| 2017Q1 | 1234.0 | 9252.0 | 3421.0 |
| 2017Q2 | 1245.0 | 9368.0 | 3321.0 |
| 2017Q3 | 1350.0 | 9440.0 | 3225.0 |
| 2017Q4 | 1333.0 |... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a>:</p>
<pre><code... | python|pandas|dataframe | 2 |
368,672 | 49,477,384 | Pandas MultiIndex, selecting values by 1. and 2. level | <p>I´ve some problems by selecting values within 1. and 2. level.</p>
<blockquote>
<p>I´ve got an MultiIndex by setting the <code>header = [0,1]</code></p>
</blockquote>
<pre><code>In[1]: df = pd.read_csv('Data.txt', sep='\t', header=[0,1], skipinitialspace=True)
In[2]: print(df.columns)
Out[2]: MultiIndex(
... | <p>You could use <code>df.loc</code>:</p>
<pre><code>import numpy as np
import pandas as pd
columns = pd.MultiIndex.from_product([['A','B','C'],['X','Y','Z']])
df = pd.DataFrame(np.random.randint(10, size=(3,len(columns))), columns=columns)
# A B C
# X Y Z X Y Z X Y Z
# 0 2 7 5 1... | python|pandas|dataframe|multi-index | 3 |
368,673 | 49,401,344 | How to store a varying size arraylist in a numpy array (for clustering purposes)? | <pre><code> a=[]
for (x,y,w,h) in faces:
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
a.append(eyes)
i+=1
print(a)
</code></pre>
<p>eyes is the detection output from detectMultiScale using eye_cascade (detecting inside ... | <p>Collect them into a list and then concatenate:</p>
<pre><code>>>> out = []
>>> for i in range(5):
... out.append(np.squeeze(np.full([i, 4], i))) # squeeze to make it more difficult
...
>>> out
[array([], shape=(0, 4), dtype=int64), array([1, 1, 1, 1]), array([[2, 2, 2, 2],
[2,... | python|numpy|opencv|multidimensional-array | 0 |
368,674 | 49,381,524 | errors with pandas import | <p>I have installed PANDAS using -> pip install --upgrade pandas.
"Requirement already up-to-date:--------"
But when I use :</p>
<pre><code>import pandas as pd
</code></pre>
<p>on spyder this is the error</p>
<pre><code>import pandas as pd
Traceback (most recent call last):
File "<ipython-input-5-7dd3504c366... | <p>The most common reasons to encounter this error is the incompatibility of pip installs and python versions. </p>
<p>Though the error log mentions that your pandas module is not available even after you've installed it, there is a possibility to run into this error is due to the presence of multiple/incompatible ver... | python|pandas | 1 |
368,675 | 49,676,246 | Replace values in python pandas column based on second df | <p>I have gone through all similar questions on stackoverflow, but the solutions still don't work for me. </p>
<p>I have two dfs:</p>
<pre><code>df1:
User_ID | Code_1
123 htrh
345 NaN
567 cewr
...
df2:
User_ID | Code_2
123 ert
345 nad
</code></pre>
<p>I want t... | <p>Use <code>DataFrame.update</code>. The id columns (<code>User_ID</code>) and the code columns (<code>Code_1</code>, <code>Code_2</code>) should have the same name across the dataframes before calling the function.</p>
<pre><code>df2.columns = ['User_ID', 'Code_1']
df1.update(df2)
</code></pre>
<p>That should be en... | python|pandas|replace|syntax | 2 |
368,676 | 49,488,326 | Pandas to Excel conditional formatting whole column | <p>I want to write a Pandas dataframe into Excel with formatting. For this I'm using <code>xlsxwriter</code>. My question is twofold:</p>
<ul>
<li><p>First, how can I apply conditional formatting to a whole column? In the <a href="http://xlsxwriter.readthedocs.io/example_conditional_format.html" rel="noreferrer">examp... | <blockquote>
<p>First, how can I apply conditional formatting to a whole column</p>
</blockquote>
<p>You can specify the cell range from the first to the last row in the column like <code>C1:C1048576</code>. This is how it is stored internally, it is just displayed as <code>C:C</code>.</p>
<p>This applies to all ca... | python|pandas|xlsxwriter | 3 |
368,677 | 49,526,859 | scipy.optimize.curve_fit a definite integral function with scipy.integrate.quad | <p>If I have a function that the independent variable is the upper limit of an definite integral of a mathematical model. This mathematical model has the parameters I want to do regression.
This mathematical model is nonlinear and can be complicated.</p>
<ol>
<li><p>How can I solve this?</p></li>
<li><p>if the output ... | <p>The error is raised inside the function <code>scipy.integrate.quad</code> because d is a <code>numpy.array</code> and not a scalar. The function given to <code>scipy.optimize.curve_fit</code> take the independent variable (<code>x_linear</code> in your case) as first argument.</p>
<p>The quick and dirty fix is to m... | python|numpy|math|scipy|curve-fitting | 0 |
368,678 | 49,651,046 | Save two arrays with Numpy.savetxt into a .csv file, with a column for each array | <p>I have difficulties with <code>numpy.savetxt</code>. Particularly, I have two arrays with <code>B</code> created by the following command <code>np.arrrange(2000,5000)</code>, while <code>print(A)</code> is like <code>[0 2 1 ... 0 1 2]</code> and I would like to save both of them in a single csv file with the format ... | <p>Your solution worked fine for me, although I needed to set the <code>fmt</code> specifier to <code>'%d'</code> for integers. What version of numpy are you on (for me <code>np.__version__ == '1.14.1'</code>)?</p>
<p>Anyway, here is a possible solution with more standard numpy:</p>
<pre><code>import numpy as np
A =... | python|arrays|numpy | 0 |
368,679 | 49,403,023 | How to determine the size of bias matrices in a neural network? | <p>I'm new to the world of machine learning. My question is how can I determine the size of the biases in a neural network (with backpropagation algorithm)? Currently, I have a 2-layer neural network (1 hidden and 1 output layer). Here's the code:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt ... | <p>The shape of your bias is correct. The shape of the gradient being subtracted from the bias in the end should be (2,1) and not (2,2) - which is the problem in your case (shape of H_gradient should not be (2,2)). </p>
<p>Also, </p>
<p><code>
#Calculate output error :
O_error = O_output - target
</code></p>
<p... | python|numpy|machine-learning|artificial-intelligence|backpropagation | 0 |
368,680 | 49,560,809 | pandas: return average of multiple columns | <p>How do you output average of multiple columns?</p>
<pre><code>Gender Age Salary Yr_exp cup_coffee_daily
Male 28 45000.0 6.0 2.0
Female 40 70000.0 15.0 10.0
Female 23 40000.0 1.0 0.0
Male 35 55000.0 12.0 ... | <p>Given this dataframe:</p>
<pre><code>df = pd.DataFrame({
"Gender": ["Male", "Female", "Female", "Male"],
"Age": [28, 40, 23, 35],
"Salary": [45000, 70000, 40000, 55000],
"Yr_exp": [6, 15, 1, 12]
})
df
Age Gender Salary Yr_exp
0 28 Male 45000 6
1 40 Female 70000 15
2 2... | python|pandas|group-by | 18 |
368,681 | 49,558,605 | Pandas extracting values from rows based on set of strings | <p>I'm trying to extract specific values(in form of key:value pairs) from a pandas column which has multiple semicolon separated pairs.</p>
<p>The input dataframe looks like this: </p>
<pre><code>9 114188457 114192289 cast_3_930|cast_1_1069|cast_2_985 0.9510007336163186 - 114188457 114188457 211,111,11... | <h1>Regex on pandas column</h1>
<p>You can use a regex expression after the <code>.str</code> parameter on a column</p>
<pre><code>df['gene_id'] = df.iloc[:,9].str.extract('gene_id \"(\w+)\";')
df['gene_name'] = df.iloc[:,9].str.extract('gene_name \"(\w+)\";')
df['gene_biotype'] =df.iloc[:,9].str.extract('gene_biotyp... | python|pandas | 1 |
368,682 | 49,677,788 | Retrieve rows in a dataframe containing words from another dataframe in pandas | <p>Am trying to retrieve rows in a dataframe containing words from another dataframe. Have attached the .csv files in the link below. I have tried this but it gives me only the single words:</p>
<pre><code>import numpy as np
import pandas as pd
sentiment_words = pd.read_csv('sentiment_words.csv')
tokens = pd.read_csv... | <p>try converting the sentiment words to a list via:</p>
<pre><code>sentiment_list = sentiment_words['sentiment_words'].tolist()
</code></pre>
<p>Then, try and match the words using this:</p>
<pre><code>result = tokens[tokens['token'].str.contains('|'.join(sentiment_list))]
</code></pre>
<p>Note: i didn't download ... | python|pandas|dataframe|matching | 1 |
368,683 | 49,551,301 | Python - key error when appending a list of dict to a nested defaultdict | <p>I'm trying to create a datastructure of nested dictionaries in Python. I read 2 relational sql-table-like csv files into dataframes and then convert them row by row into dictionaries. Inside these dictionaries I store dictionaries I created from another csv. </p>
<p>My code below works as long as I just store a dic... | <p>Your solution seems to work with input data provided (see below). Is there something I am missing?</p>
<p>As you point out, you need to test for keys in your second loop, as below. This is only apparent in your full dataset.</p>
<p><strong>Setup</strong></p>
<p>I have modified your data slightly so it demonstrate... | python|json|pandas|dictionary|defaultdict | 5 |
368,684 | 49,524,083 | Importing any module in cython file gives undefined symbol error | <p>When I use <em>any</em> import statement within modules I compile with cython, I receive the following error on importing the modules (see full code below):</p>
<pre><code>ImportError: /.../hw.cpython-35m-x86_64-linux-gnu.so: undefined symbol: __intel_sse2_strchr
</code></pre>
<p>Everything works fine on my own ma... | <p>The problem was that I used the Intel compiler without running the Intel Python distribution, or otherwise providing the Intel runtime libraries.</p>
<p>Thanks to @ead, I resolved the problem by switching to GCC using:</p>
<pre><code>CC=gcc python setup.py build_ext --inplace
</code></pre> | python|numpy|cython | 1 |
368,685 | 49,407,713 | Keras show MemoryError at model.fit() | <p>I keep getting MemoryError without additional explanation from Keras at model.fit(), no matter how small the number of neurons or batch size. Does anyone have any idea what error does this error refer to or how to fix this?</p>
<p>Error:</p>
<pre><code>Using TensorFlow backend.
Traceback (most recent call last):
... | <p>Error in numpy, solved when using np.asarray. Thank you @MatiasValdnegro and @Idavid.</p> | python|tensorflow|keras|lstm | 0 |
368,686 | 49,658,448 | TypeError: only length-1 arrays can be converted to Python scalars Dot Product | <p>Writing this algorithm for my final year project. Debugged a few, but stuck on this. Tried changing the float method but nothing really changed.</p>
<pre><code>----> 8 hypothesis = np.dot(float(x), theta)
TypeError: only length-1 arrays can be converted to Python scalars
</code></pre>
<p>Entire code - <... | <p><code>x</code> is a numpy array, which Python's builtin <code>float</code> function can't handle. Try:</p>
<pre><code>hypothesis = np.dot(x.astype(float), theta)
</code></pre> | python|pandas|numpy|machine-learning|gradient-descent | 0 |
368,687 | 49,728,797 | pip install <package>==version failed in installing tensorflow-gpu in mac which is shown in pip search | <p>I know there are lots of similar questions but I can not get answer from them.</p>
<p>It's very weird when I am trying to install tensorflow-gpu==1.7.0 just these days.
I can get tensorflow-gpu (1.7.0) from <code>pip search tensorflow-gpu</code>, but can't install it by <code>pip install tensorflow-gpu==1.7.0</code... | <p>Please see documentation for <a href="https://www.tensorflow.org/install/install_mac" rel="nofollow noreferrer">Mac</a> that says</p>
<blockquote>
<p>Note: As of version 1.2, TensorFlow no longer provides GPU support on
macOS.</p>
</blockquote>
<p>That means <strong>you are not supposed to install</strong> the... | python|tensorflow|pip | 2 |
368,688 | 27,992,246 | Iteration over a pandas Series taking forever, but I can't think of a way to solve this without it. Is there a faster way? | <p>I have a pandas Series of successive numbers, something like</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
D = pd.Series([2, 3, 4, 4, 5, 4, 3, 2, 3, 4, 5, 4, 3, 2, 1, 0],
index=pd.date_range(start='2015-01-02 12:00:00', periods=16, freq='s'))
D
2015-01-02 12:00:00 2
2015-01-02 12:0... | <p>For your toy example, your solution is remarkably fast, however it scales quite bad:</p>
<ul>
<li>10 rows --> 1.3ms</li>
<li>100 rows --> 31.5ms</li>
<li>1000 rows --> 2160ms</li>
<li>5000 rows --> 52500ms</li>
</ul>
<p>I'd suggest a more numpy based approach like</p>
<pre class="lang-py prettyprint-override"><co... | optimization|pandas|iteration|vectorization | 1 |
368,689 | 28,028,265 | joblib parallelization of 2 independent calculations on 2 cores is slower than serial | <p>I am trying to parallelize some data expansion with numpy, and I am finding that the parallelized version takes orders of magnitude longer than the serial version, so I must be making some silly mistake.</p>
<p>First, some fake data to set up the problem:</p>
<pre><code>Ngroups = 1.e6
some_group_property = np.rand... | <p>First of all:</p>
<blockquote>
<p>I am running this code on a 4-core machine, so in principle performing the calculations independently for the two populations should give me roughly a 2x speedup.</p>
</blockquote>
<p>No. In general, a speed-up that scales linearly with the number of threads would be the <em>abs... | python|numpy|parallel-processing|joblib | 2 |
368,690 | 28,156,820 | Numpy: Column dependent slicing | <p>I could not find any question concerning what I want to do so I am asking now. Basically, I want slicing in matrices where the row index depends on the column index.</p>
<p>For example:</p>
<pre><code>>>> import numpy as np
>>> x = np.arange(24).reshape(6,4)
>>> x
array([[ 0, 1, 2, 3]... | <p>You can use <code>as_strided</code> to do this:</p>
<pre><code>In [1]: from numpy.lib.stride_tricks import as_strided
In [2]: sz = x.itemsize
In [3]: d = as_strided(x[-1::-1,:], shape=(3,4), strides=sz*np.array([-4,-3]))
In [4]: d
Out[5]:
array([[20, 17, 14, 11],
[16, 13, 10, 7],
[12, 9, 6, 3]])
... | python|numpy | 4 |
368,691 | 27,977,819 | working of ndim in numpy | <pre><code>import numpy as np
>>> a=np.array([1,2,3,4])
>>> a
array([1, 2, 3, 4])
>>> a.ndim
1
</code></pre>
<p>How the dimension is 1 .I have given a equation of 3 variables it means it is a 3 dimension but it is showing the dimension as 1 . Can anyone tell me the logic of ndim?</p> | <p>You have created an array with four elements. That is, a vector. It has one dimension, as NumPy says.</p> | python|numpy | 1 |
368,692 | 28,292,426 | Concatenating/Merging List of Dataframes by Predefined columns | <p>I have the following list of dataframes:</p>
<pre><code>import pandas as pd
rep1 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP1',[1.00,23.22,11.12])], orient='columns')
rep2 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP2',... | <p>I'm not sure this is the <em>right</em> way to do this, but a kind-of neat way is to use <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">reduce</a>:</p>
<pre><code>In [11]: reduce(pd.merge, tmp)
Out[11]:
Probe Gene RP1 RP2
0 x foo 1.00 11.33
1 y bar 23.22 31.2... | python|pandas | 1 |
368,693 | 28,057,233 | Extract float from 'for loop', write to dataframe in python | <p>Thank you for your assistance in advance. </p>
<p>Currently able to group by nth day group.nth(n), and use for loop to generate list of results. </p>
<p>Here is what I have:</p>
<pre><code>import pandas as pd
import numpy as np
In [173]: data
Out [173]:
Date A
1998-04-01 0.0058263... | <p>You can add append to a list from <code>for loop</code> and then create a <code>df</code> from it.</p>
<pre><code>out = []
for x in xrange(1,21):
x = x +1
g = grouped.nth(x).sum()
out.append((x +1, ("%1.3f " % g)))
pd.DataFrame(out)
</code></pre>
<p>`</p> | python|pandas|append|group-by | 0 |
368,694 | 28,021,929 | Numpy iterator on array do not work as expected | <p>I want to declare an array of object and later to include arrays in it. I can do it this way:</p>
<pre><code>import numpy as np
v = np.empty([2,2], dtype=object)
for i in range(len(v.flat)):
v.flat[i] = np.ones([3])
</code></pre>
<p>But since Numpy has iterators, I wanted to use them:</p>
<pre><code>v = np.... | <p>And here is a solution I like:</p>
<blockquote>
<p>I am honestly not sure if this makes more sense or not (I would say it
probably makes sense). But you can use <code>i[()] = ...</code> since you want to
do <em>item</em> assignment not <em>view</em> based/sliced assignment anyway.</p>
<p>Oh, and be caref... | python|numpy|iterator | 4 |
368,695 | 28,255,734 | Ambiguous truth value with boolean logic | <p>I am trying to use some boolean logic in a function on a dataframe, but get an error:</p>
<p>In [4]:</p>
<pre><code>data={'level':[20,19,20,21,25,29,30,31,30,29,31]}
frame=DataFrame(data)
frame
Out[4]:
level
0 20
1 19
2 20
3 21
4 25
5 29
6 30
7 31
8 30
9 29
10 31
In [35]:
def calculate(x):
... | <p>Inadequate use of the function max. np.maximum (perhaps np.ma.max as well as per numpy documentation) works. Apparently regular max can not deal with arrays (easily). Replacing </p>
<pre><code>baseline=max(frame['level'],frame['level'].shift(1))#doesnt work
</code></pre>
<p>with</p>
<pre><code>baseline=np.maximum... | python|excel|algorithm|pandas|data-analysis | 1 |
368,696 | 73,399,927 | How to combine two timelines in tableau | <p><a href="https://i.stack.imgur.com/CsWRC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CsWRC.jpg" alt="enter image description here" /></a></p>
<p>I'm playing around with Tableau exploring UK unemployment data. I've used Pandas to load in data for unemployment over time for men and women and plo... | <p>I have seen multiple approaches towards this problem.</p>
<p>refer this article : <a href="https://kb.tableau.com/articles/howto/combining-start-and-end-dates-into-a-single-axis" rel="nofollow noreferrer">here</a></p>
<p>My issue was resolved using the LoD method</p>
<pre><code>MIN(
IF DATETRUNC('month', [Order ... | pandas|tableau-desktop | 1 |
368,697 | 73,431,796 | How in Tkinter to transfer variables from the input field to a function from another file for calculation by the button in applications | <p>I have an application that is used for fast calculation with substituting periods into a formula from another file</p>
<pre><code>from tkinter import *
from NewDate import P͞_tic, np
class App(Frame):
def __init__(self, parent, ):
Frame.__init__(self, parent, background="black")
self.... | <p>You have to use <code>.get</code> to fetch a value from an IntVar. Hence:</p>
<pre><code> def Calculation(self):
P1 = np.array([self.p1.get()])
P2 = np.array([self.p2.get()])
P͞_tic(P1, P2)
</code></pre> | python|pandas|tkinter|numba|jit | 1 |
368,698 | 73,198,397 | How can I zip filenames, images and predictions of a tensorflow model? | <p>I have the following code to predict image classes from files in a directory structure</p>
<pre><code>import tensorflow as tf
image_dir = "images"
model = tf.keras.applications.VGG19(input_shape=(224, 224, 3), weights="imagenet")
images = tf.keras.utils.image_dataset_from_directory(image_dir, lab... | <p>I needed to add shuffle=False to image_dataset_from_directory()</p>
<p>see Note in <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#list_files" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/data/Dataset#list_files</a></p> | tensorflow|keras | 0 |
368,699 | 73,294,314 | how to check for condition going row by row in a dataframe pandas | <p>I have a dataframe where I have to check the value for every row and modify the column respectively.</p>
<p>I have a table where have a Col1 . IF Col1 has AAA, it has to be in {"AAA":today's date}, if it is BBB then different format, if it is CCC then timestamp of todays date with 16 in hour.</p>
<pre><cod... | <p>You can try <code>Series.map</code></p>
<pre class="lang-py prettyprint-override"><code>d = {
'AAA': {'AAA': 'format1'},
'BBB': {'BBB': 'format2'},
'CCC': {'CCC': 'format3'},
}
df['out'] = df['Col1'].map(d)
</code></pre>
<pre><code>print(df)
ID Col1 Col2 out
0 1 AAA 1234 {'AAA'... | python|pandas | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.