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
17,200
48,916,541
Top Bottom pairings based on column values in a pandas dataframe
<p>I would like to generate Sector/Group wise pairs from a DataFrame based on the values in it's Score column. </p> <pre><code>+---------+-------------------+---------+ | Ticker | Sector | Score | +---------+-------------------+---------+ | ABC | Energy | 3.5 | | XYZ | E...
<p>Is this what you are after?</p> <pre><code>( df.groupby('Sector') .apply(lambda x: [df.Ticker.iloc[x.Score.idxmin()], df.Ticker.iloc[x.Score.idxmax()], x.Score.idxmin(), x.Score.idxmax()]) .apply(pd.Series) .set_axis(['Low Ticker', 'High Ticker', 'Low', 'H...
python|pandas
1
17,201
49,172,914
How to fill nan values with rolling mean in pandas
<p>I have a dataframe which contains nan values at few places. I am trying to perform data cleaning in which I fill the nan values with mean of it's previous five instances. To do so, I have come up with the following.</p> <pre><code>input_data_frame[var_list].fillna(input_data_frame[var_list].rolling(5).mean(), inpla...
<p>This should work:</p> <pre><code>input_data_frame[var_list]= input_data_frame[var_list].fillna(pd.rolling_mean(input_data_frame[var_list], 6, min_periods=1)) </code></pre> <p>Note that the <code>window</code> is <code>6</code> because it includes the value of <code>NaN</code> itself (which is not counted in the av...
python|pandas|dataframe|nan|mean
12
17,202
58,637,350
Speed up a long python code that proves to be slow only due to a single block
<p>We have a huge volume in space filled with lots of particles (~ 10^8) with known array of masses ('HI_mass'), 3d positions ('HI_position'), and some interesting fraction ('HI_fraction'). There is also some imaginary spheres (~10^3) with different but known array of masses ('mass_data'), positions ('position_data'), ...
<p>You should find a way to record timing of the individual parts of your loop. But in case it is the string to double to string conversion, what about the following way of truncating digits from the number instead of correct rounding?</p> <pre><code>import math def trunc_digits(x, digits): d = math.log10(abs(x))...
c++|python-3.x|performance|numpy
1
17,203
70,029,079
'tensorflow.keras.datasets.mnist' has no attribute 'read_data_sets'
<p><strong>Code:</strong></p> <pre><code>import tensorflow.keras.datasets.mnist as input_data mnist = input_data.read_data_sets(&quot;MNIST-data&quot;, one_hot=True) </code></pre> <p><strong>Error message:</strong></p> <blockquote> <p>AttributeError: module 'tensorflow.keras.datasets.mnist' has no attribute 'read_data...
<p>As above error shows there is no attribute 'read_data_sets' in <code>'tensorflow.keras.datasets.mnist'</code> module. However you can access mnist dataset in following two ways:</p> <p>1.Loads the mnist dataset</p> <pre><code>import tensorflow.keras.datasets.mnist as input_data mnist = input_data.load_data(&quot;MN...
python|tensorflow-datasets
0
17,204
70,026,498
How to write time to csv and read again as datetime64[ns, Europe/Berlin]?
<p>Before I am writing to csv file i have time column as:</p> <pre><code>time datetime64[ns, Europe/Berlin] </code></pre> <p>When I am reading df from csv i am getting:</p> <pre><code>time object </code></pre> <p>How to write and read time columns as the same type as before save process?</p> <p>Befor writing...
<p>For this I would use <code>pd.to_pickle(path)</code> and <code>pd.read_pickle(path)</code>, since csv cannot really store anything else than strings and numbers. With pickle, it serializes the entire DataFrame and saves it as if you had just directly dumped the python object into a file and vice versa.</p>
pandas|dataframe|csv
1
17,205
56,297,209
Data of file exported to Excel and CSV varying
<p>I am exporting a dataframe to an Excel as well as a CSV file. Certain columns have data in the format of integers. These values are being shown as integers in Excel and the dataframe output. But, they are being shown as decimals in the CSV file. </p> <pre><code>pd.to_numeric(column_name, errors = 'coerce').fillna(0...
<p>Try this code:</p> <pre><code>import pandas as pd df = pd.DataFrame({'number': [1,2,3,4,5]}) df.number=pd.to_numeric(pd.to_numeric(df.number), errors = 'coerce').fillna(0).astype(int) df.to_csv('test.csv' ,index=False) </code></pre> <p>Output:</p> <pre><code> number 0 1 1 2 2 3 3 4 4 ...
python|pandas
0
17,206
56,143,362
Is there a way to load a numpy unicode array into a memmap?
<p>I am trying to create an array of <code>dtype='U'</code> and saving that using <code>numpy.save()</code>, however, when trying to load the saved file into a <code>numpy.memmap</code> I get an error related to the size not being a multiple of 'U3'</p> <p>I am working with <code>python 3.5.2</code>. I have tried the ...
<p>The files used by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow noreferrer"><code>numpy.memmap</code></a> are raw binary files, not <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.lib.format.html#npy-format" rel="nofollow noreferrer">NPY-format</a>...
python|numpy|numpy-ndarray|numpy-memmap
2
17,207
56,419,910
What function does `with open(...)` serve while parsing a csv file with `pandas`?
<p>I just found a notebook <a href="https://github.com/elegant-scipy/elegant-scipy/blob/master/markdown/ch1.markdown#reading-in-the-data-with-pandas" rel="nofollow noreferrer">from a book</a> that has the following construction:</p> <pre><code>filename = 'data/counts.txt' with open(filename, 'rt') as f: data_table...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a> can accept a couple of different types in the first argument. The documentation says <code>filepath_or_buffer : str, path object, or file-like object</code>.</p> <p>When you run <cod...
python|pandas
0
17,208
55,636,573
Pandas: Calculate the difference between all rows and a specific row in the dataframe
<p>Hi I have data in the following format:</p> <pre><code> A B 0 2 1 1 2 1 2 2 4 3 2 4 4 3 5 5 3 5 6 3 6 7 3 6 </code></pre> <p>I want to calculate the sum of absolute differences between index 0 and all the other indexes. This means that I will calculate the difference on every column. Take the abso...
<p><code>subtract</code> with <code>.iloc</code> then <code>sum</code> the absolute values across rows:</p> <pre><code>df['C'] = df.sub(df.iloc[0]).abs().sum(1) A B C 0 2 1 0 1 2 1 0 2 2 4 3 3 2 4 3 4 3 5 5 5 3 5 5 6 3 6 6 7 3 6 6 </code></pre>
python|python-3.x|pandas|dataframe|difference
5
17,209
64,688,931
Add values to a column from a dictionary
<p>I have a dataframe as follows:</p> <pre><code>df = {'emp': [123, 234], 'state': ['AL', 'CA'], 'start_time': ['08:00', '08:00'], 'end_time': ['17:00', '17:00'] df.head() emp|state|start_time|end_time 123|AL|11/05/2020 08:00|11/05/2020 17:00 234|CA|11/05/2020 08:00|11/05/2020 17:00 </code></pre> <p>I also have a separ...
<p>Here is one approach. I added date to original data, and changed the time offset from 0 to 1, to verify that all adjustments get applied.</p> <pre><code>import pandas as pd df = {'emp': [123, 234], 'state': ['AL', 'CA'], 'start_time': ['2020-11-05 08:00', '2020-11-05 08:00'], 'end_time': ['2...
python|pandas|dictionary
1
17,210
44,097,209
Clean the noisy data with pandas drop row
<p>I am trying to reduce the noise from a large dataset with grammatical keywords. Is there a way to horizontally trim the data-set based on a particular set of keywords. </p> <pre><code>Input: id1, id2, keyword, freq, gp1, gps2 222, 111, #paris, 100, loc1, loc2 444, 234, have, 1000, loc3, loc4 434, 134, #USA, 30...
<p>Assuming you have a dataframe <code>df</code>... Use <code>isin</code> to find which rows have or don't have a list or set of words. Then use Boolean indexing to filter the dataframe. </p> <pre><code>list_of_words = ['she', 'have', 'did', 'and'] df[~df.keyword.isin(list_of_words)] </code></pre>
python|windows|pandas|dataframe|anaconda
2
17,211
44,254,816
Exact match of string in pandas python
<p>I have a column in data frame which ex df: </p> <pre><code> A 0 Good to 1. Good communication EI : tathagata.kar@ae.com 1 SAP ECC Project System EI: ram.vaddadi@ae.com 2 EI : ravikumar.swarna Role:SSE Minimum Skill </code></pre> <p>I have a list of of strings </p> <pre><code>ls=['tathagata.kar@ae.com','a.ka...
<p>You could simply use ==</p> <pre><code>string_a == string_b </code></pre> <p>It should return True if the two strings are equal. But this does not solve your issue.</p> <p><strong>Edit 2:</strong> You should use len(df1.index) instead of len(df1.columns). Indeed, len(df1.columns) will give you the number of colum...
regex|excel|python-2.7|pandas
3
17,212
44,283,732
use pandas to make pivot_table but an error occur
<p>I have the head of a dataframe like this and I want to make a pivot_table.</p> <pre><code> user_id item_id cate_id action_type action_date 0 11482147 492681 1_11 view 15 1 12070750 457406 1_14 deep_view 15 2 12431632 527476 1_1 view 15 3 13397746 531771 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a> + <...
python|pandas
4
17,213
69,524,923
Merging two data frames in pandas that don't have the same column names and are different lengths
<p>I have two data frames that I want to merge, problem is they are not the same length and don't have columns that overlap. I basically want to match the website with the company name, so they are all in one row. Some companies don't have websites, so I want these rows to just be populated with Naan.</p> <p>Example of...
<p>You can get the list of <code>Company</code> names from <code>df1</code>, then use it to make a regex pattern for extracting from <code>Website</code> column of <code>df2</code>. Get the result by left join using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow no...
python|pandas|string|dataframe|merge
1
17,214
69,487,207
Adding dataframe column to numpy.array
<p>For a regression, I would like to add a dataframe column to a numpy.array which contains dummy variables.</p> <p>Currently, the array looks like this:</p> <pre><code>[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 1] [0 0 1 0]] </code></pre> <p>I would like to add the dataframe column values (which h...
<p>You could use your numpy array to create a dataframe:</p> <pre><code>array=np.array([[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]]) new_dataframe = pd.DataFrame(data=array) </code></pre> <p>and then add your column to it like this:</p> <pre><code>new_dataframe['4'] = you...
python|arrays|numpy
1
17,215
69,636,949
Pandas, filter column for > date
<p>i am trying to filter on column assessed date like so:</p> <p><code>netnewprocess = netnewprocess[(netnewprocess['AssessedDate'] &gt; assessdateprev)]</code></p> <p>my <code>assessdateprev</code> = <code>8/31/2021 00:00</code></p> <p>The filter seems to work on most values but I still see items before Aug 31 in the ...
<p>As your column <code>AssessedDate</code> and constant <code>assessdateprev</code> are of string type rather than datetime type, your existing code actually filters by string comparison and gave the wrong result.</p> <p>It is because the string <code>8/6/2021 8:47:07 AM</code> when compared with the other string <cod...
python|pandas
3
17,216
41,192,997
Separate out (and keep) duplicate categorical data using Seaborn barplot?
<p>I'm trying to plot some hypothetical student testing scores. I'd like to have student lastname on the y-axis and test score on the x-axis (horizontal barplot). Because Student names are non-unique, I'd like to <em>allow</em> duplicates on the y-axis. I've seen ways to get rid of duplicate data in seaborn and/or pand...
<p>You can plot a bar for each unique row (by using the index as your y-coordinate), and then manually assign y-axis tick labels.</p> <pre><code>df = pd.DataFrame({ 'name': ['A', 'B', 'A', 'B'], 'score': [10, 20, 30, 40], }) ax = sns.barplot(x=df.score, y=df.index, orient='h') ax.set_yticklabels(df.name) </co...
python|pandas|matplotlib|seaborn
4
17,217
41,217,953
tensorflow evaluate while training with queues?
<p>I preprocessed my data as tfrecord. I feed my data by <strong>queue</strong> <strong>instead of feed_dict.</strong></p> <p>This is my code.</p> <pre><code>for i in range(100000000): sess.run(train_op) start_time = time.time() if i &gt; 20 and i % 10 == 0: summaries_train = sess.run(Summaries)...
<p>All is the same as the training process except that you should 1) separate the training data and evaluation data; 2) don't run the optimization operation, aka gradient descent. I hope <a href="https://github.com/eduOS/abstractive_summarization/blob/c2c_w2c/gen_utils.py#L77" rel="nofollow noreferrer">this function</a...
python|queue|tensorflow
0
17,218
54,103,624
How to fix TensorFlow Linear Regression no change in MSE?
<p>I'm working on a simple linear regression model to predict the next step in a series. I'm giving it x/y coordinate data and I want the regressor to predict where the next point on the plot will lie. </p> <p>I'm using dense layers with AdamOptmizer and have my loss function set to: </p> <p><code>tf.reduce_mean(tf.s...
<p>The issue is that I'm applying an activation to the output layer. This is causing that output to go to whatever it activates to.</p> <p>By specifying in the last layer that activation=None the deep regression works as intended.</p> <p>Here is the updated architecture:</p> <pre><code>layer_input = tf.layers.dense(...
python|tensorflow|deep-learning|training-data
0
17,219
38,167,738
pandas append same series to each column
<p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame(np.random.rand(5, 3), ['p0', 'p1', 'p2', 'p3', 'p4'], ['A', 'B', 'C']) df </code></pre> <p><a href="https://i.stack.imgur.com/Gnkl0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gnkl0.pn...
<p>You can use double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>print (pd.concat([dm] * df.shape[1], axis=1, keys=df.columns)) A B C m0 0.823788 0.823788 0.823788 m1 0.615354 0.615354 0.6153...
python|pandas
1
17,220
38,094,820
How to create Pandas Series with Decimal?
<p>I'm calculating some standard deviations which are giving FloatingPointErrors. I wanted to try converting the data series to Decimal (using <a href="https://docs.python.org/3/library/decimal.html" rel="noreferrer">https://docs.python.org/3/library/decimal.html</a>), to see if this fixes my issue.</p> <p>I can't see...
<p>would something like this work? </p> <pre><code>def column_round(decimals): return partial(Series.round, decimals=decimals) df.apply(column_round(2)) </code></pre> <p>alternatively lets use <code>np.vectorize</code> so we can use <code>decimal.quantize</code> function to do rounding, this will leave the var...
python|python-3.x|numpy|pandas|decimal
2
17,221
38,283,220
Tensorflow feed_dict with tensorflow.python.framework.errors.InvalidArgumentError
<p>my example is like the following:</p> <pre><code>import tensorflow as tf import numpy as np batch_size = 10 real_data = np.ndarray(shape=(batch_size, 1), dtype=np.int32) for i in range(batch_size): real_data[i] = i print np.shape(real_data) holder = tf.placeholder(tf.int32, shape=[None, 1]) with tf.Session(...
<p>You cannot use <code>sess.run([])</code>, you need to provide a graph node inside like:</p> <pre><code>sess.run([some_node], feed_dict=feed_dict) </code></pre>
python-2.7|tensorflow|deep-learning
0
17,222
38,206,895
Merging two datetime-indexed pandas.dataframe objects
<p>I have two datetime-indexed pandas.dataframe objects:</p> <p>object1: </p> <pre><code> DateTime Bid.ESU6 Ask.ESU6 2016-06-28 08:30:00 207000 207025 2016-06-28 08:30:11 206975 207000 2016-06-28 08:30:21 207000 207050 </code></pre> <p>object2:</p> ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> on <code>object2</code> with <code>method='nearest'</code> prior to doing the <code>join</code>:</p> <pre><code>object1 = object1.join(object2.reindex(object1.index, meth...
python|pandas
3
17,223
38,451,029
How to visualize multi-index-ed data in orange?
<p>I am using <code>pandas</code> library in python to generate a multi-indexed data, i.e., the columns are multi-indexed. The indices are <code>category</code> and <code>source</code>. I save this data as <code>.csv</code> file. In the file, the first row is the <code>category</code> values and second row is correspon...
<p>According to <a href="http://orange-visual-programming.readthedocs.io/loading-your-data/index.html" rel="nofollow noreferrer">documentation</a>, Orange does not support reading multi-indexed data.</p> <p>In order to visualize the data, you will need to convert it to a normal tabular format (one column per feature) ...
python|pandas|orange
1
17,224
66,152,314
How to convert a Python dictionary to a Numpy array?
<p>So the logistic regression from the sklearn library from Python has the <code>.fit()</code> function which takes <code>x_train</code>(features) and <code>y_train</code>(labels) as arguments to train the classifier.</p> <p>It seems that <code>x_train.shape = (number_of_samples, number_of_features)</code></p> <p>For x...
<p>It seems you are trying to store the dictionary into a numpy array. If the dictionary is small, you can directly store the values as:</p> <pre><code>import numpy as np x = np.array(list(b.values())) </code></pre> <p>However, this will run into OOM issues if the dictionary is large. In this case, you would need to u...
python|numpy|scikit-learn|kaldi
0
17,225
52,489,007
How can I take one of my pandas heirarchical indexes and one hot encode it?
<p>I have created a multi-hierarchical index from frames that have been indexed by time:</p> <pre><code>original_thing time day_1 day_2 day_3 day_4 2018-05-24 20:00:00 0 0 1 0 2018-05-25 00:00:00 0 0 0 1 2018-05-25 04:00:00 0 0 0 1 2018-05-25 08:00:00 0 ...
<p>You can use <code>OneHotEncoder</code> form <code>sklearn</code>.</p> <p>Lets start with some boilerplate code:</p> <pre><code> import pandas as pd import numpy as np from sklearn.preprocessing import OneHotEncoder df = pd.DataFrame({"one":[2,1,0,0,1,2], "abcd":[4,6,3,6,7,1]}) print(df) one abcd 0 2 ...
pandas|multi-index
0
17,226
46,261,868
Elegant way to complete a parallel operation on two arrays of unequal lengths
<p>I want to write a function in <code>numba</code> that runs a math operation on 2 arrays, and accommodate for when both arrays don't have the same element count.</p> <p>So for example: lets say I want a function that adds each element of array <code>a</code> to the elements of array <code>b</code> with these 3 possi...
<blockquote> <p>but I can clearly see three nearly identical code blocks which feel terribly wasteful. </p> </blockquote> <p>Yes, you're repeating yourself a lot in the code. On the other hand it's very easy to see what each case does.</p> <p>You could simply use two loops instead:</p> <pre><code>import numba as n...
python|arrays|performance|numpy|numba
1
17,227
46,301,047
Python 3.6: Find first occurance string(entire column value) from dataframe which starts with '$'
<p>I have dataframe with 55 columns, want to find first occurance string where column value satrts with '$'</p> <p>I tried below script, but could not achieve.</p> <pre><code>string = '' for col in df: string=df[col].str.startswith('$') if string!='': sys.exit() </code></pre> <p>sample df:</p> <pre><code>Co...
<p>You can create mask first:</p> <pre><code>m = df.astype(str).applymap(lambda x: x.startswith('$')) print (m) Col1 Col2 Col3 Col4 0 False False True True 1 False False False False </code></pre> <p>And then get position of first <code>True</code> in rows and columns by <a href="https://docs.scipy...
python|python-3.x|pandas
2
17,228
46,341,628
Fast method of converting all strings in a list to integers
<p>I've gone through the <a href="https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int">Convert all strings in a list to int</a> post</p> <p>I want to convert </p> <pre><code>results = ['1', '2', '3'] </code></pre> <p>to:</p> <pre><code>results = [1, 2, 3] </code></pre> <p>I know i can ...
<p>Multiprocessing is a way to get it done faster (in addition of using Numpy):</p> <p>E.g:</p> <pre><code>In [11]: from multiprocessing import Pool In [12]: pool = Pool(10) In [13]: pool.map(int, [str(i) for i in range(500)]) </code></pre> <p>Numpy will mostly provide a memory gain as you would be dealing with pr...
python|python-2.7|numpy|type-conversion
2
17,229
58,177,426
Outer subtraction with Numpy
<p>I simply want to do: C_i=\Sum_k (A_i -B_k)^2 I saw that this calculation is faster with a simple <code>for loop</code> than with the <code>numpy.subtract.outer</code>! Anyway I feel that <code>numpy.einsum</code> would be the fastest. I could not understand <code>numpy.einsum</code> that well. Can anyone please help...
<h2>Use at least Numba, or a Fortran Implementation</h2> <p>Both of your functions are quite slow. Python loops are very inefficient (A1), and allocating large temporary arrays is also slow (A2 and partially also A1). </p> <p><strong>Naive Numba implementation for small arrays</strong></p> <pre><code>import numba as...
python|arrays|numpy|numpy-einsum
1
17,230
69,086,092
Classification with PyTorch is much slower than Tensorflow: 42min vs. 11min
<p>I have been a Tensorflow user and start to use Pytorch. As a trial, I implemented simple classification tasks with both libraries.<br /> However, PyTorch is much slower than Tensorflow: Pytorch takes 42min while TensorFlow 11min. I referred to <a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutoria...
<p>It is because in your tensorflow codes, the data pipeline is feeding a batch of 1 image into the model per step instead of a batch of 32 images.</p> <p>Passing <code>batch_size</code> into <code>model.fit</code> <strong>does not</strong> really control the batch size when the data is in the form of datasets. The rea...
tensorflow|machine-learning|pytorch
2
17,231
44,530,818
Removing Duplicates from an array in Python depending on the first 4 letters
<p>I have a list of postcodes, e.g.</p> <pre><code>DD1 1DB DD1 5PH DD10 8JG DD10 9LJ </code></pre> <p>What I would like to do is keep the first representative, depending on the first part of the postcode e.g.</p> <p>I need to keep:</p> <pre><code>DD1 1DB DD10 8JG </code></pre> <p>I am using pandas and imported the...
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow noreferrer"><code>df['POSTCODES'].str[:4]</code></a> to obtain the first four characters, and use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="n...
python|arrays|pandas
4
17,232
60,913,123
How do filter the dataframe in such a way?
<p>Here is the output of the dataframe</p> <pre><code>Date Upper_zone Lower_zone Stock_name S/R 0 2018-02-12 163.40 155.75 ABFRL Resistance becoming support 1 2017-03-16 200.00 189.10 CROMPTON Resistance becoming support 2 2017-04-11 127.69 126.16 CUB Resistance be...
<p>You can use <code>drop_duplicate</code> on column <code>Stock_name</code> and keep the last value like this</p> <pre><code>df.drop_duplicates(subset='Stock_name', keep="last") </code></pre> <p>or keep the max value on the <code>Upper_zone</code> column like this:</p> <pre><code>df.groupby('Stock_name', group_keys...
python|pandas|dataframe
0
17,233
60,827,792
Adding Asia/Singapore Time stamp as the first column in Pandas dataframe
<p>I am trying to add an Asia/Singapore timestamp as the first column of the following pandas dataframe,and name it as 'sdc_sequence_id'.</p> <pre><code>id col1 col2 01 A B 02 C D 03 E F </code></pre> <p>expected dataframe :</p> <pre><code>sdc_sqeuence_id id col1 col2 200...
<p><strong>Try</strong>:</p> <pre><code>df["sdc_squence_id"] = datetime.strftime(datetime.now(pytz.timezone('Asia/Singapore')), "%Y-%m-%d %H:%M:%S") </code></pre> <p><strong>Explanations</strong>:</p> <ol> <li>Get the local time in a specific timezone: <ul> <li>Use the <a href="https://pypi.org/project/pytz/" rel="...
python|pandas|timestamp-with-timezone
1
17,234
71,583,217
Python and Pandas: copying values from non NaN cells to Nan Cells if key values match
<p>I'm new to python and Pandas and I encountered this issue.</p> <p>so, if I have 4 columns and some rows</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A.</th> <th>B.</th> <th>C.</th> <th>D.</th> </tr> </thead> <tbody> <tr> <td>Q50.</td> <td>12.</td> <td>34</td> <td>xy</td> </tr> <tr> <t...
<p>Use:</p> <pre><code>df.groupby('A.').apply(lambda x: x.ffill()) </code></pre> <p>or</p> <pre><code>df.groupby(df['A.'].values).ffill() </code></pre> <p>output:</p> <pre><code> A. B. C. D. 0 Q50. 12.0 34.0 xy 1 Q50. 23.0 34.0 xy 2 Q52. 1.0 50.0 CAT </code></pre> <p><em>NB. you can't do <cod...
python|pandas
0
17,235
69,735,852
Assigning custom colors to Plotly legend
<p>I am working with this csv file: <a href="https://i.stack.imgur.com/JsX2n.png" rel="nofollow noreferrer">https://i.stack.imgur.com/JsX2n.png</a> and it contains star colors as red, blue,white,etc. However, when I plot it with plotly using this code:</p> <pre><code>import plotly_express as px df = pd.read_csv('/Users...
<p>You will have to use color keyword (as @mosc9575 mentioned) and map colors from your csv table, something like that:</p> <pre><code>import pandas as pd from collections import OrderedDict import plotly_express as px df = pd.read_csv('1.csv') df_colors = list(OrderedDict.fromkeys(df[&quot;Star color&quot;])) colors...
python|pandas|plotly|plotly-python
0
17,236
69,842,469
How to convert a csv file to a Dictionary in Python?
<p>I have a csv file which has the configuration information to create the yaml file (final desired result). Firstly, I am trying to convert each row of the csv file to a Dictionary and then I can easily convert Dictionary to yaml file using yaml.dump(Created_Dictionary)</p> <p>Sample Input file (test.csv):</p> <pre><c...
<p>Try:</p> <pre><code>df = pd.read_csv(&quot;test.csv&quot;, &quot;|&quot;) my_dict = df.set_index(&quot;fieldname&quot;).to_dict(&quot;index&quot;) #convert allowed items to list df[&quot;allowed&quot;] = df[&quot;allowed&quot;].str.split(&quot;,&quot;) test_yaml = yaml.dump(df.set_index(&quot;fieldname&quot;).to_di...
python|pandas|csv|dictionary|yaml
2
17,237
69,709,010
Keras/Conv2D: Strange, I use padding=SAME, but the size is still reduced
<p>I set padding to SAME or same, but the output is still being reduced, what's wrong then? , as I understand according to the official doc, the output size shall be the same to the input one, do I forget what is important?</p> <pre><code>import tensorflow as tf x = tf.keras.Input([120, 120, 3]) conv = tf.keras.layer...
<p>It's because of <code>strides=(2, 2)</code>. It skips a step during the convolution operation and so reduces the h &amp; w by a factor of 2 at each convolutional layer. <a href="https://i.stack.imgur.com/mt0jH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mt0jH.png" alt="enter image description ...
python|tensorflow|keras
1
17,238
43,234,435
Tick label text and frequency in matplotlib plot
<p>I want to plot some data stored in a Pandas Dataframe using matplotlib. I want to put specific labels on x axis ticks. So, I set them with:</p> <pre><code>ax.xaxis.set_ticklabels(data_frame['labels']) </code></pre> <p>That works well, but it sets a tick label for each data point, making the plot unreadable, so I t...
<p>Using <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.Locator" rel="nofollow noreferrer"><code>Locator</code></a> we can define how many ticks shall be produced and where they should be placed. By sub-classing <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.MaxNLocator" rel=...
python|pandas|matplotlib|plot
2
17,239
43,100,286
Python trigonometric calculations in degrees
<p>I am converting a MATLAB program to Python for a project. I am facing some major issues with converting MATLAB's <code>sind()</code> syntax to Python. I'm using </p> <pre><code>numpy.sin(numpy.radians()) </code></pre> <p>but some of the results in Python compared to <code>Matlab</code> are displaying tremendous va...
<p>In Octave, <code>sind</code> is:</p> <pre><code>function y = sind (x) ... I = x / 180; y = sin (I .* pi); y(I == fix (I) &amp; isfinite (I)) = 0; endfunction </code></pre> <p><code>np.radians</code> (<code>np.deg2rad</code>) is, according to a note <code>x * pi / 180</code>.</p> <p>So for most values <cod...
python|matlab|numpy
2
17,240
50,473,701
Keras k_gather function
<p>Currently I'm trying to get the Keras backend function k_gather to work in R. Thus far no luck. I can only find proper documentation on the tensorflow gather function. If I follow this documentation the following piece of code should extract the (1,1,1)-entry of the tensor a.</p> <pre class="lang-python prettypri...
<p>I found a way around this k_gather problem. I now use the following procedure to permute a tensor a</p> <pre><code>library(keras) a = k_constant(c(1L, 2L,3L,4L), dtype = 'int32' , shape = c(1L, 1L, 4L )) a_1 = a[,,1:2] a_2 = a[,,3:4] a_new = k_concatenate( list(a_2, a_1)) sess = k_get_session() sess$run(a_n...
tensorflow|keras
0
17,241
50,562,606
Renaming pandas dataframe column on copy affects the original dataframe
<p>I don't understand why this renaming operation affects the original dataframe when the copy command is used. Why is df_copy a view of df and not really a copy? I would expect the print statement to output 'x' not 'y'.</p> <pre><code>df = pandas.DataFrame({'x': [0, 1]}) df_copy = df.copy(deep=True) df_copy.columns.v...
<p>From <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>Note that when copying an object containing Python objects, a deep copy will copy the data, but will not do so recursively. Updating a nested data object wil...
python|pandas|dataframe
1
17,242
45,446,752
Counting unique combination frequencies in a market-basket
<p>I have a set of 1000000 market-baskets containing 1-4 items each. I would like to calculate the frequency of each unique combination of items purchased. </p> <p>The data is organized as such:</p> <pre><code>[in] print(training_df.head(n=5)) [out] product_id transaction_id ...
<p>Well, since you cant use <code>df.groupby('product_id').count()</code>, this is the best I could come up with. We make a dict with the string representation of lists as keys, and count occurrences in it.</p> <pre><code>counts = dict() for i in df['product_id']: key = i.__repr__() if key in counts: c...
python|frequency|sklearn-pandas
2
17,243
45,719,176
How to display Runtime Statistics in Tensorboard using Estimator API in a distributed environment
<p><a href="https://www.tensorflow.org/get_started/graph_viz#runtime_statistics" rel="noreferrer">This article</a> illustrates how to add Runtime statistics to Tensorboard:</p> <pre><code> run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, _ = sess.run...
<p>I use the following hook, based on ProfilerHook, to have the estimator output the run metadata into the model directory and inspect it later with Tensorboard.</p> <pre><code>import tensorflow as tf from tensorflow.python.training.session_run_hook import SessionRunHook, SessionRunArgs from tensorflow.python.training...
python|tensorflow|tensorboard
13
17,244
45,615,026
Detection Text from natural images
<p>I write a code in <strong>tensorflow</strong> by using <strong>convolution neural network</strong> to <strong>detect</strong> the text from images. I used TFRecords file to read the street view text dataset, then, I resized the images to <strong>128</strong> for height and width.</p> <p>I used 9-<strong>conv layer<...
<p>In general and this not a rule , it's just based on my experience, you should start with a smaller net 2 or 3 conv layer, and say what happens, if you get some good result focus more on the winning topology and adapt the hyperparameters ( learnrat, batchsize and so one ) , if you don't get good result at all go deep...
tensorflow|computer-vision|deep-learning|ocr|conv-neural-network
1
17,245
45,707,831
Unable to teardown temporary file used by Pandas read_csv
<p>My unittest teardown code does not remove the file </p> <blockquote> <p>test_utility1.dat</p> </blockquote> <p>I even tried os.remove and also no luck. I don't understand why my process is holding on to the file after raising an error. I am running this on python 3.6 and using Pycharm as my IDE. All my tests pas...
<p>well, the resolution is below.</p> <p><strong>initial code snippet</strong></p> <pre><code>self.assertRaises(SystemExit, create_utility_config_dataframe, a) </code></pre> <p><strong>new code snippet</strong></p> <pre><code>with self.assertRaises(SystemExit): create_utility_config_dataframe(a) </code></pre> ...
python|unit-testing|pandas|file-permissions|temporary-files
0
17,246
62,690,682
xtics position by custom label
<p>I've been trying to put some custom labels in my <code>bar</code> plotting, but what I found is that for some reason, my custom labels are starting from the center. I'd like to start in the left position. I'm not using the artist layer.</p> <pre><code>df_train_sex_female_die.Pclass.value_counts().plot(kind=&quot;bar...
<p>Just use:</p> <pre><code>plt.xticks([0, 1, 2], custom_labels, rotation='horizontal') </code></pre>
pandas|matplotlib
1
17,247
62,721,585
how to show() geoplot?
<p>I am a novice in Geoplot, so it looks I need a help. I use PyCharm for my test project.</p> <p>The task is to build and show some charts. With pyplot it works without any problem: I build a chart and then show() it.</p> <pre><code>plt.scatter(x, y, z, c = z) plt.show() </code></pre> <p>Now I try to do the same with ...
<p>Please try to assign the returned Axes into a Figure object and then show the Figure.</p> <pre class="lang-py prettyprint-override"><code>import geopandas as gpd import geoplot as gplt usa_cities = gpd.read_file(gplt.datasets.get_path('usa_cities')) continental_usa_cities = usa_cities.query('STATE not in [&quot;HI&...
python|matplotlib|geopandas
0
17,248
54,632,080
Error evaluating a TensorArray in a while loop
<p>I've built the following <code>TensorArray</code>:</p> <pre><code>ta = tf.TensorArray( dtype=tf.float32, size=0, dynamic_size=True, element_shape=tf.TensorShape([None, None]) ) </code></pre> <p>and called <code>ta = ta.write(idx, my_tensor)</code> inside a <code>while_loop</code>.</p> <p>When e...
<p>Not sure if this is what's biting you, but you have to make sure your while_loop function takes the tensor array as input and emits an updated one as output; and you have to use the <em>final</em> version of the TensorArray at the end of the while_loop:</p> <pre><code>def fn(ta_old): return ta_old.write(...) ta_...
tensorflow
1
17,249
73,830,567
Pandas column of features to multiple columns
<p>I have a CSV file that has 9 columns, the last one is a column of a list of features as following:</p> <pre class="lang-none prettyprint-override"><code> First Name Last Name Email Grad Date Major List Appointments Count Advising Time Labels Count ...
<p>You could create a function which will receive a labels_name_list, split it by <code>,</code> and then by <code>=</code> to get the key-value pairs, and returns them as a <code>dict</code>. Something like:</p> <pre><code>def fun(label_names_list): key_val_strings = label_names_list.split(',') key_val = map(l...
python|pandas|dataframe|multiple-columns
0
17,250
73,699,154
Move rows in dataframe according to time
<pre><code>dic = {'Employee ID':emp_id, 'Log Date':emp_logdate, 'Log Time':emp_logtime} df = pd.DataFrame(dic).groupby(['Employee ID','Log Date']).agg({'Log Date':'first', 'Log Time': lambda x: ', '.join(x.unique())})['Log Time'].astype(str).str.split(', ', expand=True).reset_index() </code></pre> <p>Let's say I have a...
<p>One approach could be as follows:</p> <pre><code>import pandas as pd import numpy as np import re data = {0: {0: '7:20', 1: '7:02', 2: '11:33', 3: '11:38'}, 1: {0: '11:50', 1: '11:36', 2: '12:40', 3: np.nan}, 2: {0: '12:49', 1: '12:59' , 2: '17:06', 3: np.nan}, 3: {0: '17:20', 1: np.na...
python|pandas
1
17,251
71,440,434
Kendall Tau for series/dataframes - Pandas (Python)
<p>I have been trying to compute the <strong>Kendall's tau</strong> rank correlation coefficient for two series with the <strong>Pandas</strong> library (Python) using different methods. Surprisingly, the results were different using series/dataframe inputs, and even change with the concat order of the dataframe.</p> <...
<p>Issue solved !!</p> <p>There was a version issue with Pandas. An upgrade from Pandas 1.3.1 to Pandas 1.4.1 led to the obtention of a single coefficient: 0.421637.</p>
python|pandas|dataframe|correlation|series
0
17,252
71,198,437
Print Dataframe with for and show data and name of column
<p>I am trying to do a row-by-row print of a Dataframe with pandas.</p> <p>the dataframe is</p> <pre><code>df = pd.DataFrame(cursor.fetchall()) </code></pre> <p>and if do print(df) show this</p> <pre><code> id name stock 0 1 Fruit 8 1 2 Meet 10 2 3 Fish 30 3 4 Cake 20 </code></pre> <...
<p>One way that I accomplished this is using the following:</p> <pre><code>def f(id_, name, stock, cols): print(f&quot;The column {cols[0]} is {id_} and {cols[1]} {name} have {cols[2]} {stock}&quot;) for x, y, z in zip(df['id'], df['name'], df['stock']): f(x, y, z, df.columns) </code></pre> <p>I iterated throu...
python|pandas|dataframe
0
17,253
71,271,835
pandas multiindex assignment complex broadcasting
<p>I have a dataframe with a multiindex that looks like this:</p> <pre class="lang-py prettyprint-override"><code>In [1]: import pandas as pd In [2]: idx = pd.MultiIndex.from_product([[&quot;a&quot;, &quot;b&quot;], [&quot;p&quot;, &quot;q&quot;], [&quot;x&quot;, &quot;y&quot;]]) In [3]: df = pd.DataFrame(index=idx, ...
<p>Well after posting this I figured it out on my own. Feeling a bit dumb, but here is a way that works fine:</p> <pre class="lang-py prettyprint-override"><code>In [16]: df.loc[&quot;a&quot;] = [[1,2,3,4], [5,6,7,8]]*2 </code></pre> <p>To make it a bit more general:</p> <pre><code>In [20]: expand=len(df.index.levels[-...
python|pandas
1
17,254
71,325,884
How to calculate cumulative profit of a trades list
<p>Here is a ETH/USDT trades history, I want to calculate the cumulative profit:</p> <pre><code>import pandas as pd data_list = [('2022-01-29T01:41:43.584Z', 'buy', 2540.87, 0.0079, 20.072873), ('2022-01-31T02:01:09.263Z', 'buy', 2508.31, 0.004, 10.03324), ('2022-01-31T16:52:18.583Z', 'sell', 2661.75, 0.0118, 31.4086...
<p>You could construct a &quot;profit&quot; column with the formula used to derive 1.55:</p> <pre><code>df['profit'] = (( ( df['price'] - ( (df['price'] * df['amount']).cumsum() / df['amount'].cumsum() ).shift() ) * df['amount'] ).fillna(0)) </code></pre> <p>or...
python|pandas|dataframe|finance|algorithmic-trading
2
17,255
71,187,632
Replace empty value from colum by first word from another column's string
<p>I'm a beginner in Python. I have a df named <strong>df_opensports</strong> with lot of columns. One column is named <strong>'Sub_Categoria'</strong>. Another Column is named <strong>'Name'</strong>. I need to fill empty values from 'Sub_Categoria' with the first word from the same 'Name' column index. For example,...
<p>Not the best idea, but I believe it would solve your problem:</p> <pre class="lang-py prettyprint-override"><code>for index, row in df_opensports.iterrows(): if row[&quot;Sub_Categoria&quot;] == None: df_opensports.loc[index, &quot;Sub_Categoria&quot;] = row[&quot;Name&quot;].split(&quot; &quot;)[0] </code></p...
python|string|split|fillna|pandas-loc
1
17,256
71,255,735
Addressing polynomial multiplication and division "overflow" issue
<p>I have a list of the coefficient to degree 1 polynomials, with <code>a[i][0]*x^1 + a[i][1]</code></p> <pre><code>a = np.array([[ 1. , 77.48514702], [ 1. , 0. ], [ 1. , 2.4239275 ], [ 1. , 1.21848739], [ 1. , 0. ], ...
<p>There is a slightly complicated way to keep the product first and then divide structure.</p> <p>By first employ <code>n</code> points and evaluate on <code>a</code>.</p> <pre class="lang-py prettyprint-override"><code>xs = np.linspace(0, 1., 10) ys = np.array([np.prod(list(map(lambda r: np.polyval(r, x), a))) for x...
numpy|floating-accuracy|polynomials|polynomial-math
0
17,257
52,275,262
Pandas: undo accumulation (e.g. cumulative sum)
<p>I have received data with accumulated numbers. Is there a smart way to deaccumulate data, so I have it month by month and not stacked on top of each other?</p> <p>(Check the example xlsx here: <a href="https://docs.google.com/spreadsheets/d/1yELrJdZmi3CFJccYSi5U6GGDW-Awp5spHDnsDyshBe0/edit?usp=sharing" rel="nofollo...
<p>You can groupby the sales rep and take the row-wise difference. Then merge the datasets back together.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Date': ['01-01-2018', '01-01-2018', '01-01-2018', '01-02-2018', '01-02-2018', '01-02-2018'], 'SalesRep': ['Jakob', 'Adomas', 'Thomas', 'Jakob', 'Ad...
python|excel|pandas|cumulative-sum
4
17,258
52,029,864
How to vectorize this peak finding for loop in Python?
<p>Basically I'm writing a peak finding function that needs to be able to beat <code>scipy.argrelextrema</code> in benchmarking. Here is a link to the data I'm using, and the code:</p> <p><a href="https://drive.google.com/open?id=1U-_xQRWPoyUXhQUhFgnM3ByGw-1VImKB" rel="noreferrer">https://drive.google.com/open?id=1U-_...
<p>This may do it. It's not perfect but hopefully it obtains what you want and shows you a bit how to vectorize. Happy to hear any improvements you think up </p> <pre><code>label = np.array(label[:-1]) # not sure why this is 1 unit longer than search.shape[0]? # the idea is to make the index matrix you're for loopin...
python|numpy|scipy|signal-processing|vectorization
3
17,259
52,252,496
numpy reading a csv file to an numpy array
<p>I am new to python and using numpy to read a csv into an array .So I used two methods:</p> <p>Approach 1</p> <pre><code>train = np.asarray(np.genfromtxt(open("/Users/mac/train.csv","rb"),delimiter=",")) </code></pre> <p>Approach 2</p> <pre><code>with open('/Users/mac/train.csv') as csvfile: rows = csv.re...
<p>You can use pandas also, it is better and simple to use.</p> <pre><code>import pandas as pd import numpy as np dataset = pd.read_csv('file.csv') # get all headers in csv values = list(dataset.columns.values) # get the labels, assuming last row is labels in csv y = dataset[values[-1:]] y = np.array(y, dtype='float...
python-3.x|numpy
2
17,260
60,436,285
Tensorflow no longer knows placeholder or only works with the cpu
<p>Hello I have a problem with my tensorflow script. The script worked without problems, the past few years. Now I get the error after reinstalling tensorflow:</p> <pre><code>AttributeError: module 'tensorflow' has no attribute 'placeholder' </code></pre> <p>I tried:</p> <pre><code>import tensorflow as tf </code></p...
<p>This is the version compatibility issues. Now the version of tensorflow is 2.1.0 which has many differences from version 1.x. First youโ€™d better using the command below to convert your TensorFlow python files from version 1.x to version 2.x.</p> <p><code>tf_upgrade_v2 --infile file_v1.py --outfile file_v2.py</code>...
python|tensorflow|tensorflow2.0
0
17,261
60,354,520
error in application in the terminal using keras
<p>from tensorflow.keras.preprocessing.text import Tokenizer ImportError: No module named keras.preprocessing.text</p> <p>Any solution? thank you</p> <p>my operating system: Ubuntu 19.10</p>
<p>Upgrade your keras package to latest version with command</p> <p>pip install -U pip keras tensorflow</p>
tensorflow|ubuntu|keras
0
17,262
72,508,796
Key error when trying to fill nan values of a extremely large dataset
<pre><code># Making use of the GPU library. This only works for integer only features at present. def read_file_int(path = '', usecols = None): # LOAD DATAFRAME if usecols is not None: df = cudf.read_feather(path, columns=usecols) else: df = cudf.read_feather(path) # REDUCE DTYPE FOR CUSTOMER AND DATE #...
<p>In this line you remove <code>customer_ID</code> from the dataframe.</p> <pre><code>features_num = [x for x in df._get_numeric_data().columns.values if x not in ['customer_ID', 'target']] df = df[features_num].fillna(NAN_VALUE) </code></pre> <p>And then in the next line you try to use <code>customer_ID</code>.</p> ...
python|pandas|dataframe|kaggle
0
17,263
59,720,107
Drop dataframe columns where all rows AND header is na
<p>I have a dataframe that holds a number of NoneType values and I would like to drop all columns where all the row values AND the header is None. I am struggling to find a way to do this. In the <strong>MWE</strong> below I have managed to either drop all columns where all the rows are None OR drop all columns where t...
<p>You can use 2 conditions with an <code>&amp;</code> and invert and use <code>.loc[]</code>:</p> <pre><code>df.loc[:,~(df.columns.isna() &amp; df.isna().all())] </code></pre> <hr> <pre><code> a b c NaN 0 1 2 None NaN 1 4 5 None 7.0 </code></pre>
python|pandas|dataframe
8
17,264
59,736,998
Unable to correctly get the output of Custom Model Tflite Model in Android application
<p>I have trained a very simple model and converted it into a Tflite model as well....the python code for the model is as follows </p> <pre><code># -*- coding: utf-8 -*- """ Created on Sat Sep 28 21:05:22 2019 @author: Aneshka Goyal """ import tensorflow as tf def freeze_session(session, keep_var_names=None, output_...
<p>I solved the problem. I fixed it configuring sigmoid simplification to the number of tags instead of value=1</p>
python|android|neural-network|tensorflow-lite|firebase-mlkit
0
17,265
59,792,443
I am getting weird shape for the test set while trying to use train_test_split
<p>I am trying to apply KNN to Diabetes prima data, in order to split my data set into training and testing datasets, I have used iloc function as described in the code. But when I am using this code, I am getting really weird test data shapes. Can anyone please explain what am I doing wrong here </p> <p>here is the c...
<p>When you use <code>train_test_split</code> you're not getting pandas objects back, but numpy arrays. The output that you get is how numpy arrays show their shape. Here are a couple of examples:</p> <pre><code>import numpy as np np.array([0, 1, 2]).shape ## (3,) np.array([[0, 1, 2], [3, 4, 5]]).shape ## (2, 3) </...
python|pandas|machine-learning|knn
1
17,266
61,672,366
Search string in dataframe column that contains lists of string and return complete dataframe
<p>I have a dataframe <code>df</code> which has 4 columns <code>'A','B','C','D'</code> </p> <p>I have to search for a substring in each column and return the complete dataframe in the search order for example if I get the substring in column <code>B</code> row <code>3,4,5</code> then my final <code>df</code> would be ...
<p>There are lists in column <code>B</code>, so need <code>in</code> statement:</p> <pre><code>df1 = df[df['B'].apply(lambda x: 'cvb' in x)] print (df1) A B C D 0 asdfg [asdfgh, cvb] asdfg nbcjsh </code></pre> <p>If want use <code>str.contains</code> then is possible use <code>str.j...
python|pandas|dataframe
0
17,267
61,964,891
pandas select the minimum and max of each column and create a new dataframe
<p>this is my dataframe:</p> <pre><code>A,B,C,D 10,1,2,3 1,4,7,3 10,5,2,3 40,7,9,3 9,9,5,0 </code></pre> <p>I have just learned thank to you how to create a new dataframe selecting according to the min and max of a specific column. Thanks to @CHRD and @Quang Hoang.</p> <p>I have just realize that this it not what I...
<p>you can just call <code>.agg</code> on your entire dataframe.</p> <pre><code>df.agg(['min','max']) A B C D min 1 1 2 0 max 40 9 9 3 </code></pre>
python|pandas|dataframe|min
4
17,268
61,887,997
Check if RGB values of an image meet conditions without a loop
<p>Say I have a coloured image img, as defined below. And I have range values for R, G, and B: R1, R2, B1, and so on...</p> <p>Now I want to set all RGB values of an image to [255, 0, 0] if the following conditions satisfied [(R1 > R &amp; R &lt; R2) &amp; (G1 > G &amp; G &lt; G2) &amp; (B1 > B &amp; B &lt; B2)]....
<p>You can do the colour comparison for each colour channel at once using numpy like <code>img[:,:,2] &gt; R1</code> for the red channel. You can combine all these together like so.</p> <pre class="lang-py prettyprint-override"><code># opencv stores colour channels in BGR order by default normally img[(img[:,:,0] &gt;...
python|numpy
1
17,269
61,611,256
Create big Vector with numpy
<p>I want to create a vector with the size 10^15 with numpy and fill it with random numbers, but I get the following error:</p> <p>Maximum allowed dimension exceeded.</p> <p>Can it help if i use MPI? </p> <p>Thank you </p>
<p>The Message Passing Interface (MPI) is mainly used to do parallel computations across multiple machines (nodes). Large arrays can be split into smaller arrays and stored on different machines. However, while it's of course possible to distribute the data to different nodes, you should carefully think about the neces...
python|arrays|numpy
0
17,270
61,971,658
Replicating `np.einsum` result via normal matrix operations
<p>I have implemented a TCB Spline in Python via Numpy. The critical piece of the code appears below:</p> <pre><code>np.einsum('km,km,kl,lm-&gt;m',xdiffpow_knot, h_pow_knot[:,i], hermite_matrix, lag_knot[:,i]) </code></pre> <p>where <code>k</code> and <code>l</code> are always 4 (<code>k</code> being powers of 0 to 3...
<p>Consider:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2],[3,4]]) &gt;&gt;&gt; np.einsum('km,km,kl,lm-&gt;m',a,a,a,a) array([142, 392]) </code></pre> <p>This can be computed using basic linear algebra operations.<br> Observe the 'kl,lm' part is traditional matrix multiplication and can be sub-computed to yield 'km':...
julia|numpy-einsum
1
17,271
58,156,382
With a pandas dataframe, how can I set a background color for both levels of a multi-index when outputting to the body of an email as HTML?
<p>I have created a pandas dataframe and set a background color for the multiindex columns with the styles method. When i output it to Jupyter, both levels of the multiindex columns have the background color. But when i export it email, the background color shows on the first level only. Is there any way to color both ...
<p>i solved this myself. I had to add rowspan="2" to the header selector in styles.</p>
html|pandas|email|formatting|jupyter
0
17,272
57,826,610
How to get the top rows from a dataframe with multiple columns set as the index?
<p>I have a dataframe that has two columns 'sp' and 'bg' set as the index and is sorted by 'score'. I would like to get the top two rows for each 'sp' value in the dataframe</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([ {'sp': 'A', 'bg': 'a', 'score': 1234}, {'sp': 'A', 'bg': 'b', 'sc...
<p>This should do the trick:</p> <pre><code>import pandas as pd df = pd.DataFrame([ {'sp': 'A', 'bg': 'a', 'score': 1234}, {'sp': 'A', 'bg': 'b', 'score': 123}, {'sp': 'A', 'bg': 'c', 'score': 12}, {'sp': 'A', 'bg': 'd', 'score': 1}, {'sp': 'B', 'bg': 'a', 'score': 234}, {'sp': 'B', 'bg': 'b',...
python|pandas
1
17,273
58,075,061
TypeError: Error converting shape to a TensorShape: Only size 1 arrays are accepted
<p>I'm currently stuck on an error regarding my neural network. The dataset consists of a 2418 arrays with each containing 400 numbers. The shape is (2418,400). After trial and error I reshaped this to (2418,400,1) because I thought that would be better for the model. The error I receive when running is:</p> <pre><cod...
<p>Seems the problem is fixed with using:</p> <pre><code>Xreshaped = X.reshape((2418,400,1)) input_shape = (400,1) </code></pre>
python|tensorflow|deep-learning
0
17,274
34,229,986
How do I keep the mask when slicing a masked array in Numpy?
<p>When I create a view of a Numpy masked array (via slicing) the mask is <em>copied</em> to the view -- so that updates to the view will not change the mask in the original (but will change the data in the original array).</p> <p>What I want is to change <strong>both</strong> the original data <strong>and</strong> th...
<p>Try turning off the mask in the view before changing the value</p> <pre><code>orig_arr = ma.array([[11,12],[21,22]]) orig_arr[1,:] = ma.masked print orig_arr ## Prints: [[11 12] ## [-- --]] view_arr = orig_arr[1,:] print view_arr ## Prints: [-- --] view_arr.mask=False # or [True, False] view_arr[:] =...
python|numpy|masked-array
3
17,275
34,126,989
Plot best fit line with plotly
<p>I am using plotly's python library to plot a scatter graph of time series data. Eg data :</p> <pre><code>2015-11-11 1 2015-11-12 2 2015-11-14 4 2015-11-15 2 2015-11-21 3 2015-11-22 2 2015-11-23 3 </code></pre> <p>Code in python:</p> <pre><code>df = pandas.read_csv('~/Data.csv', parse_dates=["...
<p>Your provided code snippet is missing a <code>fig</code> definition. I prefer using <code>plotly.graph_objs</code> but the with setup below you can chose to show your figures using <code>fig.show()</code> or <code>iplot(fig)</code>. You won't be able to just include an argument and get a best fit line <em>automatica...
python|pandas|plotly|regression|plotly-python
2
17,276
36,733,895
how to compare unicode date u'2006-07-23' format and 25-06-15 08:42:43.830000000 PM using python pandas?
<p>Basically the unicode format will get from the datepicker and <code>25-06-15 08:42:43.830000000 PM</code> this format from one column my dataframe is:</p> <pre><code>query,status,received_date a,closed,25-06-15 08:42:43.830000000 PM b,pending,27-06-15 08:42:43.830000000 PM ab,closed,28-06-15 08:42:43.830000000 PM b...
<p>I think you need first convert <code>dates</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, then column <code>received_date</code> too and extract <a href="http://pandas.pydata.org/pandas-docs/stable/generated/panda...
python|python-2.7|pandas
1
17,277
36,758,077
Python Pandas: Re pivot or re groupby using the values as index
<p>I am new to Pandas and have been trying to figure out how to re-pivot or re-groupby using the output values. For example my sample csv data which I read in using read_csv below,</p> <pre><code> Transaction, Product, Dollar_Amount A, Orange, 1 A, Apple, 2 A, Pear, 3 B, Orange, 4 B, Grape, 5 ...
<p>you can use pipeline</p> <pre><code>result=(df.groupby('Transaction') .size() .sort_values(ascending=False) .reset_index() .rename(columns={0:'Count_Transactions'}) .groupby('Count_Transactions') .sum()) </code></pre> <p>almost the same result you want</p...
python|pandas
2
17,278
36,948,476
Create DataArray from Dict of 2D DataFrames/Arrays
<p>I'm trying to transition from <code>Pandas</code> into <code>Xarray</code> for <code>N-Dimensional DataArrays</code> to expand my repertoire. </p> <p>Realistically, I'm going to have a bunch of different <code>pd.DataFrames</code> (in this case row=month, col=attribute) along a particular axis (patients in the mo...
<p>From a dictionary of DataFrames, you might convert each value into a DataArray (adding dimensions labels), load the results into a Dataset and then convert into a DataArray:</p> <pre><code>variables = {k: xr.DataArray(v, dims=['month', 'attribute']) for k, v in D_patient_DF.items()} combined = xr.Datas...
python|dictionary|pandas|dataframe|python-xarray
5
17,279
55,065,419
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
<p>I am trying to write my first function using numba jit, I have a pandas dataframe that I need to iterate through and find the root mean square for each 350 points, since the for loop of python is quite slow I decided to try numba jit, the code is:</p> <pre><code>@jit(nopython=True) def find_rms(data, length): r...
<p>You had a typo in <code>append</code> and I think you also made a mistake with what the square root is to be taken of (I believe <code>resI</code> not <code>res</code>).</p> <p>Other than that, the only problem was the initialization of <code>interval</code>. <code>Numba</code> doesn't want you to pass a numpy array...
python|pandas|jit|numba
2
17,280
49,556,940
Lookup in a pandas Dataframe
<p>I have a dataframe which is similar to:</p> <pre><code>grades=pd.DataFrame(columns=["person","course_code","grade"],data=[[1,101,2.0],[2,102,1.0],[3,103,3.0],[2,104,4.0],[1,102,5.0],[3,104,2.5],[2,101,1.0]]) </code></pre> <p>On each row is the grade of a certain student in certain subject.</p> <p>And want to conv...
<p>try:</p> <pre><code>grades.pivot_table(index='person', columns='course_code', values='grade') </code></pre> <p>The <code>value</code> argument let you to choose the aggregation column.</p> <p>In order to answer your comment below, you can always add different levels when indexing. This is simply done by passing a...
python|pandas|dataframe
1
17,281
28,195,858
Filling multiple diagonal elements of a numpy 2D array
<p>What is the best way to fill multiple diagonal elements (but not all) of a 2 dimensional numpy array. I know <code>numpy.fill_diagonal</code> is the recommended way to fill all the diagonal elements.</p> <p>Currently I am just using a loop:</p> <pre><code>for i in a_list_of_indices: a_2d_array[i,i] = num </code></...
<p>You can use this without looping:</p> <pre><code>a_2d_array[a_list_of_indices,a_list_of_indices] = num </code></pre> <p>Example:</p> <pre><code>a_2d_array = np.zeros((5,5)) a_list_of_indices = [2, 3] </code></pre> <p>returns:</p> <pre><code>array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], ...
numpy
0
17,282
28,319,952
Pandas: convert list of string tuples to dataframe faster?
<p>From a text field I have the following <strong>input</strong> series, containing geographic coordinate tuples as a string:</p> <pre><code>import pandas as pd coords = pd.Series([ '(29.65271977700047, -82.33086252299967)', '(29.652914019000434, -82.42682220199964)', '(29.65301114200048, -82.36455186899968)...
<p>Another way could be to use the vectorised string method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.strings.StringMethods.extract.html" rel="nofollow"><code>extract</code></a>:</p> <pre><code>&gt;&gt;&gt; coords.str.extract(r'\((?P&lt;lat&gt;[\-\d\.]+),\s+(?P&lt;lon&gt;[\-\d\.]+)\)')...
python|string|list|pandas|dataframe
3
17,283
28,341,564
read table from keyboard in python
<p>I often use pandas to read table form file using</p> <pre><code>X = pandas.read_table('filepath',sep=' ') </code></pre> <p>that's when I input from file. But this time, I need to input a table from keyboard but don't know how?</p> <p>Thank you very much!</p>
<p>You might want to take a look at <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code></a> for Python 2 and <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>input</code></a> for Python 3</p>
python|pandas
0
17,284
73,286,034
keep match in pandas Dataframe column and remove the rest
<p>I have a list called <em>names</em></p> <pre><code>names = ['kramer hickok', 'carlos ortiz ', 'talor gooch', 'mikumu horikawa', 'yoshinori fujimoto'] </code></pre> <p>In addition, I have a <code>pandas.DataFrame</code> called <em>page</em>. The dataframe looks as follows:</p> <pre><code> name -- --------------...
<p>You can try <code>.str.extract</code></p> <pre class="lang-py prettyprint-override"><code>page['out'] = page['name'].str.extract(r'\b(' + '|'.join(names) + r')\b') </code></pre> <pre><code>print(page) name out 0 kramer hickok united states kramer hickok 1 ca...
python|pandas
1
17,285
73,260,870
Pandas datetime inconsistent format
<p>I hope someone can help me with the following: I'm trying to convert my data to daily averages using:</p> <pre><code>df['timestamp'] = pd.to_datetime(df['Datum WSM-09']) df_daily_avg = df.groupby(pd.Grouper(freq='D', key='timestamp')).mean() </code></pre> <p>df['Datum WSM-09'] looks like this:</p> <pre><code>0 ...
<p>In <a href="https://xkcd.com/1179" rel="nofollow noreferrer">https://xkcd.com/1179</a> Randall Munroe explains that &quot;you're doing it Wrong.&quot;</p> <p><a href="https://i.stack.imgur.com/xvoM9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvoM9.png" alt="iso8601" /></a></p> <p>Your source ...
python|pandas|dataframe|python-datetime
1
17,286
73,192,486
Count matching values between different columns of grouped rows
<p>This particular dataset consists of 3 households and its members. Columns 3 and 4 indicate if that member lives with their parents. Its value is the identity of mother and father in the Member column. For example member 3 lives with mother (2) and father (1).</p> <pre><code>Household Member Lives_with_m Lives_wit...
<p>One way to go, would be as follows:</p> <pre><code>import pandas as pd import numpy as np d = {'group': [1, 1, 1, 1, 1 ,2, 2, 2, 2, 3, 3, 3], 'member': [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3], 'lives_with_m': [np.nan, np.nan, 2, np.nan, 3, 3, np.nan, 2, 3, 3, np.nan, np.nan], 'lives_with_f': [np.nan, np.nan, 1, np.nan...
python|pandas|dataframe|group-by
1
17,287
30,977,494
Shuffling multiple HDF5 datasets in-place
<p>I have multiple HDF5 datasets saved in the same file, <code>my_file.h5</code>. These datasets have different dimensions, but the same number of observations in the first dimension:</p> <pre><code>features.shape = (1000000, 24, 7, 1) labels.shape = (1000000) info.shape = (1000000, 4) </code></pre> <p>It is importan...
<p>Shuffling arrays on disk will be time consuming, as it means that you have allocate new arrays in the hdf5 file, then copy all the rows in a different order. You can iterate over rows (or use chunks of rows), if you want to avoid loading all the data at once into memory with PyTables or h5py. </p> <p>An alternative...
python|numpy|hdf5|h5py
2
17,288
34,653,259
Set matplotlib plot axis to be the dataframe column name
<p>I have a dataframe like so:</p> <pre><code>data = DataFrame({'Sbet': [1,2,3,4,5], 'Length' : [2,4,6,8,10]) </code></pre> <p>Then I have a function that plots and fits this data</p> <pre><code>def lingregress(x,y): slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) r_sq = r_value ** 2 ...
<h2>Ordered columns</h2> <p>Build your dataframe with the columns in a defined order:</p> <pre><code>data = DataFrame.from_items([('Sbet', [1,2,3,4,5]), ('Length', [2,4,6,8,10])]) </code></pre> <p>Now you can use the first column as <code>x</code> and the second column as <code>y</code>:</p> <pre><code>def lingregr...
python|numpy|pandas|matplotlib
4
17,289
60,327,550
Group column by level and other column by other level pandas
<p>I have Weather data sampled Hourly and it contains [Temp, Humidity, Speed]</p> <pre><code>Timestamp Humidity Temp Speed 01/01/2019 00:00 57 23 2.222222222 01/01/2019 01:00 56 23 1.944444444 01/01/2019 02:00 55 23 1.944444444 01/01/2019 03:00 54 22 1.944444444 01/01/2019 04:00 55 22 ...
<p>If I understand correctly your intended output, you can concatenate the daily averages to the original dataframe (after changing column names).</p> <pre><code># Sample data. df = pd.DataFrame({ 'Timestamp': pd.date_range('2019-01-01 00:00', '2019-01-01 10:00', freq='H'), 'Humidity': [57, 56, 55, 54, 55, 56,...
python|pandas|dataframe|group-by
1
17,290
60,273,226
looking for an efficient way to add a column to a data frame using an apply function
<p>I am new to Pandas and looking for some inputs on if there is a better way to achieve the following:</p> <p>I have potentially millions of records of the form:</p> <pre><code>&gt;&gt;&gt; s=pd.DataFrame({"col A": pd.Categorical(["typeA", "typeB", "typeC"]), ... "col B": pd.Series(["a.b/c/d/e", "a:b:c:d:e", "a.b.c...
<p>You can do it this way.</p> <pre><code>s["col C"] = s["col B"].str.split('/|:').apply(lambda x: x[0]).apply(lambda x: ''.join([x.split('\.')[0][0] if (len(x)&gt;3) else x])) </code></pre> <p><strong>Output</strong></p> <pre><code> col A col B col C 0 typeA a.b/c/d/e a.b 1 typeB a:b:c:d:e a ...
pandas|apply
0
17,291
60,295,223
From Text file to a pandas dataframe
<p>I have a file which contains list of lists, its a text file, and it looks like that:</p> <pre><code> [[ ืฉื•ืžืจ ,ืงื•ืœื•ืจื‘ื™ ,ืงื™ื•ื•ื™ ,"ืชืคื•""ืข ืคื™ื ืง ืœื™ื™ื“ื™" ,ื’ื–ืจ ,ืขื’ื‘ื ื™ื” ,Unknown ] , [ ืžืืจื– ื ื™ื™ืฆ'ืจ ื•ืืœื™ ืฉื™ื‘ื•ืœืช ืฉื•ืขืœ ืขื ืฉื‘ื‘ื™ ืฉื•ืงื•ืœื“ ,ืคื™ื˜ื ืก ื—ื˜ื™ืคื™ ืคืจื™ื›ื™ื•ืช ื“ืงื•ืช ืงื™ื ืžื•ืŸ 60 ื’ืจื ,ืคืจื™ื›ื™ื•ืช ืžืฉื•ืœืฉื•ืช ืคืœืคืœ ,ืžืืจื– ื ื™ื™ืฆ'ืจ ื•ืืœื™ ืฉื™ื‘ื•ืœ...
<p>Read the file text and try below code - </p> <pre><code>import json import pandas as pd data = open('data.txt', 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","") remove_doulequotes = data.replace('""', '').replace('"', '') list_of_str = list(map(lambda x: '"{x}"'.format(x=...
python|pandas|dataframe|arraylist
1
17,292
60,122,391
ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations
<p>I recently upgraded my code from Python 3.3 to Python 3.7, and it's currently throwing an error which says:</p> <p><strong>ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations</strong></p> <p>Which is puzzling, because the code was working fine befo...
<p>This is not a Python issue, but something to do with pandas.</p> <p>As at version 0.25.0, the library pandas dropped support for the use of the units <code>"M"</code>(months) <code>"Y"</code> (year) in timedelta functions.</p> <p><a href="https://pandas-docs.github.io/pandas-docs-travis/whatsnew/v0.25.0.html#othe...
python|python-3.x|pandas
7
17,293
65,110,426
Get statistical info (describe()-like) for groups of years in column
<p>from a date(year)-like column I get this type of values:</p> <pre><code>+--------------------+------------+ | CUSTOMER_ID|yearSelected| +--------------------+------------+ |1 | 2010| |2 | 1992| |3 | 1996| |4 | ...
<p>From what I have understood from your question, you are struggling with how to group the individual years into 5-years ranges. Let's imagine that your dataset is called <code>dataDF</code>. Now, in order to group your individual years by groups of 5-years, you could use:</p> <pre><code>from pyspark.sql import functi...
pandas|apache-spark|pyspark|apache-spark-sql
1
17,294
65,298,267
Number of months between two dates while one date is given
<h2>Input df</h2> <pre><code>Date1 2019-01-23 2020-02-01 </code></pre> <p>note: The type of <code>Date1</code> is <code>datetime64[ns]</code>.</p> <h2>Goal</h2> <p>I want to calculate month diff between Date1 column and <code>'2019-01-01'</code>.</p> <h2>Try and Ref</h2> <p>I try the answers from th...
<p>Your solution should be changed by convert periods to integers and for second value is used one element list <code>['2019-01-01']</code>:</p> <pre><code>df['new'] = (df['Date1'].dt.to_period('M').astype(int) - pd.to_datetime(['2019-01-01']).to_period('M').astype(int)) print (df) Date1 new 0 201...
pandas
2
17,295
49,857,336
Slicing pandas raw dataframe (prior to re-organizing the data)
<p>This is my very first post but I'll do my best to make it relevant.</p> <p>I have a dataframe of stock prices freshly imported with the DataReader, from Morningstar. It looks like this :</p> <pre><code>print df.head() Close High Low Open Volume Symbol Symbol Date ...
<p>You need to be a bit careful when slice <code>DataFrames</code> with <code>[]</code></p> <p>When you provide only a single argument, it looks to slice the <code>DataFrame</code> by columns. When you write <code>df[-1]</code> you're going to get <code>KeyError: -1</code> because your df doesn't have any column label...
python|arrays|pandas|dataframe|object-slicing
2
17,296
50,068,661
How to substring the column name in python
<p>I have a column named 'comment1abc'</p> <p>I am writing a piece of code where I want to see that if a column contains certain string 'abc'</p> <pre><code>df['col1'].str.contains('abc') == True </code></pre> <p>Now, instead of hard coding 'abc', I want to use a substring like operation on column 'comment1abc' (to ...
<p>I think the answer would be simple like this:</p> <pre><code>for col in ['comment1abc', 'comment2abc']: x = col[8:11] df1[col][df1['code'].str.contains('x') == True] = '1' </code></pre> <p>Trying to use a column name within .str.contains() wasn't a good idea. Better use a string.</p>
python-3.x|pandas|dataframe
0
17,297
49,874,500
Getting words out of a numpy array of sentence strings
<p>I have a numpy array of sentences (strings) </p> <pre><code>arr = np.array(['It's the most wonderful time of the year.', 'With the kids jingle belling.', 'And everyone telling you be of good cheer.', 'It's the hap-happiest season of all.']) </code></pre> <p>(that I read...
<p>I think you can try something like this:</p> <pre><code>vocab = set() for x in arr: vocab.update(nltk.word_tokenize(x)) </code></pre> <p><code>set.update()</code> takes an iterable to add elements to existing set.</p> <p><strong>Update</strong>:</p> <p>Also, you can look at the working of <a href="http://sci...
python|string|numpy|nltk|tokenize
1
17,298
63,916,849
How to control GPU delegate fallback (C API)
<p>I'm writing a program which relies on tensorflow lite GPU v2 capabilities <a href="https://www.tensorflow.org/lite/performance/gpu_advanced" rel="nofollow noreferrer">link</a>. At initialization step, I'm trying to create the GPU v2 delegate. However, on several devices the required OpenCL library is not available a...
<p>Can you share what options you've specified with <code>optionsV2</code>? enabling <code>TFLITE_GPU_EXPERIMENTAL_FLAGS_CL_ONLY</code> experimental flag might be worth trying.</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/5874c1424db542293276cdaeb21f8de9febabd60/tensorflow/lite/delegates/gpu/delegate.h...
tensorflow|tensorflow2.0|tensorflow-lite
1
17,299
32,699,034
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>my inputs are, data input at top</p> <pre><code>Date Time Open High Low Close Volume 02/01/2015 14:30 79.52 79.73 79.52 79.71 10841 02/01/2015 14:31 79.6999 79.6999 79.61 79.67 1426 02/01/2015 14:32 79.69 79.7 79.69 79.7 800 02/01/2015 14:33 79.7 79.759 79...
<p>The error you're seeing is correct. dHaGreen0 is an array of bool values. When you ask "dHaGreen0 == True", you need to decide on one of the two following interpretations: </p> <p>Do you mean if <em>any</em> value is dHaGreen0 is True? If so, replace "dHaGreen0 == True" with "any(dHaGreen0) == True". </p> <p>Or do...
python|pandas
2