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
365,800
72,040,032
How to append None to list if result contains none or multiple results
<p>I have a csv with URLs which contain data I need to extract. Sometimes, the URL contains none or multiple results, if that is the case, I want to append a <code>None</code>to the list.</p> <p>This is the code:</p> <pre><code>import os import glob import time from urllib.request import urlopen from numpy import full ...
<p>You should clean your code before posting it. It would be best to stick to a <a href="https://stackoverflow.com/help/minimal-reproducible-example">minimal reproducible example</a>. In your case you can remove the outer loop so that we can focus on the part causing problem.</p> <p>About your code: you should set vari...
python-3.x|pandas|csv
1
365,801
72,104,552
How to fix this error when take data in Python
<p>The problem here that when I put in user='U3' and debugging I see <strong>history1[:, 1][i1][j1]</strong> and <strong>transactions1[:, 0][m]</strong> have the same value. That is ['T500'] but the expression return false (also ['T600']) and when they are have value ['T1000'], they return true. And the last output is ...
<p>Your <code>history1</code> argument has spaces after T500 and T600.</p> <pre><code> [array(['U3'], dtype='&lt;U2') array(['T500 ', 'T600 ', 'T1000'], dtype='&lt;U5')] </code></pre> <p>Your <code>transaction1</code> argument does not.</p> <pre><code>[array(['T500'], dtype='&lt;U4') array(['I1', 'I3'], dtype='&lt;U2')...
python|arrays|numpy
1
365,802
72,138,628
File system for s3 already registered when importing tensorflow_io
<p>I installed tensorflow-io with <code>pip install tensorflow-io</code>, when I import it I get: <code>tensorflow.python.framework.errors_impl.AlreadyExistsError: File system for s3 already registered</code>.<br /> The trace is this.</p> <pre><code>import tensorflow_io as tfio File &quot;/opt/miniconda/lib/python3....
<p>Okey... after a bit more trying I found how to make it work, only with some warning popping up (but it works :D). <br> In my case, I am using a 3080 GPU an probably this is the reason why it doesn't work but anyway, here is the solution: <br></p> <ol> <li>(might be worth to start in a new environment)</li> <li>Go to...
python|tensorflow|tensorflow2.0
1
365,803
72,129,667
Create list of specific columns from statistical test
<p>Currently I am looking into stationarity of my data. I run the adfuller test for each of my variable and in the next steap I want to create a column list or rather a dataframe for the stationary and non-stationary data, so that I can change the list with pct.change.</p> <p>It looks like this atm:</p> <pre><code>prin...
<p>You are getting that result because you are also appending the content of the column(<code>df[[col]]</code>) to <code>col_list</code> instead of just the column name (<code>col</code>). To get just the column names, you can use:</p> <pre><code>print(&quot;Observations of Dickey-fuller test \n&quot;) print(&quot;stat...
python|pandas
0
365,804
71,962,118
How can I reorder one column in a way that the same serie of dates is repeated?
<p>Here's the thing.</p> <p>I'm building a dataframe so my students can use it in an exercise. This is what I was looking for:</p> <pre><code>id date n 0 2022-01-01 10 0 2022-01-02 30 0 2022-01-03 40 . . . 1 2022-01-01 0 1 2022-01-02 5 1 2022-01-03 16 . . . 2 2022-01-01 99 2...
<p>This'll do what it seems like you want:</p> <pre class="lang-py prettyprint-override"><code>start_date = pd.Timestamp(&quot;2022-01-01&quot;) purchase_low = 0 purchase_high = 500 num_ids = 100 num_days = 10 ids = np.repeat(np.arange(num_ids), num_days) dates = np.tile(pd.date_range(&quot;2022-01-01&quot;, periods...
python|pandas|dataframe|series
2
365,805
72,000,917
batch size > 1 gives an error using TensorFlow 1.x
<p>I am using <a href="https://github.com/nicola-decao/s-vae-tf/blob/master/examples/mnist.py" rel="nofollow noreferrer">this</a> example of a VAE.</p> <p>The only difference I made was change the loss from binary cross entropy to MSE, like this:</p> <pre><code>class OptimizerVAE(object): def __init__(self, model, lea...
<p>I solved the issue by reshaping the output from the decoder in form: (win_size, 1), since the MLP fails to add that extra dim'n in!</p>
tensorflow|keras|deep-learning|autoencoder|tensorflow1.15
0
365,806
72,090,117
bin value of histograms from grouped data
<p>I am a beginner in Python and I am making separate histograms of travel distance per departure hour. <a href="https://i.stack.imgur.com/ICXZE.png" rel="nofollow noreferrer">Data I'm using, about 2500 rows of this. Distance is float64, the Departuretime is str.</a> However, for making further calculations I'd like to...
<p>First of all, note that the bins used in the different histograms that you are generating don't have the same edges (you can see this since you are using <code>sharex=True</code> and the resulting bars don't have the same width), in all cases you are getting 10 bins (the default), but they are not the same 10 bins. ...
python|pandas|group-by|histogram|density-plot
0
365,807
71,841,566
Loop append of numpy array element in python
<p>Who can explain how to loop add an element to the numpy array by condition?</p> <p>I wrote some code that should do add element <code>2</code> if i element of array <code>A</code> is <code>0</code> and add element <code>1</code> if i element of array <code>A</code> is not <code>0</code>.</p> <p>Here is the code itse...
<p>For iteration like this it's better to use lists. <code>np.append</code> is just a poorly named cover for <code>np.concatenate</code>, which returns a whole new array with each call. List append works in-place, and is more efficient. And easier to use:</p> <pre><code>def finalconcat(somearray): rec = [2 if i==...
python|arrays|numpy|for-loop|append
0
365,808
71,869,423
select data from excel and save it as a variable
<p>I have an excel file which has few rows of string followed by data, I have to select data column wise and save it as a variable. I have tried using openpyxl module, and I have given the code that I am working below. I am able to print the variable nm and count inside loop, but outside loop only one value of the vari...
<p>The values for <code>nm</code> and <code>counts</code> will be the last value that is iterated in your loop. To access all of the variables, you would have to store them - in a list for example:</p> <pre><code>nm_all = [] counts_all = [] for x in lamda: for nm in x: nm_all.append(nm) for y in intensity:...
python|excel|pandas|variables|openpyxl
0
365,809
71,895,882
Multiply all and only numeric values of dataframe using lambda function
<p>Dataframe stu_alcol looks like following:</p> <pre><code>school sex age address famsize Pstatus Medu Fedu Mjob Fjob reason guardian 0 GP F 18 U GT3 A 4 4 at_home teacher course mother 1 GP F 17 U GT3 T 1 1 at_home other course father 2 GP F 15 U LE3 T 1 1 a...
<p>You can update the entire df to numeric, and let 'coerce' conver the non-numerics to NaN. Multiply that by 10 and update the original df.</p> <p>This should allow you to handle mixed-type columns properly as well.</p> <pre><code>df.update(df.apply(pd.to_numeric, errors='coerce').mul(10)) </code></pre>
python|pandas
2
365,810
71,987,287
How to filter a Pandas dataframe to keep entire rows/colums if a criterium is fullfilled?
<p>I am learning Python Pandas and I am having some trouble with data filtering. I have gone through multiple examples and I cannot seem to find an approach that fits my particular need:</p> <p>In a dataframe with numerical values, I would like to filter rows and columns by the following criterium:</p> <p>&quot;If ANY ...
<p>Use:</p> <pre><code>value = 123 df[df.gt(value).any(axis=1)] </code></pre> <p>For columns, this would be:</p> <pre><code>value = 123 df.loc[:, df.gt(value).any(axis=0)] </code></pre>
python|pandas|dataframe|filter
1
365,811
72,035,588
How to use pandas and numpy to compare two excel workbooks with multiple tabs?
<p>I have two xlsx files that have multiple tabs. I need to compare values in each tab based on the tab name. (e.g. sheet1 in file1 needs to be compared with sheet1 in file2 and so on). When I use the following code, it will only compare and write the first sheet. Please help me figure out why all tabs do not get compa...
<p>With the help of a colleague I was able to troubleshoot the problem with my excel sheet comparison code. Within the 'if' loop, df2 was being overwritten. I changed the name from df2 to df2sheet within the 'if' loop and now it works beautifully.</p> <pre><code>import pandas as pd import numpy as np df1 = pd.read_exc...
python|excel|pandas|numpy|compare
0
365,812
71,917,627
Running transfer learning for my binary classification model following ResNetV250 model on tensorflow: Value error
<p>I am trying to apply transfer learning (ResNetV250 &amp; EfficientnetB0) to my binary image classification model but got a Value Error while fitting the model.</p> <p>I add the final layer with the following parameter -&gt; <code>layers.Dense(num_classes, activation='sigmoid', name='output_layer')</code> where use <...
<p>For binary classification you don't need to use a <code>unit</code> in the <code>Dense</code> layer for each class, since that would be redundant. And in this case you <em>can't</em> do so in the first place, since you use the <code>binary_crossentropy</code> loss. Try adjusting <code>layers.Dense(num_classes)</code...
python|tensorflow|deep-learning|transfer-learning|binary-image
1
365,813
71,791,146
Detecting stock prices that are easy to go up and down in a short period
<p>I'm trying to use python to detect if the price of a stock is easy to go up and down in a short period.</p> <p>The yellow line in the following pictures are the stock prices:</p> <p>pic1 <a href="https://i.stack.imgur.com/xWrd2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xWrd2.png" alt="enter ...
<p>Just an idea, but it looks like you want a lot of absolute movement, with little relative movement. For example down $1.10, up 1, down $0.90 up $1.10</p> <p>Absolute movement would be the sum of the <em>absolute</em> value of the moves: <code>1.10 +1+0.9+1.10 =$4.10</code><br /> Relative movement would be the sum of...
python|pandas|math
0
365,814
71,928,654
How to read Json data with unbalanced array length in Python
<p>I have been trying to fetch Json data from an API using Python so that I can transfer that data to sqlite3 database. The issue is that the data is unbalanced. My end goal is to transfer this json data to a .db file in sqlite3. Here is what I did:</p> <pre><code>import pandas as pd url = &quot;https://baseballsavant....
<p>It's not obvious what you want your final DataFrame to look like, but appending &quot;orient='index'&quot; avoids the problem in this case.</p> <pre><code>import pandas as pd url = &quot;https://baseballsavant.mlb.com/gf?game_pk=635886&quot; df = pd.read_json(url, orient='index') print(df) </code></pre> <p>You could...
python|pandas|database|api
0
365,815
71,820,572
Parse data from a dict with condition - pandas dataframe
<p>My pandas DataFrame has a few missing and bad values. I'd like to replace / fill this by parse data from a dictionary stored in a pandas series. Here's an example:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Addr': ['123 Street, City, 85036', '234 Street1, City, 85036', '542js'], 'Lat'...
<p>You can normalize the 'CL' column and join the newly created columns to 'Addr' and 'Lat'. Then change the values of <code>Lat</code> to 'latitude' where it's <code>np.nan</code>:</p> <pre><code>df = df[['Addr', 'Lat']].join(pd.json_normalize(df['CL'])) df.loc[df['Lat'].isna(), 'Lat'] = df.loc[df['Lat'].isna(), 'lati...
python|pandas|dictionary
2
365,816
71,963,565
Scatter plot order by hue
<p>Is there a way to set parameter to order the hue value in a scatter plot? For example I want to only show 3 values and have 3 different colors . In the chart below seaborn automatically makes 6 values and assigned a color. I'm trying to do something like this: if X &gt; 0.06 red, between 0.06 and 0.08 yellow and eve...
<p>You can try creating a new column with a new label for your conditions and plot the graph with hue as the new column.</p> <pre><code># create new column and label with defined conditions store_avg.loc[(store_avg['MOP_GC_PCT'] &gt;= 0.09), 'MOP_GC_PCT_bins'] = 'more than 0.08' store_avg.loc[(store_avg['MOP_GC_PCT'] &...
pandas|matplotlib|seaborn
2
365,817
71,983,331
Filter for most recent event by group with pandas
<p>I'm trying to filter a pandas dataframe so that I'm able to get the most recent data point for each account number in the dataframe. Here is an example of what the data looks like. I'm looking for an output of one instance of an account with the product and most recent date.</p> <pre><code>account_number product s...
<p>Would the keyword 'first' work ? So that would be:</p> <pre><code>data.groupby('account_number')['sale_date'].first() </code></pre>
python|pandas|date|filter|pandas-groupby
0
365,818
71,824,867
Databricks notebook runs faster when triggered manually compared to when run as a job
<p>I don't know if this question has been covered earlier, but here it goes - I have a notebook that I can run manually using the 'Run' button in the notebook or as a job.</p> <p>The runtime for running the notebook directly is roughly 2 hours. But when I execute it as a job, the runtime is huge (around 8 hours). The p...
<p>When running a notebook as a Job, you have to define a &quot;job cluster&quot; (in the contrast with an &quot;interactive cluster&quot; where you can attach to the notebook and hit run). There is a possible delay when the &quot;job cluster&quot; has to be spun up, but this usually only takes less than 10 minutes. Ot...
python|pyspark|databricks|pmdarima|pandas-udf
0
365,819
71,834,964
Sample Pandas Dataframe with equal number based on binary column
<p>I have a dataframe with a <code>data</code> column, and a <code>value</code> column, as in the example below. The <code>value</code> column is always binary, 0 or 1:</p> <pre><code>data,value 173,1 1378,0 926,0 643,0 1279,0 472,0 706,0 1345,0 1167,1 1401,1 1236,0 447,1 1204,1 398,0 714,0 734,0 1732,0 98,0 1696,0 160...
<p>Group your dataframe by values, and then take a sample of the smallest count from each group.</p> <pre><code>grouped = df.groupby(['value']) smallest = grouped.count().min().values try: # Pandas 1.1.0+ print(grouped.sample(smallest)) except AttributeError: # Pre-Pandas 1.1.0 print(grouped.apply(lambda df: df.s...
python|pandas|dataframe
1
365,820
72,012,067
PyTorch Dataloader: Dataset complete in RAM
<p>I was wondering if the PyTorch Dataloader can also fetch the complete dataset into RAM so that performance does not suffer if there is enough RAM available</p>
<p>You can extend <a href="https://pytorch.org/docs/stable/data.html" rel="nofollow noreferrer">torch.util.data.Dataset</a> and create your own Dataset implementation. In the <code>__init__</code> function of your custom dataset you can then load all data in a list or any other data structure, which will be fully loade...
pytorch|pytorch-dataloader
2
365,821
71,971,291
Is there a way to filter all columns of a pandas dataframe against a list?
<p>I have a list of taxonomic classifications that are not uniform across their levels within the list and I want to filter all the columns of a data-frame against each item of the list to produce a singular sub-data-frame.</p> <p>An example list would be</p> <pre><code>['Sk1','Sub1','Family 3','Clade C'] </code></pre>...
<p>Assuming other columns cannot contain the same strings from other columns (e.g. <code>Clade</code> column cannot contain <code>Family 3</code>, etc.), you can use <code>isin</code> + <code>any</code> to create a boolean mask to filter <code>df</code>:</p> <pre><code>out = df[df.isin(['Sk1','Sub1','Family 3','Clade C...
python-3.x|pandas|dataframe|filter
3
365,822
71,903,314
Create new column for each unique value in other column in pandas dataframe
<p>In my dataset I have value for each region(West, South, East and Central) at the start of each month from 2015-2018.</p> <p>I need to transform the dataset in the next way: I want to create columns for each region remove column &quot;Value&quot;: Datetime Central West East South 2015-01-01 0.1 0.2 0.3 0.4</p> <p>How...
<p>You can try <code>df.pivot</code></p> <pre class="lang-py prettyprint-override"><code>df.pivot(index='Datetime', columns='Region', values='Value').reset_index() </code></pre>
pandas|dataframe
0
365,823
72,032,077
Count how often second element is second element
<p>I have a dataframe with a column CCC that contains three-letter items. I want to count how often does each letter/element happen as first, second or third element. For example, if I have strings &quot;spr&quot; and &quot;str&quot; I have &quot;s&quot; two times as first letter, &quot;p&quot; one time as second lette...
<p>You would use .str[position]</p> <p>So Below is the solution:</p> <pre><code>df = pd.DataFrame() df['CCC'] = ['spr','str'] elements = [&quot;p&quot;,&quot;b&quot;,&quot;t&quot;,&quot;d&quot;,&quot;k&quot;,&quot;g&quot;,&quot;f&quot;,&quot;v&quot;,&quot;s&quot;,&quot;&lt;&quot;,&quot;z&quot;,&quot;S&quot;,&quot;Z&qu...
python|pandas
0
365,824
71,801,354
Effective look up between two pandas dataframe using vectorization
<p>I have two pandas dataframe: one is the main data (df1) and the other a look up table (df2).</p> <p>main data</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column1</th> <th>...</th> </tr> </thead> <tbody> <tr> <td>[Data 1, Data 2, Data 3, ...]</td> <td>...</td> </tr> <tr> <td>[Data 11,...
<p>As I understand what you are trying to accomplish, you want to add a column to the main data shown below as df1. This column should contain a dictionary with the locations defined in df2 for each entry in the list of the df1 column.</p> <p>While I have no idea why you need this and certainly would look for a better...
python|pandas|dataframe|vectorization|series
0
365,825
71,811,519
Replace the destination excel document using python pandas based on a value?
<p>I'm currently writing a reasonably basic encryption algorithm for my CS Coursework, where the encryption is based on pre-defined shuffles which are based on a 64 character ASCII clone I made (0-9, lowercase alphabet, uppercase alphabet, apostrophe and space).</p> <p>The encryption key is based on two random HEX valu...
<p>As Jon mentions, you could do string formatting. Example:</p> <pre><code>filename='spreadsheet'+key2+'.xls' excel_file =pd.read_excel(r'C:###\{}'.format(filename)) </code></pre>
python|excel|pandas
0
365,826
72,081,711
Do gradient descent on function with no input using pytorch
<p>What's the correct way to do gradient descent on an arbitrary function with <em>no</em> input using Pytorch?</p> <pre><code>x = torch.tensor(x_init, requires_grad=True) opt = torch.optim.Adam([x]) cost_fnx = cost(x) for iteration_count in range(100): opt.zero_grad() cost_fnx.backward() opt.step() </code>...
<p>The error occurs because you are trying to backpropagate on the same graph multiple times. You most likely need to recompute the cost value (your <em>regularizer</em> function since it only has the model's parameters as input) to backpropagate again. Something like:</p> <pre><code>x = x_init.requires_grad_(True) opt...
pytorch
0
365,827
72,007,544
Getting data into a map
<p>I got my .dat data formatted into arrays I could use in graphs and whatnot.</p> <p>I got my data from this website and it requires an account if you want to download it yourself. The data will still be provided below, however.</p> <p><a href="https://daac.ornl.gov/cgi-bin/dsviewer.pl?ds_id=1028" rel="nofollow norefe...
<p>You don't need to get the data into an array. Just apply <code>df.values</code> and you would have a <code>numpy</code> array of all the data in the dataframe.</p> <p>Example -</p> <pre><code>array([[-1.78750e+02, -7.70000e+01, 3.00000e-06, 3.21287e+04], [-1.76250e+02, -7.70000e+01, 5.99000e-04, 3.21287e+...
python|numpy|matplotlib
0
365,828
72,024,947
MinMaxScaler to ExtraTreesClassifier
<p>I am trying to implement ExtraTreesClassifier normalization with a specified <strong>gini</strong> value to my dataframe. I have MinMaxScaler designed which successfully ran. But I wasn't able to implement ExtraTreesClassifier.</p> <p>MinMaxScaler:</p> <blockquote> <pre><code>mM = MinMaxScaler(feature_range=(0, 1)) ...
<p>For the training part, you need to pass the target of your <code>arr</code>. Without that, you can't optimize the ExtraTreesClassifier and calculate the Gini coefficient.</p> <p>For reference, take a look at <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html" rel="n...
python|pandas|dataframe|machine-learning|database-normalization
1
365,829
71,908,345
pandas calculating median values based on the same time stamps
<p>I'd like to calculate median value of data based on the same timestamp with Pandas.</p> <p>An example of my partial dataframe looks like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">timestamp</th> <th style="text-align: left;">data</th> </tr> </thead> <t...
<p>One option is to call <code>median</code> in <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.transform</code></a>. It returns a Series having the same indices as <code>df</code> filled with the transformed median value...
python|python-3.x|pandas|pandas-groupby
1
365,830
71,824,207
Is there a way to change scale of y axis in python plot?
<p>Currently i am able to generate this plot to calculate number of people using applications, but i am getting y axis values as in decimals ,where in people cannot be in decimals. how can i change this ?</p> <pre><code>df_pivot=pd.pivot_table(df_removed1,index=['Module'],columns=['Date'], aggfunc='size').plot(kind='ba...
<p>You can try to give <code>yticks()</code> the integers generated by <code>range()</code>:</p> <pre><code>plt.yticks(range(0,2)) </code></pre> <p>Otherwise you can try:</p> <pre><code>from matplotlib.ticker import MaxNLocator plt.yaxis.set_major_locator(MaxNLocator(integer=True)) </code></pre>
python|pandas
1
365,831
71,910,255
Algorithm to know how often the event happened during some period of time within greater time range (Pandas)
<p>For example, I have Pandas dataset df of two columns: ['number'] and ['date']. In ['number'] column various numbers are placed, in ['date'] column date and time, when the number appeared, were placed in Epoch Unix Timestamp format.</p> <p>How can I count whether the particular number, for instance 20, appeared more ...
<p>I don't follow the logic of your code. For a given index <code>i</code>, you set a <code>time</code> boundary of <code>date[i] + 100</code>, then look up through the entire dataframe for rows with time greater than that boundary.</p> <p>Anyway, I'm going from the text of your question instead. The following counts t...
python|pandas|algorithm
1
365,832
71,907,567
ValueError: GeoDataFrame does not support multiple columns using the geometry column name 'geometry'
<p>I am receiving this error when I try to upload a csv file as a geodataframe.According to other questions resolutions on this site, this method should do the trick.</p> <p>Here is the code that I am using to: upload the file as a gdf, then produce a subset dataframe with only some of the columns present.</p> <pre><co...
<ul> <li>using your sample data to create a CSV. Had to replace <em>geometry</em> as sample is not a valid WKT string</li> <li>re-produced your error</li> <li>solved by loading using <strong>pandas</strong> then converting to <strong>geopandas</strong></li> </ul> <h3>solution</h3> <pre><code>df = pd.read_csv(f) cp_uni...
dataframe|csv|geometry|geopandas
1
365,833
71,945,923
create a new column based on cumulative occurrences of a specific value in another column pandas
<p>I want to count the number of occurrences of one specific value (string) in one column and write it down in another column cumulatively.</p> <p>For example, counting the cumulative number of <code>Y</code> values here:</p> <pre><code>col_1 new_col Y 1 Y 2 N 2 Y 3 N 3 </code></pre>...
<p>To count both values cumulatively you can use:</p> <pre><code>df['new_col'] = (df .groupby('col_1') .cumcount().add(1) .cummax() ) </code></pre> <p>If you want to focus on 'Y':</p> <pre><code>df['new_col'] = (df .groupby('col_1') ...
pandas|cumulative-frequency
1
365,834
71,979,347
Converting a data frame of events into a timetable format
<p>I am working on converting a list of online classes into a heat map using Python &amp; Pandas and I've come to a dead end. Right now, I have a data frame 'data' with some events containing a day of the week listed as 'DAY' and the time of the event in hours listed as 'TIME'. The dataset is displayed as follows:</p> ...
<p>IIUC you can do something like this:</p> <p><code>df</code> is from your given example data.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'ID': [108, 110, 112, 114, 116, 639, 640, 641, 642, 643], 'TIME': [15, 15, 16, 16, 15, 12, 12, 18, 16, 15], 'DAY': ['Saturday','Sunday','Wednesday','Friday'...
python|pandas|dataframe
1
365,835
71,842,159
Python Pandas multiindex
<p>i'm try create table like in example: <a href="https://i.stack.imgur.com/tpClf.png" rel="nofollow noreferrer">Example_picture</a></p> <p>My code:</p> <pre><code>data = list(range(39)) # mockup for 39 values columns = pd.MultiIndex.from_product([['1', '2', '6'], [str(year) for year in range(2007, 2020)]], ...
<p>You need to wrap the <code>data</code> in a list to force the DataFrame constructor to interpret the list as a row:</p> <pre><code>data = list(range(39)) columns = pd.MultiIndex.from_product([['1', '2', '6'], [str(year) for year in range(2007, 2020)]], ...
python|pandas|dataframe
0
365,836
72,137,456
How to append two cell values located in the same dataframe column?
<pre><code> Disclosure Source 35 36 37 38 39 202-1 GRI 202: Market Presence 40 2016 41 42 43 </code></pre> <p>The Source Column has empty values, before removing them I would like to know how can I merge &quot;GRI 202: Market Presence&quot; with &quot;2016...
<p>With the following toy dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;Disclosure&quot;: [&quot;&quot;, &quot;&quot;, &quot;202-1&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;202-2&quot;, &quot;&quot;, &quot;&quot;], &quot;S...
python|pandas|dataframe|jupyter-notebook
1
365,837
72,078,664
How do I convert numpy.datetime64('2022-04-20T00:00:00.000000000') to datetime.date(2022, 4, 04)
<p>I have a column <code>df['Date]</code> which is a datetime64[ns] type and after doing the</p> <pre class="lang-py prettyprint-override"><code>sheets= sorted(df['Date'].unique(), reverse =True) </code></pre> <p>I get a <code>numpy.datetime64('2022-04-20T00:00:00.000000000')</code> format, but I want it to be of this ...
<p>try to use something like this :</p> <pre><code>test = datetime.datetime.strptime(&quot;2022-04-20T00:00:00.000Z&quot;,&quot;%Y-%m-%dT%H:%M:%S.%fZ&quot;) new_format = &quot;%Y-%m-%d&quot; test.strftime(new_format) </code></pre>
python|numpy|datetime|datetime-format
0
365,838
72,016,709
StackingClassifier Raises Exception 'numpy.ndarray' object has no attribute 'columns'
<p>I am trying to train a StackingClassifier in Sklearn, but I keep running into this error where the fit method seems to be complaining about me having passed it numpy arrays. To my knowledge, this is how all the fit methods in sklearn are supposed to work. I read and followed the example from <a href="https://scikit-...
<p>Your categorical pipeline chains two column transformers together. After the first one, the output is a numpy array, but then the second one cannot select transformers by column name as you've requested. Notice the final error message is more informative here, <code>ValueError: Specifying the columns using strings i...
python|numpy|scikit-learn
1
365,839
72,097,716
Convert series to pandas dataframe given the index as two columns with the same name and can t use reset_index
<p>I have a series like this:</p> <pre><code>transaction_date transaction_date ticker 2012 9 DD 1 12 DD 1 2013 3 DD 1 4 CG 1 6 DD ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rename_axis.html" rel="nofollow noreferrer"><code>Series.rename_axis</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html" rel="nofollow noreferrer"><code>Series.reset_ind...
python|pandas|series
0
365,840
71,914,973
Unify equal values ​in different column in pandas?
<p>Suppose I have a column like so:</p> <pre><code>COLUMN A abc dbe dbe abc abc ajk dbe abc </code></pre> <p>I expected the follow output:</p> <pre><code>KEY abc1 dbe1 dbe2 abc2 abc3 ajk1 dbe3 abc4 </code></pre> <p>The point is to give uniquen...
<p>Try this:</p> <pre><code>df['key'] = df.groupby('COLUMNA').cumcount().add(1) df['key'] = df['COLUMNA'] + df['key'].astype(str) print(df) COLUMNA key 0 abc abc1 1 dbe dbe1 2 dbe dbe2 3 abc abc2 4 abc abc3 5 ajk ajk1 6 dbe dbe3 7 abc abc4 </code></pre>
python|pandas|merge-conflict-resolution
1
365,841
71,915,780
How to add a missing index observation in a multi Index
<p>I frequently get new datasets with new variables from time to and want to make them symmetrical for comparison purposes.</p> <p>Data is multiple indexed, where each profile can have an impact from [-2,+2] with values varying over the years.</p> <p>A) CAN'T --&gt; Don't understand how to add missing profile index 'RP...
<p>IIUC, do you want?</p> <pre><code>mux = pd.MultiIndex.from_product([list_profile, np.arange(-2,2+1)], names=['profile', 'impact']) df.set_index(['profile', 'impact']).reindex(mux, fill_value=0).reset_index() </code></pre> <p>Output:</p> <pre><code> profile impact 2020 2021 0 gun -2 0 0 1 ...
python|pandas|dataframe
1
365,842
72,125,292
data time Format recognition in exported excel with xlsxwriter
<p>I didn't find a solution for this:</p> <p>From a dataframe I generate an excel and some columns need to be in format hh:mm:ss (with no limit to 24h, for example a value can be '28:39:13'.</p> <p>When generating the excel everything looks okay. But when operating with the values of the cells isn't working properly un...
<p>The best way to solve this would be to convert the time strings to datetime objects and then set '[h]:mm:ss' as the datetime_format in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer">pandas.ExcelWriter</a>. However, I don't think it is possible t...
excel|pandas|dataframe|export-to-excel|xlsxwriter
0
365,843
71,807,860
numpy where with multiple conditions linked to dataframe
<p>I'm using numpy where with multiple conditions to assign a category based on a text string a transaction description.</p> <p>Part of the code is below</p> <pre><code>`import numpy as np conditions = [ df2['description'].str.contains('AEGON', na=False), df2['description'].str.contains...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>import re df_conditions[&quot;Condition&quot;] = df_conditions[&quot;Condition&quot;].str.lower() df_conditions = df_conditions.set_index(&quot;Condition&quot;) tmp = df[&quot;Description&quot;].str.extract( &quot;(&quot; + &quot;|&quot;.join(re.escape(c...
python|string|numpy
0
365,844
71,880,142
Fetching the first few characters of a column from a csv file using pandas
<p>I have a csv file which contains some data, here I will put some data.</p> <p><a href="https://i.stack.imgur.com/9CgqL.jpg" rel="nofollow noreferrer">enter image description here</a></p> <ul> <li>I need to fetch the first two characters from the 'ID' column as an output, where the Quantity = 10 and Max value is gr...
<p>This does the job:</p> <pre><code>df = pd.read_csv(***csv file path***) df[&quot;Max value num&quot;] = [int(max_val[:2]) for max_val in df[&quot;Max value&quot;]] desired_data = df[(df[&quot;Quantity&quot;] == 10) &amp; (df[&quot;Max value num&quot;] &gt;= 40)] desired_data = [id[:2] for id in desired_data[&quot;I...
python|pandas
0
365,845
71,801,877
How to filter column based on another column date range
<p>I currently have a dataframe where 1st column is dates (1990 - 2020) and the subsequent columns are 'stocks' that are trading and are NaN if they are not yet being traded. Is there any way to filter the columns based on date range? For example, if 2 years is selected, all stocks that are not null in all columns fro...
<p>You could try the following code:</p> <pre class="lang-py prettyprint-override"><code>df[(df['date'] &gt;= '2019-01-01') &amp; (df['date'] &lt;= '2020-12-30')] </code></pre> <p>Once you filter, you could remove all rows, which include NaN:</p> <pre class="lang-py prettyprint-override"><code>df.dropna() </code></pre>
python|pandas|dataframe|datetime
0
365,846
71,870,731
K-Means Clustering having error of "Too many indexers" when multiple columns are given
<p>The code below is of K-Means Clustering copied from <a href="https://www.analyticsvidhya.com/blog/2019/08/comprehensive-guide-k-means-clustering/#h2_10" rel="nofollow noreferrer">www.analyticsvidhya.com</a></p> <pre><code>K=3 # Select random observation as centroids Centroids = (X.sample(n=K)) plt.scatter(X[&quot;D...
<p>Here's scikit learns' k-means:</p> <pre><code>from sklearn.cluster import KMeans import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('stack_overflow.csv') X = df.iloc[:,1:] plt.scatter( X['DATE_ID'], X.iloc[:, -1], c='white', marker='o', edgecolor='black', s=50 ) plt.show() k = 3 km =...
python|numpy|machine-learning|cluster-analysis|k-means
0
365,847
71,850,862
why this line in code is showing me an error: napi.download_dataset(file, f"data/ {Current_Round} / {file}")
<p>Below is the code.</p> <pre><code># !pip install numerapi from pathlib import Path import pandas as pd import matplotlib.pyplot as plt from numerapi import NumerAPI napi = NumerAPI() napi.download_dataset(&quot;v4/train.parquet&quot;, &quot;train.parquet&quot;) # To get the current round Current_Round =napi.get_c...
<p>You wrote this:</p> <pre><code> napi.download_dataset(file, f&quot;data/ {Current_Round} / {file}&quot;) </code></pre> <p>and wound up with this diagnostic:</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'data/ 311 / v3/numerai_live_data_int8.csv' </code></pre> <p>I don't know for certai...
python|pandas|google-colaboratory
0
365,848
72,092,878
Python giving this error message when retrieving data from CSV file: "unhashable type: 'Series' "
<p>So I'm importing and reading a CSV (Excel) file to gather the mean and standard deviation of certain criteria.Here is the code that I've generated to open it and read it as well as it's corresponding shape.</p> <pre><code>data=pd.read_csv(&quot;Factors_Monthly.csv&quot;) shape_data=(data.shape) print(&quot;Data Shap...
<p>You don't need to use the <code>statistics</code> module. <code>pandas</code> has its own <code>mean</code> function. Try:</p> <pre><code>average = data.loc[data[&quot;year&quot;].ge(2000),&quot;mktrf&quot;].mean() </code></pre>
python|pandas|csv|statistics
0
365,849
71,847,150
Dask still Slower than Pandas on Large Dataset 3.2 Go
<p>I am currently Trying Dask locally (parallel processing) for the first Time on a large Dataset (3.2 Go). I am comparing Dasks speed with pandas on simple computations. Using Dask seems to result in slower execution time in any task beside reading and transforming data.</p> <p>example:</p> <pre><code>#pandas code imp...
<p>Avoid calling compute repeatedly: For example for these simple operations, do something like this</p> <pre><code> xmin, xmax = dask.compute(df.x.min(), df.x.max()) </code></pre>
pandas|parallel-processing|dask|dask-dataframe|dask-ml
2
365,850
72,138,544
Pandas: Calculate Difference between a row and all other rows and create column with the name
<p>We have data as below</p> <pre><code> Name value1 Value2 finallist 0 cosmos 10 20 [10,20] 1 network 30 40 [30,40] 2 unab 20 40 [20,40] </code></pre> <p>is there any way to do difference between all the rows</p> <p>Something final output like</p> <pre><code> Name value1 Val...
<p>You want the pairwise absolute difference of the sum of the values for each row. The easiest might be to use the underlying numpy array.</p> <h4>absolute difference of the sum of the &quot;value&quot; columns</h4> <pre><code># get sum of values per row and convert to numpy array a = df['value1'].filter(regex='(?i)va...
python|pandas|dataframe|numpy
3
365,851
16,838,659
dataframe columnwise comparision to another series
<p>It seems dataframe.le doesn't operate column wise fashion. </p> <pre><code>df = DataFrame(randn(8,12)) series=Series(rand(8)) df.le(series) </code></pre> <p>I would expect for each column in <code>df</code> it will compare to <code>series</code> (so total 12 columns comparison with <code>series</code>, so 12 colu...
<p>I'm not sure I understand the first part of your question, but as to the second part, you can count the <code>True</code>s in a boolean DataFrame using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>In [11]: df.le(s).sum(...
pandas
1
365,852
16,743,861
grouping data in arrays (python)
<p>I'm trying to make a nice ordered way of grouping objects in an array. Now I've tried the following, but it gives me an error. </p> <p>Any tips?</p> <pre><code>#body: mass, [x,y], [vx,vy], [ax, ay] bodies = np.array([[1E3, [0,0], [0,0], [0.0]],\ [1, [0,200], [31.6,0], [0,0]]]) </code></pre> <blockquote>...
<p>You can use <code>dtype=object</code>, and then store anything you wantβ€”floats, tuples, lists, arrays. But really, that's not a good idea; you pretty much lose all the benefits of numpy.</p> <p>And, because it's a bad idea, numpy doesn't make it easy for you. If you construct an array out of a list, it assumes any ...
python|arrays|numpy
3
365,853
16,972,557
How do I group by nth business day within month in Pandas?
<p>I have a DataFrame grouped by (year, month). I'd like to look at statistics of the nth row in each (year, month) group -- what's the best way to do that?</p> <p>So my setup is something like this:</p> <pre><code>import pandas as pd import numpy as np index = pd.bdate_range('2012-1-1', periods=250) data = np.rand...
<p>You will be happy to discover the method called <code>nth</code>. To access the 9th entry for each month, for example,</p> <pre><code>In [15]: group.nth(9) Out[15]: A B C D 2012 1 0.259695 0.670270 0.467452 0.796057 2 0.744701 0.633857 0.530602 0.978068 3...
python|pandas
0
365,854
17,070,333
using SciPy to integrate a function that returns a matrix or array
<p>I have a symbolic array that can be expressed as:</p> <pre><code>from sympy import lambdify, Matrix g_sympy = Matrix([[ x, 2*x, 3*x, 4*x, 5*x, 6*x, 7*x, 8*x, 9*x, 10*x], [x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11]]) g = lambdify( (x), g_sympy ) </code></pre> <p>So...
<p>The first argument to either <code>quad</code> or <code>quadrature</code> must be a callable. The <code>vec_func</code> argument of the <code>quadrature</code> refers to whether the <em>argument</em> of this callable is a (possibly multidimensional) vector. Technically, you can <code>vectorize</code> the <code>quad<...
python|matrix|numpy|scipy|numerical-integration
6
365,855
16,910,114
Delete a group after pandas groupby
<p>Is it possible to delete a group (by group name) from a groupby object in pandas? That is, after performing a groupby, delete a resulting group based on its name.</p>
<p>Filtering a DataFrame groupwise has been <a href="https://stackoverflow.com/questions/13446480/python-pandas-remove-entries-based-on-the-number-of-occurrences#comment18556837_13447176">discussed</a>. And a future release of pandas may include <a href="https://github.com/pydata/pandas/pull/3680" rel="noreferrer">a mo...
python|pandas
19
365,856
16,815,928
What does [:, :] mean on NumPy arrays
<p>Sorry for the stupid question. I'm programming on PHP but found some nice code on Python and want to "recreate" it on PHP. But I'm quite frustrated about the line</p> <pre><code>self.h = -0.1 self.activity = numpy.zeros((512, 512)) + self.h self.activity[:, :] = self.h </code></pre> <p>But I don't understand w...
<p>The <code>[:, :]</code> stands for everything from the beginning to the end just like for lists. The difference is that the first <code>:</code> stands for first and the second <code>:</code> for the second dimension.</p> <pre><code>a = numpy.zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0....
python|arrays|numpy|matrix-indexing
48
365,857
17,114,904
python pandas replacing strings in dataframe with numbers
<p>Is there any way to use the mapping function or something better to replace values in an entire dataframe?</p> <p>I only know how to perform the mapping on series.</p> <p>I would like to replace the strings in the 'tesst' and 'set' column with a number for example set = 1, test =2</p> <p>Here is a example of my data...
<p>What about <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="noreferrer"><code>DataFrame.replace</code></a>?</p> <pre><code>In [9]: mapping = {'set': 1, 'test': 2} In [10]: df.replace({'set': mapping, 'tesst': mapping}) Out[10]: Unnamed: 0 respondent brand engi...
python|replace|dataframe|pandas
87
365,858
16,992,713
Translate every element in numpy array according to key
<p>I am trying to translate every element of a <code>numpy.array</code> according to a given key:</p> <p>For example:</p> <pre><code>a = np.array([[1,2,3], [3,2,4]]) my_dict = {1:23, 2:34, 3:36, 4:45} </code></pre> <p>I want to get:</p> <pre><code>array([[ 23., 34., 36.], [ 36., 34., 45.]]...
<p>I don't know about efficient, but you could use <code>np.vectorize</code> on the <code>.get</code> method of dictionaries:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,3], [3,2,4]]) &gt;&gt;&gt; my_dict = {1:23, 2:34, 3:36, 4:45} &gt;&gt;&gt; np.vectorize(my_dict.get)(a) array([[23, 34, 36], ...
python|numpy
130
365,859
19,181,367
Using broadcasting to multiply matrix rows according to elements in a vector?
<p>Let's say I have a matrix</p> <pre><code>x=array([[ 0., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.], [ 0., 1., 1.], [ 1., 0., 0.], [ 1., 0., 1.], [ 1., 1., 0.], [ 1., 1., 1.]]) </code></pre> <p>I want to get</p> <pre><code>array([[ 0., 0., 0.], [...
<pre><code>x * np.arange(1, 9).reshape(-1, 1) </code></pre> <p>or</p> <pre><code>x * arange(1, 9)[:, np.newaxis] </code></pre> <p>Both forms make a column vector out of <code>arange(1, 9)</code>, which broadcasts nicely along the y axis of <code>x</code>.</p> <p>"The same operation for columns" is just the transpos...
python|numpy
4
365,860
18,899,440
Tkinter indeterminate progress bar not running
<p>I'm currently creating a Tkinter Gui for Python 2.7 and having trouble working the progress bar. I need to load largish files into my program which takes some time, so I wanted to get a progress bar to show the user the program isn't frozen loading the files. Unfortunately my progress bar does not seem to update whi...
<p>Python "threads" are all still sort of locked together sequentially by what's called the GIL, global interpreter lock. It basically means that threads spawned from the same python process won't run in parallel like you want them to. Instead, they all fight for time on the main python process. </p> <p>In your case, ...
python|pandas|tkinter|progress-bar
0
365,861
18,919,699
python pandas complex number
<p>I am using pandas which very efficiently sorts/filters the data they way I need.</p> <p>This code worked fine, until I changed the last column to a complex number; now I get an error.</p> <blockquote> <p>return self._cython_agg_general('mean') raise DataError('No numeric types to aggregate') pandas.core.groupb...
<p>The parse doesn't support reading of complex directly, so do the following transform.</p> <pre><code>In [37]: df['X.8'] = df['X.8'].str.replace('i','j').apply(lambda x: np.complex(x)) In [38]: df Out[38]: X.1 X.2 X.3 X.4 X.5 X.6 X.7 X.8 0 564991.15 7371277.89 0 1...
python|pandas
5
365,862
19,023,512
error with reading float from two column text file into an array in Python
<p>I have a text file which contains 2 columns separated by a tab, containing some data that I would like to read into arrays and perform some simple operations for instance plot the data. The data in the second column is in scientific notation and can takes extremely small values such varying from order of magnitude 1...
<p>Don't reinvent the wheel!, it would be much more easy to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="noreferrer"><code>numpy.loadtxt</code></a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import matplotlib.pyplot as plt &gt;&gt;&gt; data = np.loadtxt('d...
python|numpy|matplotlib
8
365,863
18,922,407
boolean and type checking in python vs numpy
<p>I ran into unexpected results in a python <code>if</code> clause today:</p> <pre><code>import numpy if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5): print 'close enough' # works as expected (prints message) if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5) is True: print 'close enough' # does NOT work as expec...
<p>You're doing something which is considered an anti-pattern. Quoting <a href="http://www.python.org/dev/peps/pep-0008/#programming-recommendations" rel="noreferrer">PEP 8</a>:</p> <blockquote> <p>Don't compare boolean values to True or False using ==.</p> </blockquote> <pre><code>Yes: if greeting: No: if gre...
python|numpy|boolean|pep8
22
365,864
19,085,280
Pandas Merge Error: MemoryError
<h1>Problem:</h1> <p>I'm trying to two relatively small datasets together, but the merge raises a <code>MemoryError</code>. I have two datasets of aggregates of country trade data, that I'm trying to merge on the keys year and country, so the data needs to be particularity placed. This unfortunately makes the use of <c...
<p>In case anyone coming across this question still has similar trouble with <code>merge</code>, you can probably get <code>concat</code> to work by renaming the relevant columns in the two dataframes to the same names, setting them as a <code>MultiIndex</code> (i.e. <code>df = dv.set_index(['A','B'])</code>), and then...
python|merge|pandas
3
365,865
22,395,153
Pandas: merge miscellaneous keys into the "others" row
<p>I have a DataFrame like this</p> <pre><code>DataFrame({"key":["a","b","c","d","e"], "value": [5,4,3,2,1]}) </code></pre> <p>I am mainly interested in row "a", "b" and "c". I want to merge everything else into an "others" row like this</p> <pre><code> key value 0 a 5 1 b 4 2 c ...
<p>First create a dataframe without d and e:</p> <pre><code>df2 = df[df.key.isin(["a","b","c"])] </code></pre> <p>Then find the value that you want the other column to have (using the sum function in this example):</p> <pre><code>val = df[~df["key"].isin(["a","b","c"])].sum()["value"] </code></pre> <p>Finally, appe...
pandas
2
365,866
22,317,443
Concatenate multiple similar CSV files into one big dataframe
<p>I have one directory where there are only the CSV files I want to use. I want to concatenate all these CSV files and create a bigger one. I've tried one code but it didn't work.</p> <pre><code>import os import pandas as pd targetdir = r'C:/Users/toshiba/Documents/ICF2011/Base Admision San Marcos 2014-2/Sabado' fi...
<p><code>listdir</code> only returns the filename, not the complete path. To get the complete path you will need to join <code>targetdir</code> and <code>file</code> (bad variable name as it masks the <code>file</code> type). Also, you will have to capture the result of <code>.append</code> as it returns a new object r...
python|csv|pandas
2
365,867
22,226,375
Histogram with stacked components
<p>Let's say that I have a value that I've measured every day for the past 90 days. I would like to plot a histogram of the values, but I want to make it easy for the viewer to see where the measurements have accumulated over certain non-overlapping subsets of the past 90 days. I want to do this by "subdividing" each...
<p>Ok, here's one way to attack it, using features from the <code>matplotlib</code> <code>hist</code> function itself:</p> <pre><code>fig, ax = plt.subplots(1, 1, figsize=(9, 5)) ax.hist([data.ix[low:high, 'values'] for low, high in [(0, 70), (70, 85), (85, 90)]], bins=15, stacked=True, rwid...
python|matplotlib|pandas|seaborn
9
365,868
22,264,046
Inverse probability density function
<p>What do I have to use to figure out the inverse probability density function for normal distribution? I'm using scipy to find out normal distribution probability density function:</p> <pre><code>from scipy.stats import norm norm.pdf(1000, loc=1040, scale=210) 0.0018655737107410499 </code></pre> <p>How can I figure...
<p>There can be no 1:1 mapping from probability density to quantile.</p> <p><img src="https://i.stack.imgur.com/TceVU.png" alt="enter image description here"></p> <p>Because the PDF of the normal distribution is quadratic, there can be either 2, 1 or zero quantiles that have a particular probability density.</p> <h2...
python|numpy|statistics|scipy
4
365,869
22,307,974
Add column to a specific CSV row using Python pandas
<p>I want to merge rows in csv files by matching the id with a given dictionary. </p> <p>I have a dictionary: l= {2.80215: [376570], 0.79577: [378053], 22667183: [269499]}</p> <p>I have a csv file. </p> <pre><code> A B C D 2000-01-03 -0.59885 -0.18141 -0.68828 -0.77572 2000-01-04...
<p>If you l were a DataFrame you could do a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">merge</a>:</p> <pre><code>In [11]: l_df = pd.DataFrame.from_dict(l, orient='index') In [12]: l_df.columns = ['F'] In [13]: l_df Out[13]: F 2.802...
python|csv|pandas
2
365,870
22,263,899
Optional parameters in np.eye()
<p>Got to learn a new function in numpy </p> <pre class="lang-py prettyprint-override"><code>np.eye(N, M=None, k=0, dtype=) </code></pre> <p>Looking at the function signature, I thought there might be another way to declare optional parameter as in dtype</p> <p>So I tried to make my own function foo</p> <pre class=...
<p>The <a href="https://github.com/numpy/numpy/blob/master/numpy/lib/twodim_base.py#L175" rel="nofollow">function signature of <code>numpy.eye</code></a> is:</p> <pre><code>def eye(N, M=None, k=0, dtype=float): </code></pre>
python|numpy
1
365,871
22,421,430
Python: get parent list
<p>Is there a way to get the parent list, if some element is given? For instance, I have two lists <code>a</code> and <code>b</code>, and I want</p> <pre><code>def func(a,b): mx = max(a[0], b[0]); mn = min(a[0], b[0]); return (the list that corresponds to (mx, mn) in the order) </code></pre> <p>Edit: for ...
<p>No, it is not possible. But you can get the list corresponding the maximum of the first elements, with <a href="http://docs.python.org/2/reference/expressions.html#conditional-expressions" rel="nofollow">conditional expression</a>, like this</p> <pre><code>a, b = [1, 2], [2, 1] c = a if a[0] &gt; b[0] else b print ...
python|list|numpy
1
365,872
21,982,681
check if dataframe is of boolean type pandas
<p>I have a pandas DataFrame as below:</p> <pre><code>In [108]: df1 Out[108]: v t 2014-02-21 10:30:43 False 2014-02-21 10:31:34 False 2014-02-21 10:32:25 False 2014-02-21 10:33:17 False 2014-02-21 10:34:09 False 2014-02-21 10:35:00 False 2014-02-21 10:35:51 Fal...
<p>You can print the <code>dtypes</code> of the columns:</p> <pre><code>In [2]: import pandas as pd df = pd.DataFrame({'a':[True,False,False]}) df Out[2]: a 0 True 1 False 2 False [3 rows x 1 columns] In [3]: df.dtypes Out[3]: a bool dtype: object In [4]: df.a.dtypes Out[4]: dtype('bool') </code><...
python|pandas|dataframe
8
365,873
22,232,311
Finding intersection between straight line and contour
<p>I am trying to find the intersection point of a straight(dashed red) with the contour-line highlighted in red(see plot). I used .get_paths in the second plot to isolate said contour line form the others(second plot). </p> <p>I have looked at a contour intersection problem, <a href="https://stackoverflow.com/questio...
<p>Use <code>shapely</code> can find the intersection point, than use the point as the init guess value for <code>fsolve()</code> to find the real solution:</p> <pre><code>#for contour def p_0(num,t) : esc_p = np.sum((((-1)**n)*(np.exp(t)**n)*((math.factorial(n)*((n+1)**0.5))**-1)) for n in range(1,num,1)) re...
python|numpy|matplotlib|computational-geometry
2
365,874
22,286,930
Is it possible to use cut on a collection of datetimes?
<p>Is it possible to use <code>pandas.cut</code> to make bins out of <code>datetime</code> stamps?</p> <p>The following code:</p> <pre><code>import pandas as pd import StringIO contenttext = """Time,Bid 2014-03-05 21:56:05:924300,1.37275 2014-03-05 21:56:05:924351,1.37272 2014-03-05 21:56:06:421906,1.37275 2014-03-0...
<p>Old question, but for any future visitors, I think this is a clearer way to calculate float timedeltas to use cut on:</p> <pre><code>import pandas as pd import datetime as dt # Get Days Since Date today = dt.date.today() df['days ago'] = (today - df['time']).dt.days # Get Seconds Since Datetime now = dt.datetime....
python|datetime|pandas
3
365,875
17,794,511
Strange behaviour with index
<p>I have a large DataFrame indexed by datetime of the type below</p> <p><code>2013-07-15 09:30:00.073000,-0.909437,0.287493,-0.071288</code></p> <p>When I try the following code I get a result</p> <pre><code>tempdf[tempdf.index[1]:tempdf.index[2]] </code></pre> <p>but when I try</p> <pre><code>tempdf[tempdf.index...
<p>You are using an indexing short-cut which doesn't apply, see here: <a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#datetime-indexing" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/timeseries.html#datetime-indexing</a></p> <p>Create a time indexed frame</p> <pre><code>In [7]: df = DataFr...
pandas
2
365,876
17,927,065
Conditional numpy array modification by the indices
<p>I have one more question about NumPy)</p> <p>I want select the some number of the nodes from grid by condition. The purpose is take the nodes that will be closest to circle, and move them to circle boundary (by Ox or Oy - it depends on what distance will be less).</p> <p><img src="https://docs.google.com/drawings/...
<p>Combine your conditions with the <code>&amp;</code> operator:</p> <pre><code>X[condition &amp; (distance_X &lt; distance_Y)] = ... Y[condition &amp; (distance_Y &lt; distance_X)] = ... </code></pre>
python|numpy
1
365,877
17,756,791
Python Process using only 1.6 GB RAM Ubuntu 32 bit in Numpy Array
<p>I have a program for learning Artificial Neural Network and it takes a 2-d numpy array as training data. The size of the data array I want to use is around 300,000 x 400 floats. I can't use chunking here because the library I am using (DeepLearningTutorials) takes a single numpy array as training data.</p> <p>The c...
<p>A 32-bit OS can only address up to aroung 4gb of ram, while a 64-bit OS can take advantage of a lot more ram (theoretically 16.8 million terabytes). Since your OS is 32-bit, your OS can only take advantage of 4gb, so your other 4gb isn't used.</p> <p>The other 64-bit machine doesn't have the 4gb ram limit, so it ...
python|numpy|ubuntu-12.04|32-bit
2
365,878
18,199,288
Getting the integer index of a Pandas DataFrame row fulfilling a condition?
<p>I have the following DataFrame:</p> <pre><code> a b c b 2 1 2 3 5 4 5 6 </code></pre> <p>As you can see, column <code>b</code> is used as an index. I want to get the ordinal number of the row fulfilling <code>('b' == 5)</code>, which in this case would be <code>1</code>.</p> <p>The column being tested c...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html">Index.get_loc</a> instead.</p> <p>Reusing @unutbu's set up code, you'll achieve the same results.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; df = pd.DataFrame(np.arange(...
python|numpy|pandas
70
365,879
4,148,505
How can I intentionally create a non-aligned numpy array?
<p>I need to intentionally create a non-aligned numpy array. In particular, I want <code>PyArray_ISALIGNED(array)</code> to return false. What causes numpy arrays not to be aligned, and how can I easily, manually trigger those conditions?</p>
<p>I don't know the details, there is a test in scipy.linalg that checks that misaligned arrays don't cause an error with Lapack.</p> <p><a href="http://projects.scipy.org/scipy/browser/trunk/scipy/linalg/tests/test_decomp.py?rev=#L1065" rel="nofollow">http://projects.scipy.org/scipy/browser/trunk/scipy/linalg/tests/t...
numpy
1
365,880
4,660,881
passing 2d array from numpy to c++ via swig can't use float**
<p>I'm exploring wrapping c++ classes with SWIG and passing in data from numpy</p> <p>I can sucessfully pass in a 1d array using the following typemap</p> <pre><code>(float*, IN_ARRAY1, int DIM1) </code></pre> <p>The size of the array is not known at compile time so I can't use the type map</p> <pre><code>(float, I...
<p>You can't seemingly pass float** to numpy C API, because they are not compatible memory representations a priori.</p> <p>In numpy, data in an array must be in one single contiguously memory region (there can be holes, but they must feet in one block as allocated by e.g. malloc):</p> <pre><code>data -&gt; | - | - ...
c++|numpy|swig
2
365,881
4,373,631
Sum array by number in numpy
<p>Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups results in group number order (in this case the result would be [3, 9, 9]). How do I do this in numpy? </p>
<p>The numpy function <code>bincount</code> was made exactly for this purpose and I'm sure it will be much faster than the other methods for all sizes of inputs:</p> <pre><code>data = [1,2,3,4,5,6] ids = [0,0,1,2,2,1] np.bincount(ids, weights=data) #returns [3,9,9] as a float64 array </code></pre> <p>The i-th eleme...
python|numpy
50
365,882
8,851,215
collapse a list of ndarray to a matrix
<p>I have a list containing objects of type numpy.ndarray, all list elements has same .shape value.</p> <p>How can I collapse this into a matrix?</p>
<p>Sounds like you're looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow"><code>numpy.vstack()</code></a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html#numpy.hstack" rel="nofollow"><code>numpy.hstack()</code></a>, depending on wh...
python|numpy
4
365,883
55,537,034
have a list from the results of a print (python datetime)
<p>I did a function that display the dates between two dates.</p> <p>I want to affect the result displayed in a list or df.</p> <p>I have this code</p> <pre class="lang-py prettyprint-override"><code>next_day = 2018-09-26 01:07:00 while True: if next_day &gt; 2018-09-26 01:20:00: break print(...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> with <code>DataFrame</code> constructor:</p> <pre><code>next_day = '2018-09-26 01:07:00' df = pd.DataFrame({'date': pd.date_range(next_day, '2018-09-26 01:20:00', fre...
python|pandas|list|datetime
1
365,884
55,486,345
complex requirements for Data wrangling using python
<p>This is my original text field</p> <pre><code>Area Brand Points USA Nike 86 USA Addidas 85 USA Speedo 84 USA Nike 83 USA Speedo 82 USA Nike 81 Japan Nike 84 Japan Nike 85 Japan Nike 86 Japan Addidas 82 Japan Addidas 80 Japan Addidas 86 Japan Speedo 84 ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mode.html" rel="nofollow noreferrer"><code>pd.Series.mode</code></a> like so:</p> <pre><code>df.groupby('Area').agg({'Brand': lambda x: x.mode().values.tolist(), 'Points': 'mean'}) </code></pre> <p>Gives:</p> <pre><code>...
python|pandas|pandas-groupby
0
365,885
55,344,092
Can the TensorFlow MTCNN model converted to the TensorFlow Lite format?
<p>I'm trying to convert MTCNN model (<a href="https://github.com/blaueck/tf-mtcnn/blob/master/mtcnn.pb" rel="nofollow noreferrer">https://github.com/blaueck/tf-mtcnn/blob/master/mtcnn.pb</a>) from .pb file to .tflite and get problems with input and output shapes. Original input shape is ?x?x3 and output shape is Nx4 w...
<pre><code>converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.representative_dataset = representative_dataset converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] converter.inference_input_type = tf.uint8 # or tf.i...
python|tensorflow|tensorflow-lite
-2
365,886
55,420,893
How can i efficiently turn columns into 0 based on filter criteria?
<p>As mentioned in the title, how can I convert column into 0 based on the list of columns. I need to convert any column into 0 after first 3 column from from the list matches to 1. </p> <p>for instance </p> <p>list1 =["a","c","d","e","b"]</p> <p>df= </p> <pre><code> a b c d e 0 1 1 0 1 1 1 0...
<p>You can do with <code>reindex</code> and <code>cumsum</code> , then <code>mask</code> back </p> <pre><code>df.mask(df.reindex(columns=filterlist).cumsum(1).gt(3),0) Out[620]: a b c d e 0 1 0 0 1 1 1 0 0 0 1 1 2 0 0 0 0 0 3 1 1 1 0 0 4 0 0 0 0 0 5 1 0 1 1 0 </code></pre>
python|python-3.x|pandas|numpy
2
365,887
55,416,700
Pandas: modify the minutes of a timestamp
<p>My code looks like this:</p> <pre><code>timestamp1 = df_all_trades.loc[index].time timestamp1 = pd.Timestamp(timestamp1) print(timestamp1) timestamp1 = timestamp1.strftime("%m-%d-%Y %H:%M:%S") + "Z" </code></pre> <p>When I print it it looks like this: <code>2019-03-16 23:40:28.783000</code> what I need is the same...
<p>In pandas you can use DateOffset:</p> <pre><code>a = pd.date_range(start='2018',end='2019') a - pd.DateOffset(minutes = 4) </code></pre>
python|pandas
2
365,888
55,414,087
How to add a column with the time to a pandas dataframe (created from a JSON)?
<p>I retrieve data (JSON format) from a software API and transform it into a dataframe to write it in a CSV (pandas library). I would add a column with the time. I would like it to be written "time" on the first row and for example "Fri Mar 29 09:16:02 2019" on the following ones. An idea on how to achieve this?</p> <...
<p>use </p> <pre><code>result_tri = result.reindex(columns=['Time','object-name','present-value']) result_tri['Time'] = time </code></pre>
python|json|pandas
1
365,889
55,257,018
Optimizing while loop in Python
<p>I have a piece of code that takes forever to run. Does anybody know how to optimize it? </p> <p>The purpose of the formula is to make a column that does the following: when <code>'action' != 0, if 'PX_LAST'&lt;'ma', populate 'buy_sell' with -1, if 'PX_LAST'&gt;'ma', populate 'buy_sell' with 1</code>; in the other c...
<p>I think you need:</p> <pre><code>import numpy as np mask1 = df_zinc['action'] != 0 mask2 = df_zinc['PX_LAST'] &lt; df_zinc['ma'] mask3 = df_zinc['PX_LAST'] &gt; df_zinc['ma'] df_zinc['buy_sell'] = np.select([mask1 &amp; mask2, mask1 &amp; mask3], [-1,1], 0) </code></pre>
python|pandas|dataframe
0
365,890
55,219,355
Numpy aggregated mean
<p>I want to calculate the mean over a numpy array but within a window from the beginning of the array until the actual value of the array. HereΒ΄s an example:</p> <pre><code>array = [1, 2, 3, 4, 5, 6, ...] windowed_means = [1, 1.5, 2, 2.5, ...] </code></pre> <p>The calculus are like:</p> <pre><code>windowed_means = ...
<p>You can try:</p> <pre><code>windowed_means = np.cumsum(array)/np.arange(1,len(array)+1) </code></pre> <p><code>numpy.cumsum</code> is the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="noreferrer">cumulative sum</a>.</p>
python|numpy
5
365,891
55,529,097
To get the entries from one column of dataframe, segregate on its properties and place them to a different columns according to that property
<p>I have a csv file which i have converted in dataframe and input file looks like this:</p> <pre><code> Date Area Input 4/5/2019 Forest apple 4/5/2019 Forest banana 4/5/2019 Forest Lion 4/5/2019 Town banana 4/6/2019 Town dog 4/6/2019 Town grapes 4/6/2019 Town cat </code><...
<p>You can create dictionary of <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> to catagories, count values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="n...
python-3.x|pandas
2
365,892
55,546,027
How to assign arbitrary metadata to pyarrow.Table / Parquet columns
<p><strong>Use-case</strong></p> <p>I am using Apache Parquet files as a fast IO format for large-ish spatial data that I am working on in Python with GeoPandas. I am storing feature geometries as WKB and would like to record the coordinate reference system (CRS) as metadata associated with the WKB data.</p> <p><stro...
<p>"Everything" in Arrow is immutable, so as you experienced, you cannot simply <em>modify</em> the metadata of any field or schema. The only way to do this is to create a <em>"new"</em> table with the added metadata. I put <em>new</em> between quotation marks since this can be done without actually copying the table, ...
python|pandas|gis|parquet|pyarrow
5
365,893
55,212,297
Pandas Float Formatting
<p>I am a newbie to Python/Pandas and do not know how to present my dataframe. I understand that the data may not need to be changed but rather how it is displayed.</p> <p>I have a dataframe as follow:</p> <pre><code> min max mean marketCap(EUR) 6.110331e+10 2.837429e+11 ...
<p>Change the display option for floats:</p> <pre><code>import pandas as pd pd.options.display.float_format = '{:.2f}'.format print(df) # min max mean #marketCap(EUR) 61103310000.00 283742900000.00 127599300000.00 #price(EUR) 3680.00 16943.95 ...
python|pandas|floating-point
0
365,894
55,520,385
Python2.7 - Pandas dataframe groupby two criterias
<p>Lets say I have a panadas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['name','time']) df = df.append({'name':'Waren', 'time': '20:15'}, ignore_index=True) df = df.append({'name':'Waren', 'time': '20:12'}, ignore_index=True) df = df.append({'name':'Waren', 'time': '20:11'}, ignore_index...
<p>You are doing it wrong. When you do <strong>df.groupby(['name'])</strong> it returns attribute <strong>groupby</strong> which is not callable. You need to apply both of it together.</p> <pre><code> df.groupby(['name', df.index.to_series().diff().ne(1).cumsum()]).groups Out: {('Kim', 2): [6, 7], ('Kim', 3): [9, ...
python|python-2.7|pandas-groupby
1
365,895
55,509,493
How to use cov function to a dataset iris python
<p>I want to get the covariance from the iris data set, <a href="https://www.kaggle.com/jchen2186/machine-learning-with-iris-dataset/data" rel="nofollow noreferrer">https://www.kaggle.com/jchen2186/machine-learning-with-iris-dataset/data</a> </p> <p>I am using numpy, and the function -> np.cov(iris)</p> <pre><code>wi...
<p>So, if you want to modify your code you could try by reading the <code>Iris.csv</code> with <code>pandas.read_csv</code> function. And then select the appropiate columns of your choice.</p> <p>BUT, here is a little set of commands to ease up this task. They use <code>scikit-learn</code> and <code>numpy</code> to lo...
python|python-3.x|numpy|covariance|iris-dataset
0
365,896
55,396,932
How to convert date format string to bool True and others to False?
<pre><code>import pandas import numpy df=pandas.DataFrame({'col1':['a','b','c','b'],'col2':['N','2018-03-12 15:35',numpy.NaN,'2017-06-12 15:35'],'col3':['c','b','b','b']}) print(df) </code></pre> <p>Output of above script is: </p> <pre><code> col1 col2 col3 0 a N c 1 b 2018-03...
<p>Create 2 masks - first convert <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>s with <code>errors='coerce'</code> and test <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.notna.html" re...
python|pandas
4
365,897
55,277,263
Pandas: Concatenate multiple column values one below the other
<p>I have this dataframe:</p> <pre><code> 0 1 0 Bin Months Since Default 1 1 0 2 2 0&lt; x &lt;=6 3 3 6&lt; x &lt;=12 4 4 12&lt; x &lt;=24 5 5 24&lt; </code></pre> <p>I want to create a new column 'texts'...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p> <pre><code>#...
python|pandas|dataframe
1
365,898
55,394,753
Create a categorized DataFrame from a Pandas list that includes Brand & Model name
<p>I have a Pandas DataFrame of car brand names &amp; car models in 1 column, car price in 1 column that looks like below.</p> <pre><code>car_name car_price BMW M50 50000 Tesla Model 3 14000 BMW M3 Series 20500 Mercedes G500 45000 Mercedes E200 12300 </code></pre> <p>How can I categ...
<p>Try something like:</p> <pre><code>car_brand =['Mercedes', 'BMW', 'Hyundai', 'KIA', 'Tesla', 'Chevrolet'] pat=r'({})'.format('|'.join(car_brand)) #'(Mercedes|BMW|Hyundai|KIA|Tesla|Chevrolet)' </code></pre> <hr> <pre><code>df['car_brand']=df.car_name.str.extract(pat) df['car_model']=df.pop('car_name').str.replace(...
python|pandas
2
365,899
55,345,428
Find and replace partial string in dataframe?
<p>I currently have two dataframes that have been pulled from CSV files that I need to join. Problem lies in the fact that the join column isn't matching and there are many files I must go through, so manual cleaning in excel isn't optional.</p> <p>Here is what I am working with...</p> <p>DF1</p> <pre><code>ID T...
<p>Use <code>str.extract</code> to extract the pattern <code>HIF-\w{4}</code> from <code>df2['HIF']</code>, you can then merge <code>df1</code> and <code>df2</code> together on "HIF".</p> <pre><code>df1.merge(df2.assign(HIF=df2['HIF'].str.extract(r'(HIF-\w{4})')), on='HIF') ID Title HIF Date Type 0 ...
python|python-3.x|pandas
5