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 |
|---|---|---|---|---|---|---|
7,200 | 53,173,312 | Comparing two panda dataframes and writing new dataframes if a row value is common between both dfs | <p>First of all I am going to explain the whole problem and if there is a better way to do this without pandas please say. I have just attempted a bunch of ways and I feel like pandas is likely the best way to go.</p>
<p>I have two text files. Each text file looks something like the following:</p>
<pre><code>Sometext... | <p>Hi mate here you could find simple example for solving your problem, I hope is gonna work for you:</p>
<p>two example data-frames:</p>
<pre><code>df1 = pd.DataFrame({
"Date" : [2013-11-24, 2013-11-24, 2013-11-24, 2013-11-24],
"Fruit" : ['Banana', 'Orange', 'Apple', 'Celery'],
"Num" : [22.1, 8.6, 7.6, 10.2],
"Colo... | python|pandas|dataframe|text | 0 |
7,201 | 65,506,956 | Matching multiple conditions and returning/appending multiple results, between two dataframes in pandas | <br/>
I'm very new to python and really don't know where to start doing the following:<br/>
I have two dataframes, df1 and df2.<br/>
<pre class="lang-py prettyprint-override"><code>df1
fruit id date
0 apple 2 01/10/20
1 pear 1 15/09/20
2 banana 3 01/06/20
3 peach 4 10/04/20
</code></pre>
... | <pre><code>df1.merge(df2,left_on=['id','date'],right_on=['uid','ndate'])
</code></pre> | python|pandas|dataframe | 0 |
7,202 | 65,856,489 | Python Pandas: How to drop rows by time? | <p>I want to keep rows with time that are between 6am (morning) and 12am (midnight), how should I do it?</p>
<p>This is my dataframe:
<a href="https://i.stack.imgur.com/Yah8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yah8x.png" alt="enter image description here" /></a></p>
<p>and this is the da... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>df.between_time</code></a>:</p>
<pre><code>df.set_index('Date Time').between_time('6:00', '23:59').reset_index()
</code></pre> | python|pandas|jupyter-notebook | 2 |
7,203 | 63,693,361 | Drop Hours, Mins, Secs in Timestamp Error | <p>I want to drop the hours/mins/sec in timestamp. I tried using <code>strftime</code> but I'm getting an error</p>
<pre><code>import pandas as pd
df = pd.read_csv('file.csv')
df['Date'] = pd.to_datetime(df.Date)
df.strftime('%Y-%m-%d')
</code></pre>
<p>Here's the exact error I'm getting:</p>
<pre><code>AttributeError... | <p>Try:</p>
<pre><code>df['Date'] = df['Date'].strftime('%Y-%m-%d')
</code></pre>
<p>or</p>
<pre><code>df['Date'] = df['Date'].dt.normalize()
</code></pre> | python|pandas | 1 |
7,204 | 63,715,251 | Performing iterative arithmetic over a column in a Pandas dataframe | <p>I am attempting to perform arithmetic on the 'data_d' column.</p>
<pre><code>dataframe
data_a data_b data_c data_d
60 0.30786 Discharge 2.31714
61 0.30792 Rest 2.34857
121 0.62095 Rest 2.38647
182 0.93398 Discharge 2.31115... | <p>We use the <code>cumsum</code> to create the <code>groupby</code> key , then do <code>cumcount</code> with <code>groupby</code> <code>map</code> the number of count back to letter</p>
<pre><code>key = df['data_c'].eq('Discharge').cumsum()
df['variable'] = df.groupby(key).cumcount().map({0:'A',1:'B',2:'C'})
df
Out[61... | python|pandas|dataframe|math|data-science | 1 |
7,205 | 63,704,174 | Encoding for patterns with Numpy | <p>I want to find up/down patterns in a time series. This is what I use for simple up/down:</p>
<pre><code>diff = np.diff(source, n=1)
encoding = np.where(diff > 0, 1, 0)
</code></pre>
<p>Is there a way with Numpy to do that for patterns with a given lookback length without a slow loop? For example up/up/up = 0 down... | <p>I learned yesterday about <code>np.lib.stride_tricks.as_strided</code> from one of StackOverflow answers <a href="https://stackoverflow.com/a/53099870/3044825">similar to this</a>. This is an awesome trick and not that hard to understand as I expected. Now, if you get it, let's define a function called <code>rolling... | python|numpy | 1 |
7,206 | 63,456,492 | Data API : ValueError: `y` argument is not supported when using dataset as input | <p>I have 45000 images of size 224*224, stored as a numpy array. This array, called <code>source_arr</code> has shape 45000,224,224 and it fits in the memory.</p>
<p>I divide this array into train, test and validate array and pre-process (normalize and convert greyscale to 3 channels RGB) them using tf.data API.</p>
<p... | <p>you have source_arr and y_train as numpy array ;so you can do :</p>
<pre><code>data_set = tf.data.Dataset.from_tensor_slices( (source_arr , y_train) )
</code></pre>
<p>if you have source_arr and y_train as tf.dataset :</p>
<pre><code>data_set = tf.data.Dataset.zip( (source_arr , y_train) )
</code></pre> | python|tensorflow|tensorflow-datasets | 2 |
7,207 | 71,897,140 | Formatting an output from data retrieved from a CSV file with Pandas | <p>Basically I'm trying to remove the row index (2) and I think the type information (bottom line of output) from the variable 'speed'. The code
is meant to retrieve information from a csv file at a certain location, but I only want the value of that location (1.5), rather than the rest of it. I have looked around but ... | <p>In this case there is no need to look for the index/row number of the row where the kart name is equal to the user inputed one and use it later. If you change</p>
<pre><code>rowNum = openCSV.index[openCSV['Name'] == kartName].tolist() # this gets the index/row number of the row where the kart name is equal to the us... | python|pandas|csv | 0 |
7,208 | 72,107,274 | Python interp function that returns first/leftmost match? | <p>I am given something like selected percentile values (5th, 10th, 25th, 50th) and so on, and need to find what percentile a given value is. So I have tried scipy and numpy, but have come across a problem. It is not uncommon for multiple percentiles to have the same value (for example a value of 0 all the way until th... | <p>Both <code>np.interp()</code> and <code>scipy.interpolate.interp1d()</code> require that the x values must be strictly increasing (i.e. <code>x[i+1] > x[i]</code>), and may return nonsense if they aren't. If you want some specific behavior, you need to preprocess your data to get rid of any repeated x values. For... | python|numpy|scipy | 0 |
7,209 | 55,500,094 | How to sum up the prediction vectors of a keras model into a single vector | <p>I have 2 keras models.
The first gets as input a string and gives
a prediction for example, five classes.</p>
<p>In the second model I want to use this output.
However, the output of the first model should be summed up into a single output for multiple inputs.</p>
<p>I want single prediction for the sum of all ent... | <p>Use <code>tf.reduce_sum()</code>:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
output = tf.Variable([[0.2, 0.0, 0.0, 0.8, 0],[0.0, 0.0, 0.4, 0, 0.6],])
reduced = tf.reduce_sum(output, axis=0)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(reduced... | tensorflow|keras | 2 |
7,210 | 55,154,163 | Pandas replace the values of multiple columns | <p>If the match value is equal to the sample_input,The value in the sample_input is replaced.
The merge method now used can match, But don't know how to replace it.
There are many duplicate values in the sample being replaced.</p>
<p>The sample_data I used upload to the github.
<a href="https://github.com/salemilk/... | <p>Here's a pretty straightforward way of comparing and contrasting two Excel files.</p>
<pre><code>import pandas as pd
import numpy as np
# Next, read in both of our excel files into dataframes
df1 = pd.read_excel('C:\\your_path\\Book1.xlsx', 'Sheet1', na_values=['NA'])
df2 = pd.read_excel('C:\\your_path\\Book2.xls... | python|pandas | 1 |
7,211 | 56,561,607 | Pandas: How to increment a new column based on increment and consecutive properties of 2 other columns? | <p>I'm currently working on a bulk data pre-processing framework in pandas and since I'm relatively new to pandas, I can't seem to solve this problem:</p>
<p><strong>Given:</strong> A dataset with 2 columns :<code>col_1</code>, <code>col_2</code></p>
<p><strong>Required:</strong> A new column <code>req_col</code> suc... | <p>Try:</p>
<pre><code>df['req_col'] = (df['col_1'].diff().gt(1) | # col_1 is not consecutive
df['col_2'].diff().ne(0) # col_2 is has a jump
).cumsum()
</code></pre>
<p>Output:</p>
<pre><code>0 1
1 1
2 2
3 2
4 2
5 3
6 4
7 5
8 6
9 6
dtype: int32
</code>... | python-3.x|pandas | 0 |
7,212 | 66,823,458 | Merging two DF's on shortest date record and delete non-matching date rows | <p>i have two df's that i need to merge into one new df based on the day, month and year of the df with the shortest record of day, month and year. In other words, if the "day", "month" and "year" columns do not match in the comparison then i need to delete those rows or do not match. The ... | <p>In <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a>, parameters <code>left_on</code> and <code>right_on</code> must be the columns you want to use to join the two DataFrames, so they have to be the same. In your case since the columns... | python|pandas|merge|multiple-columns|missing-data | 1 |
7,213 | 66,837,503 | In the data frame of probabilities over time return first column name where value is < .5 for each row | <p>Given a pandas data frame like the following where the column names are the time, the rows are each of the subjects, and the values are probabilities return the column name (or time) the first time the probability is less than .50 for each subject in the data frame. The probabilities are always descending from 1-0 I... | <p>Since the probabilities are always descending you can do this:</p>
<pre><code>>>> df.set_index("subject id").gt(.98).sum(1)
subject id
1 4
2 4
3 4
4 4
5 5
6 6
7 4
8 5
9 3
dtype: int64
</code></pre>
<p>note: I'm using <code>.98</code> instead of <code>.5</code> because I'... | python|pandas | 2 |
7,214 | 47,167,409 | Using weights initializer with tf.nn.conv2d | <p>When using <code>tf.layers.conv2d</code>, setting the initializer is easy, it can be done through its parameter. But what if I use <code>tf.nn.conv2d</code>? I use this code. Is this equivalent to setting the <code>kernel_initializer</code> parameter in <code>tf.layers.conv2d</code>? Although the program runs withou... | <p>The operation underneath is the same (see <a href="https://stackoverflow.com/questions/42785026/tf-nn-conv2d-vs-tf-layers-conv2d">here</a>).</p>
<p>As for the kernel and its initialization, I took a glimpse in the code and it <em>looked</em> the same... the <code>layers.conv2d</code> call a <code>tf.get_variable</c... | python|tensorflow|conv-neural-network|initializer | 2 |
7,215 | 68,283,948 | How can i replace a code within my pandas dataframe with a dict mapping? | <p>I have a table like below:</p>
<pre><code>Group col1 col2 col3
A shop_101 shop_102 shop_104
B shop_101 shop_105 shop_108
C shop_101 shop_103 shop_109
C shop_111 shop_122 shop_104
</code></pre>
<p>I also have a dict which has mappings of these e.g.:</p>
<pre><code>{'group_name':... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> for substrings replacement values of dict with convert keys to strings:</p>
<pre><code>d = {'group_name': {103: 'AUTO',
104: 'BUSINESS',
105: 'STORES'... | python-3.x|pandas|dataframe | 1 |
7,216 | 68,422,818 | Replace value in dataframe column until specific conditionally changing value is reached | <p>I have a dataframe df which looks like this:</p>
<pre><code>data = [["nota", "b"], ["notb", "nota"], ["a", "b"], ["a", "notb"], ["notb", "notb"],[ "nota", "notb"], ["nota", "nota&quo... | <p>Try:</p>
<pre class="lang-py prettyprint-override"><code>def process_status(x):
out, cur, cur_end = [], None, None
for v in x:
if cur is None and v in {"a", "b"}:
cur, cur_end = v, {"a": "nota", "b": "notb"}[v]
out.ap... | python|pandas|dataframe | 2 |
7,217 | 59,343,283 | ModuleNotFoundError: No module named 'torch_scope' | <p>Using the macOS terminal, I'm trying to run <code>./autoner_train.sh</code> by following <a href="https://github.com/shangjingbo1226/AutoNER#command" rel="nofollow noreferrer">this guide</a> on GitHub.</p>
<p>I have activated my <code>Conda</code> environment and check my <code>PyTorch</code> version</p>
<pre><cod... | <p>I the documentation at the <a href="https://github.com/shangjingbo1226/AutoNER#dependencies" rel="nofollow noreferrer">Dependencies</a> section you can read:</p>
<blockquote>
<p><strong>Dependencies</strong> </p>
<p>This project is based on <code>python>=3.6</code>. The dependent package for this
projec... | python|anaconda|pytorch|conda | 0 |
7,218 | 59,415,014 | Extracting numbers using regex in dataframe for heights (ft,in) | <p>I am trying to extract the numbers from a column in my Pandas data frame <code>[height]</code> using regular expressions. The data in the column is listed as a string using ft and in: e.g."<code>5ft 6in</code>". In order to visualize this data for future analysis I need to convert this format to be entirely in inche... | <ul>
<li>Use <a href="https://docs.python.org/3/library/re.html#re.findall" rel="nofollow noreferrer"><code>re.findall</code></a> to extract the digits from your given format</li>
<li>Convert the values to <code>int</code>, calculate the value in inches and return it</li>
</ul>
<pre class="lang-py prettyprint-override... | python|regex|pandas|dataframe|extract | 1 |
7,219 | 59,460,167 | Python Dataframe iterate over rows ( compare a values between them) and prepare a groups as output | <p>I have a dataframe like this
I want to group them by url and status and split a records by date, is it a more efficient way to do that?</p>
<pre><code>def transform_to_unique(df):
test = []
counter = 0
#first_row
if df.loc[0, 'status']!= df.loc[1, 'status']:
counter = counter +1
test.a... | <p>I'm not sure, whether I'm getting correctly where are you heading with the <code>test</code> column, but is this what you want to achieve (based on the sample data, you posted):</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
df.sort_values(["url", "date_scraped"], axis=0, ascending=True, in... | python|pandas|dataframe | 1 |
7,220 | 45,772,006 | Perform Conditional Grouping and selecting second best row using Cumcount in Pandas | <p>Here is the data that I have:</p>
<pre><code>ID Vehicle Calculator Offer NextCalculator NextOffer
3497827 2002 Ford Explorer Manheim Salvage 190 Copart 190
3497827 2002 Ford Explorer Manheim Salvage 190 IAA 140
3497827 2002 Ford Explorer Manheim Salvage 190 Manheim Sal... | <p>IIUC:</p>
<pre><code>In [21]: df.loc[df.query("Calculator != NextCalculator")
.groupby('ID', as_index=False).NextOffer.idxmax()]
Out[21]:
ID Vehicle Calculator Offer NextCalculator NextOffer
0 3497827 2002 Ford Explorer Manheim Salvage 190 Copart 19... | python|pandas|grouping | 2 |
7,221 | 46,112,795 | python while loop to combine and delete repeated rows | <p>I got a dataframe like:</p>
<pre><code> Type: Volume: Date: Price:....
Q 10 2016.6.1 10
Q 20 2016.6.1 20
T 10 2016.6.2
Q 10 2016.6.3
T 20 2016.6.4
T 20 2016.6.5
Q 10 2016.6.6
</code></pre>
<p><a href="https://i.stack.imgur.com/bjsiU.pn... | <p>If you want to edit an iterable while looping over it, it's generally safer to work on a copy of the data inside the loop and replace the original with that updated copy afterwards. This avoids Python getting confused about its position in the iteration (which is the problem that seems hinted at in your error, as it... | python|numpy | 1 |
7,222 | 50,755,586 | How to loop large parquet file with generators in python? | <p>Is it possible to open parquet files and iterate line by line, using generators? This is to avoid loading the whole parquet file into memory.</p>
<p>The content of the file is pandas DataFrame.</p> | <p>You can not iterate by line as it is not the way it is stored. You can iterate through the row-groups as following:</p>
<pre><code>from fastparquet import ParquetFile
pf = ParquetFile('myfile.parq')
for df in pf.iter_row_groups():
process sub-data-frame df
</code></pre> | python|pandas|dataframe|generator|parquet | 7 |
7,223 | 50,708,793 | tensorflow object detection export_inference_graph.py ckpt name | <p>Does <code>export_inference_graph.py</code> need an exact checkpoint number, or is there a way to run it so that it will use the highest numbered checkpoint in a directory?</p> | <p>It needs exact checkpoint number in the command to find the correct file.</p> | tensorflow|export|object-detection | 0 |
7,224 | 51,083,978 | Indicate whether datetime of row is in a daterange | <p>I'm trying to get dummy variables for holidays in a dataset. I have a couple of dateranges (<code>pd.daterange()</code>) with holidays and a dataframe to which I would like to append a dummy to indicate whether the datetime of that row is in a certain daterange of the specified holidays.</p>
<p>Small example:</p>
... | <p>First dont use <strong>iterrows</strong>, because <a href="https://stackoverflow.com/a/24871316/2901002">really slow</a>.</p>
<p>Better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>dt.date</code></a> with <a href="http://pandas.pyd... | python-3.x|pandas|datetime-format|date-range | 2 |
7,225 | 50,758,110 | Warm start with distribute.MirroredStrategy and tf.Estimator | <p>I'm trying run a multi-gpus training using MirroredStartegy and tf.Estimator. The first attempt is to use <code>tf.train.init_from_chekpoint</code> in the estimator <code>model_fn</code> as follow</p>
<pre><code>def model_fn(features, labels, mode, params):
.....
tf.train.init_from_checkpoint(params['resne... | <p>Restoring from checkpoints using the 2 mechanisms you tried is unfortunately not yet supported in MirroredStrategy. I've filed a github issue to track this <a href="https://github.com/tensorflow/tensorflow/issues/19958" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/19958</a>. Please follo... | tensorflow | 0 |
7,226 | 66,534,544 | Reimplementing bert-style pooler throws shape error as if length-dimension were still needed | <p>I have trained an off-the-shelf Transformer().</p>
<p>Now I want to use the encoder in order to build a classifier. For that I want to only use the first token's output (bert-style cls-token-result) and run that through a dense layer.</p>
<p>What I do:</p>
<pre><code>tl.Serial(encoder, tl.Fn('pooler', lambda x: (x[:... | <p>The mistake was not in the architecture. Problem was: My <strong>inputs were not shaped correctly</strong>.</p>
<p>The target should have been of shape (batch_size, ) but I sent (batch_size, 1). So a target array should have been, e.g.:</p>
<pre><code>[1, 5, 99, 2, 1, 3, 2, 8]
</code></pre>
<p>but I produced</p>
<pr... | tensorflow|bert-language-model|jax|trax | 0 |
7,227 | 57,404,843 | Importing json files into pandas dataframe | <p>I have a couple json files which look like this:</p>
<pre><code>data = {"75575":
{"name": "Dummy name 1",
"season": "",
"ep": "",
"channel": "Dummy channel 1",
"Schedule": ["2017-05-11", "2019-04-30", "", "", "2019-08-01", "2019-08-31", "2017-05-1... | <p>Not sure about <code>json_normalize</code>, but seems like you can just use regular <code>pd.DataFrame</code> constructor</p>
<pre><code>df = pd.DataFrame(data).T
df = df.join(pd.DataFrame(df.Schedule.tolist(), index=df.index)).drop('Schedule', 1)
</code></pre>
<p>Then simply rename the columns with the list you a... | python|pandas | 2 |
7,228 | 57,718,155 | Tensorflow is not using the GPU for python_io library | <p>I am really new to tensorflow and this might be a simple question. I was wondering what are the correct mechanism for assignment of the GPU devices in the code.
Specifically I want to transfer this part of the code to the GPU:</p>
<pre><code>tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionTy... | <p>Can you try to execute the below code and see which device it uses. </p>
<pre><code>tf.debugging.set_log_device_placement(True)
# Place tensors on the GPU
with tf.device('/GPU:0'):
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
... | python|tensorflow|deep-learning|gpu | 0 |
7,229 | 57,597,121 | How to use a boolean array to skip expensive calculations of elements in array? | <p>Is there a way in numpy to use a boolean array to skip calculations of certain elements in an array? I'd like it to skip the evaluation of <code>expensive * arr</code> whenever the corresponding element in <code>bool_arr</code> is <code>False</code>.</p>
<pre><code> results = bool_arr & (expensive * arr)
</cod... | <p>You can use the <code>bool_arr</code> to work on a subset of the array, given <code>expensive</code> can thus run on a small set of values, like:</p>
<pre><code>results = bool_arr
results<b>[bool_arr]</b> = expensive * arr<b>[bool_arr]</b></code></pre> | numpy|numpy-ndarray|short-circuiting | 1 |
7,230 | 70,387,147 | return a message and put in a new column after compare values in a dataset (using pandas) | <p>I need to see if the values in column <code>Deathrate</code> is lower than 9 and return <code>balanced</code>. If isn't return <code>Urgent</code> and put all this in a new column <code>Humanitarian Help</code>. I tried this first:</p>
<pre><code>new = country_data.filter(items=['Country', 'Deathrate']).where(countr... | <p>Try this:</p>
<pre><code>import numpy as np
country_data['Humanitarian Help'] = np.where(country_data['Deathrate'] < 9, "balanced", "Deathrate")
</code></pre>
<p>Note that I changed <code>></code> (greater than) to <code><</code> (less than) per "<code>Deathrate</code> is <strong>l... | python|pandas | 0 |
7,231 | 71,087,933 | Printing date from Year, Month and Day columns in Pandas | <p>I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
<a href="https://i.stack.imgur.com/TN0as.png" rel="nofollow noreferrer">First 5 rows of the dataframe</a>
As seen from the image, the first column is year, second month, and third day. Below is wha... | <p>try this:</p>
<pre><code>df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)
</code></pre> | python|pandas | 0 |
7,232 | 70,985,993 | concatenate dataframes with variable row sizes | <p>I have two csv files which have different row numbers.</p>
<pre><code>test1.csv
num,sam
1,1.2
2,1.13
3,0.99
test2.csv
num,sam
1,1.2
2,1.1
3,0.99
4,1.02
</code></pre>
<p>I would like to read the <code>sam</code> columns and append them to an empty dataframe. Thing is that, when I read <code>test1.csv</code>, I extra... | <p>Using <code>pandas.concat</code> and a simple dictionary comprehension:</p>
<pre><code>files = ['test1.csv', 'test2.csv']
df = pd.concat({f.rsplit('.', 1)[0]: pd.read_csv(f).set_index('num')['sam']
for f in files}, axis=1)
</code></pre>
<p>output:</p>
<pre><code> test1 test2
num
1 ... | python|pandas | 2 |
7,233 | 71,024,507 | Pandas dataframe group by 10 min intervals with different actions on other columns | <p>I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:</p>
<pre><code> timestamp |close_price|highest_price|volume| ...
2018-09-29 00:00:20 |1809 |1811 | ... |
2018-09-29 00:00:34 |1823 |1832 |
... | <p>If your data spans multiple days or periods where you don't have any data points, calling <code>resample()</code> can result in lots of additional rows with <code>NaN</code> values. I think your code is actually correct, you just got the wrong impression from seeing all the extra rows.</p> | python|pandas|group-by|pandas-groupby|pandas-resample | 1 |
7,234 | 70,751,715 | User based encoding/convert with its interaction in pandas | <p>I have this dataframe which looks like this:</p>
<p>user_id : Represents user</p>
<p>question_id : Represent question number</p>
<p>user_answer : which option user has opted for the specific question from (A,B,C,D)</p>
<p>correct_answer: What is correct answer for that specific question</p>
<p>correct : 1.0 it means... | <p>First create the final value for each <code>bundle</code> element using <code>groupby</code> and <code>cumcount</code> then pivot your dataframe. Finally reindex it to get all columns:</p>
<pre><code>bundle = [f'b{i}' for i in range(1, 16)]
values = df.sort_values('timestamp').groupby('user_iD').cumcount().add(1)
... | pandas|encoding|converters | 1 |
7,235 | 71,041,793 | Implementing Multi-Label Margin-Loss in Tensorflow | <p>I'm wanted to implement the Multi-Label Margin-Loss in Tensorflow, using as orientation the definition of pytorch, i.e.</p>
<p><a href="https://i.stack.imgur.com/3GdOf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3GdOf.png" alt="Example" /></a></p>
<p><a href="https://pytorch.org/docs/stable/ge... | <p>You could try using <code>tf.while_loop</code> like this:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
def naive(y_true, y_pred, mu = 1.0):
pos = tf.ragged.boolean_mask(y_pred, tf.cast(y_true, dtype=tf.bool))
neg = tf.ragged.boolean_mask(y_pred, tf.cast(1 - y_true, dtype=tf.bo... | python|numpy|tensorflow|tensorflow2.0 | 0 |
7,236 | 51,765,063 | Resample sum keeping the index of last observation per day pandas | <p>I have a dataframe:</p>
<pre><code>Localmax symbol dvol idx
2016-10-19 09:05:00 st1 5172.159 2016-10-19 09:05:00
2016-10-19 09:05:00 st2 5172.18 2016-10-19 09:05:00
2016-10-19 17:30:00 st1 5000 2016-10-19 17:30:00
2016-10-19 17:40:00 st2 8000 2016-10-19 17:... | <p>I think there should be a simple way better than this but this works fine:</p>
<pre><code>In [58]: df
Out[58]:
Localmax symbol dvol idx
0 2016-10-19 09:05:00 st1 5172.159 2016-10-19 09:05:00
1 2016-10-19 09:05:00 st2 5172.180 2016-10-19 09:05:00
2 2016-10-19 17:30:0... | python|pandas|resampling | 0 |
7,237 | 51,600,034 | Lazy evaluation of numpy.max | <p>Suppose I have a 1D numpy array <code>x</code> with shape <code>(n,)</code> consisting mostly of zeros, and a 2D array <code>Y</code> with shape <code>(m,n)</code>. I want to compute </p>
<pre><code>np.sum(x * np.max(Y,axis=0))
</code></pre>
<p>i.e. the dot product of <code>x</code> with the matrix <code>Y</code> ... | <p>You can use <code>np.where</code> to find the non zero indices. For example (<code>m=3</code> and <code>n=6</code>):</p>
<pre><code>x= np.array([1,0,0,2,3,1])
Y = np.array([[1,2,3,4,5,6],
[4,5,6,1,2,3],
[7,8,9,4,5,1]])
ind = np.where(x != 0)[0]
result = sum(x[ind]*np.max(Y[:,ind], axis=0... | python|numpy|functional-programming|lazy-evaluation | 1 |
7,238 | 51,763,496 | Sparse matrix output to csv | <p>I have a sparse matrix <code>z</code> that is a <code>scipy.sparse.csr_matrix</code> and has shape <code>(n,m)</code> where <code>n<<m</code>. I also have labels <code>l</code> which is simply a <code>np.array</code> of strings with size <code>n</code>.</p>
<p>What I'd like to do is make a csv file with the ... | <pre><code>In [74]: from scipy import sparse
In [75]: M = sparse.csr_matrix([[0,0,1,0,0,-1,0,3,0,-6,4],
...: [-1,0,4,0,0,0,0,0,0,0,-2]])
In [76]: M
Out[76]:
<2x11 sparse matrix of type '<class 'numpy.int64'>'
with 8 stored elements in Compressed Sparse Row format>
In [77]: M.A
Out[77]:
ar... | csv|numpy|sparse-matrix | 1 |
7,239 | 51,597,073 | python - No module named dill while using pickle.load() | <p>I have dill installed in my python 2.7 but when I try to unpickle my model it says "No module named dill". The pickled file contains pandas series.</p>
<p>EDIT :
Here's the snapshot of the traceback on ElasticBeanstalk environment</p>
<pre><code>File "/opt/python/current/app/app/models/classification.py", line 663... | <p>If version on your Elastic beanstalk or error environment is greater than your local version then downgrade your dill package to the package which is working on your EC2 or local machine.
On your local machine, check current dill package:</p>
<pre><code>pip freeze | grep -i 'dill'
</code></pre>
<p>e.g it outputs: ... | python|pandas|pickle|dill | 10 |
7,240 | 35,884,743 | Match till comma OR end of line | <p>I have a pandas DataFrame that looks like this:</p>
<pre><code>0 UDP/ax/bsd
1 T Traffic/sa
2 ICMP/v/e,stuff hi/a/abc,ab/a
</code></pre>
<p>I want to replace everything from the first encountered <code>/</code> till a comma or end of line. So I tried initially <code>df.col_A.replace('/.+','',r... | <p>You can use:</p>
<pre><code> >>> print re.sub(r'/[^,]*(,|$)', ' \1', 'ICMP/v/e,stuff hi/a/abc,ab/a')
ICMP stuff hi ab
</code></pre>
<p><a href="https://regex101.com/r/gV7gI6/3" rel="nofollow">RegEx Demo</a></p>
<p><strong>RegEx Breakup:</strong></p>
<pre><code>/ # match literal /
[^,]* # match ... | python|regex|pandas | 2 |
7,241 | 37,448,773 | Converting space-aligned text file into Pandas DataFrame | <p>I am quite new to pandas. I have a log text file. I am trying to grab few data point from the file. Below is the code that kind of gets me the desired data but not in desired format. I wanted Pandas data frame with two columns.</p>
<pre><code>import os
from collections import Counter
import pandas as pd
#print(os.... | <p>You can create a dataframe by creating a list of lists, and then use the dataframe constructor.</p>
<p>Loop through each line of the file, like you've started doing, then split each line into the different columns. You can use <a href="https://docs.python.org/3/library/re.html#re.split" rel="nofollow noreferrer">re... | python|pandas|dataframe | 0 |
7,242 | 42,097,967 | Get Max/Min from array based on another array using Numpy.where | <p>Starting with this:</p>
<pre><code>import numpy as np
x = np.array([0, 2, 8, 9, 4, 1, 12, 4, 33, 11, 5, 3 ])
y = np.array(['', '', '', '', '', 'yo', '', '', '', '', 'yo', '' ])
i = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ])
print np.amax(x[:3] )
print np.amin(x[:3] ) ... | <p>First look at the simpler version of <code>where</code>, which finds the indices:</p>
<pre><code>In [266]: np.where(y=='yo')
Out[266]: (array([ 5, 10], dtype=int32),)
</code></pre>
<p>Evidently you want all the valyes for <code>y</code>, but replacing the <code>yo</code> with some value from <code>x</code>:</p>
<... | python|arrays|numpy | 2 |
7,243 | 41,982,290 | Pandas customized group aggregation | <p>I have a question regarding pandas and customised group aggregations to find the most efficient way to calculate my values. Here is my code snippet: </p>
<pre><code>import pandas as pd
listA = list('abcdefghijklmnopqrstuvwxyz') * 2
listB = listA[::-1]
listC = listA[::2] * 2
listD = "Won"
data1 = range(52)
data2 =... | <p>Consider aggregating all <em>Data</em> columns in one <code>groupby()</code> call and then create a new column for <em>val4</em>. Then merge aggregation back to original dataframe.</p>
<pre><code># EQUIVALENT EXAMPLE DATA
listA = list('abcdefghijklmnopqrstuvwxyz') * 2
df = pd.DataFrame({'A': listA, 'B': listA[::-1]... | pandas|grouping|customization|aggregation | 1 |
7,244 | 42,012,730 | How to read two lines from a file and create dynamics keys in a for-loop, a follow-up | <p>This question follows the problem in question: <a href="https://stackoverflow.com/q/41929351/868546">How to read two lines from a file and create dynamics keys in a for-loop?</a></p>
<p>But, the nature of the problem has evolved to certain complexity that I want to address.</p>
<p>Below is the structure of my data... | <p>The question is a bit old, but interesting because you have a very clear specification and you need help to write the code. I will expose a solution following a top-down approach, which is a very well known method, using plain old python. It shouldn't be difficult to adapt to pandas.</p>
<p>The top-down approach me... | python|pandas|numpy|dictionary|defaultdict | 3 |
7,245 | 41,796,965 | Tensorflow: How to use a trained model in a application? | <p>I have trained a Tensorflow Model, and now I want to export the "function" to use it in my python program. Is that possible, and if yes, how? Any help would be nice, could not find much in the documentation. (I dont want to save a session!)</p>
<p>I have now stored the session as you suggested. I am loading it now ... | <p>I don't know if there is any other way to do it, but you can use your model in another Python program by saving your session:</p>
<p>Your training code:</p>
<pre><code># build your model
sess = tf.Session()
# train your model
saver = tf.train.Saver()
saver.save(sess, 'model/model.ckpt')
</code></pre>
<p>In your app... | python|tensorflow | 9 |
7,246 | 7,948,510 | Using pcolor to plot 3 arrays in python | <p>I read an satellite image, and got the data, lat and lon out of the image and put in an array. The dimension of the lat is (135,90) and lon is also (135,90). The dimension of the data was originally (135,90,4,9,8), which 4 represent the band of the image. After processing( which used a for loop to put all band in a ... | <p>its me again... The documentation for matplotlib says here <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pcolor" rel="nofollow">http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pcolor</a> that </p>
<blockquote>
<p>X and Y, if given, specify the (x, y) coo... | python|image-processing|numpy|matplotlib | 0 |
7,247 | 37,766,384 | Tensorflow : How to recover a tensor properly | <p>Sorry for this newbie question, but i have some trouble learning tensor flow. I know basic things about ML ( linear regression, nn, cnn, perceptron, Kmeans ..) but i did not have any experience on a particular library.</p>
<p>I'm currently learning how to save and recover datas from a graph.
In my example, i do hav... | <p>Try creating the Variable without an initial value, and with validate_shape=False, and then running the restore process.</p> | python-2.7|tensorflow|restore | 0 |
7,248 | 37,813,059 | I am getting peak frequency from wav file. But for recorded 2 channels wav it is not working | <p>I am getting the peak frequency from wav files</p>
<p>My code for getting the peak frequency from a wav file is:</p>
<pre><code>import wave
import struct
import numpy as np
import wave
import contextlib
if __name__ == '__main__':
fname = "test.wav"
frate = 0
data_size = 0
with contextlib.closing(w... | <p>Why so complicated? Consider the following</p>
<pre><code>#!/usr/bin/env python3
import numpy as np
from numpy import fft
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
sr = 44100 # sample rate
len_sig = 2 # length of resulting signal in seconds
f = 1000 # frequency in Hz
# set you time ... | python|numpy|audio|fft | 1 |
7,249 | 64,257,005 | Converting a DataArray to a DataFrame and preserve coordinate label order | <p>Is there a simple way to convert an xarray DataArray to a pandas DataFrame, where I can prescribe which dimensions get turned into index/columns? For example, suppose I have a DataArray</p>
<pre class="lang-py prettyprint-override"><code>import xarray as xr
weather = xr.DataArray(
name='weather',
data=[['Sun... | <p>In xarray 0.16.1, <code>dim_order</code> was added to <a href="http://xarray.pydata.org/en/stable/generated/xarray.DataArray.to_dataframe.html" rel="nofollow noreferrer"><code>.to_dataframe</code></a>. Does this do what you're looking for?</p>
<pre><code>xr.DataArray.to_dataframe(
self,
name: Hashable = None... | pandas|python-xarray | 1 |
7,250 | 64,205,355 | How to read a particular cell in a excel sheet through pandas? | <p>I am working on a requirement where in I need to insert value on the fly in an excel sheet that is empty. So, to accomplish the goal, I am using Pandas.</p>
<p>I have single column(date), where in multiple rows could be empty. I am reading excel file through pandas. However, I found that if a cell is blank, pandas w... | <p>pandas fills the rows with Nan when empty blocks are in between the non empty rows but in the case of empty rows at the end, it is interpreted as end and ignores them. But if you are aware of number of ignored rows at the end u can do this as below.</p>
<pre><code> from numpy import nan as Nan
import pandas a... | python|excel|pandas | 0 |
7,251 | 47,542,745 | Combining mixed data types in pandas column | <p>I have a column in a dataframe called 'Year'. When I invoke;</p>
<pre><code>filtered_df['Year'].unique()
</code></pre>
<p>My result is:</p>
<blockquote>
<p>array([2013, 2012, 2014, 2015, 2016, 2017, 2011, 2010, 2009, 2008, '2011',
'2010', '2015', '2009', 'N 117 ST / GREENWOOD AV N'], dtype=object)</p>
... | <p>usually we convert it to numeric values (all non-convertable values will be converted into <code>NaN</code>'s) in the following way:</p>
<pre><code>filtered_df['Year'] = pd.to_numeric(filtered_df['Year'], errors='coerce')
</code></pre> | python|pandas|dataframe | 2 |
7,252 | 49,337,764 | How can I calculate standard deviation in pandas dataframe? | <p>I am using norway_new_car_sales_by_model.csv <a href="https://www.kaggle.com/dmi3kno/newcarsalesnorway/data" rel="nofollow noreferrer">Dataset here</a> dataset which you find. I want to find the model that has highest sales fluctuation over the years. I am using standard deviation of the yearly total sales for each ... | <p>I think need:</p>
<p>First remove parameter <code>header=None</code> from <code>read_csv</code>, because first in csv are columns names:</p>
<pre><code>data=pd.read_csv("norway_new_car_sales_by_model.csv",encoding="latin-1")
print (data.head())
Year Month Make Model Quantity Pct
0 2007... | python|pandas|dataframe | 2 |
7,253 | 49,018,980 | Check if two numpy array rows simultaneously satisfy a proposition | <p>This is a follow-up post to a previous question of mine:</p>
<p><a href="https://stackoverflow.com/questions/48978144/check-whether-numpy-array-row-is-smaller-than-the-next">Check whether numpy array row is smaller than the next</a></p>
<p>Suppose i have the following numpy array:</p>
<pre><code>a=np.reshape(np.a... | <p>You will use exactly the same strategy than <a href="https://stackoverflow.com/a/48978474/3104974">Tai's answer</a> in your previous post:</p>
<pre><code>b = np.diff(a, axis=0)
[[ 8. nan]
[ 5. 56.]
[ 7. -12.]
[ 4. -3.]
[ 23. 15.]
[ 5. -66.]]
</code></pre>
<p>And now you use a the logic f... | python|arrays|python-3.x|numpy | 0 |
7,254 | 48,907,532 | How to sort dataframe with ignoring prefixes? | <p>I can sort dataframe by column like this:</p>
<pre><code>df.sort(columns='sort_index', inplace=True)
</code></pre>
<p>And I can sort array with ignoring prefixes like this:</p>
<pre><code>array.sort(key=lambda element: re.sub(re, "", element))
</code></pre>
<p>But how to sort dataframe with ignoring prefixes?</p... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>str.replace</code></a> with <a href="https://stackoverflow.com/q/17901218/2901002"><code>argsort</code></a> for indices and then select by <a href="http://pandas.pydata.org/... | python|pandas|dataframe|data-structures | 2 |
7,255 | 48,962,312 | ValueError: setting an array element with a sequence() | <blockquote>
<p>Before downvoting this question and marked as duplicate, let me just explain the issue, i
tried all the possible solutions with similar question here on stack,
but none of them worked. i also checked, <a href="https://github.com/numpy/numpy/issues/6584" rel="nofollow noreferrer">setting an array e... | <p>Most likely the error is cause by trying to create an array from lists or arrays of differing length. </p>
<p>Without the <code>dtype</code> the following creates an <code>object</code> <code>dtype</code> array; with a numeric <code>dtype</code> it raises this error.</p>
<pre><code>In [33]: np.array([[1,2,3],[4,5... | python|arrays|numpy|random-forest|scikit-image | 1 |
7,256 | 58,700,150 | Python Pandas: Can I import a CSV through user input using a dynamic file path? | <p>So I'm trying to create a very basic python UI where a user uploads a CSV with a list of cities and the program creates an inner join with a pre-existing database of zip codes returns a list of cities and their corresponding zip codes. My code is functional so far. I'd just like the user to be able to upload a CSV f... | <p>@gingerhaze's answer - </p>
<pre><code>import tkinter as tk
from tkinter import filedialog
import pandas as pd
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()
def getCSV():
global cities
import_file_path = filedialog.askopenfilen... | python|pandas | 0 |
7,257 | 70,047,986 | Replace a single value with multiple values | <p>Given a <code>mask</code> numpy array such as:</p>
<pre><code>mask = np.array([0, 0, 1, 0, 0, 0, 1, ...])
</code></pre>
<p>I want to replace each <code>1</code> with a <code>target</code> <strong>vector</strong>. Example:</p>
<pre><code>target = np.array([5, 4, 3, 2, 1])
mask = np.array([0, 0, 1, 0, 0, 0, 0, 0, 1,... | <p><code>numpy</code> supports assigning value for the same index multiple times in one go, like so:</p>
<pre><code>mask = np.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0])
padding_idx = [2,3,4,5,6,5,6,7,8,9,8,9,10,11]
padding_values = [5,4,3,2,1,5,4,3,2,1,5,4,3,2]
mask[padding_idx] = padding_values
>>> mask
ar... | python|numpy | 1 |
7,258 | 70,084,538 | How to drop column where you don't know the name of the column? | <p>I'm a beginner and I'm wondering about this.</p>
<p>For example I have this code:</p>
<p><code>df = example.get_data</code></p>
<p>And I only know that the the header will be a date <em>numpy.datetime64</em> type. How can I only keep the last 2 years data without knowing anything more about it?</p>
<p>I tried someth... | <p>If your column names are e.g. <code>'12/02/2021', '14/01/2021', '19/08/2019'</code> you can select all columns of the last two years like that:</p>
<pre><code>from pandas.tseries.offsets import DateOffset
last_2_years = [c for c in df.columns if pd.to_datetime(c) > pd.Timestamp.today() - DateOffset(years=2)]
df... | python|python-3.x|pandas|dataframe | 1 |
7,259 | 56,382,596 | Why do we use numpy.argmax() to return an index from a numpy array of predictions? | <p>Let me preface this by saying, I am very new to neural networks, and this is my first time using numpy, tensorflow, or keras.</p>
<p>I wrote a neural network to recognize handwritten digits, using the MNIST data set. I followed <a href="https://www.youtube.com/watch?v=wQ8BIBpya2k" rel="nofollow noreferrer">this tut... | <p>What any classification neural network outputs is a probability distribution over the class indices, meaning that the network assigns one probability to each class. The sum of these probabilities is 1.0. Then the network is trained to assign the highest probability to the correct class, so to recover the class index... | python|numpy|tensorflow|machine-learning|keras | 2 |
7,260 | 56,079,085 | How do I overcome the TypeError: cannot convert the series to <class 'float'> error | <p>I am trying to calculate the Latitude and Longitude for a number (series) of flights in which I tried to use this code </p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from math import radians, cos, sin, asin, sqrt
# convert decimal degrees to radians
lon1 = df1['from_lon'].map(radians)
lat... | <p>Below is the code which works without error. Basically you need to use Series.apply(lambda x: ) function. </p>
<pre><code>a = (dlat/2).apply(lambda x : sin(x)) ** 2 + lat1.apply(lambda x : cos(x)) * lat2.apply(lambda x:cos(x))* (dlon/2).apply(lambda x : sin(x)) ** 2
c = 2 * a.apply(lambda x : asin(sqrt(x)))
resul... | python|python-3.x|pandas|jupyter-notebook | 0 |
7,261 | 55,800,339 | Different accuracies on different machines using same seeds, code and dataset | <p>I am trying to develop a CNN for signature recognition to identify which person a given signature belongs to. There are 3 different classes(persons) and 23 signatures for each of them. Having this little amount of samples, I decided to use the Keras <code>ImageDataGenerator</code> to create additional images.</p>
<... | <p>Providing the solution here (Answer Section), even though it is present in the Question Section, for the benefit of the community. </p>
<p>Using different hardware, specifically different graphics cards will result in varying accuracies though we use same seeds, code and dataset. <code>Saving the trained model and ... | python|tensorflow|machine-learning|keras|conv-neural-network | 0 |
7,262 | 55,708,140 | Calculate new list with differences of list elements | <p>I am looking for a faster way to calculate the absolute difference between every element of two lists. </p>
<p>This is my current code, but it gets a bit slow with big arrays:</p>
<pre><code>import numpy as np
np.random.seed(10)
x_values = np.random.randint(-50,100,size=(10))
test_values = x_values * 2
# print(x_... | <p>This is a pure numpy solution. I didn't compare it against your code in terms of speed, so let me know:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
np.random.seed(10)
x_values = np.random.randint(-50,100,size=(10))
test_values = x_values*2
# create a matrix of len(test_values) times the... | python|numpy | 0 |
7,263 | 55,907,611 | How do I speed up this file creation process? | <p>I am trying to create a large flat file with fixed width columns that contains multiple layers, but processing seems to be very slow, most likely because I am iterating over each row.
For context, this is for transmitting insurance policy information.</p>
<p>The hierarchy goes like this: </p>
<pre><code>-Policy r... | <p>I ended up populating temp tables for each record level, and creating keys, then inserting them into a permanent staging table and assigning an clustered index to the keys.
I then queried the results while using <code>OFFSET</code> and <code>FETCH NEXT %d ROWS ONLY</code> to reduce memory size. I then used the multi... | python|pandas|large-files|file-writing|fixed-width | 1 |
7,264 | 64,676,672 | How can I make a distance matrix with own metric using no loop? | <p>I have a np.arrray like this:</p>
<pre><code>[[ 1.3 , 2.7 , 0.5 , NaN , NaN],
[ 2.0 , 8.9 , 2.5 , 5.6 , 3.5],
[ 0.6 , 3.4 , 9.5 , 7.4 , NaN]]
</code></pre>
<p>And a function to compute the distance between two rows:</p>
<pre><code>def nan_manhattan(X, Y):
nan_diff = np.absolute(X - Y)
length = nan_diff.size
... | <p>Use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer">pdist</a>:</p>
<pre><code>import numpy as np
from scipy.spatial.distance import pdist, squareform
def nan_manhattan(X, Y):
nan_diff = np.absolute(X - Y)
length = nan_diff.size
... | python|numpy|numpy-ndarray | 4 |
7,265 | 39,994,804 | pandas groupby apply does not broadcast into a DataFrame | <p>Using pandas 0.19.0. The following code will reproduce the problem:</p>
<pre><code>In [1]: import pandas as pd
import numpy as np
In [2]: df = pd.DataFrame({'c1' : list('AAABBBCCC'),
'c2' : list('abcdefghi'),
'c3' : np.random.randn(9),
... | <p>an easy fix would be to <code>unstack</code></p>
<pre><code>df = pd.DataFrame({'c1' : list('AAABBBCCC'),
'c2' : list('abcdefghi'),
'c3' : np.random.randn(9),
'c4' : np.arange(9)})
def myfun(s):
"""Function does practically nothing"""
req = s.values
... | python-3.x|pandas | 2 |
7,266 | 39,722,279 | Is it a good idea to apply ML libraries on pandas data frame? | <p>i am building a cognitive miner AI Bot. where My Bot has two task , one is train and other is predict.i'm using some/few ML functionalities. so here i have lots of documents(~200,000 docs) which i'm training. and then in predicting for a query, i'm following some steps to find most accurate matched document(by looki... | <p>It probably won't make much of a difference either way, in terms of performance.</p>
<p>Pandas is extremely efficient for loading data and munging it (grouping it in different ways, pivoting, creating new columns from existing columns, and so forth). </p>
<p>Once your data is ready for passing to a machine learnin... | python|pandas|numpy|artificial-intelligence | 2 |
7,267 | 44,101,223 | Dict inside dict to excel export | <p>I am trying save a dict file to excel(I've tried to use xlsxwriter).
Example:</p>
<pre><code> {'Mod1': {'A': 0.029999999999999999,
'B': 0.050000000000000003, 'C':
0.14000000000000001}, 'Mod2':{'A2': ....}}
</code></pre>
<p>I am getting the Mod1 on first Column (in excel) then the 'A' but not t... | <p>Here is a small working example based on a best guess at the output structure you are looking for. If it doesn't quite match it should be easy to change. This is more of a data structure issue than an XlsxWriter issue:</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workboo... | python|pandas|numpy|dictionary | 1 |
7,268 | 69,312,646 | How to join 2 columns of word embeddings in Pandas | <p>I have extracted word embeddings of 2 different texts (title and description) and want to train an <code>XGBoost</code> model on both embeddings. The embeddings are <code>200</code> in dimension each as can be seen below:</p>
<p><a href="https://i.stack.imgur.com/EgRIk.png" rel="nofollow noreferrer"><img src="https:... | <p>In the past for multiple inputs, I've done this:</p>
<pre><code>features = ['FastText_Title', 'FastText']
x = df[features]
y = df['Category']
</code></pre>
<p>It is creating an array containing both datasets.
I usually need to scale the data as well using MinMaxScaler once the new array has been made.</p> | python|pandas|numpy|machine-learning | 0 |
7,269 | 69,600,671 | How to groupby pandas dataframe and sum values in another column | <p>I have a pandas dataframe with 3 columns (CHAR, VALUE, and WEIGHT).</p>
<ul>
<li><p>CHAR column contains duplicate values which I need to group ['A', 'A', 'A', 'B', 'B', 'C'].</p>
</li>
<li><p>VALUE column has a unique value for every unique CHAR [10, 10, 10, 15, 15, 20].</p>
</li>
<li><p>WEIGHT column has various v... | <p>You could use <code>+=</code> instead:</p>
<pre><code>newDF = df.groupby(['CHAR', 'VALUE'], as_index=False)['WEIGHT'].sum()
newDF['VALUE'] += newDF['WEIGHT']
</code></pre> | python|pandas|dataframe | 2 |
7,270 | 69,528,507 | auto_arima(... , seasonal=False) but got SARIMAX | <p>I want to know the orders (p,d,q) for ARIMA model, so I've got to use <a href="https://pypi.org/project/pmdarima/" rel="nofollow noreferrer"><code>pmdarima</code></a> python package. but it recommends me <strong>SARIMAX</strong> model! keep reading for more details.<br />
i used <a href="https://drive.google.com/fil... | <p>It's not really using a seasonal model. It's just a confusing message.</p>
<p>In the pmdarima library, in version <a href="https://github.com/alkaline-ml/pmdarima/blob/master/doc/whats_new.rst#v151" rel="nofollow noreferrer">v1.5.1</a> they changed the statistical model in use from ARIMA to a more flexible and less ... | python|pandas|arima|pmdarima | 2 |
7,271 | 54,172,932 | How to append multiple CSV files and add an additional column indicating file name in Python? | <p>I have over 20 CSV files in a single folder. All files have the same structure, they just represent different days. </p>
<p>Example:</p>
<p>Day01.csv</p>
<p>Day02.csv</p>
<p>Day03.csv</p>
<p>Day04.csv (and so on...)</p>
<p>The files contain just two numeric columns: x and y. I would like to append all of thes... | <p>The following should work by creating the <code>filename</code> column before appending the <code>dataframe</code> to your list.</p>
<pre><code>import os
import pandas as pd
file_list = []
for file in os.listdir():
if file.endswith('.csv'):
df = pd.read_csv(file,sep=";")
df['filename'] = file
... | python|pandas|csv|append | 7 |
7,272 | 38,356,555 | Pandas: converting .xlsx file to .csv results in a zip file | <p>I am using pandas to covert .xlsx file to .csv. The problem is anytime I run the program the resulting file becomes a zip file instead of csv file.
This is my code:</p>
<pre><code> def exl2csv(x,y):
exlfilename = str(x)
exlsheetname = str(y)
workbook = xlrd.open_workbook(exlfilename)
worksheet = wor... | <p>You could use pandas to do the whole thing if you'd like.</p>
<p><code>pandas.read_excel()</code> will allow you to specify the sheet you want to read so you could do:</p>
<pre><code>def exl2csv(x,y):
exlfilename = str(x)
exlsheetname = str(y)
df = pandas.read_excel(exlfilename, exlsheetname)
csvfi... | python|excel|csv|pandas | 0 |
7,273 | 66,265,235 | Split a string into columns of a table Python | <p>I have a file containing many strings, all of the same format. These strings consist of numbers, all of which are used for providing information about a given problem. I am using Pandas to store my data currently, but not in the format I require.</p>
<p>For example, the format of the strings is as follows:</p>
<pre>... | <p>Try:</p>
<pre><code>pd.read_fwf('file.txt', withds=[4,4,8,8,1,1], dtype='str', header=None)
</code></pre> | python|pandas|dataframe | 1 |
7,274 | 66,288,251 | Combining a list of tuple dataframes in python | <p>I have a large dataset where every two rows needs to be group together and combined into one longer row, basically duplicating the headers and adding the 2nd row to the 1st. Here is a small sample:</p>
<pre><code>df = pd.DataFrame({'ID' : [1,1,2,2],'Var1': ['A', 2, 'C', 7], 'Var2': ['B', 5, 'D', 9]})
print(df)
ID V... | <p>Let us try:</p>
<pre><code>i = df.groupby('ID').cumcount().astype(str)
df_out = df.set_index([df['ID'].values, i]).stack().unstack([2, 1])
df_out.columns = df_out.columns.map('.'.join)
</code></pre>
<p><strong>Details:</strong></p>
<p><code>group</code> the dataframe on <code>ID</code> and use <code>cumcount</code> ... | python|pandas|dataframe|pandas-groupby | 1 |
7,275 | 66,030,740 | Unexpected amplitude in numpy fft | <p>I am having an issue with numpy fft not giving me the expected amplitude in the fft plot. This only happens for certain periods as input.</p>
<p>I am using a clean sine signal with a period of 25 points over 240 datapoints.</p>
<p>The np.fft.rfft gives a peak of 24.</p>
<p><img src="https://i.stack.imgur.com/YKIyl.p... | <p>Recall that an FFT is technically computed over an infinite periodic extension of your signal. Therefore, if your signal doesn’t contain an integer number of periods, the periodic extension will contain a discontinuity (in phase, and usually also in amplitude) at the period boundaries. This will manifest as a “smear... | python|numpy|fft | 6 |
7,276 | 46,316,854 | How to parse string representation back to numpy array? | <p>I used opencv to read an image and save it to redis like this:</p>
<pre><code>frame=cv2.imread('/path/to/image.png')
rd.set('frame', frame)
</code></pre>
<p>then,read it back a string representation like this:</p>
<pre><code>[[[ 38 45 51]
[ 38 45 51]
[ 38 45 51]
...,
[235 217 222]]]
</code></pre>
... | <p>The easiest thing to do would be to encode it as JSON and save that to redis. </p>
<pre><code>frame=cv2.imread('/path/to/image.png')
rd.set('frame', json.dumps(frame. tolist()))
frameString=json.loads(rd.get('frame'))
mat=np.array(frameString)
</code></pre>
<p>You can find faster and more compact serialization f... | opencv|numpy|redis | 0 |
7,277 | 46,533,197 | Understanding variable scope and changes in Python | <p>I'm using Python 3.6 and Pandas 0.20.3.</p>
<p>I'm sure this must be addressed somewhere, but I can't seem to find it. I alter a dataframe inside a function by adding columns; then I restore the dataframe to the original columns. I don't return the dataframe. The added columns stay.
I could understand if I add col... | <p>To understand what happens, you should know the difference between passing attributes to functions by value versus passing them by reference:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference">How do I pass a variable by reference?</a></li>
</ul>
<hr>
<p>You pa... | python|function|pandas | 1 |
7,278 | 58,390,827 | 'numpy.int64' object has no attribute 'loc' | <p>I have a csv file with date and two input values. Here I need to read date with value contain in first column. here I used the code and it gave me this error"'numpy.int64' object has no attribute 'loc'"</p>
<p>Here is my code:</p>
<pre><code>data = pd.read_csv("data6.csv")
data['date']= pd.to_datetime(data['date'... | <p>There are 2 possible solutions - select by positions with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>Index.get_loc</code></a> for position of <code>date</code> column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference... | python-3.x|pandas | 1 |
7,279 | 58,227,305 | KeyError: "None of [Index(['', ''], dtype='object')] are in the [columns]" when trying to select columns on a dask dataframe | <p>I am creating a dask dataframe from a pandas dataframe using the from_pandas() function. When I try to select two columns from the dask dataframe using the square brackets [[ ]], I am getting a KeyError. </p>
<p>According to dask documentation, the dask dataframe supports the square bracket column selection like th... | <p>Try loading less data at once.</p>
<p>I had the same issue, but when I loaded only a subset of my data, it worked.</p>
<p>With the large dataset, I was able to run <code>print(dask_df.columns)</code> and see e.g.</p>
<p><code>Index(['apple', 'orange', 'pear'], dtype='object', name='fruit')</code>.</p>
<p>But when I ... | pandas|dask | 0 |
7,280 | 58,512,790 | Trouble finding numpy.i | <p>I'm wanting to wrap some c++ code in python using swig, and I need to be able to use numpy.i to convert numpy arrays to vectors.</p>
<p>This has been quite the frustrating process, as I haven't been able to find any useful info online as to where I actually get numpy.i from. </p>
<p>This is what I currently have r... | <p><strong>Problem:</strong> The numpy.i file I copied over from the python2.7 package isn't compatible, and the compatible version isn't included in the installation package when you go through anaconda (still not sure why they'd do that).</p>
<p><strong>Answer:</strong> Find which version of numpy you're running, th... | python|c++|numpy|wrapper|swig | 0 |
7,281 | 58,531,223 | Efficient Way to Slice Strings in Pandas | <p>I have a dataset that has over 100 million rows that I am trying to manipulate in pandas. I am trying to slice the string in <code>a</code> based on the values in <code>b</code> and <code>c</code> as the start and end points respectively.</p>
<p><a href="https://i.stack.imgur.com/6s8SR.png" rel="nofollow noreferrer... | <p>Iterating over <code>df.iterrows()</code> is really slow because for each row it creates a separate <code>pd.Series</code> object. For 100 million rows this means 100 million such objects are being created (and discarded). It's better to <code>zip</code> the columns and use this in a comprehension like so:</p>
<pre... | python|pandas|dataframe|text-processing | 3 |
7,282 | 68,939,178 | TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object | <p>I have a dataframe</p>
<pre><code>timestamp
2020-08-26
2020-08-27
2020-08-28
</code></pre>
<p>I want it to look like this</p>
<pre><code>timestamp
2020-08-26 00:00:00
2020-08-27 00:00:00
2020-08-28 00:00:00
</code></pre>
<p>I tried</p>
<pre><code>df['timestamp'] = df['timestamp'].apply(lambda x: dt.datetime.strftime... | <p>try this,</p>
<pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d %H:%M:%S')
</code></pre> | python|python-3.x|pandas|dataframe|datetime | 2 |
7,283 | 68,964,815 | Pandas grouper date_time as per the market hours (Indian Stock Exchange) | <p>Below data is in the interval of 5 mins</p>
<p>Dataframe names as df:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>script_id</th>
<th>date_time</th>
<th>open</th>
<th>high</th>
<th>low</th>
<th>close</th>
<th>volume</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>201</td>
<t... | <p><strong>Maybe:</strong></p>
<pre><code>a = {'script_id': 'first', 'date_time': 'first', 'open': 'first', 'high':'max', 'low':'min', 'close':'last', 'volume':'sum'}
print(df.groupby(df.index // 2).agg(a))
script_id date_time open high low close volume
0 201 2019-02-04 14:55:00... | python|pandas|dataframe|pandas-groupby | 0 |
7,284 | 44,804,784 | Adding a fixed date to pandas dataframe | <p>I am reading some data and creating a dataframe with from_records in which the data contains a text timestamp HH:MM:SS:000000. I can convert to timeseries with <code>pd.to_datetime(data.timestamp, format='%H:%M:%S:%f')</code>. I know the date of the file from the filename. What is a pythonic and performant way to in... | <p>You can create string by <code>strftime</code> from date and add it to column <code>time</code>:</p>
<pre><code>df['datetime'] = pd.to_datetime(date.strftime('%Y-%m-%d ') + df['time'],
format='%Y-%m-%d %H:%M:%S:%f')
print (df)
time A datetime
0 12... | python|pandas | 2 |
7,285 | 44,425,862 | TensorFlow Convolution code Optimization | <p>I am using C++ version of TensorFLow and have built 'TensorFlow for Android' successfully using below command
'bazel build -c opt //tensorflow/examples/android:tensorflow_demo'
as described in <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android#bazel" rel="nofollow noreferrer">h... | <p>1.1) Yes it is, the code is what comes after the Cond() statement:</p>
<pre><code>// If this condition is met, the first argument is chosen, if not, the second one
// is chosen, this condition checks if the input is ColMajor or RowMajor, all of
// the tests I've done result in a RowMajor but I don't know what deter... | tensorflow|convolution | 2 |
7,286 | 60,876,793 | converting sequence of nucleotide into 2D array of integers | <p>I am trying to convert nucleotide to integer using the following mapping:</p>
<pre><code>A -> 0
C -> 1
G -> 2
T -> 3
</code></pre>
<p>The sequence of nucleotide is saved in a pandas dataframe and it looks like:</p>
<pre><code> 0
0 GGATAATA
1 CGATAACC
</code></pre>
<p>I have used the df.... | <p>Use <code>map</code>:</p>
<pre><code>list(map(lambda x: list(map(lambda c: d[c], list(x))), df[0]))
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[[2, 2, 0, 3, 0, 0, 3, 0], [1, 2, 0, 3, 0, 0, 1, 1]]
</code></pre>
<p>or</p>
<pre><code>df[0].agg(list).explode().replace(d).groupby(level=0).agg(list).toli... | python-3.x|pandas|numpy | 1 |
7,287 | 71,619,122 | Flag subset of a dataframe based on another dataframe values | <p>I've encountered a problem which I didn't succeed to solve, for now.
Your assistance on this one would be highly appreciated.</p>
<p>I have 2 dataframes:</p>
<pre><code>first_df:
A B C D
1 1 a q zz
2 2 b w xx
3 3 c e yy
4 4 d r vv
</code></pre>
<pre><code>second_df:
C1 C2
1 10 a
2 20 b ... | <p>First create Multiindex on both the dataframes then use <strong><a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.MultiIndex.isin.html" rel="nofollow noreferrer"><code>MultiIndex.isin</code></a></strong> to test for the occurrence of the index values of first dataframe in the index of seco... | python|pandas|dataframe | 1 |
7,288 | 42,383,490 | {"error": "Error loading the model"} when using /ml/v1beta1/ml.projects.predict | <p>Using the following API Explorer and body,I get the error
{"error": "Error loading the model"}. I was going to start using <a href="https://developers.google.com/resources/api-libraries/documentation/ml/v1beta1/python/latest/ml_v1beta1.projects.html#predict" rel="nofollow noreferrer">https://developers.google.com/... | <p>I added export.meta, export.index and a renamed export.data-00000-of-00001 -> export too cloud storage.</p>
<p>It was an incorrect guess based on the documentation <a href="https://cloud.google.com/ml/docs/concepts/deployment-overview#deployment_location" rel="nofollow noreferrer">https://cloud.google.com/ml/docs/c... | tensorflow|google-cloud-ml|google-apis-explorer | 0 |
7,289 | 43,242,246 | Pandas dataframe + groupby = failed zooming for x-axis ticks | <p>I am trying to plot some <code>pandas</code> dataframe data but, when it is organised into daily/monthly/yearly sums using <code>groupby</code>, the resulting plot cannot be zoomed correctly.</p>
<p>The zoom does work however the x-axis tickmarks don't update correctly. I can't work out the solution to this.</p>
<... | <p>IIUC you can do the following:</p>
<pre><code>x = df_days.groupby(pd.TimeGrouper('MS')).sum()
x.div(x.sum(1), 0).mul(100).plot(kind='area', stacked=True, color=my_colors)
</code></pre>
<p><a href="https://i.stack.imgur.com/Ypx0R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ypx0R.png" alt="ent... | python|pandas|plot|zooming | 2 |
7,290 | 72,437,202 | Count and Find Min, Max of value occurs in a dataframe column | <p>I have a dataframe like that</p>
<pre><code>Date | DayName | A | B | C
2022-03-01 Tuesday 50 20 40
2022-03-02 Wednesday 10 10 20
2022-03-03 Thurday 64 1 9
2022-03-04 Friday 9 7 12
</code></pre>
<p>I'd like to be add rows like :</p>
<pre><code>Date | DayName | A | B | C
2022-03-... | <p>You can try aggregate multiple functions over the rows then concat dataframes</p>
<pre class="lang-py prettyprint-override"><code>cols = ['A', 'B', 'C']
agg = (df[cols].agg(['count', min, max])
.rename_axis('Date')
.reset_index())
out = pd.concat([df, agg])
</code></pre>
<pre><code>print(out)
... | python|pandas|dataframe | 1 |
7,291 | 50,381,329 | How to merge 2 CSV files together by multiple columns in Python | <p>I have two CSV files. <strong>File 1</strong> that looks like:</p>
<pre><code>Ticker | Date | Marketcap
A | 2002-03-14 | 600000
A | 2002-06-18 | 520000
.
.
ABB | 2004-03-16 | 400000
ABB | 2005-07-11 | 800000
.
... | <p>I believe you need to use <code>['Date', 'Ticker']</code> instead of just <code>'Date'</code>. Also you might need to specify the <code>how</code> argument depending on what you want.</p> | python|pandas|csv|merge | 2 |
7,292 | 50,297,604 | Getting rid of the extra header row for HTML styling of Pandas multi-index DataFrames | <p>This pandas code:</p>
<pre><code>import pandas as pd
df=pd.DataFrame([[0,0,1,2,3],[0,1,3,4,5],[1,0,4,5,6],[1,1,5,6,7]],
columns=['A','B','X','Y','Z'])
df.set_index(['A','B'], inplace=True)
df
</code></pre>
<p>displays as follows in IPython Notebook:</p>
<p><a href="https://i.stack.imgur.com/OPQjw.png"... | <p>just use, columns names also in <code>set_index</code>:</p>
<pre><code>df.set_index(['A','B','X','Y','Z'], inplace=True)
df
</code></pre>
<p><a href="https://i.stack.imgur.com/R1jJJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R1jJJ.jpg" alt="enter image description here"></a></p> | python|pandas|jupyter-notebook | 0 |
7,293 | 45,656,479 | What's the best way to store Keras model params and model architecture alongside of the model? | <p>I'd like to save all the model parameters (optimizer, learning rate, batch size, etc.) and model architecture (number and types of layers) alongside of the model so that later go back analyze why some models works better.</p>
<p><strong>Is there a simple way to store this metadata along with the weights?</strong> <... | <p>From <a href="https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model" rel="nofollow noreferrer">the docs</a>:</p>
<pre><code>from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical... | machine-learning|tensorflow|neural-network|keras | 2 |
7,294 | 62,771,868 | AxisError: axis 1 is out of bounds for array of dimension 1 when calculating accuracy of classes | <p>I try to predict 10 classes using this code</p>
<pre><code>#Predicting the Test set rules
y_pred = model.predict(traindata)
y_pred = np.argmax(y_pred, axis=1)
y_true = np.argmax(testdata, axis=1)
target_names = ["akLembut","akMundur","akTajam","caMenaik", "caMenurun&qu... | <p>My guess is that your <code>test_data</code> array is only one-dimensional, so change to</p>
<pre><code>y_true = np.argmax(testdata, axis=0)
</code></pre> | python|python-3.x|tensorflow | 7 |
7,295 | 73,814,929 | Formulating self increasing flag with end string based condition | <p>I have the following Dataframe</p>
<pre><code>df = pd.DataFrame({'Category': {0: 'onboarding segment-confirmation-unexpected-input origin',
1: 'onboarding segment-confirmation-unexpected-input view',
2: 'product-availability cpf-request-unexpected-input origin',
3: 'product-availability postalcode-validation-t... | <p>Assuming you want to consider the first 2 blocks or string (blocks beinf separated by spaces):</p>
<pre><code># get substrings, keep first 2 (can be changed)
df2 = df['Category'].str.split(expand=True).iloc[:, :2]
# start new group if any value is different from the previous row
group = df2.ne(df2.shift()).any(axis... | python|pandas | 2 |
7,296 | 71,167,801 | Fill dataframe with consecutive datetimes | <p>I have a DataFrame:</p>
<pre><code>| init | end | temp
2022-02-02 10:34:00 | 2022-02-02 11:34:00 | 34
2022-02-02 11:34:00 | 2022-02-02 12:34:00 | 12
2022-02-02 13:34:00 | 2022-02-02 14:34:00 | 23
2022-02-02 14:34:00 | 2022-02-02 15:34:00 | 22
2022-02-02 17:34:00 | 2022-02-02 18:34:00 | 1... | <p>You can make temporal dataframe which consist of datetime period, then you can OUTER JOIN (using <code>pd.merge()</code>), as follows:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from datetime import timedelta
df = pd.DataFrame({
'init': ['2022-02-02 10:34:00', '2022-02-02 11:34:00',... | python|pandas|datetime | 1 |
7,297 | 71,435,149 | Check for a list of word in DataFrame pandas but skipping those words that are not in | <p>so i'm trying to filter a dataframe using a list of words. The problem is that some words could be not there but anyway could be useful.</p>
<p>These dataframe is a catalog that I'm getting from a web scraping process. For every single row, I have a different product and unique.</p>
<p>The list that I'm using came f... | <p>If is possible specify what exactly need for each match - here is necessary match 3 values of tuples use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>Series.str.findall</code></a> with <code>re.I</code> for ignore case and test len... | python|pandas|dataframe|contains | 0 |
7,298 | 60,557,274 | Creating a new Min() and Max() column based another dataframe | <p>I'm trying to create two columns in a new dataframe base on the Min and the Min from an existing dataframe. When groupby is used, it is giving min and max NAN values </p>
<pre><code>df.groupby('street').min()['sold_price']
df.groupby('street').max()['sold_price']
</code></pre>
<p>sample from existing dataframe.</p... | <p>It should be</p>
<pre><code>(df.groupby("street_name", as_index=False)
["sold_price"].agg(["min","max"])
)
</code></pre>
<hr>
<p><strong>Update</strong>: for rename:</p>
<pre><code>(df.groupby("street_name", as_index=False)
["sold_price"].agg({'low':'min', 'high':'max'})
)
</code></pre> | python|pandas | 0 |
7,299 | 60,518,772 | Convert ndarray to dict in python3 | <p>I have a ndarray that look like this</p>
<pre><code>LABEL1 99 113 2010-04-26 20:12:23+00:00
LABEL1 29 143 2010-05-06 20:12:23+00:00
LABEL1 99 323 2010-02-12 20:12:23+00:00
LABEL1 23 223 2010-04-25 20:... | <p>First convert it into dataframe:</p>
<p><strong>df:</strong></p>
<pre><code> 0 1 2 3
0 LABEL1 29 143 2010-05-06 20:12:23+00:00
1 LABEL1 99 323 2010-02-12 20:12:23+00:00
2 LABEL1 23 223 2010-04-25 20:12:23+00:00
3 LABEL2 23 23 2010-01-21 20:12:23+00:00
4 LABEL1 234 123 2010-12-2... | python|pandas|list|dataframe|arraylist | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.