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
372,200
72,804,158
How can I convert following string date-time into pandas datetime
<p>How can I convert the following string format of datetime into datetime object to be used in pandas Dataframe? I tried many examples, but it seems my format is different from the standard Pandas datetime object. I know this could be a repetition, but I tried solutions on the Stackexchange, but they don't work!</p> <...
<p>Below code will convert it into appropriate format</p> <pre><code>df = pd.DataFrame({'datetime':['2013-11-1_00:00','2013-11-1_00:10','2013-11-1_00:20']}) df['datetime_changed'] = pd.to_datetime(df['datetime'].str.replace('_','T')) df.head() </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur.com/MlUi2.png...
python|pandas|dataframe|datetime|type-conversion
2
372,201
72,510,626
How to parse pandas column in the loop if it's a dictionary
<p>I have the DataFrame, one of the column contains dictionary in rows in format:</p> <pre><code> rates 0 {'time': '2022-06-05T19:25:57.3000000Z', 'asset_id_quote': '0X', 'rate': 73571.98764837519} 1 {'time': '2...
<p>here is how you can extract the time using extract and regex</p> <p>assumption in the pattern is that time will appear as &quot;<em>'time': '2022-06-05T19:25:07.1000000Z'</em>&quot;</p> <pre><code>df['time'] = df['dict'].str.extract(r&quot;(time': ')(.*)(Z)&quot;)[1] </code></pre> <p>use Regex to remove T and Z here...
python|pandas|loops|dictionary
1
372,202
72,634,739
Pandas Add rows for each column
<p>I apologise for the title, I know it isn't the most helpful. What I'm attempting to do is restructure my data so that each of a given column is given it's own row with certain values carried over from the previous dataframe.</p> <p>My Data in its current form is something like this:</p> <pre><code>ColA | ColB | ColC...
<p>Given:</p> <pre><code> ColA ColB ColC val1 val2 val3 0 1 2 3 A B C 1 4 5 6 D E F </code></pre> <p>Doing:</p> <pre><code>df.melt(['ColA', 'ColB', 'ColC']) </code></pre> <p>Output:</p> <pre><code> ColA ColB ColC variable value 0 1 2 3 val1 A 1 4...
python|pandas
2
372,203
72,721,594
How to fix or separate in another database the bad_lines on Pandas Python
<p>I have the following code for unzip and concatenate .csv files of a directory into a new merged .csv file named <em>base_flash.csv</em></p> <pre><code>def merge(self): file_list = [self.unzipDir + '\\' + f for f in os.listdir(self.unzipDir) if f.startswith('relatorio')] csv_list = [] ...
<p>Starting with <code>pandas</code> <code>1.4.0</code>, <code>read_csv()</code> delivers capability that allows you to handle these situations in a more graceful and intelligent fashion by allowing a callable to be assigned to <code>on_bad_lines=</code>. This link gives some guidance on how to do that: <a href="https...
python|pandas|csv
1
372,204
72,535,624
The best way to plot time series data for a short period of time
<p>I have a dataset with two columns &quot;new_date&quot; and &quot;Sales&quot;. The dataset captures the daily sales for a company over 3 months in just one year 2020, &quot;i.e., Jan, Feb, and March&quot;. The size of the dataset is about 8000 rows. One day might have different transaction or different sales.</p> <pr...
<p>I'm not sure what you are exactly looking for, but based on the data I guess you could sum the <code>Sales</code> first by <code>new_date</code>.</p> <pre><code>df.groupby('new_date').sum().plot(legend=False) </code></pre> <p>When you want to sum <code>Sales</code> per week, you can use <code>resample</code>:</p> <p...
python|pandas|scikit-learn|time-series|visualization
0
372,205
72,744,810
Empty image as class variable
<p>I want to declare an image as a class variable in order to use it with different method.</p> <p>Is <code>frame = None</code> an acceptable way in python? Otherwise what is the best way?</p>
<p>If you create a variable <code>frame</code> and set its value to <code>None</code>. You can later assign it any other value that you need, for example, a class as your program requires.</p> <pre><code>class A: def __init__(self): self.a = 1 frame = None frame = A() print(frame) </code></pre> <p><strong>...
python|numpy
0
372,206
72,749,648
multiply a single column shared by multiple pandas DataFrames by a number
<p>Lets say we have the following:</p> <pre><code>Jan_22 ={'A':221, 'B':119, 'C':455,'E':677} Feb_22 ={'A':342, 'B':1223,'C':133,'D':3662,'G':321} Mar_22 ={'A':252, 'C':53} list = [Jan_22,Feb_22,Mar_22] df = pd.DataFrame(list) df </code></pre> <pre><code> A B C D E G 0 221 119.0 455 NaN 677.0 NaN 1 ...
<p>You can simply use the <code>divide</code> function of your pandas dataframe:</p> <pre><code>number_of_days = [31, 28.25, 31] df = df.divide(number_of_days, axis=0) </code></pre>
python|pandas|date
1
372,207
72,609,879
select non-NaN rows with multiple conditions from a pandas dataframe
<p>Assume there is a dataframe such as</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':[11,12,np.nan,24,np.nan]}) df col1 col2 0 1 11.0 1 2 12.0 2 3 NaN 3 4 24.0 4 5 NaN </code></pre> <p>I would like...
<p>This is how you can determine if there are <code>np.nan</code> in your data and how to use additional logic with <code>np.where()</code></p> <pre><code>df = pd.DataFrame({ 'Column1' : [1, 2, 3, 4, 5], 'Column2' : [11, 12, np.nan, 24, np.nan] }) df['Column2'] = df['Column2'].replace({np.nan : None}) df['Check...
python|pandas|dataframe
1
372,208
72,715,306
How to add multiple array outputs to a dataframe?
<p>I am working with probabilities, when I print the output, it looks as follows:</p> <pre><code>[[4.88915104e-308 1.43405787e-307 2.20709896e-308 ... 3.08740254e-307 1.68481486e-307 1.72126050e-307] [1.64744295e-004 8.66082462e-004 7.66062761e-005 ... 1.85613403e-003 9.68750380e-004 8.22260750e-004] [6.18964539e...
<p>Yes, it is possible if convert 2d array to list:</p> <pre><code>df = pd.DataFrame({'col':arr.tolist()}) </code></pre> <p>Or:</p> <pre><code>s = pd.Series(arr.tolist()) </code></pre>
python|arrays|pandas|list|dataframe
2
372,209
72,555,036
How do I return a value into a column within a dataframe based on parameters in another dataframe?
<p>I have two dataframes in Python:</p> <pre><code>product_id product_name order_name qty 01 ABC A1 1 01 ABC A2 2 01 ABC A3 3 </code></pre> <pre><code>product_name ship_date ship_qty ABC 01/01/2022 1 ABC ...
<p>Here is a solution with <code>pd.merge</code>:</p> <pre><code>res = df1.merge( df2[[&quot;ship_date&quot;, &quot;ship_qty&quot;]] .sort_values(by=&quot;ship_date&quot;) .drop_duplicates(subset=&quot;ship_qty&quot;), left_on=&quot;qty&quot;, right_on=&quot;ship_qty&quot;, ).drop(&quot;ship_qty&quo...
python|pandas|dataframe|for-loop
0
372,210
72,667,568
Python, Pandas - Trouble with code summing counts in pandas
<p>Having trouble with code I've written.</p> <p>The first df 'piv_1' contains a column 'Category' (Either 3.0 or 4.0) and columns ['Start', 'Issue', 'Comments Rec'] containing values 1,2,3...12 (numerical month values representing Jan-Dec).</p> <p>What I'm trying to achieve in 'df_sum' is, a sum-count of occurrences f...
<p>If you have df_sum dataframe for all <strong>Category</strong> values and all <strong>Month, Month Value</strong> at each <strong>Category</strong>,</p> <p>It'll work for that.</p> <pre class="lang-py prettyprint-override"><code>from collections import Counter df_grp = df.groupby('Category').aggregate({&quot;Start&q...
python|pandas|count
1
372,211
72,675,717
Plotly choropleth shows color for US and not other countries
<p>I've a pandas dataframe as following :<br /> <a href="https://i.stack.imgur.com/yhrUK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yhrUK.png" alt="dataframe" /></a></p> <p>column <code>employee_residence</code> contains an ISO 3166 country code for each unique country .</p> <p>I want to plot a...
<p><strong>update:</strong> Now that the data has been published, I used that data to recreate the graph. Since the original data is the ISO3166-2 format country abbreviation, install the library to get the ISO-3166-3 format country abbreviation. Add it to the original data frame and draw a graph.</p> <pre><code>import...
python|pandas|plotly
1
372,212
72,580,858
assign looping result to a variable in python
<p>please help me, I'm stuck to assign lopping output to a variable</p> <p>here's my code</p> <pre><code>a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5] for obs in a: if obs &gt; 0: print('2') elif obs &lt; 0.1: print('1') </code></pre> <p>the output is</p> <pre><code>2 1 2 2 2 2 </code></pre> <p>I want to sav...
<p>IIUC, store the result in the list 'b', as in below example</p> <pre><code>a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5] b=[] for obs in a: if obs &gt; 0: b.append(2) elif obs &lt; 0.1: b.append(1) print(b) </code></pre> <pre><code>[2, 1, 2, 2, 2, 2] </code></pre>
python|pandas|loops
1
372,213
72,643,492
Text file lines to csv columns
<p>I m trying to transfer data from a text file to csv. My text file contains lots of rows delimited by /n.</p> <p>My text file is like:</p> <pre><code>1 CONTINUE A:data B:data C:data D:data Something A $Param = data $Param2 = data 2 CONTINUE </code></pre> <p>and so on, the structure is the same</p> <...
<p>Question is pretty hard to find the real problem. I made the code, but please tell me if your problem clearly exists.</p> <pre class="lang-py prettyprint-override"><code>txt_lines = txt.split(&quot;\n&quot;) df_dict = dict() for line in txt_lines: if not line: continue if &quot;:&quot; in line: ...
python|pandas|csv|text|extract
0
372,214
72,817,093
Multiplying 3d matrix and 3d matrix
<p>I'm trying to do the multiplying of 3d matrix and 3d matrix, my matrix is as follows:</p> <pre><code>Z = np.array([ [[0,0,0.25],[0.25,0.5,0.75],[0,0,0.25],[0.75,1.0,1.0],[0.75,1.0,1.0]], [[0,0,0.25],[0,0,0.25],[0.5,0.75,1.0],[0,0,0.25],[0,0,0.25]], [[0,0,0.25],[0,0,0.25],[0,0,0.25],[0,0.25,0.5],[0,0,0.25]], [[0,0,0....
<p>I suggest you take a look at the <a href="https://numpy.org/doc/stable/reference/generated/numpy.tensordot.html" rel="nofollow noreferrer">documentation</a> of the <code>tensordot()</code> function to actually understand what it is doing with the matrices:</p> <pre><code>import numpy as np Z = np.array([ [[0,0,0.25...
python|arrays|numpy|matrix
1
372,215
72,524,486
I get this error --> AttributeError: 'NoneType' object has no attribute 'predict'
<p>I get this error many times.</p> <pre><code>Traceback (most recent call last): File &quot;E:\AI and ML-pr\day14\test.py&quot;, line 38, in &lt;module&gt; result = loaded_model.predict(test_image) AttributeError: 'NoneType' object has no attribute 'predict...
<p>The problem appears to be the line: <code>loaded_model = loaded_model.load_weights(&quot;modell.h5&quot;)</code></p> <p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#load_weights" rel="nofollow noreferrer">documentation for load_weights()</a>:</p> <blockquote> <p>When loading a weight f...
python|numpy|tensorflow|opencv|keras
1
372,216
72,758,578
Slice each string row of pandas dataframe according a pattern array
<p>I need to slice a string row of pandas in different positions, and I want to use vectorization for that. Some one can help me? Each line has this pattern:</p> <pre><code>012016010402AAPL34 010APPLE DRN R$ 0000000004150000000000422000000000041500000000004213000000000420800000000039500000000004350...
<p>It looks like you need <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer"><code>pandas.read_fwf</code></a>, reading your file directly:</p> <pre><code>l = [0,2,10,12,24,27,39,49,52,56,69,82,95,108,121,134,147,152,170,188,201,202,210,217,230,242,245] import numpy as...
python|pandas|string|dataframe|slice
1
372,217
72,674,495
9 decimal places of array elements in Python
<p>How do I ensure that all the array elements after an operation are accurate to 9 decimal places? The desired output is attached.</p> <pre><code>import numpy as np A=np.array([[1,2,3],[4,5,6],[7,8,9]]) A1=A*2 print([A1]) </code></pre> <p>The desired output is</p> <pre><code>[array([[ 2.000000000, 4.000000000, 6.000...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html" rel="nofollow noreferrer"><code>np.set_printoptions</code></a>.</p> <pre><code>import numpy as np A = np.array([[1,2,3],[4,5,6],[7,8,9]], dtype=float) A1 = A * 2 np.set_printoptions(precision=9, floatmode='fixed') pr...
python|numpy
2
372,218
72,509,011
Pandas: How to get lists of 5 most frequent value in column for each hour of the day?
<p>I have some pandas data.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>A</th> <th>B</th> </tr> </thead> <tbody> <tr> <td>2021-05-06 12.00</td> <td>18.5</td> <td>0</td> </tr> <tr> <td>2021-05-06 13.00</td> <td>20.3</td> <td>9.7%</td> </tr> <tr> <td>2021-05-06 14.00</td> <t...
<p>Starting from:</p> <pre><code>df = pd.DataFrame( [ {&quot;Date&quot;: &quot;2021-05-06 10.00&quot;, &quot;A&quot;: 18.5, &quot;B&quot;: &quot;9.7%&quot;}, {&quot;Date&quot;: &quot;2021-05-06 10.00&quot;, &quot;A&quot;: 20.3, &quot;B&quot;: &quot;9.7%&quot;}, {&quot;Date&quot;: &quot;2021-...
python|pandas
0
372,219
72,777,428
How to loop all the questions in pivot table in Python?
<p>I am working on a survey and the data looks like this:</p> <pre><code>ID Q1 Q2 Q3 Gender Age Dep Ethnicity 001 Y N Y F 22 IT W 002 N Y Y M 35 HR W 003 Y N N F 20 IT A 004 Y N Y M ...
<p>IIUC, you can use <code>pd.wide_to_long</code>:</p> <pre><code>out = (pd.wide_to_long(df, stubnames='Q', i=['ID', 'Dep', 'Ethnicity'], j='Question') .reset_index().rename(columns={'Q': 'Response'}).assign(Count=1) .pivot_table('Count', ['Question', 'Dep', 'Response'], 'Gender', ...
python|pandas|loops|pivot-table
1
372,220
72,715,339
How to get corresponding numpy array values after performing calculation on another related array
<p>I have a function that returns two NumPy arrays (width and height) like so:</p> <pre><code>width, height = calc_heigh_width(data) width &gt;&gt;&gt; array([390, 20, 65, 1000]) height &gt;&gt;&gt; array([2, 7, 3, 1]) </code></pre> <p>Imagine the widths as being points on an x-axis, so they go from 0 to 1000 in this...
<p>you can just zip the values and use the same algorithm you have written. i did not check the correctness of your solution, just changed it so that it returns the format you want. check it out</p> <pre><code> width = [390, 20, 65, 1000] height = [2, 7, 3, 1] cord = sorted(list(zip(width, height)), key=lambda tup: tu...
python|numpy
1
372,221
72,725,088
filtering a dataframe using another dataframe
<pre><code>data = {'a':['a','b','c','d','e','f','g'], 'b':['Y','N','Y','Y','Y','N','Y'], 'c':['Qualified','Unqualified','Qualified','Unqualified','Qualified','Unqualified','Qualified']} df = pd.DataFrame(data) df_para = {'Y/N':['','y','n'], 'Q/U':['unqualified','','unqualified']} df_para = pd.D...
<p>Reason is <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/gotchas.html#using-the-in-operator" rel="nofollow noreferrer">in operator test indices</a>:</p> <blockquote> <p>Using the Python in operator on a Series tests for membership in the index, not membership among the values.</p> </blockquote> <bl...
python|pandas|filter
1
372,222
72,610,933
convert pandas Series of lists of strings to float - type issues
<p>How do I properly convert this pandas series/array which for some reason it sees as an object into a float ? each element in each line of the array needs to be converted.</p> <p>I've tried to_numeric but I get dataType errors</p> <pre><code>&lt;PandasArray&gt; [['1703.0', '1144.0', '2172.0', '735.0'], ['1120.0', '6...
<p>While you <em>can</em> initialize a Series or DataFrame as object type, with values equal to lists or other containers pointing to other data, Pandas is not designed to hold data structures like this. If you organize your data this way, you will get many of the nice features of pandas such as indexing and broadcasti...
python|arrays|pandas
0
372,223
72,807,160
Reshaping torch tensors of PIL images leads to multiple gray images of same image
<pre><code># creating a flower dataset f_ds = torchvision.datasets.ImageFolder(data_path) # a transform to convert images to tensors to_tensor = torchvision.transforms.ToTensor() for idx, (img, label) in enumerate(f_ds): if idx == 2100: # random PIL image display(img) print(img.size, img.m...
<p>ToTensor permutes the array and returns a tensor in the shape [C, H, W]. Using reshape to swap the order of dimensions is wrong and will interleave the image.</p> <p>I should have used tenosor.permute to change the dimensions not reshape.</p> <p><a href="https://discuss.pytorch.org/t/to-tensor-transform-is-messing-m...
python|numpy|python-imaging-library|reshape
0
372,224
72,756,704
Convert column of Timestamps to datetime.datetime. Works on 1 row, not on column
<p>I've looked at every answer on this site, including this one: <a href="https://stackoverflow.com/questions/22554339/convert-timestamp-to-datetime-datetime-in-pandas-series">convert timestamp to datetime.datetime in pandas.Series</a> and nothing is working. It always returns a Timestamp.</p> <p>I have a dataframe wit...
<pre><code>import pandas as pd df = pd.DataFrame({'time': [1451602801, 1451606401, 1451610001, 1451613601, 1451617201]}) df['datetime'] = pd.to_datetime(df['time'], unit='s') print(df) </code></pre> <p>Output</p> <pre><code> time datetime 0 1451602801 2015-12-31 23:00:01 1 1451606401 2016-01-01 00...
python|mysql|pandas|dataframe|datetime
0
372,225
72,717,556
Wrong output datatype (results out of range) on equation with numpy
<p>Got 2 arrays:</p> <pre><code>print(arr1.shape) print(arr1.dtype) print(arr2.shape) print(arr2.dtype) </code></pre> <p>output</p> <pre><code>(500, 500) uint8 (500, 500) uint8 </code></pre> <p>How do I correctly substract one from another so the output datatype would fit the real result? Doing this:</p> <pre><code>sub...
<p>A very general approach would be to just cast your arrays to whatever output type you're planning on using:</p> <pre><code>arr1 = arr1.astype(float) arr2 = arr2.astype(float) sub = arr1 - arr2 </code></pre> <p>Another, more subtle, approach is to perform only the casts that you need. An operation like <code>res = a ...
python|python-3.x|numpy
0
372,226
59,490,479
tensorflow lite conversion failed. "undefined symbol : _ZTIN10tensorflow6DeviceE" occured
<pre><code>tflite_model = converter.convert() tflite_model_file = 'converted_model.tflite' with open(tflite_model_file, "wb") as f: f.write(tflite_model) </code></pre> <p>When I finally converted model within dot convert method, I got some error.</p> <p>Error Message:</p> <pre><code>ValueError: Failed to parse th...
<p>I had the same issue - installing nightly build (currently '2.1.0-dev20200104') solved it.</p> <pre><code>!pip3 uninstall tensorflow !pip3 install tf-nightly </code></pre>
tensorflow|tensorflow-lite|transfer-learning
4
372,227
59,543,480
Read data-set and add it to double quotes
<pre><code>Scott Logistics Corp Transportation One LLC Brothers Logistics Inc Western Express Inc Dart Advantage Logistics Western Express Inc Western Express Inc Landstar Inway Circle Logistics Inc </code></pre> <p>See above data set i want to add each name in a double quotes e.g ("Scott Logistics Corp") or see below...
<p>If you want to add double quotes then pure python is plenty:</p> <pre><code>with open(r"text_1.txt",'r') as file: for line in file: line = re.sub(r'\n','',line) lines_new = (f'"{line}\"\n') with open("text_2.txt", "a") as f1: f1.writelines(lines_new) "Scott Logistics Corp"...
python|pandas|list
0
372,228
59,624,085
write a function to groupby year and calculate the average and count the size in pandas
<p>I have a dataframe as shown below</p> <pre><code>Contract_ID Place Contract_Date Price 1 Bangalore 2018-10-25 100 2 Bangalore 2018-08-25 200 3 Bangalore 2019-10-25 300 4 Bangalore 2019-11-25 200 5 ...
<p>Use:</p> <pre><code>def func(df): df['Contract_Date'] = pd.to_datetime(df['Contract_Date']) return (df.groupby(['Place', df['Contract_Date'].dt.year.rename('Year')]) .agg(Number_of_Contracts=('Contract_ID','size'), Average_Price=('Price','mean')) .reset_ind...
pandas|function|pandas-groupby
1
372,229
59,897,030
error in converting string datetime into proper datetime format and calculate total seconds from HH:MM:SS.sss time part in pandas dataframe
<p>I have a pandas dataframe which has date time stamp in string format as follows:</p> <pre><code>df = pd.DataFrame({'date_time':['2019-06-19 02:10:52.563', '2019-06-20 06:20:35.123', '2019-06-21 15:38:24.567', '2019-06-22 13:45:56.243', '2019-06-23 09:37:34.789']}) </code></pre> <p>What I want to do is to :</p> <o...
<p>IIUC add another convert with <code>to_timedelta</code></p> <pre><code>pd.to_timedelta(pd.to_datetime(df['date_time']).dt.time.astype(str)).dt.total_seconds() 0 7852.563 1 22835.123 2 56304.567 3 49556.243 4 34654.789 Name: date_time, dtype: float64 </code></pre>
python|python-3.x|pandas|datetime
2
372,230
59,811,054
Using pd.to_numeric to convert number "01898" in Chinese code to 1898 not working
<p>I tried to get the stock codes from a Chinese news extracted from the web site '<a href="http://www.etnet.com.hk/www/tc/news/categorized_news_list.php?page=1&amp;category=result" rel="nofollow noreferrer">http://www.etnet.com.hk/www/tc/news/categorized_news_list.php?page=1&amp;category=result</a>'. However, the foll...
<p>Python's <code>int</code> can handle non-ASCII Unicode digits, so this works:</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd base_url = "http://www.etnet.com.hk/www/tc/news/categorized_news_list.php?page=1&amp;category=result" result = requests.get(base_url) src = result.content s...
python|pandas|unicode|character-encoding
2
372,231
59,762,422
how to decode png with tensorflow 2.x API without using the palette contained in the png file
<p>png files are usually index values assosiated with a default palette. by default, index values can be read by PIL image, for example:</p> <pre><code> import tensorflow as tf from PIL import Image import numpy as np path = '1.png' image1 = Image.open(path) print(image1.mode) array1 = n...
<p><strong>Ideal solution</strong></p> <p>A clean solution would be to re-implement a custom op to decode a PNG without palette conversion.</p> <p>Currently, the palette conversion in TF for the <code>decode_png</code>-op is done at <a href="https://github.com/tensorflow/tensorflow/blob/38cdb9ff8548efc920039d68dd94b5...
tensorflow2.0
0
372,232
59,681,271
Selecting rows in pandas based on threshold date per id
<p>I want to select rows from my pandas DataFrame where records are before a certain date for each id.</p> <p>I have some threshold dates for each id:</p> <pre><code>thresholds = pd.DataFrame({'id':[1, 2, 3], 'threshold_date':pd.date_range('2019-01-01', periods = 3)}) thresholds id threshold_date 0 1 2019-01...
<p>You can use <code>merge</code> for joining on <code>id</code> with <code>query</code> for filtering:</p> <pre><code>(thresholds.merge(df,on='id',how='left',suffixes=('_x','')) .query("threshold_date_x &gt; threshold_date").reindex(columns=df.columns)) </code></pre> <hr> <pre><code> id threshold_date value 0 ...
python|pandas|dataframe|data-analysis
2
372,233
59,551,201
Creating a symmetric array with power of an element
<p>I am trying to create an array which is symmetric with elements placed as below</p> <p><a href="https://i.stack.imgur.com/QzkLo.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QzkLo.gif" alt="correct_pic"></a></p> <p>I have written the following code to get this form with parameter being 0.5 and...
<p>We can leverage <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> after creating a ranged array to represent the iterator variable and then performing an outer-subtraction to simulate <code>i-j</code> part -</p> <pre><code>n = 4 p = 0.5 ...
python|numpy|for-loop|matrix|symmetric
3
372,234
59,846,913
Saving data from Arduino using Python - loss of data
<p>With the help of web, i have created a code that collects the data form Arduino uno, and saves it to csv file. The data collected are raw values of MEMS accelerometers.</p> <p>The problem in code is that very often i loose a lot of data, if not all, if i terminate the Python. I noticed that at a random time, the o...
<p>You need to append new data to your dataframe. Passing <code>mode='a'</code> in <code>pd.Dataframe.to_csv</code> will allow you to do that.</p> <pre><code>import time tStart = str(time.time()).split('.')[0] fileOut = tStart+'.csv' while True: while (arduinoData.inWaiting()==0): pass arduinoString...
python|pandas|arduino
1
372,235
59,882,100
how to correctly use tf.function with a TensorFlow Dataset
<p>I'm trying to use TF Datasets with a @tf.function to perform some preprocessing on a directory of images. Inside the <em>tf</em> function the image file is read as a RAW string tensor and I'm trying to take a slice from that tensor. The slice, the first 13 characters, represent info about .ppm images (header). I get...
<p>To manipulate string values in TF, have a look at the <a href="https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/strings" rel="nofollow noreferrer">tf.strings namespace</a>.</p> <p>In this case, you can use <code>tf.strings.substr</code>:</p> <pre><code>@tf.function def ppm_to_png(filepath): ppm_bytes ...
python|tensorflow|tensorflow2.0
0
372,236
59,733,921
How to create sequences out of a dataframe and put them in an array of arrays or a list?
<p>For the input of:</p> <pre><code>df = pd.DataFrame(np.array([[1, "A"],[2, "A"],[3, "B"],[4, "C"],[5, "D" ],[6, "A" ],[7, "B" ],[8, "A" ],[9, "C" ],[10, "D" ],[11,"A" ], [12, "A"],[13, "B"],[14, "B"],[15, "D" ],[16, "A" ],[17, "B" ],[18, "A" ],[19, "C" ],[20, "D" ],[21,"A" ], ...
<p>Here I'm using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumsum()</code></a> to give all elements in the same sequence a "Sequence ID" (the value goes up by 1 every time a "D" is encountered)</p> <p>Then use <a href="https://pandas...
python|arrays|pandas|list|dataframe
1
372,237
59,814,635
Why `scipy.dot is numpy.dot` False?
<p>Why is that false? well, the dot product is same in whole math.</p> <p><img src="https://i.stack.imgur.com/UOpC4.png" alt="enter image description here"></p>
<p>Up until scipy 1.4.0, <code>scipy.dot</code> was exactly the same as <code>numpy.dot</code>, and <code>scipy.dot is numpy.dot</code> would return True. As of scipy 1.4.0, <code>scipy.dot</code> is deprecated, as are all the other numpy names that had been copied to the <code>scipy</code> namespace. You can read ab...
numpy|scipy|dot-product
2
372,238
59,486,265
Multi GPU training slower than single GPU on Tensorflow
<p>I have created 3 virtual GPU's (have 1 GPU) and try to speedup vectorization on images. However, using provided below code with manual placement from off docs (<a href="https://www.tensorflow.org/guide/gpu#manual_device_placement" rel="noreferrer">here</a>) I got strange results: training on all GPU two times slower...
<p>There are two basic misunderstandings that are causing your trouble:</p> <ol> <li><p><code>with tf.device(...):</code> applies to the graph nodes created within the scope, not <code>Session.run</code> calls.</p> </li> <li><p><code>Session.run</code> is a blocking call. They don't run in parallel. TensorFlow can only...
python|python-3.x|tensorflow|multi-gpu
7
372,239
59,805,307
Add a row of strings, like a second column name, to pandas dataframe
<p>I would like to add string data to the first row of a dataframe (i.loc[0,:])</p> <p>So that when printed the dataframe looks something like so:</p> <pre><code>Col1 Col2 Col3 A B C 4 2 4 1 6 2 5 8 6 </code></pre> <p>I would then like to total the column totals from the start of the numeri...
<p>I think that this is a multiple part question.</p> <p>Assuming that the name of each column is Col1, Col2, Col3, and you want to add a row in which the value in the cell is a string I would try the following:</p> <pre><code>df.loc['index you want to insert your row into'] = ['A', 'B', 'C'] </code></pre> <p>I am n...
python|pandas|dataframe
0
372,240
59,737,218
Find words and create new value in different column pandas dataframe with regex
<p>suppose I have a dataframe which contains: </p> <pre><code>df = pd.DataFrame({'Name':['John', 'Alice', 'Peter', 'Sue'], 'Job': ['Dentist', 'Blogger', 'Cook', 'Cook'], 'Sector': ['Health', 'Entertainment', '', '']}) </code></pre> <p>and I want to find all 'cooks', whether in ca...
<p>Here's one approach:</p> <pre><code>df.loc[df.Job.str.lower().eq('cook'), 'Sector'] = 'gastronomy' </code></pre> <hr> <pre><code>print(df) Name Job Sector 0 John Dentist Health 1 Alice Blogger Entertainment 2 Peter Cook gastronomy 3 Sue Cook gastronomy </code></...
python|regex|pandas
4
372,241
59,561,002
How can I optimize the 5-layer loop using functions provided by torch?
<p><code>x</code> is the tensor with the shape of (16, 10, 4, 25, 53), <code>y</code> has the same size as <code>x</code>.<br> <code>mean</code>'s shape is (25, 53), the size of <code>jc</code> and <code>ac</code> are both (16, 10, 4).</p> <p>How can I optimize the following expression with torch functions?</p> <pre>...
<p>I think you are looking at <a href="https://pytorch.org/docs/stable/notes/broadcasting.html#broadcasting-semantics" rel="nofollow noreferrer">broadcasting</a> your tensors along singleton dimensions.<br> First, you need the <em>number</em> of dimensions to be the same, so if <code>mean</code> is of shape <code>(25,5...
pytorch|vectorization
2
372,242
59,869,234
How can I see all the records with beautiful soup
<pre><code>#! /usr/bin/python import urllib import pandas as pd import source as source from bs4 import BeautifulSoup from urllib.request import Request, urlopen for line_id in range(1, 3): line_id = line_id + 1 x = str(line_id) req = Request('https://tfl.gov.uk/bus/route/' + x, headers={'User-Agent': 'Mozill...
<p>You don't have your scraping logic inside the for-loop, so you will get information only from the last value of <code>x</code> (your <code>Line Id</code>).</p> <p>This script will get information from pages 1 to 2:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://tfl.gov.uk/bus/route/{}...
python|html|pandas|beautifulsoup|request
0
372,243
59,637,211
Python/Pandas: Unique table transpose and transform
<p>I have an Excel table like the one below, where the number '1' marks in which bucket a given store falls under.</p> <pre><code>+-------+-------+-----------+----------+----------+------------+----------+ | | | | H | H | N | G | +-------+-------+-----------+--------...
<p>I will give it a try. First, you should make the excel file from which to read the data more pandas-friendly, by adding an extra line for the names of the columns and properly naming the rows:</p> <p><a href="https://i.stack.imgur.com/uqa4P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uqa4P.pn...
python|pandas
1
372,244
59,779,778
Optimize performance for transposing values to 0 and 1
<p>Let's say we have a list of employees and some other data:</p> <pre><code> Employee Location Title 0 1 Location1 Title1 1 2 Location2 Title1 2 3 Location3 Title2 3 4 Location1 Title3 4 5 Location1 Title2 </code></pre> <p>I am transposing it to features and labels w...
<p>This should do the trick:</p> <pre class="lang-py prettyprint-override"><code>df["_dummy"]=1 df2=pd.concat([ df.pivot_table(index="Employee", columns="Location", values="_dummy", aggfunc=max), df.pivot_table(index="Employee", columns="Title", values="_dummy", aggfunc=max) ], axis=1).fillna(0).astype(int).r...
python|pandas|dataframe|machine-learning
2
372,245
59,556,710
TFJS save model to http with headers
<p>I am trying to save and upload a tfjs model with additional headers ( for class names ) using guide at <a href="https://www.tensorflow.org/js/guide/save_load" rel="nofollow noreferrer">https://www.tensorflow.org/js/guide/save_load</a> with backend copied from <a href="https://gist.github.com/dsmilkov/1b6046fd6132d7...
<p>If your goal is to store some auxiliary information (such as class labels) with the model, there is a relatively little-known feature of <code>tf.LayersModel</code> in TensorFlow.js that will make your life easier. It's simpler than using a header.</p> <p>It is the <code>setUserDefinedMetadata()</code> and <code>ge...
python|flask|tensorflow.js
2
372,246
59,828,012
Matplotliib: Creating multi bar charts for multiple columns from a Pandas dataframe
<p>I have a Pandas dataframe with four columns; the first is a centretype (x axis) and I want the rest of the columns to be displayed as side by side columns for each centretype by year. I am not sure what I'm doing wrong, as I am getting only the values for 2019 but I want 2018 and 2017 displayed too.</p> <p><a href=...
<p>The reason that your picture contains just one column is <code>df = c2</code>. Apparently <em>c2</em> contains only one of columns from your DataFrame. Delete this instruction.</p> <p>As a test, I performed just:</p> <pre><code>df.plot.bar(width=0.7, rot=60, figsize=(12,6), legend=False); </code></pre> <p>getting...
python|pandas|matplotlib|charts|seaborn
1
372,247
59,580,709
replace \n from a list in a data frame
<p>I have:</p> <pre><code>df=pd.DataFrame({'text':[['\nThere are a lot of\n things that \nare worthy','\nS\nU\nP\nE\nR'],['\nAnd there is \nlots to see']]}) df 0 [\nThere are a lot of\n things that \nare wort... 1 [\nAnd there is \nlots to see] </code></pre> <p>I want to replace all \n's, and keep the same struct...
<p>You can do:</p> <pre><code>import re df['new'] = df['text'].apply(lambda x: [re.sub(r'\n', '', y) for y in x]) </code></pre>
regex|pandas
2
372,248
59,881,433
How do I return data from Pandas DataFrame to be returned by Django's JsonResponse?
<p>The answer to this is probably something really simple, but after hours of searching, I really could not find it.</p> <p>I am trying to return a JsonResponse using Django from a pandas dataframe. One of the many things I've tried is the following:</p> <pre><code>from django.http import JsonResponse from django.vie...
<p>You need to pass python objects (dictionary or list for example) as <code>JsonResponse</code> data. But <code>to_json</code> return string. So try to parse it:</p> <pre><code>import json @csrf_exempt def do_request(request): result = pd.DataFrame({'bla':[1,2,3],'bla2':['a','b','c']}).to_json(orient='records') ...
python|django|pandas|jsonresponse|to-json
5
372,249
59,684,917
Game of Life in Python: problem with matplotlib animation
<p>My matplotlib animation function is not running. Any suggestions are much appreciated. As result, there should be an animation running from current to new generation (using the new_state function). </p> <p>"state" is the current array which is a random array. That is passed into the new_state function and should be...
<p>I'm no matplotlib expert, but I'd guess this is closer to what you wanted:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def dead_state(height, width): array = np.zeros((height,width), dtype=int) return array def random_state(width, height): ...
python|numpy|matplotlib|animation|conways-game-of-life
0
372,250
59,739,451
How to make non-unique Pandas column into a unique one
<p>Say I have the following dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Name': ['Jim','Bob','Tim','Sal','Mel'], 'Time': [7,7,7,8,9], 'Value':[15,13,17,6,27]}) Out[1]: Name Time Value 0 Jim 7 15 1 Bob 7 13 2 Tim 7 17 3 Sal ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a>:</p> <pre><code>df['Time'] += df.groupby('Time').cumcount() / 10 </code></pre> <pre><code> Name Time Value 0 Jim 7.0 15 1...
python|pandas|dataframe
8
372,251
59,705,706
How do I randomly rotate a square in a 2D array?
<p>My task to detect a rectangle no matter where it is in a picture. For that, I generated random pixels and randomly generated squares in the picture. It varies in shape and size.</p> <p>The only thing that is missing is that the rectangle is always at a straight angle. <strong>I want the rectangle to be randomly rota...
<p>Your shape is simple, but I like to use <em><a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer">einsum</a></em> for shapes with hundreds of points.</p> <p>You can get the idea from this. <code>s00</code> is just a polygon represented by an ndarray:</p> <pre><code>ar...
python|arrays|numpy|matplotlib
1
372,252
59,846,177
Merging two dataframes based on irregular time column
<p>I have two irregular times-series as dataframes (DataA and DataB) whose rows represent the value of a trait (A or B) of items at various times:</p> <pre><code>DataA DataB time item_id valueA time item_id valueB 0 x A1 3 x B1 1 y A2 4...
<p>start by merging your frames and ordering them:</p> <pre><code>df = pd.merge( left=dataA_df, right=dataB_df, on=['time', 'item_id'], how='outer' ) df = df.sort_values('time') </code></pre> <p>then forward fill by item_id</p> <pre><code>df.groupby('item_id').ffill() time item_id valueA valueB 0...
python|pandas|dataframe|merge|time-series
4
372,253
59,798,597
Groupby in dataframe and pass a list of complete rows to reduction function
<p>So I have:</p> <pre><code>import pandas as pd d = { id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], d = 'date':[13, 7, 6, 12, 18, 11, 17, 5, 3, 17], 'foo': ['abc','def','def','abc','klm','abc', 'klm','xyz', 'pqr', 'klm'], 'bar': ['123','456','333','123','...
<p>Simpliest is create custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a>:</p> <pre><code>def fun(sr): vals = list(map(tuple, sr[['id','date']].to_numpy().tolist())) sr['dicts']...
python|pandas|pandas-groupby
3
372,254
59,774,433
Python load .txt as array
<p>Just have a colors.txt file with data: </p> <pre><code>[(216, 172, 185), (222, 180, 190), (231, 191, 202), (237, 197, 206), (236, 194, 204), (227, 184, 194), (230, 188, 200), (232, 192, 203), (237, 199, 210), (245, 207, 218), (245, 207, 218)] </code></pre> <p>now just try to read this in python as an array</p> <p...
<p>The problem is that you are appending in string data from your file, when you really want a <code>list</code>. So use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>literal_eval</code></a> to safely evaluate the data type:</p> <pre class="lang-py prettyprint-ov...
python|arrays|numpy|file
2
372,255
59,797,310
How do you put quotations around a result from a for loop in Python?
<p>In Python, I am attempting to have the for loop iteration result in quotations so that it passes to another function within the loop. Here is my code along with further explanation of what I'm attempting to do:</p> <pre><code>read = pd.read_csv('Stocks.csv', header=None, delimiter=',') for x in read[0]: Tick...
<p>thank you for your contributions. I found out that the problem exists with the first row of my csv file is "Symbol" as a header and it is causing the issue. How do I go about skipping the first row or indicating that their is a header row in my code so that the iteration begins on row two? Thanks again!</p>
python|pandas|for-loop|quotations
0
372,256
59,891,132
How to put the output of a function into a dataframe?
<pre><code>def sentiment_analyzer_scores(sentence): for sentence in df['clean_text']: score =analyser.polarity_scores(sentence) print({&lt;40{}".format(sentence,str(score))) print(sentiment_analyzer_scores(df['clean_text']) </code></pre> <p>This is the code I want to put the output into a datafra...
<p>In general you can create a new column in this way:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col':['hello', 'bye']}) df['len'] = df['col'].apply(len) print(df) </code></pre> <p>Output:</p> <pre><code> col len 0 hello 5 1 bye 3 </code></pre> <p>In your case I think that something like...
python|pandas|dataframe
1
372,257
59,843,548
Python: ValueError (CSV row has different number of fields) with CSV and Tensorflow
<p>this is my first question. </p> <p>I´m working on a program, that predicts a number of people in a room. I got a CSV-file with data for this. The CSV has 6 columns and 96 rows (including header). But when I run the program, this error occurs:</p> <p><strong>ValueError: Problem inferring types: CSV row has differen...
<p>I suggest you to check your csv file to check which line as the issue. Because it can be a blank line at the end of the file or a missing comma or so many others things... </p> <pre><code>import csv with open(filename, 'r') as f1: csvlines = csv.reader(f1, delimiter=',') for lineNum, line in enumerate(csvl...
python|csv|tensorflow|dataset
1
372,258
59,684,085
Accessing numpy array elements by key
<p>Is there an easy way to access array elements by (string) key as well as by index? Suppose I have an array like this:</p> <pre><code>x = array([[0, 4, 9, 1], [1, 3, 9, 1], [3, 5, 6, 2], [6, 2, 7, 5]]) </code></pre> <p>I am looking for way to specify a set of keys (for example <code...
<p>You can use a pandas DataFrame:</p> <pre><code>import numpy as np import pandas as pd x = np.array([[0, 4, 9, 1], [1, 3, 9, 1], [3, 5, 6, 2], [6, 2, 7, 5]]) df = pd.DataFrame(x) df.columns = df.index = ['A', 'C', 'G', 'T'] df A C G T A 0 4 9 1 C 1 3 9 1 G...
python|numpy|indexing
1
372,259
59,591,417
Can't conver complex to float where is no complex numbers
<p>"Can't conver complex to float" error refers to <code>M[i] = odwr_funk_PM(kat_PM[i])</code>. There is no any complex numbery in <code>kat_PM</code> array.</p> <pre class="lang-py prettyprint-override"><code>def odwr_funk_PM(kat_PM): kat_PM= math.radians(kat_PM) kat_PM_0= 0.5*math.pi*(math.sqrt(6)-1) y=...
<p>You do in fact have a negative value in your data: -101.54242018 Fix this, and your complex values should disappear.</p>
python|function|numpy|math|complex-numbers
2
372,260
59,612,155
Check Normal distribution with Kolmogorov test
<p>I am a learning statistics using python, and I have a task to check that data have Normal Distribution with mean=10 and dispersion=5.5. I've checked scipy.stats.kstest function, but I don't understand how to interpret the results, and where I should pass mean and dispersion args.</p> <p>Thank you, for your help</p...
<h1>Generate a dataset</h1> <pre><code>import scipy import matplotlib.pyplot as plt # generate data with norm(mean = 0,std = 15) data = scipy.stats.norm.rvs(loc = 0,scale = 15,size = 1000,random_state = 0) </code></pre> <h1>Perfrom KS-test</h1> <pre><code># perform KS test on your sample versus norm(10,5.5) D, p = ...
python|pandas|numpy|scipy|statistics
1
372,261
59,639,706
How can I fix this error with sklearn.preprocessing?
<p>Code:</p> <pre class="lang-py prettyprint-override"><code>onehotencoder = OneHotEncoder(categorical_features = [3]) </code></pre> <p>resulting in the error:</p> <pre><code>TypeError: __init__() got an unexpected keyword argument 'categorical_features' </code></pre>
<p><a href="https://stackoverflow.com/questions/59639706/how-can-i-fix-this-error-of-sklearn-preprocessing#comment105441399_59639706">As Chris said</a>, the <code>categorical_features</code> parameter for <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow ...
python|pycharm|sklearn-pandas
1
372,262
59,687,894
How to append inconsistently ordered log file data to pandas dataframe?
<p>I need to process a list of log files and convert string data in those files to one dataframe for analysis. Each log file contains one or more pairs of lines corresponding to an ID, an error occurrence, and the time the error cleared. But if there were several simultaneous errors on different IDs, the errors are lis...
<p>Try with some similar like this:</p> <pre><code>import pandas as pd from io import StringIO import numpy as np data = """ ID1 Error code A ID1 Error cleared: 00:01:00 ID2 Error code B ID3 Error code B ID4 Error code A ID2 Error cleared: 00:02:00 ID3 Error cleared: 00:02:00 ID4 Error cleared: 00:02:00 ID5 Error cod...
python|pandas|append
0
372,263
59,537,810
Numba: Fast way of replacing keys with values in an array
<p>I want to replace <code>keys</code> with <code>values</code> in an large size <code>array</code> having repeating elements. I am trying <code>numba</code> and <code>numpy</code> mapping method. The code for both approaches are as follows.</p> <pre><code>import numpy as np from numba import njit, prange array1 = np...
<p><strong>Improving the Numba method (reducing complexity)</strong></p> <p>Since you only want to change a relatively small amount of values, you can use a set to determine if the actual array element has to be changed. Additionally you can use search_sorted to get the right key, value pair. For this small example t...
python|arrays|performance|numpy|numba
1
372,264
59,568,219
Confused how to replaces values in one data frame from another based on conditions
<p>Hi guys I have two dataframes below and confused what is the best way to accomplish this</p> <pre class="lang-py prettyprint-override"><code>input_df.columns Index(['Username', 'Full Name', 'Email', 'Department',],dtype='object') compare_df.columns Index(['Email', 'Department', 'Username'], dtype='object') </code>...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a>:</p> <pre><c...
python|pandas
1
372,265
59,500,220
How to install the latest version of TensoFlow 2?
<p>I am wondering that why I cannot install the <em>TensorFlow 2.0.0</em> (stable version until now <a href="https://www.tensorflow.org/versions" rel="nofollow noreferrer">in their official website</a> even <a href="https://pypi.org/project/tensorflow/" rel="nofollow noreferrer">in PyPi</a>)</p> <p>I used to had the Te...
<p>Mentioning the solution in this section (even though it is mentioned in the Comments Section), for the benefit of the community.</p> <p>Any of the below steps will resolve the issue:</p> <ol> <li>Using the <code>Tensorflow</code> Version, <code>2.0.0b1</code> for the Ubuntu Version 16.04 (Xenial Xerus) Or</li> <...
python|tensorflow|pip|ubuntu-16.04|tensorflow2.0
2
372,266
59,639,205
Concat list of dataframes and merge by index to separate dataframe
<p>I want to concatenate a list of dataframes. However, I also want to use the list index of each dataframe so I can do a cross join from a separate dataframe.</p> <p>To illustrate:</p> <p>dfA</p> <pre><code> A B 0 A0 B0 1 A1 B1 </code></pre> <p>dfB</p> <pre><code> A B 0 A2 B2 1 A3 B3...
<pre><code>import pandas as pd dfD = pd.concat([dfA, dfB]) dfD = pd.concat([dfD, dfC], axis = 1) </code></pre>
python|pandas
-1
372,267
59,718,820
ode not working for the stuart landau equation?
<p>I am not sure what the issue is in this piece of code. I am trying to solve the following ODE. I solved it with ODEint and for some reason it just gave a flat line answer, which is definitely incorrect. I have corrected the errors in the jacobian and changed the parameters, but nothing is working. I have a version o...
<p>Taking the first component as likely more correct, and assuming that the system is the real and imaginary part of a complex ODE, I read for that <code>z'=-c*z*|z|^2</code>. </p> <p>Note that the real and imaginary parts are</p> <pre><code>A2*(-coeffr*A[0]+coeffi*A[1]), A2*(-coeffr*A[1]-coeffi*A[0]) </code></pre> ...
python|numpy|for-loop|scipy|ode
0
372,268
59,622,320
More input to LSTM
<p>I'm not sure how to feed a data to LSTM, where I have 6 columns with relation. I was using a model designed for one input and tried to change the dimensions. First I added </p> <p><code>nsamples, nx, ny = X_train.shape</code></p> <p><code>X_train = X_train.reshape((nsamples,nx*ny))</code></p> <p>To make sure that...
<p>Your code has this as Flatten: <code>reg.Flatten()</code></p> <p>Try this instead: <code>reg.add(Flatten())</code></p> <p><strong>EDIT:</strong></p> <p>I have tried the code similar to yours below, and it worked. I'm not sure why your Y has shape of (7,6). Try to understand how my code is <strong>conceptually</st...
python|numpy|tensorflow|keras|lstm
1
372,269
59,585,624
Vectorize a for loop in numpy to calculate duct-tape overlaping
<p>I'm creating an application with python to calculate duct-tape overlapping (modeling a dispenser applies a product on a rotating drum).</p> <p>I have a program that works correctly, but is really slow. I'm looking for a solution to optimize a <code>for</code> loop used to fill a numpy array. Could someone help me v...
<p>There is no need for any looping at all here. You have effectively two different <code>line_mask</code> functions. Neither needs to be looped explicitly, but you would probably get a significant speedup just from rewriting it with a pair of <code>for</code> loops in an <code>if</code> and <code>else</code>, rather t...
python|numpy|for-loop|vectorization|numba
8
372,270
59,525,252
pandas groupby remove multiple index
<p>I have a dataframe with a column that I want to groupby and sort by a column value. After groupby I find there are multiple indexes, one of them is the index of origin dataframe, I want to delete this index.</p> <p>A sample data frame:</p> <pre><code>&gt; d = pd.DataFrame(np.array([[0, 0, 1, 1, 2, 2, 2], ...
<p>The only thing I can think of to accomplish this task would be to use <code>openpyxl</code>. First save the output to excel with the multi-index using <code>pandas</code> then delete the column using <code>openpyxl</code> to maintain the format you are looking for.</p> <pre><code># export multi-index DataFrame to e...
python|pandas|pandas-groupby
1
372,271
59,505,843
Convert an object from a parsed csv to int Python
<p>This branches off my previous question - <a href="https://stackoverflow.com/questions/59495149/filling-null-spots-in-csv-in-python">Filling Null Spots in CSV in Python</a>. I am making this a new question as I feel the issues I have encountered have entirely changed my question. </p> <p>I want to convert the data i...
<p>Here is another way of doing this without replace:</p> <p><em>Note: This might be expensive as this solution reshapes the dataframe.</em></p> <p><strong>Step1:</strong> Creating the dataframe:</p> <pre><code>s=&quot;&quot;&quot; Col1,Col2,Col3,Col4,Col5 45,34,23,98,18 66, ,25, 18, ,52,56,100 &quot;&quot;&quot; from...
python|pandas|types
2
372,272
32,238,391
Writing numpy.random.get_state() to file
<p><code>numpy.random.get_state()</code> returns a <code>tuple</code>. I want to write this to a file so I can use the same state later if required.</p> <p>I got it down to the following, but <code>csv</code> throws an error:</p> <pre><code>import csv import numpy as np def write_state(): with open("state_file",...
<p>Python built-in <code>cPickle.dump/load</code> can efficiently write and read many objects such as tuples.</p> <h2>Writing</h2> <pre><code>from cPickle import dump import numpy as np with open('state.obj', 'wb') as f: dump(np.random.get_state(), f) </code></pre> <h2>Reading</h2> <pre><code>from cPickle impo...
python|file|python-2.7|numpy|tuples
1
372,273
32,298,270
What can axis names be used for in python pandas?
<p>I was excited when I learned that it is possible name the axes of pandas data structures (panels, in particular). I named my axes now some plots are labelled and the axis names show up in <code>mypanel.axes</code>.</p> <p>So then I thought, hm, seems like I should be able to use my axes names in place of <code>item...
<p><code>Panel</code> is a bit less developed compared to other <code>pandas</code> structures, so as far as I'm aware, named axes can't be used for much. That <code>transpose</code> use-case seems reasonable, may be worth making an issue.</p> <p>Two alternatives to consider - one is to store your <code>Panel</code> ...
python|pandas
1
372,274
32,190,009
behavior of len() with arange()
<p>With this dataframe, dff:</p> <pre><code> A B 0 0 a 1 1 a 2 2 b 3 3 b 4 4 b 5 5 b 6 6 c 7 7 c </code></pre> <p>I understand how <code>len(dff) == 8</code></p> <p>However, I don't understand the answer from:</p> <pre><code>dff['counts'] = np.arange(len(dff)) </code></pre> <p>which is </p> <p...
<p>You seem to misunderstand what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow"><code>np.arange</code></a> does:</p> <pre><code>In [32]: np.arange(8) Out[32]: array([0, 1, 2, 3, 4, 5, 6, 7]) </code></pre> <p>Here the length of your df is being used to set the <code>s...
python|pandas
2
372,275
32,247,239
Having an issue with pandas df.replace
<p>The gist is that I need to write a database sorting program, and most of it works, but here's a little niggle; for the last part it needs to be sorted out as an average but the problem is that my CSV file isn't delimited so it looks something like this:</p> <pre><code> name name1 score1 sco...
<p>Hmm, not sure how your csv looks like, there could be a better way to do this based on how the csv looks. But basically your issue is that when you do-</p> <pre><code>scores3 = scores3.replace(']', '') </code></pre> <p>You just point scores3 to a new series, this does not change anything in your original DataFrame...
python|csv|pandas|replace
0
372,276
32,484,372
Polar transformation of pandas DataFrame
<p>I have a <code>pandas.DataFrame</code> 2048 by 2048 with <code>index</code> and <code>columns</code> representing y and x coordinates respectively.</p> <p>I want to make an axis transformation and get to polar coordinates, making a new <code>pandas.DataFrame</code> with <code>index</code> and <code>columns</code> r...
<p>This should not be problematic if your dataframe is built as I understand it (though I think I am wrong). To build an example:</p> <pre><code>from __future__ import division import numpy as np, pandas as pd index = np.arange(1,2049,dtype=float) cols = np.arange(2050,4098,dtype=float) df = pd.DataFrame(index=ind...
python|pandas
0
372,277
40,366,120
python pandas- AttributeError: 'Series' object has no attribute 'columns'?
<p>I am trying to count the number of times the current row's value for a specific column 'df1' falls between the low-high range values in the previous 5 rows (in 2 side by side columns). This is a follow-up question - Dickster has already done the heavy lifting <a href="https://stackoverflow.com/questions/40271809/how...
<p>This <code>y[:-1]</code> makes an access to a <code>Rolling</code> object that doesn't support column indexing, that is the meaning of <code>[:-1]</code> in your code. You should apply a transformation function and get an actual series before filtering.</p>
python|pandas|user-defined-functions|series
4
372,278
40,357,002
Find row in pandas and update specific value
<p>I have a dataframe with columns <code>id, uid, gid, tstamp</code>. I'm able to locate a specific row by doing <code>df[df['id'] == 12]</code> which gives:</p> <pre><code> id uid gid tstamp 711 12 CA CA-1 47585768600 </code></pre> <p>How can I update the value of <code>uid</code> and <code>gid</c...
<p>You can select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="noreferrer"><code>ix</code></a> and set values to <code>['IN','IN-1']</code>:</p> <pre><code>print (df) id uid gid tstamp 711 12 CA CA-1 47585768600 711 15 CA CA-1 47585768600 df.ix[...
python|pandas
7
372,279
40,771,400
How to efficiently get indices of rows of DataFrame, where these rows meet certain cumulative criteria?
<p>For example I would like to get letters indicating a row where period of at least two consecutive drops in other column begins.</p> <p>Exemplary data:</p> <pre><code> a b 0 3 a 1 2 b 2 3 c 3 2 d 4 1 e 5 0 f 6 -1 g 7 3 h 8 1 i 9 0 j </code></pre> <p>Exemplary solution with simple loop:</p> <...
<p>Here's one approach with some help from <code>NumPy</code> and <code>Scipy</code> -</p> <pre><code>from scipy.ndimage.morphology import binary_closing arr = df.a.values mask1 = np.hstack((False,arr[1:] &lt; arr[:-1],False)) mask2 = mask1 &amp; (~binary_closing(~mask1,[1,1])) final_mask = mask2[1:] &gt; mask2[:-1] ...
python|performance|pandas|vectorization
3
372,280
40,538,967
How can I use pandas assign to create a new column with multiple conditions?
<p>I have a pandas dataframe with the following columns:</p> <pre><code>Date, Variable 1, rank_pct </code></pre> <p>I am trying to use assign to create a new column called "ls" that has 1, -1, or 0 in it.</p> <ol> <li>If the rank_pct is &lt;0.10, put a 1 in the column ls</li> <li>If the rank_pct is >0.90, put a -1 i...
<p>you can use nested <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a>:</p> <pre><code>data.assign(ls=np.where(data.rank_pct&lt;.1, 1, np.where(data.rank_pct&gt;.9, -1, 0))) </code></pre>
python|pandas|assign
1
372,281
40,757,007
pandas: counting numbers and combining results from apply
<p>I am trying to count consecutive zeros (e.g. 2 consecutive zeros or 3 consecutive zeros) in groups and combine the results in a new dataframe.</p> <pre><code>raw_data = {'groups': ['x', 'x', 'x', 'x', 'x', 'x', 'x','z','y', 'y', 'y','y', 'y', 'z'], 'runs': [0, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 0, 2]} df = pd.Dat...
<p>You can use:</p> <pre><code>#get original unique sorted values of groups orig = np.sort(df.groups.unique()) #add new groups for distinguish 0 in one group df['g'] = (df.runs != df.runs.shift()).cumsum() #filter only 0 values df = df[df.runs == 0] print (df) groups runs g 0 x 0 1 1 x 0 1 2...
python|pandas|apply
2
372,282
40,516,641
How to label columns of data as x and y
<p>I am new to coding and I have been having trouble plotting some imported data. I have been using:</p> <pre><code>import numpy as np import matplotlib as plt np.loadtxt('file_name') </code></pre> <p>and I would receive something like this but much longer, </p> <pre><code>array([[ 2.45732966e+06, 9.97563892e-01...
<p>Initialise matplotlib and the plotfunction</p> <pre><code>import matplotlib import matplotlib.pyplot as plt </code></pre> <p>store your data into an array (assuming its not several Gb of data)</p> <pre><code>array = np.loadtxt('file_name') </code></pre> <p>plot it. The [:,0] can be read like a matrix element whe...
python|numpy|matplotlib|plot
2
372,283
40,454,543
Symmetrization of scipy sparse matrices
<p>Is there a simple and efficient way to make a sparse scipy matrix (e.g. lil_matrix, or csr_matrix) symmetric? </p> <p>When populating a large sparse co-occurrence matrix it would be highly inefficient to fill in [row, col] and [col, row] at the same time. What I'd like to be doing is:</p> <pre><code>for i in data:...
<p>Yep, there is definitely a more efficient and simple way. hpaulj's answer should work if you are creating a matrix, but if you already have one, you can do:</p> <pre><code>rows, cols = sparse_matrix.nonzero() sparse_matrix[cols, rows] = sparse_matrix[rows, cols] </code></pre> <p>This should work for all types of ...
python|numpy|scipy
6
372,284
40,774,045
Join two Pandas Dataframes
<p>We have two tables:</p> <p><strong>Table 1: EventLog</strong></p> <pre><code>class EventLog(Base): """""" __tablename__ = 'event_logs' id = Column(Integer, primary_key=True, autoincrement=True) # Keys event_id = Column(Integer) data = Column(String) signature ...
<p>According to your data schema, you have incompatible types where <code>id</code> in <em>event_logs</em> is an Integer and <code>event_log_id</code> in <em>machine_event_logs</em> is a String column. In Python the equality of a string and its equivalent numeric value yields false:</p> <pre><code>print('0'==0) # Fals...
python|pandas|dataframe
2
372,285
40,343,061
Duplicate columns with Pandas merge?
<p>I have a data frame <code>a</code>:</p> <pre><code>ID value1 1 nan 2 nan 3 nan 4 nan 5 nan </code></pre> <p>and then two other data frames, <code>b</code> and <code>c</code>:</p> <pre><code>ID value1 2 20 3 10 ID value1 1 58 4 20 </code></pre> <p>When I do <cod...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas|merge|duplicates
3
372,286
40,551,492
Pandas merge on DatetimeIndex TypeError: object of type 'NoneType' has no len()
<p>take the following very simple example:</p> <pre><code>import pandas as pd import numpy as np import datetime base = datetime.datetime(2016, 10, 1) date_list = [base - datetime.timedelta(days=x) for x in range(0, 100)] df1 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'), index = date_l...
<p>In the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">documentation</a> it states that: "<code>left_on</code>" can be "label or list, or array-like" As you are passing "True" there comes the error. If you just omitt "left_on", it seems to work f...
python|pandas
2
372,287
40,763,482
Pandas: getting a list inside a dataframe as row
<p>I have a list like this:</p> <p><code>l1=[1,2,3,4,5,6,7,8]</code></p> <p>This list is supposed to be a row of a dataframe, which I create empty like this:</p> <p><code>df = pd.DataFrame(columns=['A','B','C','D','E','F','G','H'], index=['l1','l2','l3','l4'])</code></p> <p>Now I want the val...
<p>Use simply <code>list</code>:</p> <pre><code>df.loc['l1'] = l1 print (df) A B C D E F G H l1 1 2 3 4 5 6 7 8 l2 NaN NaN NaN NaN NaN NaN NaN NaN l3 NaN NaN NaN NaN NaN NaN NaN NaN l4 NaN NaN NaN NaN NaN NaN NaN NaN </cod...
python|pandas|dataframe|row|series
1
372,288
40,602,574
How to make an array like [[123][234][345]] using numpy?
<p>I have an array like <code> [1,3,4,5,6,2,1,,,,] </code></p> <p>now, I want to change it to <code> [[1,3,4],[3,4,5],[4,5,6],[5,6,2],,,,] </code></p> <p>How can I achieve this using numpy? Is there any function to do so? And, using loop is not an option. </p>
<p><a href="http://www.scipy-lectures.org/advanced/advanced_numpy/" rel="nofollow noreferrer">np.lib.stride_tricks.as_strided</a> method will does that. </p> <blockquote> <p>Here strides is (4,4) for 32 bit int. If you want more flexible code, I have commented stride parameter in the code. shape parameter determines...
python|numpy
2
372,289
40,393,663
How do I define a Dataframe in Python?
<p>I am doing some work in a jupyter notebook using python and pandas and am getting a weird error message and would really appreciate the help. The error I am receiving is "NameError: name 'DataFrame' is not defined" </p> <pre><code>import pandas as pd d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'], ...
<p>The below code works: </p> <pre><code>import pandas as pd d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'], 'age': [22,38,26,35], 'fare': [7.25, 71.83, 0 , 8.05], 'survived?': [False, True, True, False]} df = pd.DataFrame(d) print(df) </code></pre> <p>Instead of: </p> <pre><code>DataF...
python|pandas|dataframe
17
372,290
40,423,402
ValueError: logits and targets must have the same shape (tf.learn, DNNLinearCombinedClassifier)
<p>I'm trying to train the <a href="https://www.tensorflow.org/versions/r0.11/tutorials/wide_and_deep/index.html" rel="nofollow noreferrer">'Wide &amp; Deep Learning'</a> model on my own datasets, and this error occurs when I fit the model to the training set.</p> <pre><code>-------------------------------------------...
<p>The problem is you have to specify <code>n_classes=24</code> in <code>DNNLinearCombinedClassifier</code>'s constructor. See <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L606" rel="nofollow noreferrer">here</a> for documentation....
python|machine-learning|neural-network|tensorflow|deep-learning
0
372,291
40,568,438
Python pandas dataframe: find max for each unique values of an another column
<p>I have a large dataframe (from 500k to 1M rows) which contains for example these 3 numeric columns: ID, A, B</p> <p>I want to filter the results in order to obtain a table like the one in the image below, where, for each unique value of column id, i have the maximum and minimum value of A and B. How can i do?</p> <p...
<p>Sample data (note that you posted an image which can't be used by potential answerers without retyping, so I'm making a simple example in its place):</p> <pre><code>df=pd.DataFrame({ 'id':[1,1,1,1,2,2,2,2], 'a':range(8), 'b':range(8,0,-1) }) </code></pre> <p>The key to this is just using <code>i...
python|pandas|dataframe|grouping
8
372,292
40,522,981
Is there way to package Tensorflow for c++ api?
<p>I've been developing c++ project using a Tensorflow c++ api. it just execute created tensorflow's graph from Python. I build it using bazel with Tensorflow code now. But I think it's inefficient way.</p> <p>I want just Tensorflow library and header files, and Just compile my project only using Cmake.</p> <p>I know...
<p>As far as I know, there is no official distributable C++ API package. There is, however, <a href="https://github.com/FloopCZ/tensorflow_cc" rel="nofollow noreferrer">tensorflow_cc</a> project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. According to your desc...
c++|tensorflow
3
372,293
40,580,161
Issue with dropping columns
<p>I'm trying to read in a data set and dropping the first two columns of the data set, but it seems like it is dropping the wrong column of information. I was looking at <a href="https://stackoverflow.com/questions/26347412/drop-multiple-columns-pandas">this</a> thread, but their suggestion is not giving the expected...
<p>If I understand your question correctly, you have a multilevel index, so drop columns [0, 1] will start counting on non-index columns.</p> <p>If you know the position of the columns, why not try selecting it directly, such as:</p> <pre><code>df = df.iloc[:, 3:] </code></pre>
python-3.x|pandas
0
372,294
40,404,325
Finding max in numpy skipping some rows and column
<p>I want to find the max row and column index in a numpy matrix. But it not be in the a set of rows or columns. Thus, it should skip those rows and columns while computing the max.</p> <p><strong>Example:</strong></p> <pre><code># finding max in numpy matrix [row,col] = np.where(mat == mat.max()) </code></pre> <p>...
<p>Let <code>a</code> be the input array, <code>rows_rem</code> and <code>cols_rem</code> be the rows and column indices to be skipped respectively. We would have an approach using masking, like so -</p> <pre><code>m,n = a.shape d0,d1 = np.ogrid[:m,:n] a_masked = a*~(np.in1d(d0,rows_rem)[:,None] | np.in1d(d1,cols_rem)...
python|numpy|matrix
3
372,295
40,687,077
Applying a function to an entire DataFrame in Pandas
<p>Probably a trivial question, but how does one apply a function to an entire "matrix" with Pandas? It seems to me that apply either works row-wise or column-wise, but what if I want to do both? E.g.</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]}) &gt;&gt;&gt; df A B 0 10 ...
<p>This is usually not the way a DataFrame is used, since the columns may have different types.</p> <p>If, however, all columns have the same type, it may be sensible to cast the DataFrame to a matrix, like </p> <pre><code>m = df.as_matrix() </code></pre> <p>and then work with <code>m</code>, e.g.</p> <pre><code>m...
python|pandas
0
372,296
40,485,304
matplotlib pcolormesh artifact
<p>I have <a href="https://dl.dropboxusercontent.com/u/54733883/surface.txt" rel="nofollow noreferrer">a file</a> describing a grid over the earth with the format:</p> <pre><code>lon1,lat1,value1 lon2,lat2,value2 ... </code></pre> <p>I wrote the following script in order to plot it:</p> <pre><code>import matplotlib....
<p>Following the comment by @Eric </p> <blockquote> <p>Your problem is that latitudes and longitudes are cyclic, and your largest longitude value wraps around</p> </blockquote> <p>I've changed the code to reorder the longitudes before plotting so that they are continuous.</p> <pre><code>data=np.loadtxt('surface....
python|numpy|matplotlib
0
372,297
18,476,659
Pandas: replicating SASs proc means by attribute out=agg
<p>I have a function foo that operates on a dataframe; specifically two columns of the dataframe. So something like,</p> <pre><code>def foo(group): A = group['A'] B = group['B'] r1 = somethingfancy(A,B) #this is now a float r2 = somethinggreat(A,B) #this is another float return {'fancy':r1,'great':r2} </code...
<p>Instead of returning a <code>dict</code>, return a <code>Series</code>:</p> <pre><code>def foo(group): A = group['A'] B = group['B'] r1 = randn() r2 = randn() return Series({'fancy': r1, 'great': r2}) df = DataFrame(randn(10, 1), columns=['a']) df['B'] = np.random.choice(['hot', 'cold'], size=1...
python|pandas
2
372,298
18,529,657
How to get a graph axis into standard form
<p>I have plotted a graph where the scale on the y axis is large (10^6) however at the moment the axis is displaying the whole number. How can i get the axis to be displayed in standard form?</p> <pre><code>range_v=142 max_actual_diff=0 max_ID=0.0 for i in range(0,fev[ind_2008].shape[0]): id_temp=ID[ind_2008[i]]...
<p>This can be done by manually setting the format strings for the yticks:</p> <pre><code>x = plt.linspace(0, 10, 100) y = 1e6 + plt.sin(x) ax = plt.subplot(111) ax.plot(x, y) ax.set_yticklabels(["{:.6e}".format(t) for t in ax.get_yticks()]) plt.subplots_adjust(left=0.2) plt.show() </code></pre> <p><img src="https:/...
python|graph|numpy|matplotlib
2
372,299
18,418,963
How to install PIL (or any module really) to the raspberry pi?
<p>I want to install PIL and python-numpy at the least. I want to turn an image into an array but really can't seem to find info on installing/using modules to raspberry pi. Could somebody just explain?</p>
<p>Assuming that you are using the Raspberry Pi Foundation's recommended Raspbian image, those packages are available through the package manager. For numpy, you want to run this as root, using sudo if appropriate:</p> <pre><code>apt-get install python-numpy </code></pre> <p>Installing PIL is similar; just find the p...
python|numpy|python-imaging-library|raspberry-pi
2