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
358,900
50,961,714
concat result of groupby pandas
<p>I am raising this question for learning a new method for myself.</p> <p>I have a dataframe like below,</p> <pre><code> ID Value 0 1 10 1 1 12 2 1 14 3 1 16 4 1 18 5 2 32 6 2 12 7 2 -8 8 2 -28 9 2 -48 10 2 -68 11 3 12 12 3 1 1...
<p>Yup, very possible and quite simple with <code>pd.concat</code>, in fact.</p> <pre><code>df = pd.concat({k : g.reset_index(drop=True) for k, g in df.groupby('ID')}, axis=1) df.columns = df.columns.droplevel(0) </code></pre> <p>Or, a minor variation in Dark's (now deleted) answer (which does not give you the opport...
python|pandas
2
358,901
51,111,792
Python: build object of Pandas dataframes
<p>I have a dataframe that has <code>dtype=object</code>, i.e. categorical variables, for which I'd like to have the counts of each level of. I'd like the result to be a pretty summary of all categorical variables. </p> <p>To achieve the aforementioned goals, I tried the following:</p> <p>(line 1) grab the names of a...
<p>I think simpliest is use loop:</p> <pre><code>df = pd.DataFrame({'A':list('abaaee'), 'B':list('abbccf'), 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aacbbb')}) print (df) A B C D E F 0 a ...
python|pandas
1
358,902
50,885,560
Pandas functions are not showing data for all the columns
<pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn as sk df = pd.read_csv('train.csv') print df.describe() </code></pre> <p>The above is a simple code to read a csv file and using the describe functions. The code is displaying the following output</p> <pre><code> ...
<p>Try setting the maximum number of columns to <code>None</code>, as below:</p> <pre><code>pd.set_option('display.max_columns', None) </code></pre>
python|pandas
0
358,903
51,013,184
Reconstruct numpy array using indexing
<p>I have a <code>numpy</code> array of <code>3*k</code> elements, where <code>k</code> is an integer. For instance, for <code>k=3</code> I have the array <code>A</code>. Below, <code>x</code>, <code>y</code>, and <code>z</code> are filled by drawing elements from <code>A</code> as shown in the following example:</p> ...
<p>You can do </p> <pre><code>np.array([x,y,z]).T.reshape(-1) </code></pre>
python|numpy|indexing
1
358,904
50,865,860
get total by groups for all rows, selected rows and percent of total pandas
<p>let us say I have a pandas dataframe called mydf. I.e.,</p> <pre><code>import pandas as pd mydf = pd.DataFrame({ 'type':['A','A','A', 'B','B','B', 'C'], 'state':['NY','CA','NY', 'NY','CA','CA', 'WY'], 'date':['2018-01-02','2018-01-04','2018-02-06', '2018-01-01','2018-01-24','2018-02-10'...
<p>First transform dates to months:</p> <pre><code>mydf["date"] = mydf["date"].dt.strftime("%Y%m") </code></pre> <p>Then use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>groupby.agg</code></a>:</p> <pre><code>def t...
python|pandas
2
358,905
50,746,579
Unique values in each column into a column with the number of it's occurrences, pandas
<p>I have a data-set on a claim-level record. </p> <p><img src="https://i.stack.imgur.com/Adl6n.png" alt="Data-frame Example"></p> <p>And I want to create another dataframe with the occurrences of each unique value in one week. </p> <p><img src="https://i.stack.imgur.com/P8pk7.png" alt="The new data-frame Example"> ...
<p>I think this is function you're looking for</p> <pre><code>df['column_name'].value_counts() </code></pre>
python|excel|pandas|aggregate|data-science
1
358,906
51,054,292
how to make only some of the values in the conv filter trainable in tensorflow
<p>So basically I want to train a cnn using tensorflow. To cover a large area in the image, I would ideally want a large filter. However, large filter means larger number of variables which could lead to more sever overfitting. So, I'm thinking about using a sampling filter which has a lot of constant zeros and the res...
<p>There might be a way to do this via some sort of masking operation, however I think your best bet would be to use dilated convolutions. These insert "holes" between the filter values which sounds like what you are looking for. The standard convolution ops in Tensorflow support this; <code>tf.nn.conv2d</code> has a <...
python|tensorflow
1
358,907
50,816,520
Filter Pandas series based on .sum() totals
<p>I have data that contains a row per user, then many columns populated with <code>1</code> or <code>0</code> based on their interaction with a particular product category.</p> <p>I am running some correlation analysis, and I'd like to remove the less significant categories to make my analysis easier to read, I used ...
<p>You want to filter the columns in the dataframe. You're on the right track with the <code>True</code> and <code>False</code> results, you just have to use this as a filter</p> <p>Assuming the data is in a dataframe called <code>df</code>, this will return only the columns you want:</p> <pre><code>totals = df.sum()...
python|pandas
2
358,908
51,104,911
Select hourly data based on days
<p>I have a time series <code>hourly_df</code>, containing some hourly data:</p> <pre><code>import pandas as pd import numpy as np hourly_index = pd.date_range(start='2018-01-01', end='2018-01-07', freq='H') hourly_data = np.random.rand(hourly_index.shape[0]) hourly_df = pd.DataFrame(hourly_data, index=hourly_index) ...
<ol> <li>save the <code>daily_index</code> as a <code>dataframe</code> </li> <li>merge on index using <code>hourly_df.merge(daily_index, how = 'inner', ...)</code></li> </ol>
python|pandas|filter|time-series|selection
-1
358,909
50,967,922
Is tensorflow running on GPU or CPU? (windows)
<p>Im trying since a while to install tensorflow-gpu and had a lot of trouble with CUDA. First the Visual Studio integration in the CUDA setup always gave me an error, but if i leave out the Visual studio integration during CUDA installation, the installation is working. Is the Studio integration mandatory for using te...
<p>Take a look at the last line in your log. </p> <p>'job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce GTX 1070, pci bus id: 0000:21:00.0, compute capability: 6.1'</p>
tensorflow
1
358,910
50,772,236
why i can't reshape (None, 375) to (25,15) by usint tf.reshape()
<p>There is a 25*15 image, and i want to identify what it is by using CNN.</p> <p>When training my CNN, I input a numpy named 'img' as datasets which shape is (200, 375):</p> <pre><code>sess.run(train, feed_dict={X: imgs, Y: labels} </code></pre> <p>This numpy contains 200 sample ,each of them have 375 features.</p>...
<p>You don't seem to reshape the dict variable you are feeding to the placeholder. You have to reshape your img variable as well into shape [-1, 25, 15, 1]</p>
python|numpy|tensorflow|deep-learning|conv-neural-network
0
358,911
51,090,945
Slicing my data frame is returning unexpected results
<p>I have 13 CSV files that contain billing information in an unusual format. Multiple readings are recorded every 30 minutes of the day. Five days are recorded beside each other (columns). Then the next five days are recorded under it. To make things more complicated, the day of the week, date, and billing day is show...
<p>Could be <code>pd.append</code> requiring matched row indices for numerical values.</p> <pre><code>import pandas as pd import numpy as np output = pd.DataFrame(np.random.rand(5,2), columns=['a','b']) # fake data output['c'] = list('abcdefghij') # add a column of non-numerical entries tmp = pd.DataFrame(columns=...
python|pandas|slice|nan
1
358,912
50,697,550
Deep learning with TENSORFLOW: Issues with saving and loading models
<p><strong>Contextualization</strong><br> I am building a model for image recognition with tensorfow. In fact, I am trying to save my model then restore it in order to make prediction. </p> <p><strong>Procedure</strong><br> I built a CNN with this structure</p> <pre><code>__________________________________________...
<p>[Issue solved]<br> I am calling the operation, that's why I am getting a none value. Instead, i need to call the tensor associated with that operation and feed it with input. So instead of doing this:</p> <pre><code>output=graph.get_operation_by_name("the_output_for_prediction") </code></pre> <p>I should have done...
python|tensorflow|machine-learning|keras|deep-learning
0
358,913
51,013,512
How to make a dataframe containing complex numbers from dataframes with real numbers in python?
<p>In python, I have a dataframe with 2 columns of real numbers. I want to make complex number and use those two columns as real and imaginary parts of my new set of data. I have tried <code>complex(df['wspd'].astype(float),df['wdir'].astype(float))</code> but I still get this error:</p> <pre><code>cannot convert the ...
<p>The function <code>complex</code> can handle only scalars. You can convert the second column to imaginary multiplying by <code>1j</code>, then sum:</p> <pre><code>df['wspd'] + df['wdir'] * 1j </code></pre> <p><strong>Sample</strong>:</p> <pre><code>df = pd.DataFrame({'wspd':[10.23,2.4,30.6], 'wdir':[2.3,7.8,4]}) ...
python|pandas|dataframe|complex-numbers
4
358,914
50,777,214
Python ctypes: how to pass row outputs from a C function into a pandas DataFrame?
<p>My question is how to parse tab-delimited output from a C function into a pandas DataFrame via ctypes:</p> <p>I am writing a Python wrapper in Python3.x around a C library using ctypes. The C library currently does database queries. The C function I am accessing <code>return_query()</code> returns tab-delimited row...
<p>I was going to make a comment but stackoverflow block me from that.</p> <p>1- The pandas object pass to c functions like PyObject *, so lib.return_query.argtypes = (<strong>c_types.c_void_p</strong>, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)</p> <p>2- If you are returning a tab-delimited rows that sounds ...
python|c|pandas|ctypes|python-c-api
1
358,915
50,965,616
Compute sum of pairwise sums of two array's columns
<p>I am looking for a way to avoid the nested loops in the following snippet, where <code>A</code> and <code>B</code> are two-dimensional arrays, each of shape <code>(m, n)</code> with <code>m</code>, <code>n</code> beeing arbitray positive integers:</p> <pre><code>import numpy as np m, n = 5, 2 a = randint(0, 10, (m...
<p><a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>einsum</code></a> needs to perform elementwise multiplication and then it does summing (optional). <strike>As such it might not be applicable/needed to solve our case.</strike> Read on!</p> <p><st...
python-3.x|numpy|multidimensional-array|numpy-ndarray|numpy-einsum
2
358,916
50,987,530
Tensorflow tf.trainable_variables(scope="") function
<p>I tried to simplify my tensorflow code with the following replacement:</p> <pre><code>f_vars = tf.trainable_variables("foo") </code></pre> <p>instead of the prior syntax:</p> <pre><code>t_vars = tf.trainable_variables() f_vars = [var for var in t_vars if var.name.startswith('foo')] </code></pre> <p>Before, i tri...
<p>The function call <code>tf.trainable_scope('foo')</code> requires the definition of a variable scope named 'foo'.</p> <p>For Example:</p> <pre><code>a = tf.Variable(1, name='a') with tf.variable_scope('foo'): b = tf.Variable(1, name='b') </code></pre> <p>To get the trainable variables you call:</p> <pre><code>...
python|tensorflow|jupyter-notebook
1
358,917
51,080,382
Running a second python script before continuing with the first
<p>I have been trying to figure out how to call a second script and get it to run before continuing on with my current one. </p> <p>I have my first script (file1.py) which defines a string called PATH_DATA. The second script (file2.py) imports PATH_DATA using:</p> <pre><code>from file1 import PATH_DATA </code></pre> ...
<p>If you want to continue using your current workflow, wrap anything with side effects in file1 like this, and define the variable you want to import outside of it.</p> <pre><code>PATH_DATA = "your/path" if __name__ == "__main__": print("do stuff with side effects") </code></pre> <p>The stuff under "if name equ...
python-3.x|pandas
1
358,918
50,672,875
Select Dataframe Columns based on Number of Nulls in Each
<p>I have seen similar questions but what I am facing is slightly different. I am trying to select a subset of the columns in my dataframe, based on whether the columns have less than 300 nulls.</p> <pre><code>df[df.columns[df.isnull().any()]].isnull().sum()&lt;300 </code></pre> <p>I have succeeded at creating this b...
<p>Let us using <code>thresh</code> from the doc <em>Require that many non-NA values.</em></p> <pre><code>df.dropna(axis = 1,thresh = len(df)-300) </code></pre>
python|pandas|dataframe
4
358,919
51,047,191
How to store result in for loop
<p>I am trying to create a report using python where for loop iterates for each location but once i run this code it only gives data for last location.How can i store result from this loop.</p> <pre><code>import inflect import pandas as pd add_sum_data=pd.read_excel("~Add_Summary_17062018.xlsx") location_code=add_...
<p>It's possible to use <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="nofollow noreferrer"><code>list</code></a> for that:</p> <pre><code>results = list() for GO in location_code: results.append(add_sum_data.loc[add_sum_data["location"]== GO]) </code></pre> <p><code>resul...
python|pandas
1
358,920
51,113,561
Is it possible to create an intelligent chatbot using tensorflow?
<p>I have done research on how to create a chatbot that is capable of machine learning. My first prototype was based on using dialogflow, however, there was certain issues that I faced that did not allow the chatbot to be capable of machine learning. (I.e Dialogflow doesn't allow the bot to store previous user's querie...
<p><a href="https://github.com/chiphuyen/stanford-tensorflow-tutorials/tree/master/assignments/chatbot" rel="nofollow noreferrer">A neural chatbot using sequence to sequence model with attentional decoder. </a></p> <p>This is a fully functional chatbot with Tensorflow.</p>
tensorflow|artificial-intelligence|chatbot|android-studio-2.3
1
358,921
50,823,521
How to include multiple predictors (int and string types) in sk-learn machine learning pipeline?
<p>Here is the data table:</p> <p><a href="https://i.stack.imgur.com/paa5L.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/paa5L.jpg" alt="enter image description here"></a></p> <p>I am following this ML <a href="https://towardsdatascience.com/multi-label-text-classification-with-scikit-learn-30714...
<p>What you want is to combine your tf-idf features with standard numerical/categorical features. You can achieve this by using a <code>FeatureUnion</code> transformer. Two very nice resources are here - <a href="http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html" rel="nofollow noreferr...
python-3.x|pandas|machine-learning|scikit-learn|pipeline
0
358,922
51,109,841
Difference between 2 dates which are objects in dataframe
<p>Dataframe has 2 dates which are of "object" datatype. StartDate and EndDate are in the mm/dd/yyyy format.</p> <pre><code> Name StartDate EndDate bou1 1/9/2017 1/10/2017 bou2 12/31/2016 1/10/2017 </code></pre> <p>Output:</p> <pre><code> Name St...
<p>you first need to convert to datetime for those columns and then subtract.</p> <p>try</p> <pre><code>df['startDate'] = pd.to_datetime(df['startDate']) df['EndDate'] = pd.to_datetime(df['EndDate']) df['difInDate'] = (abs(df['startDate'].sub(df['EndDate'], axis = 0))) / np.timedelta64(1, 'D') print(df['difInDate']) ...
pandas|date
1
358,923
50,974,234
Efficiently get permutation of 3 numpy arrays of differing sizes and types
<p>I have 3 numpy arrays of arbitrary size and type as indicated: </p> <blockquote> <p>time (datetime), lats (float64), longs (float64)</p> </blockquote> <pre><code>import numpy as np import pandas as pd time = np.asarray(['2018-05-01T00:30:00.000000000','2018-05-01T01:30:00.000000000','2018-05-01T02:30:00.000000...
<p>You can avoid a lot of your low-level numpy manipulations by using MultiIndex.from_product, and it has the advantage that you won't lose type information. This bypasses the very slow pd.to_datetime call. For example:</p> <pre><code>time = pd.date_range("2018-05-01", freq="30min", periods=24).values lats = np.lins...
python|arrays|pandas|numpy
1
358,924
51,016,230
How to change values in a column into binary?
<p>New to python and I am stuck at this. My CSV file contain this:</p> <pre><code>Sr,Gender 1,Male 2,Male 3,Female </code></pre> <p>Now I want to convert the Gender values into binary so the the file will look something like:</p> <pre><code>Sr,Gender 1,1 2,1 3,0 </code></pre> <p>So, I imported the CSV file as <code...
<p>Try this:</p> <pre><code>import pandas as pd file = open("your.csv", "r") data = pd.read_csv(file, sep = ",") gender = {'male': 1,'female': 0} data.Gender = [gender[item] for item in data.Gender] print(data) </code></pre> <p>Or</p> <pre><code>data.Gender[data.Gender == 'male'] = 1 data.Gender[data.Gender == '...
python|python-3.x|pandas
10
358,925
50,791,150
Running python code on CUDA
<p>While trying to run this code <a href="https://wltrimbl.github.io/2014-06-10-spelman/intermediate/python/04-multiprocessing.html" rel="nofollow noreferrer">https://wltrimbl.github.io/2014-06-10-spelman/intermediate/python/04-multiprocessing.html</a> on my GPU system which has 300 cores, i used the comment with tf.de...
<p>No, it won't run without a GPU optimized version of TensorFlow.</p> <p>Python multiprocesing is for CPU only. TensorFlow GPU is available (see here <a href="https://www.nvidia.com/en-us/data-center/gpu-accelerated-applications/tensorflow/" rel="nofollow noreferrer">https://www.nvidia.com/en-us/data-center/gpu-accel...
python-3.x|tensorflow|cuda
-2
358,926
51,015,217
groupby to get the average, using dynamic condition
<p>I have been searching about groupby using conditions and found many posts about that. This one for example: <a href="https://stackoverflow.com/questions/24250832/pandas-conditional-group-specific-computations">Pandas: conditional group-specific computations</a></p> <p>However, I couldn't find any where the conditio...
<p>It looks like you are just trying to get the <code>expanding().mean()</code> of the <code>ID</code>-grouped <code>Total</code> column, e.g.:</p> <pre><code>In []: df['x'] = df.groupby('ID')['Total'].expanding().mean().values df Out[]: ID Seq Total x 0 1 1 1 1.000000 1 1 2 2 1.500...
python|pandas|pandas-groupby
2
358,927
51,095,427
numba\jit doesn't allow the use of np argsort in nopython mode
<p>Receiving this error message:</p> <pre><code>Failed at nopython (nopython frontend) [1m[1m[1mInvalid usage of Function(&lt;function argsort at 0x0000000002A67840&gt;) with parameters (array(float64, 2d, C), axis=int64) * parameterized In definition 0: </code></pre> <p><br> While using this code</p> <pre><code...
<p><code>np.argsort</code> works in numba, but not the <code>axis</code> keyword. You could write your code <code>indexTable = np.argsort(finaltable, axis=0)</code> like this:</p> <pre><code>indexTable = np.empty_like(finaltable) for j in range(indexTable.shape[1]): indexTable[:, j] = np.argsort(finaltable[:, j]) ...
python-3.x|numpy|jit|numba|numpy-ndarray
7
358,928
50,980,088
String of decimal values to numeric without round off
<pre><code>0.03611642492570208 </code></pre> <p>such numbers are present as string in a CSV file, I wish to read them and perform mathematical operations, but when I read it it is read as String and when i convert it to numeric form it is rounded off.</p> <p>How can i convert it to numeric value without loosing preci...
<p>We have nothing to worry about, as this is rounded down to 6 digits only for the purposes of screen display. If we save the file, we'll see that the digits are still there.</p> <p>If we absolutely want to force pandas to read this column as number then we can do</p> <pre><code>import pandas as pd import numpy as n...
python|python-3.x|pandas
1
358,929
50,763,427
Apply on Dataframe returning all None
<p>I am trying to multiply the values of a column by 12 if that row/column isn't <code>None</code>. </p> <p>I have tried:</p> <pre><code>def length_inches(x): if x is not None: int(x)*12 df['LENGTH'] = df['LENGTH'].notnull().apply(length_inches) </code></pre> <p>And I have tried:</p> <pre><code>def len...
<p>You din't <code>return</code> anything from your functions (you <code>return</code>ed <em>None</em>):</p> <pre><code>def length_inches(x): if x is not None: return int(x)*12 else: return None df['LENGTH'].apply(length_inches) </code></pre>
python|pandas|apply|series
3
358,930
50,906,899
How get the last day of a month of a list of dates
<p>I find different solution for my problem, but i find the correct answer. SO now i have to ask:</p> <p>I want to find the last day of a month in a list... Every time i get the following Error: </p> <pre><code>AttributeError: 'RangeIndex' object has no attribute 'month' </code></pre> <p>I started like this:</p> <...
<p>Try this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a':['2017-01-01 06:00:00', '2017-01-01 07:00:00', '2017-02-02 08:00:00']}) df['a'] = pd.to_datetime(df['a']) print(df['a'].groupby(df.a.dt.to_period("M")).apply(lambda x: x.values.max())) </code></pre> ...
python|pandas|datetime
2
358,931
50,918,037
Error thrown with truth values pandas
<p>I'm using a dataframe within a function to alter that dataframe. I get thrown this error: </p> <blockquote> <p>The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </p> </blockquote> <pre><code>def hello(column): if data['State'] == 'CA': answer = column * ...
<p><code>data['State']</code> is a Series. Therefore, <code>data['State'] == 'CA'</code> is also a Series of boolean values. Do you want all of them to be true for the condition to be true? Or just some of them? In the former case, use <code>if (data['State'] == 'CA').all():</code>. In the latter case, <code>if (data['...
python|pandas
1
358,932
51,085,180
Find matching substrings in two lists
<p>I have two lists: A and B. List lengths are not the same and they both contain strings. What is the best way to match substrings in both the lists?</p> <pre><code>list_A = ['hello','there','you','are'] list_B = ['say_hellaa','therefore','foursquare'] </code></pre> <p>I would like a list of matching substrings call...
<p>This is one approach. Using a <code>list comprehension</code>. </p> <pre><code>list_A = ['hello','there','you','are'] list_B = ['hell','is','here'] jVal = "|".join(list_A) # hello|there|you|are print([i for i in list_B if i in jVal ]) </code></pre> <p><strong>Output:</strong></p> <pre><code>['hell', 'here...
python|string|pandas
3
358,933
20,770,748
Fast increment of many sub-spans of an array
<p>Is anyone familiar with a faster way to increment spans of indexes, as done by the following <code>patch(ar, ranges)</code>? In other words, it counts overlapping ranges, somewhat like a histogram. Maybe there is a vectorized method that already does something similar?</p> <pre><code>import numpy as np ar = np.zero...
<p>I think there is no such method in numpy, how every it's very easy to write a cython function to speedup the calculation:</p> <p>Create the random range first:</p> <pre><code>import numpy as np N = 1000 idx = np.random.randint(0, N, (100000, 2)).astype(np.uint64) idx.sort(axis=1) tidx = [tuple(x) for x in idx.tol...
python|performance|numpy|pandas|scipy
1
358,934
20,691,508
Why does pandas use (&, |) instead of the normal, pythonic (and, or)?
<p>I understand the <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#boolean-indexing" rel="nofollow noreferrer">pandas docs</a> explain that this is the convention, but I was wondering why?</p> <p>For example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(6,4)...
<p>Because <code>&amp;</code> and <code>|</code> are overridable (customizable). You can write the code that drives the operators for any <code>class</code>.</p> <p>The logic operators <code>and</code> and <code>or</code>, on the other hand, have standard behavior that cannot be modified.</p> <p>See <a href="http://d...
python|pandas
17
358,935
20,592,110
Pandas Re-indexing command
<p>*RE <a href="https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe">Add missing dates to pandas dataframe</a>, previously ask question</p> <pre><code>import pandas as pd import numpy as np idx = pd.date_range('09-01-2013', '09-30-2013') df = pd.DataFrame(data = [2,10,5,1], index =...
<p>Short answer: <code>df.index = pd.DatetimeIndex(df.index);</code> converts the string index of <code>df</code> to a DatetimeIndex.</p> <hr> <p>You have to make the distinction between different types of indexes. In </p> <pre><code>df = pd.DataFrame(data = [2,10,5,1], index = ["09-02-2013","09-03-2013","09-06-2013...
python|indexing|pandas|dataframe
2
358,936
20,787,736
Import Error with Numba: Wrong ELF class: ELFCLASS64
<p>I'm trying to use continuum analytics modules, specifically numpy and numba. When I try to import one of these modules I get </p> <pre><code>ImportError: /home/username/.local/lib/python2.7/site-packages/numpy/core/multiarray.so: wrong ELF class: ELFCLASS64 </code></pre> <p>From what I've been able to figur...
<p>With the help from Xapa in the comments, I realized that my modules were installed as the 64 bit version but that I had installed the 32 bit version of anaconda.</p>
python|numpy|elf|importerror|numba
1
358,937
20,637,259
Double linebreak fails with matplotlib and xkcd style
<p>The following python3 code does not work, because of the <strong>double</strong> linebreak in line 9:</p> <pre><code># -*- coding: utf-8 -*- from matplotlib import pyplot as plt import numpy as np plt.xkcd() fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.spines['right'].set_color('none') ax.spines['top'].set...
<p>Two hacks to fix this:</p> <ul> <li><p>replace the double newline with "\n.\n" (i.e. add a small dot)</p> <pre><code>plt.text(4, 400, '-&gt; 1 Pig ~ 150 kg\n.\n-&gt; Butching =&gt; 80 to 100 kg meat') </code></pre></li> <li><p>Split your multiline text into multiple calls to text (best result)</p> <pre><code>plt....
python|numpy|matplotlib|plot
1
358,938
20,624,428
How to save numpy array of Strings (with commas) to CSV?
<p>tl;dr ANSWER: Don't use numpy. Use <code>csv.writer</code> instead of <code>numpy.savetxt</code>.</p> <p>I'm new to Python and NumPy. It seems like it shouldn't be so difficult to save a 2D array of strings (that contain commas) to a CSV file, but I can't get it to work the way I want.</p> <p>Let's say I have an a...
<p>Adding <code>fmt="%s"</code> doesn't put quotes around each field—the quotes are part of the Python string literal for the string <code>%s</code>, and <code>%s</code> just says that any value should be formatted as a string. If you want to force quotes around everything, you need to have quotes <em>in the format str...
python|arrays|postgresql|csv|numpy
5
358,939
20,431,717
pandas dataframe groupby: sum/count of only positive numbers
<p>I have a dataframe ('frame') on which I want to aggregate by Country and Date:</p> <pre><code>aggregated=pd.DataFrame(frame.groupby(['Country','Date']).CaseID.count()) aggregated["Total duration"]=frame.groupby(['Country','Date']).Hours.sum() aggregated["Mean duration"]=frame.groupby(['Country','Date']).Hours.mea...
<p>Not as elegant as above, but deals differently some corner cases. <code>df</code> stands for <code>frame</code> from original question.</p> <pre><code>&gt;&gt;&gt; df.groupby(['Country','Date']).agg(lambda x: x[x&gt;0].mean()) Hours Country Date Japan 01 jan 3.0 USA 01 jan 3.5 &gt;&gt;&g...
python|pandas
9
358,940
33,457,880
Different intervals for Gauss-Legendre quadrature in numpy
<p>How can we use the NumPy package <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.legendre.leggauss.html" rel="noreferrer"><code>numpy.polynomial.legendre.leggauss</code></a> over intervals other than <code>[-1, 1]</code>?</p> <hr> <p>The following example compares <a href="http://docs...
<p>To <a href="https://en.wikipedia.org/wiki/Gaussian_quadrature#Change_of_interval" rel="noreferrer">change the interval</a>, translate the x values from [-1, 1] to [a, b] using, say,</p> <pre><code>t = 0.5*(x + 1)*(b - a) + a </code></pre> <p>and then scale the quadrature formula by (b - a)/2:</p> <pre><code>gauss...
python|numpy|scipy|numerical-integration
7
358,941
33,242,793
Masked Array: How to change symbol representing masked values
<p>I'd like to change the symbol representing masked values in printed masked array. What I get is:</p> <pre><code>&gt;&gt;&gt; print ma.array([[1, 0,0,1],[1,0,1,0]],mask=[[0,0,0,1],[1,1,0,1]]) [[1 0 0 --] [-- -- 1 --]] </code></pre> <p>I would prefer:</p> <pre><code>[[1 0 0 -] [- - 1 -]] </code></pre> <p>I've tr...
<p>You were close!</p> <pre><code>In [4]: np.ma.masked_print_option.set_display("-") In [5]: np.ma.array([[1, 0,0,1],[1,0,1,0]],mask=[[0,0,0,1],[1,1,0,1]]) Out[5]: masked_array(data = [[1 0 0 -] [- - 1 -]], mask = [[False False False True] [ True True False True]], fill_value = 999999) </co...
python|arrays|numpy
4
358,942
33,101,797
HDF5 file grows in size after overwriting the pandas dataframe
<p>I'm trying to overwrite the pandas dataframe in hdf5 file. Each time I do this, the file size grows up while the stored frame content is the same. If I use mode='w' I lost all other records. Is this a bug or am I missing something?</p> <pre><code>import pandas df = pandas.read_csv('1.csv') for i in range(100): st...
<p>Read the big warning at the bottom of this <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#delete-from-a-table" rel="noreferrer">section</a></p> <p>This is how HDF5 works.</p>
python|pandas|hdf5|pytables
6
358,943
33,086,724
Dataframe not getting ordered by column names
<p>I have a dictionary as below:</p> <pre><code>entity_dict= {u'bam': 1.0, u'ham': 1.0, u'jam': 0.82390874094431876, u'kam': 1.0, u'lam': 1.0, u'mam': 0.82390874094431876, u'pam': 1.0, u'ram': 1.0, u'sam': 0.82390874094431876, u'tam': 1.0} </code></pre> <p>I am trying to convert it into dataframe, I write th...
<p>Python dictionnary are not ordered. Try using the <a href="https://docs.python.org/3.4/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> structure from the python collections module. </p> <p>Here is the code:</p> <pre><code>import pandas as pd from collections import OrderedDict ent...
python|pandas
2
358,944
33,130,780
Vectorizing complex assignment logic in numpy
<p>I have some complex assignment logic in a simulation that I would like to optimize for performance. The current logic is implemented as a set of nested for loops over a variety of numpy arrays. I would like to vectorize this assignment logic but haven't been able to figure out if this is possible</p> <pre><code>imp...
<p>It seems there is a dependency between iterations within the innermost nested loop in the second part/group of the nested loops and that to me seemed like difficult if not impossible to vectorize. So, this post is basically a partial solution trying to vectorize instead the first group of two nested loops, which wer...
python|numpy|vectorization
0
358,945
33,399,981
Simplifying double einsum
<p>I'm trying to use <code>numpy.einsum</code> to simplify a loop I have in my code.</p> <p>Currently, my code looks something like this:</p> <pre><code>k = 100 m = 50 n = 10 A = np.arange(k*m*n).reshape(k, m, n) B = np.arange(m*m).reshape(m, m) T = np.zeros((n, n)) for ind in xrange(k): T += np.dot(A[ind,:,:]...
<p>On my PC your timing would be:</p> <pre><code>np.einsum('nij,njk-&gt;ik', np.einsum('nij,jk-&gt;nik', A.transpose(0,2,1), B), A) # 100 loops, best of 3: 4.55 ms per loop </code></pre> <p>You can achieve that with:</p> <pre><code>T2 = np.einsum('nij, il, kln -&gt;jk', A, B, A.T) # 10 loops, best of 3: 51.9 ms per...
python|arrays|numpy|vectorization|numpy-einsum
4
358,946
33,179,122
Seaborn: countplot() with frequencies
<p>I have a Pandas DataFrame with a column called "AXLES", which can take an integer value between 3-12. I am trying to use Seaborn's countplot() option to achieve the following plot:</p> <ol> <li>left y axis shows the frequencies of these values occurring in the data. The axis extends are [0%-100%], tick marks at eve...
<p>You can do this by making a <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.twinx" rel="noreferrer"><code>twinx</code></a> axes for the frequencies. You can switch the two y axes around so the frequencies stay on the left and the counts on the right, but without having to recalculate the counts...
python|pandas|matplotlib|data-visualization|seaborn
51
358,947
33,193,171
ImportError: cannot import name __check_build while importing TfidfVectorizer from sklearn
<p>I am using Python 2.7.10 and have installed scikit-0.15.2 using pip and i already have "numpy-1.1.10" and "scipy-0.16.0" installed and it works fine but when i try to import TfidfVectorizer from sklearn to construct a term document matrix with tf-idf values</p> <pre><code>from sklearn.feature_extraction.text import...
<p>For windows user try to install numpy+mkl package from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn</a> and after successful installation restart the python</p>
python|numpy|scipy|scikit-learn
4
358,948
9,119,139
python imshow grayscale static color values
<p>I understand using matplotlib.pyplot's imshow gives me a nice sketch that can be used to visualize matrices. My question is that when I want to visualize a matrix, the function adjusts the color density according to the values I am passing. for example:</p> <pre><code>#define a numpy matrix with values between 0 an...
<p>You can use the <code>vmin</code> and <code>vmax</code> keyword arguments of <code>imshow</code> as documented <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">here</a>. In particular, if you modify your <code>imshow</code> call to</p> <pre><code>plt.imshow(k, ...
python|numpy|matplotlib
2
358,949
9,071,446
'Tiling' a 2d array using numpy
<p>I'm tring to reduce the size of a 2D array by taking the majority of square chunks of the array and writing these to another array. The size of the square chunks is variable, let's say n values on a side. The data type of the array will be an integer. I'm currently using a loop in python to assign each chunk to a...
<p>Here is a function that will find the majority much more quickly, it's based on the implementation of numpy.unique.</p> <pre><code>def get_majority(a): a = a.ravel() a = np.sort(a) diff = np.empty(len(a)+1, 'bool') diff[0] = True diff[-1] = True diff[1:-1] = a[1:] != a[:-1] where = np.wh...
python|arrays|numpy
3
358,950
9,410,331
Multiple plots in a single matplotlib figure
<p>In a Python script, I have a set of 2D NumPy float arrays, let say n1, n2, n3 and n4. For each such array I have two integer values offset_i_x and offset_i_y (replace i by 1, 2, 3 and 4).</p> <p>Currently I'm able to create an image for one NumPy array using the following script:</p> <pre><code> def make_img_fro...
<p>You may want to consider the <a href="https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_axes" rel="nofollow noreferrer">add_axes</a> function of matplotlib.pyplot.</p> <p>Below is a dirty example, based on what you want to achieve. Note that I have chosen values of offsets so the example works...
python|numpy|matplotlib
4
358,951
9,205,104
3g coverage map - visualise lat, long, ping data
<p>Suppose I've been driving a set route with a 3g modem and GPS on my laptop, while my computer back at home records the ping delay. I've correlated ping with GPS lat/long, and now I'd like to visualise this data.</p> <p>I've got about 80,000 points of data per day, and I'd like to display several month's worth. I'm ...
<p>To simplify your question, you have two set of points, one for ping&lt;1000, one for ping>=1000. Since the count of points is very large, you can't plot them directly by scatter(). I created some sample data by:</p> <pre><code>longs = (np.random.rand(60, 1) + np.linspace(-np.pi, np.pi, 80000)).reshape(-1) lats = np...
python|numpy|matplotlib|scipy|interpolation
2
358,952
9,182,735
numpy 64bit support in PTVS and numpy System.Int64 casting
<p>I am trying to write some code with IronPython and numpy that calls a .NET assembly. Version info: numpy-2.0.0-1 scipy-1.0.0-2 IronPython 2.7.1</p> <p>I installed scipy and numpy according to the instructions given here:</p> <p><a href="http://www.enthought.com/repo/.iron/" rel="nofollow">http://www.enthought.com/...
<p>What I needed was:</p> <pre><code>listValues.tolist() instead of list(listValues) </code></pre> <p>the list() method will keep each element wrapped. This forum post had the answer I was looking for: <a href="http://www.python-forum.org/pythonforum/viewtopic.php?f=3&amp;t=2962&amp;p=12102" rel="nofollow">http://www...
.net|numpy|64-bit|ironpython|scipy
0
358,953
6,055,407
What is the proper way of using Python record arrays
<p>I would like to combine several lists or arrays into a single record array. In the following code I want to created a record array with two colums: &quot;a&quot; and &quot;b&quot;. The first column will contain letters from &quot;a&quot; to &quot;j&quot;, the second one will contain numbers from 0 to 9</p> <pre><cod...
<p>There are different ways to achieve your result. One simple option is</p> <pre><code>a = list('abcdefghij'); b = range(10) desc = {'names': ('a', 'b'), 'formats': ('S4', 'f4')} d = numpy.array(zip(a, b), dtype=desc) </code></pre>
python|numpy|record
3
358,954
6,256,249
Passing arguments to mpmath quad integration
<p>I'm integrating some pretty nasty functions, and scipy.integrate.quad is not handling the situation very well. I was planning to use mpmath.quad with tanh-sinh method, but I need to pass some arguments to the function that is being calculated, like this:</p> <pre><code>mpmath.quad(f,[0,mpmath.pi],method='tanh-sinh'...
<p>Use lambda:</p> <pre><code>import mpmath arg_1 = 1 arg_2 = 9 print mpmath.quad(lambda x: f(x, arg_1, arg_2), ...) </code></pre>
python|numpy|scipy|mpmath
3
358,955
66,539,694
pandas - Creating a database of pro cod league and I am having trouble accessing certain things
<p>I am trying to sum up all the match wins for each team, there are 12 different teams and each row has &quot;team&quot; and &quot;match win&quot;. I want to be able to sum up the match wins for each team but I am running into a ton of errors with the ways I have tried to do it. I tried to use iterrows and iteritems b...
<p>This?</p> <pre><code>df.groupby('team')['match win'].sum() </code></pre>
python|pandas|database|dataframe
1
358,956
66,444,473
In Numpy, how to use an array of items as the guide to determine the index of items in a second array?
<p>This is hard to describe with a good title. Here is what I want to do:</p> <p>I have a numpy array with unique items in it:</p> <pre><code>unique_arr = np.asarray([1, 4, 12, 5]) </code></pre> <p>...then I have a second array that is very long, and has many occurrences of the items in the first array:</p> <pre><code>...
<p>You can use <code>searchsorted</code>, but then you need to sort <code>unique_arr</code> first:</p> <pre><code>unique, idx = np.unique(unique_arr, return_index=True) a = np.searchsorted(unique, long_arr) long_idxs = idx[a] </code></pre> <p>Output:</p> <pre><code>array([2, 1, 1, 0, 2, 3, 3]) </code></pre> <p>Note t...
python|arrays|numpy
3
358,957
66,660,354
Understanding pos_weight argument in BCEWithLogitsLoss
<p>I am trying to understand how the <code>pos_weight</code> argument is being used in <code>BCEWithLogitsLoss</code> in order to be able to correctly define the <code>pos_weight</code> Tensor. The documentation only mentions: &quot;a weight of positive examples. Must be a vector with length equal to the number of clas...
<p>I didn't manage to find a definitive answer but from my experiments it seems I was right, i.e. negative sample weights are considered to be 1 and increasing the weights past 1 for positive samples makes them more important. Additionally, the LCM approach for figuring out the weights is actually both not good and not...
pytorch
1
358,958
66,463,776
Plot outliers using matplotlib and seaborn
<p>I have performed outlier detection on some entrance sensor data for a shopping mall. I want create one plot for each entrance and highlight the observations that are outliers (which are marked by True in the <em>outlier</em> column in the dataframe).</p> <p>Here is a small snippet of the data for two entrances and a...
<ul> <li><code>seaborn.lmplot</code> is a <code>Facetgrid</code>, which I think is more difficult to use, in this case.</li> </ul> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import seaborn as sns import pandas as pd for i, group in df.groupby(['entrance']): # plot all the valu...
python|pandas|matplotlib|seaborn
1
358,959
66,600,346
Operating on inner level multi-index columns
<p>Suppose I have a dataframe of multi-index columns,</p> <pre><code> TSLA MSFT Year revenues other_revenues expenses revenues other_revenues expenses 2019 851 10 110 200 13 213 2018 725 ...
<p>First create new DataFrame filled by <code>sum</code>s and <code>MultiIndex</code> to <code>df1</code>:</p> <pre><code>sub = ['revenues', 'other_revenues', 'expenses'] df1 = df.sum(level=0, axis=1) df1.columns = pd.MultiIndex.from_product([df1.columns, ['sum']]) </code></pre> <p>Then use <a href="http://pandas.pyd...
python|pandas|dataframe|multi-index
2
358,960
66,401,739
Subsetting pandas dataframe based on two columnar values
<p>I am trying to subset a large dataframe (5000+ rows and 15 columns) based on unique values from two columns (both are dtype = object). I want to <em>exclude</em> rows of data that meet the following criteria:</p> <p>A column called 'Record' equals &quot;MO&quot; <strong>AND</strong> a column called 'Year' equals &qu...
<p>I believe you're just missing some parenthesis.</p> <pre><code>df = df[(df['Record'] != &quot;MO&quot;) &amp; (df['Year'] != &quot;2017&quot;)] </code></pre> <p><strong>Edit:</strong> After some clarification:</p> <pre><code>df = df[~((df['Record']=='MO')&amp; (df['Year']=='2017')| (df['Year']=='...
sql|python-3.x|pandas|dataframe|subset
0
358,961
66,539,037
Pandas: populating column values with date and time string based on conditions
<p>I have a Pandas dataframe <code>df</code> that looks as follows:</p> <pre><code>created_time action_time 2021-03-05T07:18:12.281-0600 2021-03-05T08:32:19.153-0600 2021-03-04T15:34:23.373-0600 2021-03-04T15:37:32.360-0600 2021-03-01T04:57:47.848-0600 2021-03-01T08:37:39...
<p>First of all, I think your life would be easier if you convert the columns to datetime dtypes from the go. Then, its just a matter of running an apply op on the 'created_time' column.</p> <pre><code>df.created_time = pd.to_datetime(df.created_time) df.action_time = pd.to_datetime(df.action_time) df.elapsed_time = df...
python|pandas|numpy
1
358,962
66,551,891
How can I get the "index" from a look alike dict in Pandas?
<p>I have basically the same problem of this guy: <a href="https://stackoverflow.com/questions/66535128/how-can-i-get-a-string-column-that-look-like-a-dictionary-and-get-the-last-item">How can I get a string column that look like a dictionary and get the last item of it?</a>. However, instead of getting the last number...
<p>You could parse the strings with <code>literal_eval</code> and index <code>dict.keys</code> to obtain the last key:</p> <pre><code>from ast import literal_eval df['col_B'] = df.col_B.map(literal_eval) df.col_B.map(lambda x: list(x.keys())[-1]) 0 8 1 15 2 30 Name: col_B, dtype: object </code></pre> <p>Thou...
python|pandas|split
4
358,963
66,341,199
pandas loc search by part of a string not using regexp
<pre><code>import pandas as pd data = {'name': ['HelloWorld', 'ByeWorld'], 'physics': [22, 33], 'chemistry': [44, 55]} a = pd.DataFrame(data) b = a.loc[a['name'] == 'Hello'] print(b) </code></pre> <p>This code would not return any rows, but I would like to achieve it would return the first row, bec...
<p>You want</p> <p><code>b = a.loc[a['name'].str.contains('Hello')]</code></p> <p>also if your only looking at the start of a string you can use</p> <p><code>b = a.loc[a['name'].str.startswith('Hello')]</code></p> <p>Not</p> <p><code>b = a.loc[a['name'] == 'Hello']</code></p> <p>this line of code will only return True ...
python|pandas|pandas-loc
1
358,964
66,425,524
I just can't add rows with the same name to another dataset?
<p>what i want to do; combining the data of columns of the same name in the dataset with the column of the same name in dataset2.However, when I select join = 'inner', only a data set of columns with the same name is created. When I choose join = 'outer', all columns are added to the data set. But what I want to do is;...
<p>This is what I have tried based on your problem.</p> <p>Firstly, we have 2 data like below:</p> <p>list1.txt</p> <pre><code>Message Source,Customer Id,Social Medya,Subject Whatsapp,1047,İnstagram,Product information Whatsapp,6211,Facebook,Product İnformation </code></pre> <p>list2.txt</p> <p...
python|python-3.x|pandas|dataframe
2
358,965
66,436,120
Get every year last date values from data frame
<p>I have a Data frame like this(from 1971 to 2021).</p> <pre><code> date AUDUSD Close 42 2020-12-29 0.7608 41 2020-12-30 0.7676 40 2020-12-31 0.7709 39 2021-01-04 0.7664 38 2021-01-05 0.7767 37 2021-01-06 0.7799 36 2021-01-07 0.7...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><code>GroupBy.last</code></a> by years:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) df = df.groupby(df['date'].dt.year).last().reset_index(drop=True) print (df) ...
python|pandas|dataframe
4
358,966
66,587,482
Printing output of entire python script to text (and preferably CLI as well)
<p>Back again. The script I'm working on for lower limit of detection (LLoD) for laboratory assays ran fine yesterday, but now that I'm trying to direct the output to a .txt, I'm running into all kinds of errors. Have tried the <code>sys.stdout = open(&quot;test.txt&quot;, &quot;w&quot;)</code> with <code>sys.stdout.cl...
<p>Pipe the script to the <code>tee</code> command, which copies its input to a file and stdout.</p> <pre><code>python yourscript.py | tee filename.txt </code></pre>
python|python-3.x|pandas|numpy
1
358,967
66,418,483
When the input shape is incompatible, what will tensorflow actually do?
<p>Thanks for your reading.</p> <p>I train a LSTM predictor with fixed dimension <code>(None, 5, 2)</code>, and I test the predictor with smaller dimension <code>(None, 1, 2)</code>, and I got the warning:</p> <pre><code>WARNING:tensorflow:Model was constructed with shape (None, 5, 2) for input Tensor(&quot;input_1_1:0...
<p>Tensor computations are executed as a TensorFlow graph - see <a href="https://www.tensorflow.org/guide/intro_to_graphs" rel="nofollow noreferrer">https://www.tensorflow.org/guide/intro_to_graphs</a>. Normally graph execution is faster.</p> <p>The second dimension of LSTM is dynamic. In such cases keras have to rebui...
tensorflow|keras
0
358,968
66,548,258
numpy resize array width by zeros
<p>I'm a typical user of R, but in python I'm stuck.</p> <p>I have a lot of images saved as NumPy array I need to resize the pad of array/images to 4k resolution from different widths which oscillated between <code>1620</code> to <code>2800</code>, the height is constant: <code>2160</code>.</p> <p>I need to resize the ...
<p>I think you just need <code>hstack</code>, assuming you want half the width to go on either side:</p> <pre><code>def pad_with(vector, pad_width): temp = np.hstack((np.zeros((vector.shape[0], pad_width//2)), vector)) return np.hstack((temp, np.zeros((vector.shape[0], pad_width//2)))) arr2 = pad_with(arr,Final...
python|arrays|numpy
2
358,969
66,525,345
List of words matched with text column in dataframe
<p>I have 2 dataframes, first with the column of text data (more than 10k rows) and second with keywords (almost 100 list)</p> <p>DataFrame 1:</p> <pre><code> Text a white house cat plays in garden cat is a domestic species of small carnivorous mammal cat is walking in garden behind white house yellow banana ...
<p>This will work. It creates a list of the number of matches per list of keywords, then looks up the <code>ID</code> of the max values in that list.</p> <pre><code>import pandas as pd import ast df1 = pd.DataFrame(['a white house cat plays in garden', 'cat is a domestic species of small carnivorous mammal', 'cat is w...
python-3.x|pandas|dataframe|nlp|keyword-search
1
358,970
66,682,467
Inserting dataframe from Python into Snowflake Null issue
<p>Here is my code snippet -</p> <pre><code>import datetime from snowflake import connector from snowflake.connector.pandas_tools import write_pandas import pandas as pd import pickle class SnowflakeDataFetcher: def __init__(self): self.username = '***' self.password = '***' self.ctx_a = c...
<p>It seems the issue is about the space character in &quot;GTC Name&quot;. If you use GTC_Name (on both your DataFrame and table), it will work.</p>
python|pandas|snowflake-cloud-data-platform
1
358,971
66,474,061
Customising transfer learning model tensorflow-Keras
<p>I'm trying to add add conv layers to the transfer learning code mentioned below. But not sure how to proceed. I want to add <code>conv, max-pooling, 3x3 filter and stride 3 and activation mode ReLU</code> or <code>conv, max-pooling, 3x3 filter and stride 3 and activation mode LReLU</code> this layer in the below men...
<p>You can do it several ways, one of them is:</p> <pre><code>model = Sequential([ base_model, GlobalAveragePooling2D(name='avg_pool'), Dropout(0.4), Conv(...), # the layers you would like to add for the base model MaxPool(...), ... ]) model.compile(...) </code></pre>
python|tensorflow|keras|deep-learning|transfer-learning
1
358,972
66,443,114
having problem using ssd_inceptionv2 in colab ( error import tf_slim as slim ModuleNotFoundError: No module named 'tf_slim'
<p>I have a <code>ModuleNotFoundError</code> while using the <code>ssd_inceprionv2</code> within colab.</p> <pre class="lang-py prettyprint-override"><code>ModuleNotFoundError: No module named 'tf_slim' </code></pre> <p>Here is what I've so far:</p> <pre class="lang-py prettyprint-override"><code>%cd /content !git clon...
<p>It looks like <code>tf_slim</code> is not installed on Colab. Install <code>tf_slim</code> manually</p> <pre><code>!pip install tf_slim </code></pre>
python|tensorflow|using|solid-state-drive|coco
0
358,973
66,364,569
TensorBoard with Trax
<p>Anyone managed to log the loss with TensorBoard? I am using the trax ml library. I am getting this error <code>TypeError: 'SummaryWriter' object is not callable</code>.</p> <p>I am using the <code>SummaryWriter</code> from <code>jaxboard</code> and then adding it to <code>callbacks</code> within <code>training.Loop<...
<p>Worked when I removed the line with callbacks, summary_writer and instead added this on google colab:</p> <pre><code>%load_ext tensorboard %cd '/content/drive/MyDrive/path_to_the_notebook_/' # *train* folder is created by trax and holds the logs for the train run # to log the eval run change to --logdir eval %tensor...
tensorflow|tensorboard|trax
1
358,974
66,562,851
Convex Hull for all linestrings (ca. 1Million) in a Geodataframe
<p>I have a Geopandas dataframe with ca. 1million linestrings for which I want to calculate their convex hull with the corresponding tool (GeoSeries.convex_hull) from Geopandas. It results in a very long calculation time (ca. 4hours). Does someone has an idea how to do this faster?</p> <p>The Geodataframe looks like th...
<p>Make sure you have <code>pygeos</code> installed - <a href="https://geopandas.readthedocs.io/en/latest/getting_started/install.html#using-the-optional-pygeos-dependency" rel="nofollow noreferrer">https://geopandas.readthedocs.io/en/latest/getting_started/install.html#using-the-optional-pygeos-dependency</a>. That wi...
python|geopandas
0
358,975
66,696,638
Loop inside tf.function, impossible to compute gradients
<p>I'm trying to compute gradients with respect to some variables defined inside a loop in a tf.function, however I always get a None result. Here is a basic example replicating the problem:</p> <pre><code>@tf.function def problem(): test = tf.constant(1.0) with tf.GradientTape() as tape: for i in tf.rang...
<p>Using <code>.range()</code> might work but I think when you are writing a <code>tf</code> operation, having <code>np</code> calls might prevent the operation from running on the GPU. However the problem was raised before, check <a href="https://github.com/tensorflow/tensorflow/issues/41594" rel="nofollow noreferrer"...
tensorflow|tensorflow2.0
2
358,976
66,591,219
How do I divide a Numpy array along axis-0 into a list of equal sized numpy arrays?
<p>For example array</p> <pre><code>x = np.array([1, 2, 3, 4, 5, 6]) </code></pre> <p>Divided into 4 &quot;folds&quot; along axis-0 would be like a list</p> <pre><code>[array([1]), array([2]), array([3]), array([4])] </code></pre> <p>Clearly, for this to be achieved some data has to be removed. In this case the 5th and...
<p>It is straightforward, as you said, to trim the array before partitioning:</p> <pre><code>n = 4 x[:len(x)//n*n].reshape(n,-1) </code></pre> <p>Output:</p> <pre><code>array([[1], [2], [3], [4]]) </code></pre>
python|arrays|numpy
2
358,977
66,478,621
How could I reshape a DF of n columns into a unified DF with 3 columns where's n is always a multiple of 3?
<p>I'm currently trying to reshape my pandas DataFrame of <code>n</code> columns (which are always multiples of 3) into a combined DF with 3 columns. Atm I'm using a dirty method of splitting the original DF into individual DFs and them merging it all together. In code is looks something like this, where the numbers re...
<p>All credit to <a href="https://stackoverflow.com/users/4238408/quang-hoang">@Quang Hoang</a> for pointing me in the right direction. Thank you!</p> <p>managed to come up with the following solution.</p> <pre><code>df['column1'].str.split(',', expand=True) df = df.to_numpy() num = df.shape num = int((num[0]*num[1])/3...
python|pandas
0
358,978
66,441,339
Type errors when creating incremental date column in pandas
<p>I have data [read_data] as :</p> <pre><code>month 0 1 2 </code></pre> <p>I have a code to create column date as:</p> <pre><code>start = 201907 #This is YYYYMM start_dt = pd.to_datetime(start, format='%Y%m') read_data['date'] = read_data['month'].apply(lambda x: pd.DateOffset(months=x-1)).add(start_dt) </code></pre...
<p>You can do this:</p> <pre><code>In [349]: df['date'] = df.month.apply(lambda x: start_dt.date() + pd.DateOffset(months=x-1)) In [350]: df Out[350]: month date 0 0 2019-06-01 1 1 2019-07-01 2 2 2019-08-01 </code></pre>
python|pandas|datetime
1
358,979
66,522,960
Python 3: Groupby 3 DataFrame columns to check availability in a 4th column and add label 0 or 1 to 5th column
<p>My first time posting on StackoOverflow. Please be kind.</p> <p>I tried to find the exact solution for this problem but have failed to do so.</p> <p>What I am attempting to do is groupby <em><strong>ProductID, Class, Material</strong></em> columns to see what are the null and non-null values in a column and assign 0...
<p>Try this:</p> <pre><code>df['level'] = df[['ProductID', 'Class', 'Material']]\ .apply(lambda x: 0 if x.isna().sum() &gt; 0 else 1, axis=1) </code></pre>
python-3.x|pandas
0
358,980
66,588,418
groupby and then count by status
<p>I have a dataframe similar to this:</p> <pre><code>id name status output 123 John a 33.33% 232 Wang b 50% 324 Wang a 50% 424 Cici a 100% 553 John b 33.33% 653 John b 33.33% </code></pre> <p>I need to 1) groupby name 2) count the percentage where status ...
<p>Also try this without a lambda function:</p> <pre><code>df['output'] = df['status'].eq('a').groupby(df['name']).transform('mean') </code></pre>
python|pandas
2
358,981
66,730,152
Fastest way to check pandas dataframe and show other elements in the other columns at the same row
<p>If there is a list of words to check...</p> <pre><code>word_list = ['word1', 'word2', 'word3'] </code></pre> <p>and a data frame like</p> <pre><code>Word,Score_a,Score_b,Score_c word5,10,15,20 word6,40,60,80 word3,40,20,10 </code></pre> <p>What is the fastest way to find the corresponding scores for each word in the...
<p>To elaborate on comments above:</p> <pre><code>df.set_index('Word') #set Word column as index df.loc['word5', :] # access row </code></pre> <p>Output:</p> <pre><code> Score_a 10 Score_b 15 Score_c 20 </code></pre> <p>If you don't want to set Word as index, you can also use <code>.iloc</code>:</p> <pre><co...
python|pandas|dataframe
1
358,982
66,642,295
Percentage of values in a nested dictionary
<p>I would like to obtain the percentage of values in a nested dictionary of the form:</p> <pre><code>{'first': OrderedDict([('Jan', 2), ('Feb', 1)]), 'second': OrderedDict([('Jan', 3), ('Feb', 5)])} </code></pre> <p>The expected result should be like:</p> <pre><code>{'first': OrderedDict([('Jan', 40%), ('Feb', 16.6%)]...
<p>Ordered Dictionary in python follows some of the traits as a normal dictionary you can update the value using .update('k': 'v')</p> <p><code>for k, v in d.items(): v.update({'Jan': (v['Jan']/5)*100}) v.update({'Feb': (v['Feb']/6)*100}) </code></p>
python|pandas|numpy|dictionary
0
358,983
66,624,873
Getting negative (inverted) image in Pytorch
<p>I want to get the negative of an image straight from the data loader and feed it as a tensor. Are there any libraries that I can use? I have tried torch <code>transforms</code> and didn't find any.</p> <p><a href="https://i.stack.imgur.com/oxVNJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oxVN...
<p>Don't struggle a lot just use <code>255-image</code> it will give you a negative image...Try it</p>
python|image-processing|pytorch|torchvision
4
358,984
66,595,461
Select value from third column after matching condition of two columns
<pre><code>df = pd.DataFrame({ 'x': ['p1','p2','p3','p2','p3','p4',], 'y': ['p2','p3','p4','p3','p4','p5'], 'z': ['100','200','300','400','500','600'] }) </code></pre> <pre><code>Expected outcome: | x | y | z | a | | -------- | ---------|----------|----------| | p1 | p...
<p>Here are duplicated in <code>x</code> and <code>y</code>, so solution is more complicated:</p> <pre><code>df['g1'] = df.groupby('x').cumcount() df['g2'] = df.groupby('y').cumcount() mapped = df.set_index(df[['y','g2']].apply(tuple, 1))['z'] df['new'] = df[['x','g1']].apply(tuple, 1).map(mapped) print (df) x y...
python|pandas|conditional-statements
2
358,985
66,607,172
Selecting closest values by Euclidian distance from the mean from a numpy array
<p>I'm sure there's a straightforward answer to this, but I'm very much a Python novice and trawling stackoverflow is getting me tantalisingly close but falling at the final hurdle, so apologies. I have an array of one dimensional arrays (in reality composed of &gt;2000 arrays, each of ~800 values), but for representat...
<p>you can put the array in with the dist array, and sort based on the distance to the mean:</p> <pre><code>import numpy as np group = np.array([[0,1,3,4,5],[0,2,3,6,7],[0,4,3,2,5]]) group_mean = group.mean(axis = 0) distances = [[np.linalg.norm(x - group_mean),x] for x in group] distances.sort(key=lambda a : a[0]) ...
python|arrays|numpy|sorting|euclidean-distance
0
358,986
66,618,475
Counting unique mentions in Pandas dataframe column while grouped by multiple other columns
<p>For a school project I am attempting to determine the number of mentions specific words have in Reddit titles and comments. More specifically, stock ticker mentions. Currently the dataframe looks like this (where type could be a string of either title or comment):</p> <pre><code> ...
<p>Sound like a simple <code>groupby</code> should do it:</p> <pre><code>df.groupby(['mentions','subreddit','type']).count() </code></pre> <p>produces</p> <pre><code> body score id created mentions subreddit type {GE} stocks comment ...
python|pandas|dataframe
2
358,987
66,652,971
having problem with tfds.load() oxford data in jupyter notebook
<p>dataset, info = tfds.load('oxford_iiit_pet:3.<em>.</em>', with_info=True)</p> <p>ValueError: not enough values to unpack (expected 3, got 1)</p>
<p>Please check the name of the dataset.. The correct dataset name is <code>oxford_iiit_pet</code>.</p> <p>You can follow below code to import the dataset:</p> <pre><code>!pip install tensorflow_datasets import tensorflow as tf import tensorflow_dataset as tfds dataset = tfds.load('oxford_iiit_pet', split='train', sh...
tensorflow|jupyter-notebook|image-segmentation
0
358,988
66,725,269
Python Pandas - Lookup a variable column depending on another column's value
<p>I'm trying to use the value of one cell to find the value of a cell in another column. The first cell value ('source') dictates which column to lookup.</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['John', 'Andrew', 'Bob', 'Fred'], 'B': [ 'Fred', 'Simon', 'Andrew', 'Andrew'], 'source...
<p>Let us do <code>numpy</code> way since <code>lookup</code> will not longer work in the future version</p> <pre><code>df['new'] = df.values[df.index,df.columns.get_indexer(df.source)] df Out[339]: A B source new 0 John Fred A John 1 Andrew Simon B Simon 2 Bob Andrew ...
python|python-3.x|pandas|dataframe
7
358,989
66,415,367
Pandas advanced groupby and filter by date
<p>Create the output dataframe from input, how to filter for rows when target == 1 for the first time for each id, or in order words removing consecutive occurrence for each ids where target is 1 however keep all 0s in target before target = 1.</p> <p>Input</p> <pre><code>ID date target a1 2019-11-01 0 a1...
<p>You could keep only the rows in the groupby where the cumsum of target is &lt;= 1, then group again and make sure that a zero after a one is dropped using .ne</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID': ['a1', 'a1', 'a1', 'a1', 'a1', 'a2', 'a2', 'a2', 'a2'], 'date': ['2019-11-01', '2019-12-01', ...
python|pandas|dataframe|data-manipulation
2
358,990
66,370,099
Finding x for a bi-exponential curve fit?
<p>I am using python to batch process some data and plot it. I can fit it quite well using scipy.curve_fit, a bi-exponential function and some sensible initial guesses. Here is a code snippet:</p> <pre><code>def biexpfunc(x, a, b, c, d, e): y_new = [] for i in range(len(x)): y = (a * np.exp(b*x[i])) + (...
<p>Turns out, your question has nothing to do with curve fitting but is actually about root finding. <code>Scipy.optimize</code> has a <a href="https://docs.scipy.org/doc/scipy/reference/optimize.html#root-finding" rel="nofollow noreferrer">whole arsenal of functions</a> for this task. Choosing and configuring the righ...
python|numpy|interpolation|curve-fitting|scipy-optimize
0
358,991
66,466,249
Compare list of tuples against column in dataframe
<p>I'm learning pandas and I have a problem I can't solve.</p> <p>I have a dataframe with around 200k rows, being one of the columns an id. It looks like this:</p> <pre><code> call_id id utterance channel seq sentiment 0 uuid str str str float </code></pre> <p>I also have a ...
<p>You can make a dataframe out of list of tuples, like this: <code>df = pd.DataFrame(list_of_tuples, columns =['id', 'pattern_id'])</code> and then join it with the main dataframe, like this: <code>joined = main_df.merge(df, on='id', how='inner')</code>. The <code>pattern_id</code> is included in <code>joined</code> f...
python|pandas|dataframe|tuples
1
358,992
66,373,930
Reassigning slice of Pandas column after modifying values
<p>I need to perform the following operations in a loop: Select a slice of a pandas dataframe, then modify values of the slice (specifically, winsorize the data), then write the modified values back to the slice. What is the best practice for this? I have tried several ways, but the resulting column is usually full of ...
<p>I think pandas.DataFrame.combine_first or pandas.DataFrame.update should solve this issue. There are examples here <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html</a></p>
python|pandas
0
358,993
66,703,796
How to convert YOLOv4 Darknet Weights to Tensorflow format if you trained with custom anchors?
<p><strong>Main Question:</strong></p> <p><em>What changes should I do to the repo's source code to successfully convert my YOLOv4 darknet weight (with custom anchors) to Tensorflow format?</em></p> <p><strong>Background:</strong></p> <p>I used <a href="https://github.com/hunglc007/tensorflow-yolov4-tflite" rel="nofoll...
<p>I posted an answer to one of your <a href="https://stackoverflow.com/questions/66705733/how-to-convert-yolov4-csp-darknet-weight-to-tensorflow-format">earlier question</a> about YoloV4 (CSP) conversion. Did you try and see if that worked?</p> <p>If that worked, you can try to use your own config file and weights in ...
python|tensorflow|object-detection|tensor|yolo
2
358,994
66,726,138
read multiple nested json file with python pandas
<p>im beginner with python. i want to read this json file data1 like in the attachment. i have tried to read all columns in the file, but i can only read the 'data' nest. i don't know how to read all the columns in both &quot;data&quot; and &quot;quotes&quot; nest. can you please help me? Thankyou</p> <p><a href="https...
<p>Here you go. You should use <code>pd.json_normalize</code> and concatenate that with the dataframe made from <code>data['status']</code></p> <pre><code>df = pd.concat([pd.DataFrame(data['status'],index=[0]), pd.json_normalize(data, record_path=['data'])], axis=1) print(df) # &gt; timestamp ...
python|json|pandas
0
358,995
66,621,190
Feeding pyplot with different size arrays on x and y values
<p>I have two numpy arrays. One is for x axis entries, the other is for y axis as you can see in the code below</p> <pre><code> plt.figure(figsize=(10, 10)) plt.plot(range(0,len(TVals_R)),TVals,'bo',markersize=1,label='Dry Run') #I need x and y arrays in different size here plt.figure(figsize=(10, 10)) p...
<p>It looks like the best way of doing this is to ignore errors and so 2 plots with different x-axis ranges can be overlaid. And this solutions doesn't require fig, ax separation.</p> <pre><code> plt.figure(figsize=(10, 10)) try: plt.plot(range(0,len(TVals)),TVals,'o',markersize=1,label='Dry Run') ...
numpy|matplotlib|x-axis
0
358,996
66,450,026
python excel subtract with 2 worksheet
<p>Is it possible to create a python script to automatic which is subtract cell value with 2 worksheet in one excel file? I have checked some documents, and seem that use the method of <strong>pandas</strong> or <strong>openpyxl</strong> to do so. But I can't to do that. Do you have any suggestion to me? Many thanks.</...
<p>Do so in excel coule be way easier I think. There could be a smarter way to write this code.</p> <p><strong>[NOTE]</strong> I just do the subsctraction cell by cell, so if there's any mismatch like <strong>same row but different dept.id</strong> or <strong>same col but different item</strong> will make errors. If yo...
python|excel|pandas|openpyxl|subtraction
1
358,997
66,442,648
Loading pretrained BERT model issue
<p>I am using Huggingface to further train a BERT model. I saved the model using two methods: step (1) Saving the entire model using this code: <code>model.save_pretrained(save_location)</code>, and step (2) save the state_dict of the model using this code: <code>torch.save(model.state_dict(),'model.pth')</code> Howeve...
<p>I was going through the same thing. Turns out that this might be due to version indifference of both PyTorch and transformers. It has to be version-specific.</p> <p>I used the following without downloading the latest bert-base-uncased model :</p> <pre><code>pip install torch==1.5.1 pip install transformers==3.0.2 M...
python|pytorch|huggingface-transformers
0
358,998
66,607,523
merge similar values in a row on python pandas
<p>I want to merge row cell values that are similar for example I have: <a href="https://i.stack.imgur.com/S1lVe.png" rel="nofollow noreferrer">input</a></p> <p>Where there are multiple values that are similar and I would like to get <a href="https://i.stack.imgur.com/Rx5Ng.png" rel="nofollow noreferrer">Output</a></p>...
<p>In the end i gave each row a name and melted</p> <pre><code>pd.melt(df, id_vars=['name']) </code></pre> <p>#added duplicated the value column</p> <pre><code>df['d'] = df['value'] </code></pre> <p>#rounded the new column</p> <pre><code> df.round({'d':3,}) </code></pre> <p>#grouped the df</p> <pre><code> df.groupby(['...
python|pandas
0
358,999
66,561,620
How to group rows with duplicate value in 1 column and different value in another column without removing/dropping other duplicated rows?
<p>I have a dataframe with about 12K+ rows and 16 columns. Some of the rows are duplicates, which is fine, but I want to group those who are duplicated at 1 column, but different at this 1 specific column. For a simple example, refer below :</p> <pre><code>ID Plate_Number A SWD1314 A SKT5721 B ...
<p>An alternative with <code>drop_duplicates</code>:</p> <pre><code>df.drop_duplicates(subset=['ID', 'Plate_Number'], keep=False) </code></pre> <p>Output:</p> <pre><code> ID Plate_Number 0 A SWD1314 1 A SKT5721 </code></pre>
python|pandas|dataframe
2