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
18,200
64,493,983
How to perform multiple if condition in python
<p>I have this excel function where it says:</p> <pre><code>=IF(id =&quot;pre_stage&quot;;&quot;a&quot;;IF(id=&quot;static&quot;;&quot;b&quot;;&quot;c&quot;)) </code></pre> <p>I tried to implement this in my python script to create a new column.</p> <pre><code>df['type'] = df['id'].apply(lambda x: 'a' if x == 'pre_stag...
<p>Instead of using a lambda, you can pass in a function to <code>apply</code>:</p> <pre><code>def f(x): if x == 'pre_stage': return 'a' elif x == 'static': return 'b' return 'c' df['type'] = df['id'].apply(f) </code></pre> <p>You can also use a dictionary:</p> <pre><code>d = {'pre_stage': ...
python|pandas
2
18,201
64,542,426
How add date_range between two dates - Python Pandas
<p>I would like to treat the time overlap between some days. As you can see in my df, I have a begin on the date 2019-10-25 and the end at 2019-10-27:</p> <pre><code>begin end info 2019-10-25 10:39:58.352073 2019-10-25 10:40:06.266782 toto 2019-10-25 16:35:22.485574 20...
<p>Assuming <code>begin</code> and <code>end</code> are already of <code>Timestamp</code> type:</p> <pre><code># Generate a series of Timedeltas for each row n = ( (df['end'].dt.normalize() - df['begin'].dt.normalize()) .apply(lambda d: [pd.Timedelta(days=i) for i in range(d.days+1)]) .explode() ).r...
python|pandas|date-range
1
18,202
47,701,987
Pandas cannot plot timeseries imported from Excel
<p>This is my DataFrame obtained importing from an Excel .xls</p> <pre><code> 0 1 664 2017-12-07 19:08:54 1.1377 665 2017-12-07 19:10:31 1.1374 666 2017-12-07 19:12:17 1.1377 667 2017-12-07 19:13:28 1.1377 668 2017-12-07 19:15:25 1.1379 </code></pre> <p>I think is correclt...
<p>You probably want to plot column 1 agains column 0, i.e. the numbers against the dates? This would be done via </p> <pre><code>df.plot(x=0,y=1) </code></pre> <p>Your columns are unnamed. So you may also name them and reset the index to something useful (or as below, not so useful ;-))</p> <pre><code>df.columns = ...
excel|pandas|matplotlib
1
18,203
47,780,845
Solve over-determined system of linear equations
<p>I have a rather simple system of equations of the form:</p> <pre><code>1*A + 0*B + x2*C + y2*D = x1 0*A + 1*B + y2*C + x2*D = y1 </code></pre> <p>where the pairs <code>(x1,y1)</code> and <code>(x2,y2)</code> are known floats of length <code>N</code> (the system is over-determined), and I need to solve for the <cod...
<p>Keeping everything else fixed, changing <code>M1</code> and <code>M2</code> to</p> <pre><code>M1 = np.vstack([l1.T, l2.T]) M2 = np.concatenate([x1, y1]) </code></pre> <p>should do the job.</p>
python|numpy|linear-algebra|least-squares
2
18,204
49,054,969
Sum all columns in each column in csv using Pandas
<p>The program I have written generally has done what I've wanted it to do - for the most part. To add totals of each column. My dataframe uses the csv file format. My code is below:</p> <pre><code>import pandas as pd import matplotlib.pyplot class ColumnCalculation: """This houses the functions for all the column m...
<p>Your last column isn't being parsed as floats, but strings.</p> <p>To fix this, try casting to numeric before summing:</p> <pre><code>import locale locale.setlocale(locale.LC_NUMERIC, '') df['2017'] = df['2017'].map(locale.atoi) </code></pre> <p>Better still, try reading in the data as numeric data. For example...
python|pandas|dataframe
0
18,205
58,914,060
How do I obtain Kernel Density Estimator on a 2D image/array using sklearn?
<p>I am working with some images and would like to obtain their KDE using sklearn. At first I tried an example for a random data that apparently is working just fine:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity from sklearn.preprocessing import normaliz...
<p><strong>I think maybe you need to use <code>sklearn.preprocessing.StandardScaler</code> instead of <code>normalize</code>.</strong></p> <p>When I use your method on 5000 random points from an image (<code>uint8</code> hence the shift to 1 I guess), I get:</p> <p><a href="https://i.stack.imgur.com/njsyE.png" rel="n...
python|numpy|scikit-learn
1
18,206
58,701,885
How to iterate over a dataframe with publish date column to make a daily mapping table
<p>I'm using Python 3.7 for this task. I have a dataframe that stores blog ids, blog names and publish dates. I need to convert that to a new dataframe that will map every single day and URL to what the ID was. I'd need to this to run through the previous day's date (20191103 as of writing this). Assumptions include t...
<p>A perfect job for <code>merge_asof</code>:</p> <pre><code># Your Publish Date column is string, Need to convert it to Timestamp df['Publish Date'] = pd.to_datetime(df['Publish Date'], format='%Y%m%d') def summarize(g): # A date range that covers from the first Publish Date to the current day d = pd.date_ra...
python-3.x|pandas|date|dataframe
1
18,207
70,161,033
How do I split a column based on strings, clean up data, then do calculations on it?
<p>Still learning my way around Python and trying to figure out how to process some data. I've got a dataframe with 1 column that I need to extract into 3 columns of data. I don't need to keep the original column.</p> <p>Here's the data - &quot;Given Data&quot; is the original column and I want to extract out columns...
<p>Try with <code>str.strip</code> and <code>str.split</code>:</p> <pre><code>df[[&quot;A&quot;, &quot;B&quot;]] = df[&quot;Given Data&quot;].str.strip(&quot;()&quot;).str.split(&quot; / &quot;, expand=True).astype(int) df[&quot;C&quot;] = df[&quot;A&quot;].div(df[&quot;B&quot;]) &gt;&gt;&gt; df Given Data A ...
python|pandas|dataframe
2
18,208
70,190,758
How do I repeat a set of values across all entries in a dataframe?
<p>I apologize if this question has been asked but I don't know how to properly ask it and thus find the answer.</p> <p>I have a dataframe:</p> <p>val1 val2<br /> val1 val3<br /> val2 val1<br /> val2 val3</p> <p>I want to append a set of years to every entry:</p> <p>val1 val2 1990<br /> val1 val2 1991<br /> val1 val2 1...
<p>You can use a <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge.html" rel="nofollow noreferrer">cross join in Pandas.</a></p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame({ 'col1': ['val1', 'val1', 'val2', 'val2'], 'col2': ['val2', 'val3', 'val1', 'val3'] }) &gt;&gt;&gt; df1 col1 col2 0 ...
python|pandas|dataframe|group-by
2
18,209
70,150,051
Pandas minus same row value with next row value
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Time</th> <th>Agg</th> <th>Value</th> <th>Needed Value</th> </tr> </thead> <tbody> <tr> <td>10:55:00</td> <td>178.0</td> <td>322.0</td> <td>322</td> </tr> <tr> <td>11:00:00</td> <td>354.0</td> <td>-</td> <td>(322-354)-32</td> </tr> <tr> <td>11:05:...
<p>For improve performance is used <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/enhancingperf.html#using-numba" rel="nofollow noreferrer"><strong>numba</strong></a>:</p> <pre><code>from numba import jit @jit(nopython=True) def f(a, b): d = np.empty(a.shape) d[0] = b[0] for i in range(1...
pandas|dataframe
1
18,210
56,237,415
removing encoding "UTF8": 0x00 chars from pandas dataframe for psycopg2 cursor
<p>I am trying to insert rows into a Postgresq database using the following code I grabbed somewhere in SO:</p> <pre><code>def to_sql(engine, df, table, if_exists='fail', sep='\t', encoding='utf8', schema='public', dtypes_sql=None, verbose=False): # Create Table ## istruzioni diverse se le colonne hanno dt...
<p>Removing the null in pandas data frame can be performed as follows:</p> <pre><code>import re re_null = re.compile(pattern='\x00') input_file_df.replace(regex=re_null,value=' ', inplace=True) </code></pre> <p>this would avoid the 0x00 issue</p>
pandas|postgresql|encoding|utf-8|sqlalchemy
1
18,211
65,009,980
Pandas Dataframe calculate Time Difference for each Day
<p>so i have this dataframe:</p> <pre><code>import pandas as pd d = {'Time': ['01.07.2019, 06:21:33', '01.07.2019, 06:32:01', '01.07.2019, 06:57:33', '01.07.2019, 07:24:33', '01.07.2019, 08:26:25', '01.07.2019, 09:12:44', '01.07.2019, 10:02:01', '01.07.2019, 12:22:22', '02.07.2019, 13:26:25'...
<p>The value for the day part is conditionally applied whether zero or more than zero in order to get rid of the values having days with more than zero such as</p> <pre><code>df[&quot;dff&quot;] = df.groupby((df[&quot;Action&quot;] == &quot;Closed&quot;).cumsum())[&quot;Time&quot;].diff().shift(-1) df.loc[ df[&quot;df...
python|pandas|dataframe
1
18,212
64,979,100
How to create duplicate Dates in Python
<p>I have a data frame named df and it has a column DATES, I want to fill it with 1million dates(doesn't need to be unique) in day.month.year format. Ex: 01.01.2020</p>
<p>Replace <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.now" rel="nofollow noreferrer"><code>dt.now()</code></a> with whatever date you want:</p> <pre><code>df[&quot;DATES&quot;] = np.repeat(dt.now().strftime(&quot;%m.%d.%Y&quot;),1000000) </code></pre>
python-3.x|pandas|dataframe|date
0
18,213
40,015,666
Grouping a pandas dataframe in a suitable format for creating a chart
<p>Suppose I have the following pandas dataframe:</p> <pre><code>In [1]: df Out[1]: sentiment date 0 pos 2016-10-08 1 neu 2016-10-08 2 pos 2016-10-09 3 neg 2016-10-09 4 neg 2016-10-09 </code></pre> <p>I can indeed create a dataframe that makes summary statistics about the s...
<p>You need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a>:</p> <pre><code>gf = df.groupby(["date", "sentiment"]).size().unstack(fill_value=0).reset_index() #remove column name 'sentiment' gf.columns.name = None print (gf) ...
python|pandas|dataframe|pivot-table|reshape
2
18,214
40,193,750
Datatypes mismatch when calculating entropy with softmax
<p>I am using below code to calculate entropy for the predicted labels and actual labels. Data is obtained from CIFAR-10 dataset.</p> <p>I used astype(np.float32) to ocnvert the source data into ndarrays and thereafter used dtype as float32 in tf.constant(). The error message</p> <blockquote> <p>TypeError: DataType...
<p><code>tf.nn.sparse_softmax_cross_entropy_with_logits</code> accepts sparse labels of integer type. To use one-hot float labels, consider using <code>tf.nn.softmax_cross_entropy_with_logits</code> instead.</p>
python|tensorflow|softmax
0
18,215
44,126,221
Pandas: How can I make data frame with double columns?
<p>This is how data frame looks (for <code>APPL</code>): <a href="https://i.stack.imgur.com/ybr86.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybr86.png" alt="enter image description here"></a></p> <p>And there is another data frame of <code>DELL</code>, having same format with above.</p> <p>Wha...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> if need all columns:</p> <pre><code>df = pd.concat([df1, df2], axis=1, keys=('AAPL','DELL')) </code></pre> <p>EDIT:</p> <p>If need filter only <code>Open</code> and <code>C...
python|pandas
2
18,216
69,370,793
How to find the count of spaces in a dataframe using python
<p>I have an excel file which has few columns, I need to find no.of spaces in the column values.</p> <p>Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Key</th> </tr> </thead> <tbody> <tr> <td>Identifier</td> </tr> <tr> <td>Identifier Number</td> </tr> <tr> <td>user identifier numb...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>Series.str.count</code></a> with <code>\s+</code> for match spaces:</p> <pre><code>df['count'] =df['Key'].str.count('\s+') print (df) Key count 0 Id...
python|pandas
2
18,217
40,925,136
Store grouped data with variable
<p>I have a general question about pandas. I have a DataFrame named <code>d</code> with a lot of info on parks. All unique park names are stored in an array called <code>parks</code>. There's another column with a location ID and I want to iterate through the parks array and print unique location ID counts associate...
<p>When you subset the first time, you're not assigning <code>d[d['Park'] == 'ARKO']</code> to anything. So you haven't actually changed the data. You only viewed that section of the data.</p> <p>When you assign <code>x = d[d['Park']=='AKRO']</code>, <code>x</code> is now only that section that you viewed with the fir...
python|pandas|for-loop|grouping
1
18,218
40,966,975
Pandas Series: string date to epoch unix seconds
<p>I have a Pandas Dataframe where one column is in a string date format as below</p> <pre><code>0 time 1 September 20 2016 2 September 20 2016 3 September 19 2016 4 September 16 2016 </code></pre> <p>What would be a succinct way for replacing time to be in epoch unix seconds? </p>
<p>You can modify the values of a column using the Series' <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html#pandas.Series.apply" rel="nofollow noreferrer"><code>apply</code></a> method by giving it a function containing the actions you want to perform on <em>each</em> of the value...
python|pandas
4
18,219
53,845,873
Tensorflow:How to add regularization in the model
<p>I want to add regularization into my optimizer like this:</p> <pre><code>tf.train.AdadeltaOptimizer(learning_rate=1).minimize(loss) </code></pre> <p>But I don't know how to design the function "loss" into the code below</p> <p>The website I saw is: <a href="https://blog.csdn.net/marsjhao/article/details/72630147"...
<p>Regularization are added to loss function. Your Optimizer <code>AdadeltaOptimizer</code> do not support regularization parameter. If you want to add regularization to your optimizer you should use <code>tf.train.ProximalAdagradOptimizer</code> as it has <code>l2_regularization_strength</code> and <code>l1_regulariza...
python|tensorflow|deep-learning
3
18,220
53,906,313
Sklearn cross_val_score with multi input KerasClassifier
<p>The goal is to perform cross validation on a Keras model with multiple inputs. This works fine with a normal sequential model with only one input. However, when using the functional api and extending to two inputs sklearns <code>cross_val_score</code> does not seem to work as expected.</p> <pre><code>def create_mod...
<p>You could run your own cross validation implementation. Example CV implementation could look like this:</p> <pre><code>import numpy as np from sklearn.model_selection import StratifiedKFold input_1 = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] input_2 = [[11], [12], [13], [14], [15], [16], [17], [18], [19],...
tensorflow|scikit-learn|keras
5
18,221
66,113,315
How to process data returned by Paramiko from remote shell command in memory using Pandas?
<p>I have a problem when exporting data from hive via Paramiko. Usually I do the following as a substitute for the bad lines error but on the same server</p> <pre><code>with open('xxx.tsv', 'r') as temp_f: # get No of columns in each line col_count = [ len(l.split(&quot;,&quot;)) for l in temp_f.readlines() ] #...
<p>The <code>StringIO</code> is already a <em>file-like</em> object. So you use it instead of the <code>temp_f</code> <em>file</em>:</p> <pre><code>with StringIO(edge_out_str_n) as edge_out_csv: # get No of columns in each line col_count = [ len(l.split(&quot;,&quot;)) for l in edge_out_csv.readlines() ] ##...
python|pandas|ssh|hive|paramiko
1
18,222
52,465,856
Python: merging channels in opencv and manually
<pre><code>def frame_processing(frame): out_frame = np.zeros((frame.shape[0],frame.shape[1],4),dtype = np.uint8) b,g,r = cv2.split(frame) alpha = np.zeros_like(b , dtype=np.uint8) print(out_frame.shape) print(b.shape);print(g.shape);print(r.shape);print(alpha.shape) for i in range(frame.shape[0]): for j in range(fr...
<p>Use <code>cv2.inRange</code> to find the mask, then merge them with <code>np.dstack</code>:</p> <pre><code>#!/use/bin/python3 # 2018/09/24 11:51:31 (CST) import cv2 import numpy as np #frame = ... mask = cv2.inRange(frame, (225,225,225), (255,255,255)) #dst = np.dstack((frame, 255-mask)) dst = np.dstack((frame, m...
python|numpy|opencv|array-broadcasting|numpy-ndarray
4
18,223
52,846,115
How to group daily time series data into smaller dataframes of weeks
<p>I have a dataframe that looks like this:</p> <pre><code> open high low close weekday time 2011-11-29 2.55 2.98 2.54 2.75 1 2011-11-30 2.75 3.09 2.73 2.97 2 2011-12-01 2.97 3.14 2.93 3.06 3 2011-12-02 3.06 3.14 3.03 3.12 4...
<p>filter before <code>drop_duplicates</code></p> <pre><code>df[df.weekday.isin([4,5,6,0])].drop_duplicates('weekday') Out[10]: open high low close weekday 2011-12-02 3.06 3.14 3.03 3.12 4 2011-12-03 3.12 3.13 2.75 2.79 5 2011-12-04 2.79 2.90 2.61 2.83 6 2011-12-05...
python|pandas
0
18,224
52,517,206
how to evaluate using tf.estimator.train_and_evaluate?
<p>I am using tf.estimator.train_and_evaluate(...) to do distributed training, take the first worker as chief, and second worker to do evaluation. the cluster is as following with 8 workers and 2 ps.</p> <pre><code>{ "cluster": { "ps": ["100.77.4.147:61415", "100.77.14.144:52383"], "chief": ["100.7...
<p>update:</p> <p>finally, it works. evaluator should not included in workers list. FYI.</p>
tensorflow|tensorflow-estimator
0
18,225
52,726,340
numpy: creating recarray fast with different column types
<p>I am trying to create a recarray from a series of numpy arrays with column names and mixed variable types. </p> <p>The following works but is slow:</p> <pre><code> import numpy as np a = np.array([1,2,3,4], dtype=np.int) b = np.array([6,6,6,6], dtype=np.int) c = np.array([-1.,-2.-1.,-1.], dtype=np.f...
<p><code>np.rec.fromarrays</code> is probably what you want:</p> <pre><code>&gt;&gt;&gt; np.rec.fromarrays([a, b, c], names=['a', 'b', 'c']) rec.array([(1, 6, -1.), (2, 6, -2.), (3, 6, -1.), (4, 6, -1.)], dtype=[('a', '&lt;i8'), ('b', '&lt;i8'), ('c', '&lt;f4')]) </code></pre>
python|numpy|recarray
1
18,226
52,451,132
How to remove duplicate value among columns irresppective of their order in python or pyspark?
<p>I have a dataframe in which i have duplicate value among columns. I want to remove only those values from the dataframe that are common for all the columns</p> <p>INPUT DATAFRAME:</p> <pre><code>+----------+-----------+------------+ | A | B | C | +----------+-----------+------------+ | Foo...
<p>The concept of a "dataframe" refers to a data structure that takes the form of an array in which there is some relationship across columns, and another relationship across rows. Here, there doesn't seem to be a relationship across a row: "Food", "Party", and "Driving", for instance, aren't connected to each other. S...
python|pandas|pyspark
0
18,227
46,601,814
How separate assignment of a value to a Variable and computational graph in TensorFlow?
<p>I have the following simple Theano code which I want to reproduce in TensorFlow:</p> <pre><code>import theano as th import theano.tensor as T import numpy as np x = T.vector() c = th.shared(np.array([1.0, 2.0])) y1 = x + c c.set_value(np.array([10.0, 20.0])) y2 = x + c c.set_value(np.array([100.0, 200.0])) print '...
<p>You just shouldn't overwrite the Python variable <em>c</em> with the assign operation. You can assign a new value to <em>c</em> just by running the corresponding <em>assign</em> operation like this:</p> <pre><code>s = tf.Session() x = tf.placeholder(tf.float32) c = tf.Variable([1.0, 2.0]) y1 = x + c s.run(tf.assign...
python|tensorflow|theano
1
18,228
58,397,051
Read multiple .csv files and extract (in new .csv files) all rows corresponding to non-empty cells across a specific column
<p>I have multiple .csv files (about 250). Each of them have exactly the same columns. All of them, have enough empty cells across many of the columns. I am interested to extract only all rows corresponding to non-empty cells of a specific column (named 20201-2.0). I believe it will work better with <strong>pandas</str...
<pre><code>df = pd.read_csv('myfile.csv').dropna(subset='20201-2.0') </code></pre>
python|pandas|csv
2
18,229
69,148,822
how to replace nan value with lambda layer?
<p>I want to replace nan values with a lambda layer in Tensorflow. I write the below code and it replaces nan data with 0 but when I pass it to next layer they are all nan!!! can anyone say why this happened and how to fix it?</p> <pre><code># split into train test sets X_train, X_test, y_train, y_test = train_test_spl...
<p>I answer my question in case somebody has the same problem. this leakage is because I pass x_train for both x and y in model.fit, which is correct for autoencoder models but in this case, I remove nan data of x_train in x position but do not remove nan data of x_tarin in y position. to fix this you should pass data ...
python|tensorflow|lambda|nan
0
18,230
69,240,972
How to save the rows in different columns based on the conditions?
<p>I want to select rows based on the index like 0 to 30 index &amp; save them to a data frame and again pick the index from 30 to 60 &amp; save them into the same data frame but different column and I want to do it multiple times. How can I do that?</p> <p>I don't know how to do it, please help me out.</p>
<p>If df is is your initial DataFrame:</p> <pre><code>df1 = pd.DataFrame(index = df.index) df1['&lt;=30'] = df[df.index &lt;= 30]['your_col_of_interest'] df1['&gt;30 &amp; &lt;60'] = df[(df.index &gt; 30) &amp; (df.index &lt;= 60)]['your_col_of_interest'] </code></pre>
python-3.x|pandas|dataframe|data-analysis|data-science-experience
0
18,231
44,743,512
Finding the sum of each column and combined them to find the top 3 highest value
<pre><code>a = pd.DataFrame(df.groupby('actor_1_name')['gross'].sum()) b = pd.DataFrame(df.groupby('actor_2_name')['gross'].sum()) c = pd.DataFrame(df.groupby('actor_3_name')['gross'].sum()) x = [a,b,c] y = pd.concat(x) p =['actor_1_name','actor_2_name','actor_3_name','gross'] df.loc[y.nlargest(3).index,p] </code></p...
<p>I believe you need:</p> <pre><code>df = pd.DataFrame({'actor_1_name':['a','a','a','b','b','c','c','d','d','e'], 'actor_2_name':['d','d','a','c','b','c','c','d','e','e'], 'actor_3_name':['c','c','a','b','b','b','c','e','e','e'], 'gross':[1,2,3,4,5,6,7,8,9,10]}...
pandas
0
18,232
61,177,042
A script to correct corrupted date values
<p>my dataframe contains numerous incorrect datetime values that have been fat-fingered in by the people who entered those data. The errors are mostly 2019-11-12 was entered at 0019-12-12 and 2018 entered as 0018. There are so many of them, so I want came up with a script to correct them en mass. I used the following...
<p>This is because of the limitations of timestamps : see this <a href="https://stackoverflow.com/questions/32888124/pandas-out-of-bounds-nanosecond-timestamp-after-offset-rollforward-plus-adding-a">post</a> about <em>out of bounds nanosecond timestamp</em>. </p> <p>Therefore, I suggest correcting the column as a stri...
python|pandas|datetime
1
18,233
71,707,367
Pandas dataframe shallow copy not reacting to data changes?
<p>I have a wrapper class to work with a specific dataframe and some modifier functions/callables to operate with it.</p> <pre class="lang-python prettyprint-override"><code>class PhoneNumberCleaner: def __init__(self, data: pd.DataFrame, pattern: str): self.data = data # shallow copy? self.pattern...
<p>This line:</p> <pre class="lang-py prettyprint-override"><code>class PhoneNumberCleaner: def __call__(self, *args, **kwargs) -&gt; pd.DataFrame: ... return self.data.drop(drop_mask_index) </code></pre> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html" rel="nofol...
python|pandas|wrapper|shallow-copy
1
18,234
71,452,209
Save GAN generated images one by one
<p>I have generated some images from the Fashion Mnist dataset, However, I am not able to come up with a function or the way to save each image as a single file. I only have found a way to save them in groups. Can someone help me on how to save images one by one?</p> <p>This is what I have for the moment:</p> <pre><cod...
<p>Try using <code>plt.imsave</code> to save each image separately:</p> <pre><code>def generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training=False) fig = plt.figure(figsize=(4, 4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(predictio...
python|tensorflow|matplotlib|keras|generative-adversarial-network
2
18,235
42,291,286
CNTK: csv column format in example 104
<p>In CNTK example (CNTK_104_Finance_Timeseries_Basic_with_Pandas_Numpy) the data look likes: <a href="https://i.stack.imgur.com/eTE32.png" rel="nofollow noreferrer">get_stock_data</a></p> <p>I have try pd.read_csv to read my own csv data:</p> <pre><code>url = 'http://localhost/csv/SPY0.csv' data = pd.read_csv(ur...
<p>You need add parameter <code>index_col</code> for read column to <code>index</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>.</p> <p>Also you can convert <code>index</code> to <code>DatetimeIndex</code> by <code>parse...
python|csv|pandas|cntk
1
18,236
69,710,321
How to auto create a new column after value_counts in Panda?
<p>This is the data</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Price Rating</th> <th>Food Rating</th> <th>Service Rating</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>2</td> </tr> <tr> <td>4</td> <td>5</td> <td>5</td> </tr> <tr> <td>3</td> <td>4</td> <td>3</td> </tr> <tr> ...
<p><code>melt</code> then <code>crosstab</code></p> <pre><code>s = df.melt() out = pd.crosstab(s.value,s.variable) out Out[228]: variable Food Rating Price Rating Service Rating value 1 2 2 1 2 0 ...
python|pandas
2
18,237
69,852,332
Python Generate dummy in dataframe based on another variable(pandas)
<p>I have dataframe with many variables. I would like to generate a dummy variable based on column 1, for example. If column 1's observation is more than 0.25 then the dummy variable is filled with 1. If column 1' observation is less than 0.25, then the dummy variable is filled with 0. Any ideas? Thanks a lot.</p>
<p>IIUC compare values for greater like <code>0.25</code> and then cast to integers for map <code>True/False</code> to <code>1/0</code>:</p> <pre><code>df[1] = df[1].gt(0.25).astype(int) </code></pre> <p>If first column:</p> <pre><code>df.iloc[:, 0] = df.iloc[:, 0].gt(0.25).astype(int) </code></pre>
python|pandas|dataframe|dummy-variable
1
18,238
43,143,003
How can I speed up deep learning on a non-NVIDIA setup?
<p>Since I only have an AMD A10-7850 APU, and do not have the funds to spend on a $800-$1200 NVIDIA graphics card, I am trying to make due with the resources I have in order to speed up deep learning via tensorflow/keras.</p> <p>Initially, I used a pre-compiled version of Tensorflow. InceptionV3 would take about 1000-...
<p>After researching this topic for a few months, I can see 3.5 possible paths forward:</p> <p>1.) Tensorflow + OpenCl as mentioned in the comments above:</p> <p>There seems to be some movement going on this field. Over at Codeplay, Lukasz Iwanski just posted a comprehensive answer on how to get tensorflow to run wit...
tensorflow|deep-learning|theano|caffe|torch
21
18,239
43,365,714
How to convert great_circle distance to timedelta in Python?
<p>I have used great_circle function to find the distance between two coordinates.For example, if i have the following data:</p> <pre><code>lat1= ['-77.85'] lon1= ['80.23'] lat2= [-22.4532'] lon2= ['62.45'] </code></pre> <p>And to find the distance i use the following code: </p> <pre><code>import pandas as pd from g...
<p>You need to be sure time is correctly formated and never input floats.</p> <p>You can convert a float to minutes and hours with the following command:</p> <pre><code># time = distance / speed time = 2.75 # 2 hours + 45 minutes result = '0 days {0:02.0f}:{1:02.0f}:00'.format(*divmod(time * 60, 60)).split(":") # =...
python|pandas|timedelta|great-circle
0
18,240
43,217,028
Pandas COUNTIF based on column value
<p>I am trying to essentially do a COUNTIF in pandas to count how many items in a row match a number in the first column. </p> <p>Dataframe:</p> <pre><code>a b c d 1 2 3 1 2 3 4 2 3 5 6 3 </code></pre> <p>So I want to count instances in a row (b,c,d) that match a. In row 1 for instance it should be 1 as only d match...
<p>You can use <code>eq</code>, which you can pass an <code>axis</code> parameter to specify the direction of the comparison, then you can do a row sum to count the number of matched values:</p> <pre><code>df.eq(df.a, axis=0).sum(1) - 1 #0 1 #1 1 #2 1 #dtype: int64 </code></pre>
python|pandas|dataframe
7
18,241
72,280,652
Creating dummy variables from a string column in pandas
<p>So I have a pandas df as follows and my goal is to take the <code>MATCHUP</code> column and make it several more dummy columns.</p> <pre><code>INDICATOR MATCHUP 1 [ &quot;APPLE&quot;, &quot;GRAPE&quot; ] 1 [ &quot;APPLE&quot;, &quot;GRAPE&quot; ] 0 [ &quot;GRAPE&quot;, &quot;BANA...
<p>Check <code>explode</code> with <code>str.get_dummies</code></p> <pre><code>import ast df = df.join(df['MATCHUP'].map(ast.literal_eval).explode().str.get_dummies().groupby(level=0).sum()) </code></pre>
python|pandas
3
18,242
45,587,387
Pandas not dropping columns
<p>Hi I've tried to drop columns based on a boolean array but for some odd reason pandas does not seem to be dropping the columns at all. </p> <p>The boolean array is and (376,). It only contains True and False values. </p> <pre><code>for x in range(0,len(analysis)-1): if analysis[x] == False: col = dt...
<p>IIUC you don't need <code>loop</code>:</p> <pre><code>dtest = dtest.loc[:, analysis] </code></pre> <p>Demo:</p> <pre><code>In [320]: df = pd.DataFrame(np.random.rand(5, 10), columns=list(range(1, 11))) In [321]: df Out[321]: 1 2 3 4 5 6 7 8 ...
python|arrays|pandas|numpy
4
18,243
62,649,479
Create column based on the comparative match between two dataframes
<p>I have a dataframe A which has a column called <code>A['Income']</code> and another dataframe B which has columns - <code>B['Income']</code> and <code>B['category']</code>. I need to compare <code>A['Income']</code> with <code>B['Income']</code> and create A<code>['category']</code> such that, when <code>A['Income'...
<p>Try with <code>merge_asof</code></p> <pre><code>df=pd.merge_asof(A.sort_values('Income'),B,on='Income').fillna(0.1) Income category 0 489 0.1 1 900 0.1 2 1000 1.1 3 1234 1.1 4 1456 1.1 5 2980 1.2 6 3007 1.2 7 4569 1.3 8 7065 2.1 9...
python|pandas
4
18,244
62,575,336
ValueError: Shapes (1, 107, 3) and (1, 107, 2) are incompatible
<p>I have such a problem, and it happened on the latest version of tensorflow. I hope somebody can give me some suggestions. my code as below:</p> <pre><code>%tensorflow_version 2.x import tensorflow as tf import numpy as np import h5py import t3f import matplotlib.pyplot as plt filename = &quot;./video.h5&quot; np.ra...
<p>I have solved this issue! It's caused by the rank be different between tensor.So,I modified one of tensor rank in order to match another.</p>
tensorflow2.0|tensor
0
18,245
62,482,739
Getting unexpected shape using tensordot
<p>I'm trying to do dot product between two tensors of shape (2000, 1, 64) (2000, 30, 64) When I do tf.tensorbot between these two with the following code</p> <pre><code>test = tf.tensordot(enc_op,tf.transpose(query_with_time_axis),axes=1) </code></pre> <p>I'm getting the output shape as (2000, 30, 1, 2000) But I hav...
<p>try using,</p> <pre><code>a=tf.transpose(a,perm=[0,2,1]) </code></pre> <p>and then,</p> <pre><code>test=tf.matmul(b,a) </code></pre> <p>where <code>a</code> is the first tensor and <code>b</code> is the 2nd</p>
python-3.x|tensorflow|deep-learning|tensor|attention-model
1
18,246
62,817,252
Pandasql not working when I add an analytical function
<p>I'm having an issue with the pandasql library. The library works great until I attempt an analytical function in which case I get the error:</p> <pre><code>**Error message** OperationalError: near &quot;(&quot;: syntax error </code></pre> <p>The table and code used is as follow:</p> <pre><code>question_id, average k...
<p><code>pandasql</code> uses a <code>sqlite</code> in memory database by default. <code>sqlite</code> only supports analytic functions as of version 3.25.0. You must upgrade <code>sqlite</code>. If you're in a Google Colab notebook, <a href="https://stackoverflow.com/questions/59427642/upgrading-sqlite-in-colab">thi...
pandasql
1
18,247
54,320,195
How to replace NaN values with 0 in index dataframe
<p><img src="https://i.stack.imgur.com/K2Aba.png" alt="enter image description here"></p> <p>How do I replace the NaN values to 0 while keeping it in this index form?</p>
<p>You can process the original index as a Series first and then re-assign the index:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Column1': [1, 2, 3, 4], 'Column2': [5, 6, 7, 8], 'Column3': [8, 9, 10, 11]}, index=['a', 'b', np.nan, np.nan]) df.index = pd.Series(df.index).replace(np.nan, ...
python|pandas
0
18,248
54,613,859
Plot Price as Horizontal Line for Non Zero Volume Values
<p>My Code:</p> <pre><code>import matplotlib.pyplot as plt plt.style.use('seaborn-ticks') import pandas as pd import numpy as np path = 'C:\\File\\Data.txt' df = pd.read_csv(path, sep=",") df.columns = ['Date','Time','Price','volume'] df = df[df.Date == '08/02/2019'].reset_index(drop=True) df['Volume'] = np.where((df...
<p>Based on your image, I think you mean <em>horizontal lines</em>. Either way it's pretty simple, Pyplot has <a href="https://matplotlib.org/2.1.2/api/_as_gen/matplotlib.pyplot.vlines.html" rel="nofollow noreferrer">hlines</a>/<a href="https://matplotlib.org/2.1.2/api/_as_gen/matplotlib.pyplot.vlines.html" rel="nofoll...
python|python-3.x|pandas|matplotlib
1
18,249
73,618,223
Plotting a large data set while filtering for a year that is not a variable in that data set
<p>Really easy question from a starting python programmer, but I am have been fighting this for two days now.</p> <p>I want to plot life expectancy vs gdp in a scatter plot. This comes from a huge 60000 row data set containing the years 1950 until 2018. For this specific scatterplot I am only interested in 2018. How do...
<pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('GDP_LE_2018.csv') df = pd.DataFrame(df) df = df.query('Year &gt; == 2018') le = df['Life expectancy'] gdp = df['GDP per capita'] plt.scatter(gdp, le) plt.show() </code></pre> <ol> <li>convert Dataframe.</li> <li>filter(query).</li> </ol...
python|pandas|dataframe|matplotlib|scatter-plot
0
18,250
73,805,446
Filter Pandas Dataframe with or statement
<p>I have a pandas dataframe that I want to to filter the dataframe using column 'closed_date', which contains dates. I am trying to filter so that either the value is null or the value is a date within the last year.</p> <pre class="lang-py prettyprint-override"><code>df = df[(df['closed_date']&gt;dt.today()-td(days=3...
<p>I think you are missing the parentheses to call the method <code>isnull</code>. Try:</p> <pre><code>df = df[(df['closed_date'] &gt; dt.today() - td(days=365)) | (df['closed_date'].isnull())] </code></pre>
python|pandas|dataframe|filter
1
18,251
73,831,486
Extract 1st Column data and update 2ndColumn based on 1st Column data
<p>I have an excel file with the following data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LogID</th> </tr> </thead> <tbody> <tr> <td>T-1111</td> </tr> <tr> <td>P-09899</td> </tr> <tr> <td>P-09189,T-0011</td> </tr> <tr> <td>T-111,T-2111</td> </tr> <tr> <td>P-09099,P-7897</td> </tr> <t...
<p>You can use:</p> <pre><code># mapping dictionary for types d = {'T': 'Tank', 'P': 'Pump'} # extract letters before - s = df['LogID'].str.extractall('([A-Z])-')[0] # group by index g = s.groupby(level=0) df['LogType'] = (g.first() # get first match .map(d) # map type name # mask...
pandas|lambda
2
18,252
71,220,159
Combine 2 arrays using numpy
<p>If I have a list of points <code>[x1, x2..xn, y1, y2..yn]</code> how can I get <code>[x1, y1, x2, y2..xn, yn]</code> using numpy?</p> <p>This is what I did, but idk how to continue</p> <pre><code>u = [x for idx, x in enumerate(l) if idx &lt; len(l) / 2] v = [x for idx, x in enumerate(l) if idx &gt;= len(l) / 2] </co...
<p>Numpy solution (using <code>np.column_stack()</code> instead of <code>zip</code>):</p> <pre><code>list_a = np.array([100.0, 200.0, -10.0]) list_b = [False, False, True] print(np.column_stack((list_a, list_b))) [[100. 0.] [200. 0.] [-10. 1.]] </code></pre> <p>Alternative:</p> <pre><code>list_a = [100.0, 200....
python|numpy
1
18,253
71,273,328
Change the structure of column name
<p>I have the column as</p> <pre><code>id_no| 2021-05-19 00:00:00 | 2021-05-20 00:00:00 | decider 100 20 20 878 200 64 38 917 </code></pre> <p>here idno is the index and the rest are columns I want the outupt as</p> <pre><code>id_no| 2021...
<p>We can try <code>str</code> slice when other column length are not greater than 10</p> <pre><code>df.columns = df.columns.astype(str).str[:10] df Out[356]: id_no 2021-05-19 2021-05-20 decider 0 100 20 20 878 1 200 64 38 917 </code></pre>
python-3.x|pandas|dataframe|datetime
3
18,254
71,365,529
How print all rows after select specific value in row by pandas?
<p>I select minimum low price from these dataframe but I want print all rows after a row have minimum price. I try something but the result only specific row.</p> <pre><code>data = client.get_historical_klines(symbol=i, interval=&quot;1h&quot;, start_str=&quot;24 hours ago&quot;, end...
<p>Use this</p> <p>df_new = df[df[&quot;Low&quot;]==df[&quot;Low&quot;].min()] or df_new= df.loc[df[&quot;Low&quot;]==df[&quot;Low&quot;].min()]</p> <p>print(df_new)</p>
python|pandas|dataframe|python-3.7
0
18,255
52,068,007
Iterating over pandas columns and calculating new columns in each iteration
<p>I have a dataframe that looks like this </p> <pre><code>d = {'A': [10, 20, 30, 40], 'B': [20, 30, 40, 50],'C': [30, 40, 50, 60]} df = pd.DataFrame(data=d) A B C 10 20 30 20 30 40 30 40 50 40 50 60 </code></pre> <p>I am trying to b...
<p>You have two questions in it . </p> <p><em>1st maybe you did not aware of it . Your data data type is string. We need convert to int firstly</em> </p> <pre><code>df=df.astype(int) </code></pre> <p>Then we using <code>div</code> and <code>add</code></p> <pre><code>pd.concat([df,df.div(10).add(df.sum(1),0).add_pr...
python|pandas|for-loop
4
18,256
52,235,280
How to perform conditional addition of columns in Pandas DataFrame?
<p>I have below dataset. And I want to add the salary of each emp depending upon the months emp_worked.For ex as shown in below dataset emp with name 'aaa' worked for 4 months So I want to do addition of columns jan to Apr and stored it in Total_ sal column.</p> <pre><code>`import pandas as pd` data=pd.read_csv("...
<pre><code>df['Total_sal'] = df[df.columns[df.columns.get_loc('jan'):df.columns.get_loc('apr')]].sum(axis=1) </code></pre> <p>out:</p> <pre><code> emp_id emp_name months_worked total_sal jan feb mar apr may jun jul aug sep oct nov dec Total_sal 1 aaa 4 NaN 2000 1 2.0 3 4.0 5555.0 NaN 74343.0 8 ...
python|python-3.x|pandas|dataframe
0
18,257
60,731,612
Is there a way to load a sql query in a pandas >= 1.0.0 dataframe using Int64 instead of float?
<p>When loading the output of query into a DataFrame using pandas, the standard behavior was to convert integer fields containing NULLs to float so that NULLs would became NaN. </p> <p>Starting with pandas 1.0.0, they included a new type called pandas.NA to deal with integer columns having NULLs. However, when using p...
<p>Have you tried using select isnull(col_name,0) from table_name. This converts all null values to 0.</p> <p>Integers are automatically cast to float values just as boolean values are cast to objects when some values are n/a.</p>
python|pandas
1
18,258
72,756,847
Tensorflow running time detect
<p>I've been training a TF2 model like</p> <pre><code>class MyModel(): def __init__(self): self.inp = Input(name='inp', shape=[None, self.inp_tgt.n_feat], dtype='float32') self.network = MyAttentionModel() self.model = Model(inputs=self.inp, outputs=self.network.outp) self.model.sum...
<p>You can use Callbacks to check the time per each epoch.</p> <pre><code>class TimeCallback(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.times = [] def on_epoch_begin(self, epoch, logs={}): self.epoch_time_start = time.time() def on_epoch_end(self, epoch, logs={}): ...
python|tensorflow
0
18,259
72,600,532
FunctionTransformer & creating new columns in pipeline
<p>I have a sample data:</p> <pre><code>df = pd.DataFrame(columns=['X1', 'X2', 'X3'], data=[ [1,16,9], [4,36,16], [1,16,9], [2,9,8],...
<p>If I understand you correctly, you want to add a new column based on a given column, e.g. <code>X2</code>. You need to pass this column as an additional argument to the function using <code>kw_args</code>:</p> <pre><code>import pandas as pd from sklearn.preprocessing import FunctionTransformer from sklearn.pipeline...
python|pandas|pipeline
2
18,260
72,683,765
Unable to obtain boxes for a TFLITE Yolov5 model
<p>I trained a model allowing the detection of '+' characters on an image thanks to Yolov5. I want to use this model in TFLITE. However, when I infer an image in the model, I have trouble interpreting the output.</p> <p>Here is how I infer in my model :</p> <pre><code>interpreter = tf.lite.Interpreter(&quot;/Users/maxi...
<p>Please check <a href="https://github.com/ultralytics/yolov5/issues/1981" rel="nofollow noreferrer">https://github.com/ultralytics/yolov5/issues/1981</a></p> <p>'shape': array([ 1, 25200, 85], dtype=int32)</p> <p>[x ,y ,w ,h , conf, class0, class1, ...] total 85 columns</p> <p>col 0-3 is boxes, col 4 is conf, a...
tensorflow|yolov5|tflite
0
18,261
72,567,769
how can I un-groupby my dataframe in pandas?
<p>I have a dataset like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>project id</th> <th>phase 1</th> <th>phase 2</th> <th>phase 3</th> </tr> </thead> <tbody> <tr> <td>112</td> <td>29</td> <td>157</td> <td>213</td> </tr> <tr> <td>113</td> <td>36</td> <td>121</td> <td>23</td> </tr>...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df = df.set_index(&quot;project id&quot;) df = ( df.assign(cumulative=df.sum(axis=1)) .stack() .to_frame(name=&quot;days&quot;) .reset_index() .rename(columns={&quot;level_1&quot;: &quot;phase&quot;}) ) df[&quot;phase&quot;] = df[&quot;phas...
pandas|dataframe|group-by
0
18,262
59,899,234
splitting the words in a row to several row based on certain value of another column Python
<p>I have this dataframe <strong>df</strong>:</p> <pre><code>columnId column2 column3 countsOfWord id1 hogedijk klarenbeek 2016 2 id2 hogedijk klarenbeek zuidoost hoged...
<p>IIUC we do <code>explode</code> then <code>cumcount</code> split the group to sub group </p> <pre><code>s=df.assign(column2=df.column2.str.split(' ')).explode('column2') s=s.groupby([s.columnId,s.groupby('columnId').cumcount()//2]).\ agg({'columnId':'first','column2':' '.join,'column3':'first','countsOfWor...
python|pandas
3
18,263
61,623,709
How to split a dataset into a custom training set and a custom validation set with pytorch?
<p>I'm using a non-torchvision dataset and I have extracted it with the ImageFolder method. I'm trying to split the dataset into 20% validation set and 80% training set. I can only find this method (random_split) from PyTorch library which allows splitting dataset. However, this is random every time. I'm wondering is t...
<p>If you look "under the hood" of <a href="https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html#random_split" rel="nofollow noreferrer"><code>random_split</code></a> you'll see it uses <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Subset" rel="nofollow noreferrer"><code>torch.ut...
python|machine-learning|neural-network|pytorch
1
18,264
62,010,942
How to use pd.read_csv() on this web page?
<p>I am having difficulties using pd.read_csv() on the web page to use the "Download Data" button since I do not see the typical .zip or .csv at the end. What would be the correct url to use to directly download the data with pd.read_csv()?</p> <p>Link:</p> <p><a href="https://climate.weather.gc.ca/climate_data/daily...
<p>When you open Firefox developer tools -> Network tab, you will see the URL when you click the download button. (Chrome has something similar too)</p> <pre><code>import pandas as pd url = 'https://climate.weather.gc.ca/climate_data/bulk_data_e.html?format=csv&amp;stationID=27211&amp;Year=2019&amp;Month=5&amp;Day=1&...
python|pandas
3
18,265
58,058,732
Python absolute value on list nested within dataframe
<p>I have a dataframe like this:</p> <pre><code>Current Dataframe: ID Price Price_List 0 Prodt1 1500 [-5.2, -4.6, -3.3, 0] 1 Prodt2 17 [-9.2, -8.4, -2.1, 0] </code></pre> <p>and I would like to apply the absolute value to the list in Price_List (except the zero-value), and add it back to its...
<p>You could use a list comprehension to iterate over the lists in <code>Price_List</code> and extend each list with the absolute values of all elements except <code>0</code> with a conditional expression (note that <code>if j</code> is enough as the expression will evaluate to <code>False</code> only when <code>j</cod...
python|pandas|list|dataframe
3
18,266
54,695,719
How to store numpy.ndarray on DynamoDB?
<p>I have this <code>numpy.ndarray</code> generated by <a href="https://github.com/ageitgey" rel="nofollow noreferrer">@ageitgey's</a> <a href="https://github.com/ageitgey/face_recognition" rel="nofollow noreferrer">facial_recognition Python library</a> when I call the <code>face_encodings</code> function. I need to sa...
<p>You can try converting <code>results</code> to a string of bytes using <code>ndarray.tostring</code>. This should be straightforward to work with for Dynamo.</p> <pre><code>arr = np.array([1, 2]) encoded = arr.tostring() encoded # b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00' </code></pre> <...
python|arrays|numpy|amazon-dynamodb|numpy-ndarray
4
18,267
49,656,725
ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory
<p>I installed <code>Tensorflow 1.6.0</code> - GPU version with anaconda in a Python 3.6.4 environment.</p> <p>When I do <code>import tensorflow as tf</code>, I get the following error:</p> <pre><code>ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory </code></pre> <p>The different...
<p>The accepted answer is wrong (installing <code>nvidia-cuda-toolkit</code>). By installing the toolkit you are basically installing a second CUDA on top of already installed cuda from the nvidia guide.</p> <p>The problem turned out to be an issue with symbolic links. Inspiration is from this topic <a href="http://que...
python-3.x|tensorflow|ubuntu-16.04
7
18,268
49,720,339
Split pandas on large white space
<p>I need to split the following dataframe (a single column) into three, by large whitespace:</p> <p>df = </p> <pre><code>0 boots 0330 on 31 mar clp n... 1 tesco stores 6292 on 31 mar clp n... 2 uniqlo on 31 mar clp n... </code></pre> <p>...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> by regex <code>\s{2,}</code> - <code>2 or more whitespaces</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add_prefix.h...
python|pandas|text|split
1
18,269
73,393,364
How to make a p * q matrix from a numpy.nd array(Where p*q = n)?
<p>I have these two array</p> <pre><code>data1 = [[&quot;ab&quot;,&quot;bc&quot;,&quot;ca&quot;], [&quot;bc&quot;,&quot;cd&quot;,&quot;da&quot;], [&quot;be&quot;,&quot;cd&quot;,&quot;db&quot;]] topics1 = [[&quot;ab&quot;,&quot;db&quot;],[&quot;be&quot;,&quot;cd&quot;]] </code></pre> <p>I have to find the intersection o...
<pre><code>import numpy as np img_mat = np.array( mat11 ) shape = ( len(data1), len(topics1) ) l = np.matrix(img_mat.reshape(shape)) import pandas as pd l_df = pd.DataFrame(l) l_df = l_df.rename_axis('Docs').reset_index() l_df.Docs = pd.Series([&quot;D&quot;+str(ind) for ind in l_df.Docs]) suffix = 'Topic' l_df = l_df...
arrays|pandas|numpy
1
18,270
73,371,287
cufflinks `df.iplot()` doesn't work with vscode/jupyter
<p>I'm trying to use cufflinks to plot a dataframe, and <code>df.iplot()</code> is not working––it does not return after 10s. I'm running from <code>vscode</code> + <code>jupyter</code> extension. <code>plotly</code> works fine. Any suggestions on what I am doing wrong?</p> <pre><code>import cufflinks as cf cf.set_con...
<p>I found an answer here: <a href="https://nbviewer.org/gist/santosjorge/5fdbe947496faf7af5e6" rel="nofollow noreferrer">https://nbviewer.org/gist/santosjorge/5fdbe947496faf7af5e6</a></p> <p>All I needed to do was to go into offline mode:</p> <pre><code>cf.set_config_file(offline=True) </code></pre>
python|pandas|jupyter-notebook|plotly|cufflinks
0
18,271
73,297,057
Error with pandas.Dataframe.to_sql -> PostgreSQL database due to timestamp datatype mismatch
<p>I'm having trouble with <strong>inserting rows</strong> to my <strong>PostgresSQL table</strong> using the <code>pandas.DataFrame.to_sql()</code> method. Any help is appreciated, thank you!</p> <p>Sample dataframe:</p> <pre><code>index | m_date | ticker | close 0 | 1514937600 | AMD | 11.55 </code></pre> <...
<p><code>1514937600</code> is not a timestamp it is an epoch.</p> <p>This can be seen with:</p> <pre><code>select to_timestamp(1514937600); 2018-01-02 16:00:00-08 </code></pre> <p>You will need to convert the value to a Python <code>datetime</code> before sending it to database. Something like:</p> <pre><code>import...
python|pandas|postgresql
0
18,272
73,243,024
Pandas read_fwf is limiting string data to 127 characters upon read in
<p>I am reading a fixed-width file into a pandas dataframe, but I notice that the data is not being properly stored into the dataframe. The cells in the dataframe are being restricted to 127 characters.</p> <p>Input file:</p> <pre><code>Column 1 Column 2 Column 3 *see s...
<p>As an alternative, you could read the input file with Python <code>readlines</code>. Then, apply Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.rsplit.html#pandas.Series.str.rsplit" rel="nofollow noreferrer">rsplit</a> with <code>n=2</code> using space by default, or any other pattern...
python|pandas|export-to-csv
0
18,273
67,398,501
Python dictionary from API has 1 heading I want to get rid of
<p>so this is what i get from the API, but I really dont need the first &quot;dividends&quot; heading</p> <pre><code>{ &quot;dividends&quot;: [ { &quot;currency&quot;: &quot;USD&quot;, &quot;date&quot;: &quot;2021-05-04&quot;, &quot;dividend&quot;: &quot;0.1100&quot;, ...
<p>You are close, select data by key <code>dividends</code>:</p> <pre><code>df= pd.DataFrame(esponse_parsed['dividends']) </code></pre>
python|pandas|api|csv
2
18,274
67,469,409
Persian path for read_excel
<p>I want to read a file with pd.read_excel and also load_workbook and I have persian names in my path. I get the following error: FileNotFoundError: No such file</p> <p>my code:</p> <pre><code>df1 = pd.read_excel(r'X:\\Frosh\\دیتابیس فروش\\ ثبت اطلاعات فروش.xlsx', sheet_name='پيش فاکتور') wb3=load_workbook(r'X:\\Frosh...
<pre><code>wb = xlrd.open_workbook(&quot;دیتابیس فروش ثبت اطلاعات فروش.xlsx&quot;, encoding_override='utf-8') df = pd.read_excel(wb) </code></pre>
python|excel|pandas|path|farsi
0
18,275
59,921,931
Taking the minimum value between current and previous day - rolling().min()
<p>I have this data frame:</p> <pre><code>ID Date X 123_Var 456_Var 789_Var A 16-07-19 1 NaN NaN NaN A 17-07-19 7 777.0 250.0 810.0 A 20-07-19 3 NaN NaN NaN A 21-07-19 4 295.0 272.0 490.0 A 22-07-19 8 778.0 600.0 544.0 A 25-07-19 8 ...
<p>After further explanation from comment, you may try these steps. Convert <code>Date</code> to datetime dtype if it is not in <code>datetime</code>. Set <code>Date</code> to index. Doing rolling by by <code>offset</code> instead of integer.</p> <pre><code>n = 2 cols = ['123_Var', '456_Var', '789_Var'] df.Date = pd.t...
pandas
2
18,276
59,949,165
Checking if values in a column are a superset of another array
<p>I have this data as an example. I need to check which <code>a</code> values have all corresponding values of <code>b</code>. For example which <code>a</code> have all <code>[1,2]</code> corresponding <code>b</code> values.</p> <pre><code>In [1]: df = pd.DataFrame( {'a':['A','A','A','B','B','B','C','C'], 'b':[1,...
<p>Use a pivot table:</p> <pre><code>df.pivot('a','b','a').dropna(subset=[1,2]).index </code></pre> <p>Or use groupby:</p> <pre><code>df.groupby('a').b.apply(lambda x: set(x.tolist()).issuperset([1,2])) </code></pre> <p>or if you need it in a list:</p> <pre><code>( df.groupby('a') .b.apply(lambda x: set(x....
python|pandas|pandas-groupby
2
18,277
60,239,453
How to loop a dataframe in Pytorch?
<p>I have a problem when I want to loop my <code>DataFrame</code> created before so I can pass it into my classifier, but I can't neither loop my <code>DataFrame</code> nor pass a filename to the classifier. What can I do?</p> <pre><code>dataset=pd.DataFrame({ 'filename':train, ...
<p>Maybe you can try wrapping up your dataframe in PyTorch's dataloader. This will help you generate batches of train/validation dataset. This <a href="https://stackoverflow.com/a/50385303/3687851">answer</a> by Allen will give you some direction. Once you have a dataloader in place, you can easily iterate over it dur...
loops|dataframe|pytorch|conv-neural-network
0
18,278
65,193,858
Unable to Install Pandas on Cents 7 Linux Server
<p>I have a Centos7 linux server, on that i have deployed Django application, now i have to use pandas in the application, but post installing the pandas by using pip3.6 command and i am getting below error, please someone help</p> <pre><code>ImportError at / Unable to import required dependencies: numpy: IMPORTANT: ...
<p>You have to execute the installation with root permissions.</p> <pre><code>sudo pip3 install pandas </code></pre> <p>or alternatively</p> <pre><code>pip3 install --user pandas </code></pre>
python|django|pandas|numpy|centos7
0
18,279
65,410,065
Which axis does Keras Conv1D layer work on?
<p>I'm writting a model with Keras for time series analysis. The structure of the info I'm sending to the neural network is <code>(samples, timesteps, features)</code></p> <p>My idea is to have three steps on the design of the network. A first step with a (or some) Conv1D layers, then another with LSTMs and finally som...
<p>By default, it's applied to the axis with the time steps.</p> <pre><code>import tensorflow as tf timesteps = 7 features = 10 inputs = tf.random.uniform(shape=(100, timesteps, features), maxval=1, dtype=tf.float32) filters = tf.random.uniform(shape=(3, 1, 1), maxval=1, dtype=tf.float32) print(tf.keras.layers.Conv1...
python|tensorflow|keras|deep-learning|conv-neural-network
1
18,280
65,305,974
Tensorflow - Getting Probes of Pretrained models
<p>I need to get the probes of a pretained model in TensorFlow (dataset imagenet), that is for each block of a VGG16, or ResNet50 or any other pertained model in TensorFlow, I want to have a prediction of the class <code>y_hat</code>, so an array of zeros but for the predicted class which will be 1.</p> <p>I have writt...
<p>Your methodology is correct : the problem is that the first layers of a big model like ResNet50 or VGG16 are really big. Connecting a fully connected (dense) layer to a big output (like 112x112x64) leads to a very heavy weights.</p> <p>There is some strategy against that problem described in the paper <a href="https...
python|tensorflow|keras|deep-learning
0
18,281
65,264,523
TensorFlow - Interleave multiple indipently preprocessed TFRecord files
<p>I have multiple <code>TFRecord</code> files from the Waymo Dataset, each containing consecutive points that are not consecutive across files. I'm building an input pipeline that preprocesses data for time series prediction via the <code>window()</code> API but I need to avoid the window to span accross multiple file...
<p>Solved it by looping over all TFRecord files and appending the corresponding datasets to a dataset list. Then, following this <a href="https://stackoverflow.com/questions/49058913/interleaving-multiple-tensorflow-datasets-together">tip</a> to interleave all the preprocessed datasets.</p>
python|tensorflow|parsing|tensorflow2.0|tensorflow-datasets
0
18,282
65,314,061
Python pandas create a new row within dataframe based on a conditions on certain rows above
<p>I have the following dataframe,</p> <p><a href="https://i.stack.imgur.com/ybKrp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybKrp.png" alt="dataframe" /></a></p> <p>I want to create a new row called test within the index column, which checks if the <code>pd</code> row is the same sign (negativ...
<p>You can use a simple comparison:</p> <pre><code>df.loc['test', :] = df.loc['pd'].ge(0).eq(df.loc['cn']) </code></pre> <p>Output:</p> <pre><code> x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 pd -0.00137 0.00658 0.004332 -0.005762 0.005905 0.001333 0.001611...
python|pandas|conditional-statements
2
18,283
64,172,047
How to stop training CNN part while continue training ANN part in a Multi-input Model?
<p>I made a <em>multi-input</em> model in Keras which takes image <code>shape=[N, 640, 480, 3]</code> as well as numerical data <code>shape=[N, 19]</code> and does prediction on 12 classes. Following is the model defining part of code:</p> <pre><code># # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # # ...
<p>Im not using keras but after a quick google search this should be the answer: You can freeze layers, so that certain parameters are not learnable anymore:</p> <pre class="lang-py prettyprint-override"><code># this freezes the first N layers for layer in model.layers[:N]: layer.trainable = False </code></pre> <p>...
tensorflow|keras
0
18,284
63,890,400
Tensorflow equivalent of PyTorch NLLLoss
<p>is there a tensorflow built in equivalent of PyTorchs Negative-Log-likelihood function?</p> <p><a href="https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html</a></p>
<blockquote> <p>is there a tensorflow built in equivalent of PyTorchs Negative-Log-likelihood function?</p> </blockquote> <p>Yes:</p> <ul> <li><a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseCategoricalCrossentropy" rel="nofollow noreferrer"><code>tensorflow.keras.losses.SparseCategoricalCross...
python|tensorflow
1
18,285
63,838,417
Tensorboard resume training plot
<p>I ran a reinforcement learning training script which used Pytorch and logged data to tensorboardX and saved checkpoints. Now I want to continue training. How do I tell tensorboardX to continue from where I left off? Thank you!</p>
<p>I figured out how to continue the training plot. While creating the summarywriter, we need to provide the same <code>log_dir</code> that we used while training the first time.</p> <pre><code>from tensorboardX import SummaryWriter writer = SummaryWriter('log_dir') </code></pre> <p>Then inside the training loop step n...
pytorch|tensorboard|tensorboardx
6
18,286
47,007,073
Find percentile in pandas dataframe based on groups
<pre><code>Season Name value 2001 arkansas 3.497 2002 arkansas 3.0935 2003 arkansas 3.3625 2015 arkansas 3.766 2001 colorado 2.21925 2002 colorado 1.4795 2010 colorado 2.89175 2011 colorado 2.48825 2012 colorado 2.08475 2013 colorado 1.68125 2014 colora...
<p>You can use <code>groupby</code> + <code>quantile</code>:</p> <pre><code>df.groupby('Name')['value'].quantile([.1, .9]) Name arkansas 0.1 3.174200 0.9 3.685300 colorado 0.1 1.620725 0.9 2.656375 Name: value, dtype: float64 </code></pre> <p>And then call <code>np.searchsorted</cod...
python|pandas|numpy
2
18,287
46,812,663
What is the Tensorflow equivalent of numpy.random.multivariate_normal?
<p>I want to draw random samples given mean and Co-variance matrix. In numpy I can do that using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.multivariate_normal.html" rel="nofollow noreferrer"><code>numpy.random.multivariate_normal</code></a> function. What is the Tensorflow equiva...
<p>I think you are looking for <code>tf.contrib.distributions.MultivariateNormalDiag</code>, as seen in the <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/contrib.distributions/multivariate_distributions" rel="nofollow noreferrer">TensorFlow Official Documentation</a>.</p>
numpy|tensorflow
0
18,288
46,959,173
Trying to properly shape tensors in tensorflow. Can't get the dimensions correct
<p>I'm running a simple univariate logistic regression program written in Tensorflow. I can't, however, get my shapes properly from my training set to the x placeholder. I've been trying various methods to do so, I'm always getting the error:</p> <pre><code>ValueError: Cannot feed value of shape (70,) for Tensor 'Pl...
<p>You are printing the shape of your <code>x</code> placeholder and <code>train_x</code> batch, but what about labels? Your <code>x</code> placeholder is of the shape (?, 2), so it seems that the error is not referring to <code>x</code>, it is referring to <code>y</code>, which is (?, 1). Check the shape of your <code...
python|tensorflow
0
18,289
63,026,464
Unmelt a dataframe by column data values
<p>I have a dataframe as below.(df1)</p> <pre><code>name,Measure,Value gift,cost,20 gift,Factor,0.2 newsletter,cost,15 newsletter,Factor,0.05 seminar,cost,23 seminar,Factor,0.3 </code></pre> <p>I need to be converted to dataframe df2.</p> <pre><code>name cost factor gift 20 0.20 newsletter 15 0.05 seminar...
<p>You can try with <code>pd.DataFrame.pivot</code>:</p> <pre><code>df.pivot(index='name',columns='Measure', values='Value').rename_axis(None, axis=1) </code></pre> <p>Output:</p> <pre><code> Factor cost name gift 0.20 20.0 newsletter 0.05 15.0 seminar 0.30 23.0 </cod...
python|pandas
2
18,290
63,304,981
3D Autoencoder has low error but poor results when plotting
<p>I am making an auto-encoder to reduce the dimensionality of lung CT scans (3D).</p> <p>The input is 176(patients) x 30(slices) x 256 x 256 x 1. While it achieves a loss of 0.1233 (binary_crossentropy), when I plot the predictions it makes on the training set they don't look very good. Do you have any suggestions abo...
<p>A better way of knowing if your training is working when using binary is to use accuracy. Try changing:</p> <pre><code>autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') </code></pre> <p>to</p> <pre><code>autoencoder.compile(optimizer='adadelta',loss='binary_crossentropy', metric=['binary_accuracy...
python|tensorflow|machine-learning|autoencoder
0
18,291
63,223,501
Creating a list of lists from a dataframe based on a condition
<p>im working with some financial data and I want to create a list of lists while iterating through a df and a certain condition is met</p> <p>e.g: df</p> <pre><code> 25 Day 250 Day Date 2001-12-07 1.4 1.5 2001-12-10 1.6 1.7 2001-12-11 1.8 1.2 2001-12-12 1.4 1.5 2001-12-13 1....
<p>You can filter using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a> then convert each row to list using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noref...
python|pandas
0
18,292
67,806,453
Create ID when exploding dataframe
<p>Im trying to explode a dataframe series which retains the list position in order to create an another index.</p> <pre><code>df = pd.DataFrame({'A': [[255, 255, 255], [0, 0, 0], [255, 255, 255]], 'B': [[255, 255, 255], [0, 0, 0], [255, 255, 255]]}) print(df) A B 0 [255, 255, 255] [255,...
<p>Let us try <code>explode</code> then <code>cumcount</code></p> <pre><code>s = pd.concat([df[[x]].explode(x) for x in ['A','B']],axis=1) s['C'] = s.groupby(level=0).cumcount().add(1).astype(str).radd('item') s Out[476]: A B C 0 255 255 item1 0 255 255 item2 0 255 255 item3 1 0 0 item1 1 ...
python|pandas
2
18,293
67,992,716
Python Pandas - Create list of values AND count by two columns
<p>So I have the following pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/bc0IJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bc0IJ.png" alt="enter image description here" /></a></p> <p>What I would like to do is create a new column that contains a unique list of all the dest_hostname...
<p>IIUC use agg</p> <pre><code>df.groupby(['user', 'user_agent'])['dest_hostname'].agg(['unique', 'count']) </code></pre>
python|pandas|dataframe
3
18,294
61,604,990
Number of distinct labels and input data shape in tf.data Dataset
<p>The <a href="https://www.tensorflow.org/tutorials/keras/classification" rel="nofollow noreferrer">Tensorflow Fashion-MNIST</a> tutorial is great... but it seems clear you have to know <strong>in advance</strong> that there are 10 distinct labels in the dataset, and that the input data is image data of size 28x28. I ...
<p>According to <a href="https://stackoverflow.com/questions/56218014/how-to-acquire-tf-data-datasets-shape">the accepted answer to this question</a>, Tensorflow <code>tf.data.Dataset</code> instances are <strong>lazily evaluated</strong>, meaning that you could, in principle, need to iterate the through an entire data...
tensorflow
0
18,295
61,217,336
Why doesn't torch.autograd compute the gradient in this case?
<p>Why doesn't torch.autograd compute the gradient in this case?</p> <pre><code>import torch x = torch.tensor([1., 2., ], requires_grad=True) y = torch.tensor([x[0] + x[1], x[1] - x[0], ], requires_grad=True) z = y[0] + y[1] z.backward() x.grad </code></pre> <p>Output is a blank line (None). The same occurs for <code...
<p>When you use <code>torch.tensor</code> for <code>y</code>, it just uses the values of <code>x</code> to initialize the tensor, the gradient chain is lost.</p> <p>This works:</p> <pre><code>x = torch.tensor([1., 2., ], requires_grad=True) y = [x[0] + x[1], x[1] - x[0], ] z = y[0] + y[1] z.backward() x.grad </code><...
python|pytorch|gradient|backpropagation|autograd
2
18,296
68,653,770
Can not find the pytorch model when loading BERT model in Python
<p>I am following <a href="https://towardsdatascience.com/how-to-compute-sentence-similarity-using-bert-and-word2vec-ab0663a5d64" rel="nofollow noreferrer">this</a> article to find the text similarity. The code I have is this:</p> <pre><code>from sentence_transformers import SentenceTransformer from tqdm import tqdm fr...
<p>You may need to use the model without sentence_transformers.</p> <p>The following code is tweaked from <a href="https://www.sbert.net/examples/applications/computing-embeddings/README.html" rel="nofollow noreferrer">https://www.sbert.net/examples/applications/computing-embeddings/README.html</a></p> <p>As I understa...
python-3.x|pytorch|similarity|bert-language-model|sentence-transformers
0
18,297
68,529,082
Extract values of two columns from a dataset based on the column's value of another dataset
<p>I am trying to extract values of two columns from a dataset based on the column's value of another dataset.</p> <p>Example:</p> <p>df1:</p> <pre><code>index ID Value 0 45 04 1 32 03 2 34 08 3 6 05 4 ...
<p>You can do as you wanted and just drop an extra column:</p> <pre><code>(pd.merge(df1, df2, on=&quot;ID&quot;, suffixes=('', '_y')) .drop('index_y', axis=1) .sort_values('index') ) </code></pre> <p>Output:</p> <pre><code>index ID Value Weight Height 0 45 4 54 163 1 32 3 ...
python|pandas
1
18,298
52,921,739
Pandas Two Dataframes subtract based on multi indexes
<p>I have two dfs and I want to subtract based on the multi indexes</p> <p>profitDf</p> <pre><code>Company Product Amount Google Pixel 2 3000 Microsoft Window 10 4000 Amazon AWS 10000 </code></pre> <p>costDf</p> <pre><code>Company Product Amount Google Pixel 2 10000 Microsoft Win...
<p>Since it is multiple index using <code>merge</code> </p> <pre><code>pdf.merge(cdf,on=['Company','Product'],how='outer').fillna(0).eval('Diff=Amount_x-Amount_y') Out[205]: Company Product Amount_x Amount_y Diff 0 Google Pixel2 3000.0 10000.0 -7000.0 1 Microsoft Window10 4000.0 1000...
python|pandas
1
18,299
53,082,639
Python : Removing the contents of a cell based on a specific condition
<p>I have a *.xlsx file as below -</p> <pre><code> A B C [['Neutral']] ['nan'] [['Neutral']] ['nan'] Bad [['Negative']] ...
<p>try this,</p> <pre><code>mask=df['A'].isnull() df.loc[mask]='' </code></pre> <p>Output:</p> <pre><code> A B C 0 1 2 Bad [['Negative']] ['Bad'] 3 Meh [['Neutral']] ['Meh'] 4 </code></pre> <p>F...
python|pandas
2