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 |
|---|---|---|---|---|---|---|
363,700 | 69,496,321 | Pandas read_sql_query turning float number to int | <p>I'm trying to extract info from an SQL database to Python. Two columns of the database are numbers, primarily in float format. My problem arises with numbers with more than 6 digits, read_sql_query reads them as int so the decimals do not appear in the dataframe. For example, if the database in SQL looks like this:<... | <p>This Seems to just be a case of your IDE limiting the number of significant figures in the display rather than the data type changing, you could check this by printing the column at issue to the console by</p>
<pre><code>print(query.Payed.values)
</code></pre> | python|pandas|dataframe|read-sql | 0 |
363,701 | 69,353,400 | Mapping pandas df to JSON Schema | <p>Here is my df:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>text</th>
<th>date</th>
<th>channel</th>
<th>sentiment</th>
<th>product</th>
<th>segment</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>I like the new layout</td>
<td>2021-08-30T18:15:22Z</td>
<td>Snowflake</td>
<t... | <p>One option is to use a nested list comprehension:</p>
<pre><code># Start with your example data
d = {'text': ['I like the new layout'],
'date': ['2021-08-30T18:15:22Z'],
'channel': ['Snowflake'],
'sentiment': ['predict'],
'product': ['Skills'],
'segment': ['EMEA']}
df = pd.DataFrame(d)
# S... | python|json|pandas | 1 |
363,702 | 69,431,143 | How to create a cumulative counter for sales in a financial year? | <p>My df looks like this.</p>
<pre><code>Policy_No Date
1 10/1/2020
2 20/2/2020
3 20/2/2020
4 23/3/2020
5 18/4/2020
6 30/4/2020
7 30/4/2020
</code></pre>
<p>I would like to create a cumulative counter of policies logged in different dates based on ... | <p>there's a function called <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer">cumsum</a> which does that:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({"Policy_No":[1,2,3,4,5,6,7],"Date":["10/1/2020",&quo... | python|pandas|pandas-groupby|counter|data-manipulation | 1 |
363,703 | 69,531,018 | Appending columns with different first valid index | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame(
list(zip([1, 2, 3, 4, 5, 6, 7, 12, 32, 4, 2, 4],
[5, 6, 7, 84, 5, 3, 12, 32, 3, 5, 3],
[9, 10, 11, 12, 4, 5, 2, 12, 45, 45, 65, 34],
[13, 14, 15, 16, 12, 23, 5, 12, 3, 2, 5, 3],
[17, 18, 19, 20, ... | <p>Use <code>bfill</code>:</p>
<pre><code>>>> df.bfill(axis=1)["A"]
0 1.0
1 2.0
2 7.0
3 84.0
4 4.0
5 5.0
6 5.0
7 12.0
8 4.0
9 53.0
10 35.0
</code></pre> | python|pandas|dataframe|indexing|append | 1 |
363,704 | 69,417,810 | how to load multiple files in a folder from s3 to Python Notebooks | <p>I have a series of s3 files in one folder on s3, their format looks as below:</p>
<pre><code>aac0202-2121-41.csv
aac0202-2121-42.csv
aac0202-2121-43.csv
aac0202-2121-44.csv
...aac0202-2121-70.csv
</code></pre>
<p>They all have the same columns, I am trying to read_csv and aggregate them together.</p>
<p>The file sho... | <p>Try:</p>
<pre><code>df_list = []
for number in arange(41, 71, 1):
df = pd.read_csv('s3://ap/data/tm/aac0202-2121-%s.csv'%number)
df_list.append(df)
df_final = pd.concat(df_list)
</code></pre> | python|pandas|amazon-s3 | 0 |
363,705 | 69,315,596 | numpy Structured arrays append and remove records | <p>let's say we have this structured array :</p>
<pre><code>x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],
dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])
</code></pre>
<p>how to delete the first row :('Rex', 9, 81.0) ?
and how add another row ??</p> | <p>Are you wanting this: <em>(with <a href="https://numpy.org/doc/stable/reference/generated/numpy.insert.html#numpy.insert" rel="nofollow noreferrer"><code>np.insert</code></a>)</em></p>
<pre><code>>>> x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])... | python|numpy|structured-array | 2 |
363,706 | 69,643,275 | How to Get overlapping Records for a particular group in Pandas Dataframe | <p>I have a csv file (Delimited with '|') with data something like this:</p>
<pre><code>|origin|destination|class|eff_start_date|eff_end_date|price
0|A|B|1|2016-01-01|2016-12-31|37.4
1|A|B|2|2016-01-01|2016-12-31|30.4
2|A|C|1|2016-01-01|2016-12-31|94.0
3|A|C|2|2016-01-01|2016-12-31|80.0
4|A|B|1|2017-01-01|2017-12-31|38... | <p>I think you put the shift at the wrong position. This would then point out the rows, where the end date from the previous row and the start date from the current row are "overlapping".</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from datetime import timedelta
df_fares = pd.read... | python|pandas|dataframe|date | 0 |
363,707 | 69,504,437 | How can I get the positions of a group? | <p>I have pandas dataframe like this</p>
<pre><code>data = [[1, 'a'], [2, 'a'], [3, 'b'], [4, 'b'], [5, 'a'], [6, 'c']]
df1 = pd.DataFrame(data, columns=['Id', 'Group'])
</code></pre>
<pre><code>Id Group
1 a
2 a
3 b
4 b
5 a
6 c
</code></pre>
<p>Without changing order I need to get... | <p>try, <code>transform</code> + <code>cumcount</code></p>
<pre><code>df1['position'] = df1.groupby('Group').transform('cumcount') + 1
</code></pre>
<hr />
<pre><code> Id Group position
0 1 a 1
1 2 a 2
2 3 b 1
3 4 b 2
4 5 a 3
5 6 c 1... | python|pandas | 3 |
363,708 | 69,652,613 | Pandas plot line with different line styles? | <p>I am plotting several lines on the same plot, using the <code>ggplot</code> style. With this style, the lines become all solid lines. So the visibility is not good. How can I change each line to have different styles, e.g., one with dashed lines, or something?</p>
<pre><code>import pandas as pd
import matplotlib.pyp... | <p>You can use <code>linestyle</code> to change each line with different styles.</p>
<p>Here is an example :</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig,ax = plt.subplots(figsize=(15,5))
ax.set_title('Loss curve', fontsize=15)
ax.set_ylabel('Loss')
ax.set_xlabel('Epoc... | python|pandas|matplotlib | 1 |
363,709 | 69,471,371 | Pandas: Multiply row value by groupby of another column as a new column | <p>I have a DataFrame that looks like this. I am trying to add a new column df['new_sales'] where I multiply df['rate'] by the groupby sum of df['state','store'].</p>
<pre><code>import pandas as pd
data = [['california', 'a', 11, 0.6], ['california', 'a', 12, 0.4], ['california', 'b', 32, 0.7]]
df= pd.DataFrame(data, c... | <p>Use the <code>transform</code> option, to align the values with the length of the original dataframe; should be faster than an apply, and without the anonymous function :</p>
<pre class="lang-py prettyprint-override"><code>df['NewSales'] = df.groupby(['state', 'store']).sales.transform('sum') * df.rate
print(Df)
... | python|pandas|dataframe | 1 |
363,710 | 69,305,111 | Increment a column based on the condition of another column in python | <p>I have a data frame and I want to create a new column name "new" based on a condition on a different column "col". Create the new column name "new" and count it whenever it finds any value in "col".</p>
<pre><code> index col
1 2.11.67
2 N... | <p>You can use a combination of <code>notna</code>, <code>cumsum</code>, and <code>where</code>:</p>
<pre><code>mask = df['col'].notna()
df['new'] = mask.cumsum().where(mask)
</code></pre>
<p>output:</p>
<pre><code> col new
index
1 2.11.67 1.0
2 NaN NaN
3 NaN NaN
4 ... | python|python-3.x|pandas | 2 |
363,711 | 69,616,621 | Python multiprocessing manager showing error when used in flask API | <p>I am pretty confused about the best way to do what I am trying to do.</p>
<p>What do I want?</p>
<ol>
<li>API call to the flask application</li>
<li>Flask route starts 4-5 multiprocess using Process module and combine results(on a sliced pandas dataframe) using a shared Managers().list()</li>
<li>Return computed res... | <p>Stack has an ongoing bug preventing me from commenting, so I'll just write up an answer..</p>
<p>Python has 2 (main) ways to start a new process: "spawn", and "fork". Fork is a system command only available in *nix (read: linux or macos), and therefore spawn is the only option in windows. After 3... | python-3.x|pandas|flask|multiprocessing | 1 |
363,712 | 69,434,511 | How to remove specific records based on column pattern | <p>I have a table like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>event</th>
<th>value</th>
<th>time</th>
</tr>
</thead>
<tbody>
<tr>
<td>seed</td>
<td>57</td>
<td>2021-08-01 09:49:23</td>
</tr>
<tr>
<td>ghy</td>
<td>869</td>
<td>2021-08-02 09:50:12</td>
</tr>
<tr>
<td>repo</td>
... | <p>Because element in <code>value column</code> is string. you can <code>.split()</code> them and sort them with <code>np.sort</code> then back them to string and use <code>drop_duplicates()</code> like below.</p>
<p>Try this:</p>
<pre><code>import numpy as np
df['value2'] = df['value'].apply(lambda x : ','.join(np.so... | python|pandas|dataframe | 2 |
363,713 | 69,554,764 | How to get Matrix using numpy | <p>I want to make matrix like below using numpy</p>
<pre><code>matrix_example = [[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, ... | <p>There's already a <code>np.matrix</code> function that makes what you probably want</p>
<p>For you example, it should be as easy as</p>
<p><code>my_matrix = np.matrix(matrix_example)</code></p>
<p>Have a look at the official documentation for further info :)<br />
<a href="https://numpy.org/doc/stable/reference/gene... | python|numpy | 0 |
363,714 | 69,651,212 | appending values to coordinates in array of zeros | <p>I am generating two parameters e.g.</p>
<pre><code>s1 = [0, 0.25, 0.5, 0.75, 1.0]
s2 = [0, 0.25, 0.5, 0.75, 1.0]
</code></pre>
<p>based on dimensions of both these lists above, i am creating a grid of zeros:</p>
<pre><code>np.zeros((5,5))
</code></pre>
<p>I then pair up each of the numbers in each list so they form ... | <p>The easiest way is probably to construct a meshgrid and transpose it so that the axises are the way you want them:</p>
<pre><code>np.array(np.meshgrid(s1, s2)).transpose(1, 2, 0)
</code></pre> | arrays|python-3.x|numpy|numpy-ndarray | 1 |
363,715 | 69,430,019 | How to get index of multiple, possibly different, elements in numpy? | <p>I have a numpy array with many rows in it that look roughly as follows:</p>
<pre><code>0, 50, 50, 2, 50, 1, 50, 99, 50, 50
50, 2, 1, 50, 50, 50, 98, 50, 50, 50
0, 50, 50, 98, 50, 1, 50, 50, 50, 50
0, 50, 50, 50, 50, 99, 50, 50, 2, 50
2, 50, 50, 0, 98, 1, 50, 50, 50, 50
</code></pre>
<p>I am given a variable <strong>... | <p>The follwing <code>numpy</code> solution rather aggressively uses the assumptions listed in OP. If they are not 100% guaranteed some more checks may be in order.</p>
<p>The mildly clever bit (even if I say so myself) here is to use the data array itself for finding the right destinations of their indices. For exampl... | python|arrays|numpy|multidimensional-array|indexing | 1 |
363,716 | 69,470,332 | I get error: module 'tensorflow.keras.layers' has no attribute 'Normalization' | <p>I use</p>
<pre><code>layers.Normalization()
</code></pre>
<p>in Keras, in <code>keras.Sequential</code>
When I try to run it, I get the following error:</p>
<blockquote>
<p>module 'tensorflow.keras.layers' has no attribute 'Normalization'</p>
</blockquote>
<p>I've seen the command <code>layers.Normalization()</code>... | <p>One reason can be that you are using the tensorflow version older then the required to use that layer. There are two ways to get around this problem.</p>
<ol>
<li>Upgrade tensorflow as discussed above.</li>
<li>Or you can add the layer as follows:</li>
</ol>
<pre><code>tf.keras.layers.experimental.preprocessing.Nor... | tensorflow|keras | 12 |
363,717 | 69,401,183 | How to create a pandas Series (column), based in a match with a value in another Dataframe? | <p>my question is the following: I do not know very well all the pandas methods and I think that there is surely a more efficient way to do this: I have to load two tables from .csv files to a postgres database; These tables are related to each other with an id, which serves as a foreign key, and comes from the source ... | <p>Well indeed, I was not understanding very well all the pandas functions, I could solve my problem using merge, I did not know that pandas had a good implementation of the typical Join in SQL.</p>
<p>This documentation helped me a lot:</p>
<ol>
<li><p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/m... | python|pandas|postgresql|dataframe|series | 0 |
363,718 | 69,532,735 | Convert pandas Dataframe to python native int | <p>Versions where problem occurs:</p>
<pre><code>python 3.6.13
pandas 1.1.5
numpy 1.19.2
</code></pre>
<p>This seems trivial but I can't find a satifying solultion so far. First, I import data into a pandas Dataframe before loading to an SQL database. The failure message that I've gotten is:</p>
<pre><code>Programmin... | <p>You should know which int bit length your database uses and convert with the appropriate type: <code>np.int8</code>/<code>np.int16</code>/<code>np.int32</code>/<code>np.int64</code></p>
<p>Example:</p>
<pre><code>import numpy as np
df['col'].astype(np.int8)
</code></pre> | python|sql|pandas|numpy | 0 |
363,719 | 69,590,653 | Im trying to write the data in the list into an excel sheet,and the list is displayed as shown below.If i try list[0] i only get 22, how to get A too? | <p>so the when I just display list out its showed as:</p>
<pre><code>A 22
WO 8
Name: 7, dtype: int64
</code></pre>
<p>and when I try list[0] it only prints the value 22.</p>
<p>how do I print the whole row like:</p>
<pre><code>A 22
</code></pre>
<p>Also I'm trying to write this into an excel sheet. And im thi... | <p>Here is a step-by-step guide to writing lists to excel using pandas and printing the first row in the data frame (or all rows).</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
list_1 = [0, 1, 2]
list_2 = ['A', 'B', 'C']
data_as_dictionary = {'Name':list_2, 'Value':list_1}
df = pd.DataFrame(d... | python|pandas|list|dataframe|data-science | 2 |
363,720 | 40,804,054 | How to restore a saved variable in tensorflow? | <p>I am trying to restore a saved variable in tensorflow. Seems like it is very very complicated. </p>
<p>I use the alexnet implementation in <a href="http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/" rel="nofollow noreferrer">http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/</a></p>
<p>in a python file, alexnet.py, I ... | <p>Restoring from the meta graph prepares the graph, not the data. Restoring data requires adding at training time the values you want to restore to collection objects, and reload these collections at restore time. The <a href="https://www.tensorflow.org/versions/master/how_tos/variables/index.html" rel="nofollow">offi... | tensorflow | 0 |
363,721 | 41,050,710 | How do you read a geojason url into a geopandas dataframe or pandas dataframe? | <p>I tried this this but I got a messy outlook</p>
<pre><code>from io import StringIO, BytesIO
Trial ='https://data.cityofnewyork.us/resource/t7ny-aygi.geojson?vendorid=VTS&payment_type=CRD&$limit=500'
trialck = requests.get(Trial).content
final = pd.read_csv(StringIO(trialck.decode('utf-8')), sep = '\t')
fina... | <p>You can try <code>pandas.io.json.json_normalize</code>. In this case, it cannot handle the full json return, but if you specify the <code>'features'</code> key in the json, pandas can convert that to a dataframe.</p>
<pre><code>import requests
url = 'https://data.cityofnewyork.us/resource/t7ny-aygi.geojson?vendorid... | pandas|anaconda|geopandas | 3 |
363,722 | 40,836,670 | Extract a part of values from a column | <p>I have a dataframe df which has one of the column called "Results". That columns has values like - </p>
<pre><code>Results
Movie passed 1 of 3 tests
Movie passed 2 of 3 tests
Movie passed 3 of 3 tests
<empty string>
Movie passed 1 of 3 tests
</code></pre>
<p>I want to create a new column which extract the nu... | <p>You can use <code>extract()</code> method and capture the digits after the word <code>passed</code>, if nothing matches, it returns <code>nan</code> by default but you use <code>fillna()</code> method to replace <code>nan</code> with <code>0</code>:</p>
<pre><code>df.Results.str.extract('passed ([0-9]+)').fillna(0)... | python|pandas|dataframe | 2 |
363,723 | 40,868,156 | Removing duplicates on 1 field based on priority list from another field in pandas | <p>I've got a large set of data where I'm trying to remove duplicates based on 2 fields. Sample set:</p>
<pre><code>WOE_ID ISO Locationname Language Placetype Parent_ID ID Username
2347578 US Maine ENG State 23424977 1 sampleuser
2444322 US Maine ENG Town ... | <p>I think you can use ordered <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow noreferrer"><code>Categorical</code></a>, then sort <code>DataFrame</code> by column <code>Placetype</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.h... | pandas | 7 |
363,724 | 41,065,371 | Is it possible to get monthly stock prices from Google Finance? | <p>In Python, monthly stock prices from Yahoo Finance as follows...</p>
<pre><code>import pandas_datareader.data as web
data = web.get_data_yahoo('IBM','01/01/2016',interval='m')
</code></pre>
<p>I tried to get monthly stock prices from Google Finance, but daily stock prices are returned</p>
<pre><code>data = web.g... | <p>According to the <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html#google-finance" rel="nofollow noreferrer">documentation</a>, this is indeed possible. </p>
<p>EDIT: The example below, despite being part of the documentation, does not seem to work. I have found that the following works a... | python|pandas | 0 |
363,725 | 41,077,285 | How to pack two values of shape (?, 2) and (?, 3) in tensorflow? | <p>I'm trying to use tf.pack on two values that have shape (?, 2) and (?, 3) by axis=0, but I get the error that they're incompatible. Is there a way for me to stack the values by columns so I have a value of shape (?, 5)?</p> | <p>You can use <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/array_ops.html#concat" rel="nofollow noreferrer">tf.concat()</a> for this.</p>
<pre><code>a = tf.placeholder('float', (None, 2))
b = tf.placeholder('float', (None, 3))
c = tf.concat(1, [a,b])
</code></pre> | python|tensorflow|pack | 1 |
363,726 | 41,045,510 | Pandas: read_csv ignore rows after a blank line | <p>There is a weird .csv file, something like:</p>
<pre><code>header1,header2,header3
val11,val12,val13
val21,val22,val23
val31,val32,val33
</code></pre>
<p>pretty fine, but after these lines, there is always a blank line followed by lots of useless lines. The whole stuff is something line:</p>
<hr>
<pre><code>head... | <p>There is not any option to terminate <code>read_csv</code> function by getting the first blank line. This module isn't capable of accepting/rejecting lines based on desired conditions. It only can ignore blank lines (optional) or rows which disobey the formed shape of data (rows with more separators).</p>
<p>You ca... | python|pandas | 4 |
363,727 | 40,978,472 | How to pick values based on aggregation of other columns in a group by with Python Pandas? | <p>I have data that looks like this:</p>
<pre><code>system question answer grade rank
sys1 q1 a1 A 5
sys1 q1 a1 B 10
sys2 q1 a1 C 1
sys2 q1 a1 D 11
</code></pre>
<p>My goal is to group by questi... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> first and then aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.last.html" rel="nofollow nor... | python|pandas|dataframe|group-by|criteria | 1 |
363,728 | 40,938,834 | Export a basic Tensorflow model to Google Cloud ML | <p>I am trying to export my local tensorflow model to use it on Google Cloud ML and run predictions on it.</p>
<p>I am following the <a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/mnist_export.py#L47" rel="nofollow noreferrer">tensorflow serving example with mnist data</a>. There... | <p>Tensorflow Serving and Google Cloud ML are two different things, don't mix them up. Cloud ML is a fully managed solution (ML as a service), whereas TF Serving requires you to set up and maintain your infrastructure - it's just a server. They are unrelated and have different requirements in input/output handling. </p... | python|machine-learning|tensorflow|tensorflow-serving|google-cloud-ml | 6 |
363,729 | 41,170,382 | Parameter estimates for generic data for any function | <p>I have a function. For example:</p>
<pre><code>def g(w,d,e):
s = w-1.
s1 = s**d+2.
s2 = 42. + s1*e**(1/2)
return s2
</code></pre>
<p>Lets <code>data = np.array([1,2,3,4,5])</code> it is <code>s2</code>. But I don't know <code>d</code> and <code>e</code>.</p>
<p>How I can <strong>estimate</stro... | <p>According to your question, your function could be written as</p>
<pre><code>def g(w,d,e):
return 42. + ((w-1)**d+2)*e**(1/2)
</code></pre>
<p>so what you seem to need instead of a fitting procedure that minimizes the squared error between predicted values and observed values is a non-linear equation solver. S... | python|python-2.7|pandas|numpy|scipy | 1 |
363,730 | 41,095,576 | Is there any way in python for searching pattern from a dataframe and extracting its corresponding values? | <p>I have a Dataframe like this.</p>
<pre><code> Area of Power Cons. Device Name 2016-09-02 2016-09-03
0 01.11KVA VCB-I South SJ 11 South Zone Con 32328.19 33157.12
1 02.11KVA VCB-II Sout SJ 11 South Zone Con 43879.94 45152.77
2 03.11 KVA VCB-I Nort SJ 11 North Zone Con ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with mask where first convert all values to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.lower.html" rel="nofollow noreferre... | python|regex|pandas|dataframe | 3 |
363,731 | 40,784,621 | Applying a function to only part of a Pandas Dataframe columns | <p>I have a Dataframe that looks like this:</p>
<pre><code>Date Last
2016-11-03 101.58
2016-11-04 100.50
2016-11-07 103.55
2016-11-08 104.63
2016-11-09 106.15
2016-11-10 107.65
2016-11-11 106.74
2016-11-14 108.22
2016-11-15 107.92
2016-11-16 106.03
</code></pre>
<p>and a simple fu... | <p>You could rewrite your <code>new_def</code> function to take a date parameter:</p>
<pre><code>def new_def(val, date):
return val+70.0 if date < pd.datetime(2016, 11, 9) else val
</code></pre>
<p>And then apply it like this:</p>
<pre><code>df.apply(lambda r: newdef(r['Last'], r.name), 1)
</code></pre> | python|pandas | 1 |
363,732 | 40,922,319 | Generate all polynomial terms of certain degree | <p>Having list of n terms </p>
<pre><code>ts = ['t1','t2','t3',...,'tn']
</code></pre>
<p>there is a task to achieve all possible q-length combinations of this terms.</p>
<p>Thus, for</p>
<pre><code>ts = ['t1','t2']
q = 4
</code></pre>
<p>the answer will be</p>
<pre><code>[['t1','t1','t1','t1'],['t1','t2','t2','t... | <p>What you need are combinations with replacement. The simplest solution is to use the aptly named <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement" rel="nofollow noreferrer"><code>itertools.combinations_with_replacement</code></a>:</p>
<pre><code>>>> list(ite... | python|arrays|python-2.7|numpy|itertools | 1 |
363,733 | 40,958,982 | How to fit two keras ImageDataGenerators for sets of images | <p>I am looking for a solution or an example for the following task:</p>
<p>I have sets of images of the <strong>same objects taken from different angles</strong>.
I would like to build a deep-CNN with keras, which can take <strong>sets</strong> of two images, perform data augmentation on each image separately, and fe... | <p>using the pickle_safe=True solved the problem</p> | python|tensorflow|deep-learning|keras | 1 |
363,734 | 40,790,009 | Tensorflow generate random values unexpected behaviour | <p>I want to generate a random Vector and don't understand tensorflows results....</p>
<p>Code:</p>
<pre><code>import tensorflow as tf
some_test = tf.Variable(
tf.random_uniform([20], -1.0, 1.0, dtype=tf.float32))
init_op = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init_op)
random = sess.run(som... | <p>Okay this is very confusing but the reason it did not work was that I was running some other Tensorflow Code in parallel. After I stopped this code the random generation works as expected. I doubt this is expected behaviour though.</p>
<p>If I use <code>with tf.device('/cpu:0'):</code> it works on my machine even i... | tensorflow | 2 |
363,735 | 40,823,179 | Create a Large Numpy Array | <p>I am trying to create a symmetrical numpy array with values ranging between 0.4- 1 with 20000*20000 rows and columns. However, I am getting a memory error when I create this big array.
Please find my code below.</p>
<p>import numpy as np</p>
<pre><code>def random_symmetric_matrix(n):
_R = np.random.uniform(0.... | <p>I copied your function, and removed the print and savetxt:</p>
<pre><code>In [574]: def random_symmetric_matrix(n):
...: _R = np.random.uniform(0.4,1,n*(n-1)//2)
...: P = np.zeros((n,n))
...: print('...')
...: P[np.triu_indices(n, 1)] = _R
...: print(',,,')
...: ... | python|arrays|numpy|out-of-memory | 1 |
363,736 | 53,925,575 | Creating an XML file in python nodes are missing | <p>I want to create a XML file with elementtree library.</p>
<p>the XML file should look like:</p>
<pre><code><files>
<file>
<ans>EP16</ans>
<ep></ep>
<date>2017-03-15</date>
<concepts>~what</concepts>
</file>
... | <p>If you want a <code><file></code> tag per each row in the <code>dffiles</code> thing, move that inside the loop too.</p>
<pre><code>nrofrows = dffiles.shape[0]
for i in range(nrofrows):
file = ET.SubElement(XMLfiles, "file")
serie = dffiles.iloc[i]
child1 = ET.SubElement(file, "an")
child1.tex... | python|xml|pandas|elementtree | 2 |
363,737 | 53,898,104 | Set indices of dataframe as a single key in dictionary | <p>I have a dataframe such as:</p>
<pre><code>df = {'index': [0, 0, 0, 0, 0, 1,1,1,1,1, 2,2,2,2], 'value': ['val1', 'val2', 'val3', 'val4', 'val5', 'val6','val7','val8','val9','val10', 'val11','val12','val13','val14']}
</code></pre>
<p>I'd like to get a dictionary where each index would become a key in my dictionary,... | <p>I can think of something like:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'index': [0, 0, 0, 0, 0, 1,1,1,1,1, 2,2,2,2], 'value': ['val1', 'val2', 'val3', 'val4', 'val5', 'val6','val7','val8','val9','val10', 'val11','val12','val13','val14']})
df.groupby(by='index').apply(lambda x: list(x['value'])).to_dic... | python|pandas|dictionary|dataframe | 2 |
363,738 | 53,814,677 | Python pandas: filtering rows based on time criteria using pandas | <p>I have a CSV file with millions of rows in the following format:</p>
<pre><code>Amount,Price,Time
0.36,13924.98,2010-01-01 00:00:08
0.01,13900.09,2010-01-01 00:02:04
0.02,13907.59,2010-01-01 00:04:54
0.07,13907.59,2010-01-01 00:05:03
0.03,13925,2010-01-01 00:05:41
0.03,13920,2010-01-01 00:07:02
0.15,13910,2010-01-0... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Grouper.html" rel="nofollow noreferrer"><code>pd.Grouper</code></a>:</p>
<pre><code>n=5
df.groupby(pd.Grouper(key = 'Time', freq=f'{n} min')).first()
Amount Price
Time
2010-01... | python|pandas|datetime|filtering | 1 |
363,739 | 53,956,468 | How to find source indexes of window max for dataframe? | <p>I have a dataframe with <code>DatetimeIndex</code> and I want to find maximum elements for each window. But also I have to know indexes of elements.
Example data:</p>
<pre><code>data = pd.DataFrame(
index=pd.date_range(start=pd.to_datetime('2010-10-10 12:00:00'),
periods=10, freq='H'),
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.aggregate.html" rel="nofollow noreferrer"><code>Resampler.agg</code></a> with custom function, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow noreferre... | python|pandas|dataframe|argmax | 4 |
363,740 | 54,093,274 | Need to get ranked values in a column after group by | <p>I have a dataframe as below:</p>
<pre><code>Card_x Country Age Code Card_y Diff
S INDIA Adult Garments S 9.2
S INDIA Adult Grocery S 21.33
S INDIA Adult Garments M 151.4
S INDIA Adult Grocery M 202.15
S INDIA Adult Grocery G 48.7
S INDIA Adult Gar... | <p>Try:</p>
<pre><code>df.sort_values('Diff').groupby(['Card_x','Country','Age','Code'])['Card_y']\
.agg(list).reset_index()
</code></pre>
<p>Output:</p>
<pre><code> Card_x Country Age Code Card_y
0 S INDIA Adult Garments [S, E, D, G, M, A]
1 S INDIA Adul... | python|python-3.x|pandas | 3 |
363,741 | 54,041,234 | How to check Data Frame columns contains numeric values or not? Python 3.6 | <p>I have dataframe with two columns - REGIONID & REGIONNAME</p>
<p>I want to update REGIONID with REGIONNAME if REGIONID contains Numeric values.</p>
<pre><code>Data_All.loc[Data_All['REGIONID'].str.isnumeric() is True , 'REGIONID'] = Data_All['REGIONNAME']
</code></pre>
<p>I am getting error like</p>
<pre><co... | <p>Remove <code>is True</code> because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.isnumeric.html" rel="nofollow noreferrer"><code>isnumeric</code></a> return boolean mask:</p>
<pre><code>Data_All.loc[Data_All['REGIONID'].str.isnumeric(), 'REGIONID'] = Data_All['REGIONNAME']
</code... | python|python-3.x|pandas|dataframe | 2 |
363,742 | 54,137,029 | Shift non-overlapping columns so that they overlap/align | <p>I've got unevenly spaced timeseries that a resample to a slightly higher frequency (in this case <code>1min</code>) so that I can perform some calculations. Now there is one column, named <code>minor</code> in the example, which some times delayed by a few rows, some times it is correctly aligned. I need to find a w... | <p>I found a solution after understanding how <code>agg</code>/<code>aggregate</code> works. I was not able to completely avoid loops, but at least it is only looping over the aggregated blocks, while the rest is vectorized.<br>
This solution should work for most kinds of inputs/types, as long as general shape and inde... | python|pandas|time-series|aggregate-functions|pandas-groupby | 0 |
363,743 | 54,073,369 | Tensorflow on Golang Model sessionn run error : nil-Operation. If the Output was created with a Scope object, see Scope.Err() for details | <p>iam use golang with tensorflow model. With this code :
```</p>
<pre><code> output, err := sessionModel.Run(
map[tf.Output]*tf.Tensor{
graphModel.Operation("input").Output(0): tensor,
},
[]tf.Output{
graphModel.Operation("output").Output(0),
},
nil)
</code></pre>
<p>```</p>
... | <p>The error says the <code>Output</code> attribute (of a certain the node) is a nil operation.</p>
<p>Hence <code>graphModel.Operation("input").Operation(0)</code> or <code>graphModel.Operation("output").Output(0)</code> returns <code>nil</code>.</p>
<p>To correct this, you have to refer to an existing node in the g... | tensorflow|go | 3 |
363,744 | 54,159,814 | RuntimeError: The shape of the mask [1682] at index 0 does not match the shape of the indexed tensor [1, 1682] at index 0 | <p>I am designing an stacked autoencoder trying to train my neural network on movie rating if the user doesnt rate any movie it will not consider it </p>
<p>My training set runs perfectly but when i run test set it shows me this error </p>
<p>RuntimeError: The shape of the mask [1682] at index 0 does not match the s... | <p><strong>Change</strong>:</p>
<pre><code>output[target == 0] = 0 # I get error at this line
</code></pre>
<p><strong>To</strong>:</p>
<pre><code>output[(target == 0).unsqueeze(0)] = 0
</code></pre>
<p><strong>Reason</strong>:</p>
<p>The <code>torch.Tensor</code> returned by <code>target == 0</code> is of th... | tensorflow|pytorch|autoencoder | 3 |
363,745 | 54,118,069 | ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=2 | <p>When I try to give Elmo embedding layer output to conv1d layer input it giving the error</p>
<blockquote>
<p>ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=2</p>
</blockquote>
<p>I want to add a convolution layer from the output of the Elmo embedding layer</p>
<pre><code>im... | <p>A <code>Conv1D</code> layer <a href="https://keras.io/layers/convolutional/#Conv1D" rel="nofollow noreferrer">expects input of the shape</a> <code>(batch, steps, channels)</code>. The channels dimension is missing in your case, and you need to include it even if it is equal to 1. So the output shape of your elmo mod... | tensorflow|keras | 2 |
363,746 | 53,908,051 | How to make Hadamard product along axis with numpy? | <p>I am trying to make the Hadamard product of a 3-D with a 2-D array. The 2-D array shares the shape of the first two axes of the 3-D array and should be moved along the 2 axis (thus, the 3rd) for the multiplications, meaning: make Hadamard product with slice 0, then slice 1, and so on (cf. image, schematic).</p>
<p>... | <p>Have a look at how <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasting</a> works. Essentially you can append an axis to perform element wise operations, for example this works</p>
<pre><code>import numpy as np
a = np.random.rand(10, 3)
b = np.rando... | python|arrays|numpy|array-broadcasting|numpy-ufunc | 2 |
363,747 | 53,881,855 | How to confirm my tensorflow model is restoring successfully? | <p>Here is my code for the prediction part from a trained model after 1000 steps. </p>
<pre><code>class vandys_speak(object):
def __init__(self,session,input_mfcc, model_file):
self.model_file = model_file
self.model = model_trainer(training_mode=False, batch_size=2, sent_max_len = 10)
self.session = sess... | <p>According to <a href="https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint" rel="nofollow noreferrer">Tensorflow docs</a>:</p>
<blockquote>
<p>To ensure that loading is complete and no more assignments will take
place, use the <strong>assert_consumed</strong>() method of the status object returned
b... | python|tensorflow | 0 |
363,748 | 54,066,263 | selective building of new dataframe with existing dataframes in addition to calculation | <p>Fill in the Pandas code below to create a new DataFrame, customer_spend, that contains the following columns in this order: customer_id, name, and total_spend. total_spend is a new column containing the sum of the cost of all the orders that a particular customer placed.</p>
<p>I'm doing an online course related to... | <p>Consider first aggregating <code>orders</code> by <code>customer_id</code>, then merging the resulting <code>customer_id</code>-indexed DataFrame onto the desired columns of <code>customers</code>:</p>
<pre><code>cust2spend = orders.groupby('customer_id').sum()[['order_total']].reset_index()
cust2spend
customer_id ... | python|python-3.x|pandas|numpy|merge | 2 |
363,749 | 53,806,916 | pandas split-apply-combine with results returned to original DataFrame | <p>I want to document a particular case of the <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow noreferrer">'split-apply-combine'</a> method here. </p>
<p>The issue: I start with a DataFrame and I have to do some processing of the data that requires a groupby split and returns some res... | <p>You can use transform for Res2 and Res3 is simply the sum. No need to create two new columns</p>
<pre><code>df['Res2'] = df.groupby('Group').Res1.transform('mean')
df['Res3'] = df['Prop2'] + df['Res1']
Group Prop1 Prop2 Res1 Res2 Res3
0 A S1 2004 0 1.5 2004
1 A S2 2004 1 1.5... | pandas|pandas-groupby | 1 |
363,750 | 54,036,347 | Django turn pandas dataframe into queryset | <p>I have a django app that renders querysets into tables. </p>
<p>I need to perform a few modifications of the underlying querysets and it would be the most convenient to convert the querysets into dataframes, do some magic there and then convert the resulting dataframe back into a queryset so that I can feed it into... | <p>Really, that does not seem to be trivial, since <code>QuerySet</code> sorta expects there to be a relational database beneath the hood. You could implement an adapter <code>QuerySet</code>-like class that would have the same methods as a <code>QuerySet</code>, but implement its functionality as <code>pandas</code> c... | django|pandas | 3 |
363,751 | 54,244,415 | nested for loops with pandas dataframe | <p>I am looping through a dataframe column of headlines (sp500news) and comparing against a dataframe of company names (co_names_df). I am trying to update the frequency each time a company name appears in a headline. </p>
<p>My current code is below and is not updating the frequency columns. Is there a cleaner, faste... | <p>You can probably speed this up; you're using dataframes where other structures would work better. Here's what I would try.</p>
<pre class="lang-py prettyprint-override"><code>from collections import Counter
counts = Counter()
# checking membership in a set is very fast (O(1))
company_names = set(co_names_df["Name... | python|pandas|dataframe | 1 |
363,752 | 53,981,434 | Randomly selecting Unique (not repeated) elements from a tensor in Tensorflow | <p>This is a follow up to these two SO questions</p>
<p><a href="https://stackoverflow.com/questions/53951879/tensorflow-how-to-select-random-values-from-tensor-while-excluding-padded-value">Tensorflow: How to select random values from tensor while excluding padded values?</a></p>
<p><a href="https://stackoverflow.co... | <p>Set replace=False parameter</p>
<p>np.random.choice(x.reshape(-1),s, replace=False)</p>
<p>full code</p>
<pre><code>nuMs = tf.placeholder(tf.float32, shape=[None, 2])
size = tf.placeholder(tf.int32)
y = tf.py_func(lambda x, s: np.random.choice(x.reshape(-1),s, replace=False), [nuMs , size], tf.float32)
with tf.... | python|tensorflow | 0 |
363,753 | 54,045,283 | split a column into multiple lists, and keep deliminator | <p>I have a dataframe, which I need to split a column on character "Y" and keep this deliminator. For example,</p>
<pre><code> import pandas as pd
d1 = pd.DataFrame({'user': [1,2,3],'action': ['YNY','NN','NYYN']})
</code></pre>
<p>The output dataframe should look like this, </p>
<pre><code> d2 = pd.DataFr... | <p>Sounds like you need </p>
<pre><code>d1.action.str.split('([^Y]*Y)').map(lambda x : [z for z in x if z!= ''])
Out[234]:
0 [Y, NY]
1 [NN]
2 [NY, Y, N]
Name: action, dtype: object
</code></pre> | pandas|list|split | 1 |
363,754 | 54,081,670 | Is there a way to rewrite the function data1.groupby(level=0)['total_tax'],apply(lambda x: x.shift()) to avoid Setting With Copy Warning | <p>I'm working with a big dataset and when I'm performing this function:</p>
<pre><code>data1['total_t_1'] = data1.groupby(level=0)['total_tax'].apply(lambda x: x.shift())
</code></pre>
<p>I'm getting this error: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc... | <p>It's just warning you that <code>data1</code> came from a slice of another DataFrame, and that you therefore shouldn't expect the original DataFrame to be updated when you change <code>data1</code>. If you want to make the warning go away then set <code>data1 = data1.copy()</code> first. See the link from pault's co... | python|python-3.x|pandas|lambda|pandas-groupby | 1 |
363,755 | 54,237,869 | Pandas Applying multiple greater than and less than grouping rows by specific column | <p>I am creating 3 pandas dataframes based off of one original pandas dataframe. I have calculated standard deviations from the norm. </p>
<pre><code>#Mean
stats_over_29000_mean = stats_over_29000['count'].mean().astype(int)
</code></pre>
<p>152542</p>
<pre><code>#STDS
stats_over_29000_count_between_std = stats_ov... | <p>Pandas now has the <code>Series.between(left, right, inclusive=True)</code>, that allows both <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="noreferrer">both comparisons at the same time</a>.</p>
<p>In your case:</p>
<pre><code>stats_2_and_over_under_3_stds = \... | python|python-3.x|pandas | 6 |
363,756 | 54,053,339 | Creating a dataframe where one of the arrays has a different length | <p>I am learning to scrape data from website through Python. Extracting weather information about San Francisco from <a href="https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168" rel="nofollow noreferrer">this page</a>. I get stuck while combining data into a Pandas Dataframe. Is it possible to crea... | <p>You can loop each forecast_items value with <code>iter</code> and <code>next</code> for select first value, if not exist is assigned fo dictionary <code>NaN</code> value:</p>
<pre><code>page = requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168")
soup = BeautifulSoup(page.content, ... | python|pandas|dataframe | 0 |
363,757 | 54,077,218 | Pandas to_datetime convert year-week to date in 2019, first week is wk0 | <p>I used to use year and week number to convert to date for some propose.
it works well before 2019, but when i tried to import 2019 wk1 data, it wired.</p>
<p>2019 wk1 becomes between 2019-01-07 ~ 2019-01-03</p>
<p>But on the contrary, if i use date to convert to year and wk, it's correct.</p>
<p>May I know what's... | <p>According to <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">strftime() and strptime() Behavior</a>,</p>
<blockquote>
<p>%W: Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first... | python|pandas | 1 |
363,758 | 54,241,367 | How to find where in numpy array a zero element is preceded by at least N-1 consecutive zeros? | <p>Given a numpy array (let it be a bit array for simplicity), how can I construct a new array of the same shape where 1 stands exactly at the positions where in the original array there was a zero, preceded by at least N-1 consecutive zeros?</p>
<p>For example, what is the best way to implement function <code>nzeros<... | <p><strong>Approach #1</strong></p>
<p>We can use <a href="https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html" rel="noreferrer"><code>1D</code> convolution</a> -</p>
<pre><code>def nzeros(a, n):
# Define kernel for 1D convolution
k = np.ones(n,dtype=int)
# Get sliding summations for ze... | python|arrays|numpy | 10 |
363,759 | 54,210,128 | Tensorflow text_generation | <p>I'm working through the code<br>
<a href="https://www.tensorflow.org/tutorials/sequences/text_generation" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/sequences/text_generation</a></p>
<p>When I arrive at the line the following error is produced. </p>
<pre><code> sampled_indices = tf.random.categ... | <p>tf.random.categorical probably has been changed to tf.random.multinomial, assuming example_batch_predictions are logits:
<a href="https://www.tensorflow.org/api_docs/python/tf/random/multinomial" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/random/multinomial</a></p> | python|tensorflow | 4 |
363,760 | 54,185,221 | Extracting only numbers from series Python | <p>I have a series that looks like:</p>
<pre><code>ID
WTG-1
11
11-1
12B1
13-1
5
6
G7
.
.
</code></pre>
<p>I simply want to be able to extract <em>all</em> the numbers from each <code>ID</code>.</p>
<p>When I use my code:</p>
<pre><code>df['ID'] = df['ID'].str.extract('(\d+)', expand=True)
</code></pre>
<p>It does ... | <p>Using <code>findall</code></p>
<pre><code>df.ID.str.findall('(\d+)').apply(''.join)
Out[92]:
0 1
1 11
2 111
3 121
4 131
5 5
6 6
7 7
Name: ID, dtype: object
</code></pre> | python|regex|string|pandas|dataframe | 4 |
363,761 | 53,971,612 | First Column Not Imported as Index Pandas | <p>I have the following csv file:</p>
<p><a href="https://i.stack.imgur.com/rHkih.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rHkih.png" alt="enter image description here"></a></p>
<p>I created it by using the pandas export option:</p>
<pre><code>database.to_csv('database.csv')
</code></pre>
... | <p>Just do:</p>
<pre><code>database = pd.read_csv("database.csv", index_col=0)
</code></pre> | python-3.x|pandas|csv | 1 |
363,762 | 53,857,953 | After how many columns does the Pandas 'set_index' function stop being useful? | <p>As I understand it, the advantage to using the <code>set_index</code> function with a particular column is to allow for direct access to a row based on a value. As long as you know the value, this eliminates the need to search using something like <code>loc</code> thus cutting down the running time of the operation.... | <p>The real downside of setting everything as index is buried deep in the advanced indexing docs of Pandas: <a href="https://pandas.pydata.org/pandas-docs/stable/advanced.html#indexing-potentially-changes-underlying-series-dtype" rel="nofollow noreferrer">indexing can change the dtype of the column being set to index</... | python|pandas|indexing | 2 |
363,763 | 54,048,170 | Combining two series into one with mismatching indicies | <p>I'm trying to merge two series with mismatching indicies into one, and I'm wondering what best practices are. </p>
<p>I tried combine_first but I'm getting an issue where combining a series [0, 24, ...] with a series [1, 25, ...] should give a series with indicies [0, 1, 24, 25, ...] but instead I'm getting [0, 12,... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> followed by <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>sort_index</code><... | python|pandas|sorting|series | 2 |
363,764 | 53,838,570 | Custom Loss Function - Attention to small regions | <p>I want to use a loss function which includes an expression for the area used by the attention model.</p>
<p>My model is a classification model, designed to perform the decision based on a small region of the original image.</p>
<p>So I would like my loss function to be:</p>
<pre><code>Loss = categorical_crossentr... | <p>Make a model that outputs both things, <code>y_pred</code> and <code>A</code>:</p>
<pre><code>#blablabla functional API model definition
model = Model(inputs, [predictions, areaOutput])
</code></pre>
<p>Make a custom area loss:</p>
<pre><code>def areaLoss(trueArea, predArea):
return predArea
</code></pre>
<p... | tensorflow|keras|loss-function | 2 |
363,765 | 54,070,412 | How can I vectorize a loop over a Pandas DataFrame in Python? | <p>I need to make this code run fast by vectorization</p>
<pre><code>final1 = pd.DataFrame()
for index, row in demo1.iterrows():
a = np.random.choice([0, 1], size=1000, p=[1 - row['prob'], row['prob']])
b = a * row['syb'] * (1 + row['percentage_change_syb'] / 100)
final1 = final1.append(pd.DataFrame(b).T)
... | <p>Since you did not supply data to work against, the following code is unchecked, but should work:</p>
<pre><code>def computation(prob, syb, percentage_change_syb):
a = np.random.choice([0, 1], size=1000, p=[1 - prob, prob])
b = a * syb * (1 + percentage_change_syb / 100)
return b.T
final1 = computation(... | python|pandas|dataframe|vectorization | 1 |
363,766 | 54,173,484 | Why can all dataframe columns be accessed in the series passed to the aggregating function when using DataFrameGroupBy.agg? | <p>I made an observation while playing around with the <code>apply</code> and <code>agg</code> methods of <code>DataFrameGroupBy</code> objects which I cannot explain.</p>
<hr>
<p><strong>Introduction</strong></p>
<p>I understand the following code, but it may be useful as an introduction for the question.</p>
<p>I... | <p>It actually does raise a <code>KeyError</code> which you can see when wrapping the access in <code>try/except</code>:</p>
<pre><code>In [23]: def func(df):
...: print(type(df))
...: print(df)
...: print()
...: try:
...: df['col0']
...: except KeyError:
...: ... | python|pandas | 3 |
363,767 | 54,092,258 | Model.predict() ValueError: Cananot feed value of shape (300,300,3) for Tensor which has shape (?,300,300,3) | <p>I have trained my classifier which is working well. But I am facing a value error here about the shape. I even resize the testing image in shape (300,300,3). please help.</p>
<p>I am trying to predict an image from the training classifier I build. But everytime I try to do this it gives me this value error. Which I... | <p>So, I tried the link which @Flika205 mentioned and it does work. But for possible best answer you should use np.expand_dims(img, axis = 0). </p>
<p>My code is below</p>
<pre><code>predictingimage = "D:/compCarsThesisData/data/image/78/12/2012/722894351630dc.jpg" #67/1698/2010/6805eb92ac6c70.jpg"
predictImageRead =... | python|tensorflow|image-processing|machine-learning | 0 |
363,768 | 54,105,419 | Add numbers with duplicate values for columns in pandas | <p>I have a data frame like this:</p>
<pre><code>df:
col1 col2
1 pqr
3 abc
2 pqr
4 xyz
1 pqr
</code></pre>
<p>I found that there is duplicate value and its pqr. I want to add 1,2,3 where pqr occurs. The final data frame I want to achieve is:</p>
<pre><code>df1
col1 co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.duplicated.html" rel="noreferrer"><code>duplicated</code></a> with <code>keep=False</code> for all dupe rows and add counter created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.... | python|pandas|dataframe | 18 |
363,769 | 53,980,468 | What is the recommended way to compute a weighted sum of selected columns of a pandas dataframe? | <p>For example, I would like to compute the weighted sum of columns 'a' and 'c' for the below matrix, with weights defined in the dictionary <code>w</code>.</p>
<pre><code>df = pd.DataFrame({'a': [1,2,3],
'b': [10,20,30],
'c': [100,200,300],
'd': [1000,2000,30... | <p>You could use a Series as in your first example, just use reindex afterwards:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': [1,2,3],
'b': [10,20,30],
'c': [100,200,300],
'd': [1000,2000,3000]})
w = {'a': 1000., 'c': 10.}
print(df.dot(pd.Series(... | python|pandas|dot-product | 4 |
363,770 | 54,011,684 | Reversing order in incrementing digits | <p>I have a list of numbers, and I'm trying to do the following in a way as efficient as possible.</p>
<p>For each consecutively incrementing chunk in the list I have to reverse its order.</p>
<p>This is my attempt so far:</p>
<pre><code>l = []
l_ = []
i = 0
while i <= len(a)-1:
if a[i] < a[i+1]:
l... | <p>Try this:</p>
<p>(with fixes from @Scott Boston and @myrmica)</p>
<pre><code>nums = [1, 3, 5, 4, 6, 8, 9, 7, 2, 4] # sample input
chunk = [] # keep track of chunks
output = [] # output list
for i in nums:
if chunk and i < chunk[-1]:
output.extend(chunk[::-1]) # add reversed chunk to output
... | python|list|numpy|sorting | 0 |
363,771 | 54,218,533 | How do I convert this array type, which I want to be a float64 type | <p>Because there's a pair of single quotes outside the array. I always report errors when I process data, and I want to convert it to another type.</p>
<p>arr.dtype = 'float64' , That doesn't work</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>> arr = np.array('[1,2,3,4]... | <pre class="lang-py prettyprint-override"><code> >>> import ast
>>> import numpy as np
>>> arr9 = '[1,2,3,4]'
>>> arr9 = ast.literal_eval(strArr)
>>> arr9
[1, 2, 3, 4]
>>> type(arr9)
<class 'list'>
>>> arr = np.array... | python-3.x|numpy | 0 |
363,772 | 54,207,772 | Reorder row values from lowest to highest | <p>I'm attempting to take a dataset with 5 columns of data and order the data in each row from lowest to highest. So far I've come up with a method that will loop through 0-4 and return value, but I get stuck at there as I can't figure out how create columns for all 5 row values. Any help would be greatly appreciated. ... | <p>Try:</p>
<pre><code>pd.DataFrame(np.sort(df.values, axis=1), index=df.index, columns=df.columns)
</code></pre>
<p>Output:</p>
<pre><code> S1 S2 S3 S4 S5
0 1713 203145 203458 1627752 1629027
1 1713 45222 203145 1627752 1629027
2 1713 203145 203458 1627752 1629027
3 45... | python|pandas | 0 |
363,773 | 53,949,850 | Efficient way to get union of set of vectors in Numpy | <p>I'm trying to implement a specific binary search algorithm. "Results" should be an empty set in the beginning, and during the search, Results variable will become a union with the new results that we get.</p>
<p>Basically:</p>
<pre><code>results = set()
for result in search():
results = results.union(result)
</c... | <p>Here's some basic set operations.</p>
<p>Define a pair of lists (they could be <code>np.array([1,2,3])</code>, but that's not what you show.</p>
<pre><code>In [261]: a = [1,2,3]; b=[3,4,5]
</code></pre>
<p>A list of several of those:</p>
<pre><code>In [263]: alist = [a, b, a]
In [264]: alist
Out[264]: [[1, 2, 3]... | python|arrays|numpy | 1 |
363,774 | 53,815,935 | Why does SciPy's curve_fit function care about the type of xdata? | <p>I was trying to fit some data using SciPy's <code>curve_fit</code> and got really weird results. So I tried and tried and tested and found the issue in the type of <code>xdata</code>. When <code>xdata</code> is of type <code>int</code>, the results become very weird. But that does not hold for all functions <code>f<... | <p>It is not <code>curve_fit</code>that cares about the type of <code>x</code>, it's your function <code>poly4</code>. Numpy preserves the type of the arrays in its operations. Since you are taking the n-power of an integer, you will quickly run into an integer overflow, which therefore produces unexpected results.</p>... | python|numpy|matplotlib|scipy | 1 |
363,775 | 38,372,903 | Pandas: print pivot_table to dataframe | <p>I have data</p>
<pre><code>id year val
123 2014 1
123 2015 0
123 2016 1
456 2014 0
456 2015 0
456 2016 1
789 2014 1
789 2015 0
789 2015 0
</code></pre>
<p>And I want to print pivot_table and get</p>
<pre><code>date 2014 2015 2016
ID
123 1 0 1
456 ... | <p>You can use:</p>
<pre><code>group = output.pivot_table(index='id', values='val', columns='year', fill_value=0)
print (group)
year 2014 2015 2016
id
123 1 0 1
456 0 0 1
789 1 0 0
</code></pre>
<p>EDIT:</p>
<p>You get these values with real data, becasue... | python|pandas | 2 |
363,776 | 38,311,872 | Flip Pandas dataframe on column and create dictionary | <p>I have a Pandas dataframe with 2 columns, e.g.</p>
<pre><code> name case
0 a 01
1 a 03
2 b 04
3 b 05
4 b 06
5 b 08
6 b 09
7 b 12
8 c 01
9 c 02
10 c 03
11 c 04
</code></pre>
<p>What I need is a dictionary:</p>
<pre><code>{"a": ["01", "03"],
"b": ["04", "05", "06", "... | <p>After performing the <code>groupby</code>, use <code>apply</code> to get a list, and then call <code>to_dict</code>:</p>
<pre><code>df.groupby('name')['case'].apply(list).to_dict()
</code></pre>
<p>The resulting output:</p>
<pre><code>{'a': ['01', '03'], 'c': ['01', '02', '03', '04'], 'b': ['04', '05', '06', '08'... | python|pandas | 7 |
363,777 | 38,449,404 | **ImportError**: unable to load extension module '/home/wyx/pypy3env/site-packages/numpy/core/**multiarray.pypy3-52.so**': | <p>I created a virtualenv of <strong>PyPy 5.2.0-alpha0 with GCC 4.6.3</strong> on Ubuntu 14.04.
After that installed numpy (using pip) for pypy successfully, when i do
<code>import numpy</code> in the pypy3 intepreter the following error occurrs:</p>
<pre><code>ImportError: unable to load extension module
'/home/wyx/p... | <p>You can't fix this, I'm afraid. <code>pypy3</code> 5.2 does not support <code>numpy</code>.</p> | python|numpy|pypy | 0 |
363,778 | 38,121,665 | Multiply NumPy ndarray with every element in another binary ndarray of different size | <p>I have two ndarrays :</p>
<pre><code>a = [[30,40],
[60,90]]
b = [[0,0,1],
[1,0,1],
[1,1,1]]
</code></pre>
<p>please notice that a shape might be larger but always square array (50,50) , (100,100)
The wanted result is :</p>
<pre><code>Result = [[a*0,a*0,a*1],
[[a*1,a*0,a*1],
[[a*1,a*... | <p>Indeed there's a NumPy built-in <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html" rel="nofollow"><code>np.kron</code></a> for such block-based elementwise multiplication problems. To solve your case, it could be used like so -</p>
<pre><code>np.kron(b,a)
</code></pre>
<p>Sample run -</p... | python|numpy | 2 |
363,779 | 38,435,289 | How to get positional coordinates (n×2) for a uniformly spaced array? | <p>I am trying to make an array of line elements (23×23 grid) using the <a href="http://www.psychopy.org/api/visual/visual.html#psychopy.visual.ElementArrayStim" rel="nofollow"><code>ElementArrayStim</code></a> from PsychoPy. </p>
<p>For the <code>xys</code> parameter for positions of the line elements, I am trying to... | <p>You were very close, just needed to create a 3D array of coordinates from <code>xaxis</code> and <code>yaxis</code> and then reshape that 3D array to get a 529 rows × 2 columns 2D array as required:</p>
<pre><code>In [21]: xy = np.dstack(np.meshgrid(xaxis, yaxis)).reshape(-1, 2)
In [22]: xy
Out[22]:
array([[-220,... | python|arrays|numpy|psychopy | 3 |
363,780 | 38,168,016 | How to know when to use numpy.linalg instead of scipy.linalg? | <p>Received wisdom is to prefer <code>scipy.linalg</code> over <code>numpy.linalg</code> functions. For doing linear algebra, ideally (and conveniently) I would like to combine the functionalities of <code>numpy.array</code> and <code>scipy.linalg</code> without ever looking towards <code>numpy.linalg</code>. This is n... | <p>So, the normal rule is to just use <code>scipy.linalg</code> as it generally supports all of the <code>numpy.linalg</code> functionality and more. The <a href="https://docs.scipy.org/doc/scipy/reference/linalg.html" rel="noreferrer">documentation</a> says this:</p>
<blockquote>
<p><strong>See also</strong></p>
<p><c... | python|arrays|numpy|scipy | 13 |
363,781 | 38,189,657 | Pandas not working in Downloads Directory | <p>When I enter my <code>Downloads</code> directory on Mac OSX (10.9.5), I entered Python from my terminal and tried to import pandas using <code>import pandas as pd</code></p>
<pre><code>name:Downloads name$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] o... | <p>It looks like you have a file called <code>token.py</code> in your Downloads directory.
It is getting imported instead of the <code>token.py</code> module from the standard library:</p>
<pre><code> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tokenize.py", line 30, in <module>... | python|macos|pandas | 1 |
363,782 | 38,161,133 | How do I efficiently map only those points that fall within the bounding box of a map? | <p>I have the following code, where <code>mp</code> is a <code>Shapely</code> <code>Multipolygon</code> off of a <code>Fiona</code> box:</p>
<pre><code>ax = fig.add_subplot(111)
minx, miny, maxx, maxy = mp.bounds
w, h = maxx - minx, maxy - miny
ax.set_xlim(minx, maxx)
ax.set_ylim(miny, maxy)
ax.set_aspect(1)
patches =... | <p>I guess it would be most efficient to filter the points on a pandas level. For that get the bounds of the Multipolygon using its <code>bounds</code> property and then filter the dataframe using</p>
<pre><code>df[(df.lat > latmin) & (df.lat < latmax)
& (df.long > longmin) & (df.long < lon... | python|pandas|matplotlib | 1 |
363,783 | 38,427,431 | Tensorflow - How access loss value for each example in batch? | <p>During training I periodically evaluate my tensorflow network using a modified version of the tensorflow example do_eval() function. My evaluation loss is:</p>
<pre><code>evalLoss = tf.nn.l2_loss(tf.sub(prediction, truthValues_placeholder))
</code></pre>
<p>This produces a single scalar loss value. I feed batch tr... | <p>As tf.nn.l2_loss(t) just returns sum(t ** 2) / 2, </p>
<ol>
<li>Yes.</li>
<li>Yes.</li>
<li>You can just name the result of sub() like below.</li>
</ol>
<p>Then get the eachLoss value by run() or eval() method.</p>
<pre><code>eachLoss = tf.sub(prediction, truthValues_placeholder)
evalLoss = tf.nn.l2_loss(eachLoss... | tensorflow | 2 |
363,784 | 38,493,468 | What are the parameters of TensorFlow's dynamic_rnn for this simple data set? | <p>I want to train an RNN language model using TensorFlow.</p>
<p>My training data is a sequence of 5 tokens represented with integers like so</p>
<pre><code> x = [0, 1, 2, 3, 4]
</code></pre>
<p>I want the unrolled length of the RNN to be 4, and the training batch size to be 2. (I chose these values in order to req... | <p>most rnn cells require floating point inputs, so you should first do an embedding lookup on your integer tensor to go from the Categorical values to floating point vectors in your dictionary/embedding. i believe the function is tf.nn.embedding_lookup. the output of that should be a 3-tensor shaped batch x time x e... | tensorflow|recurrent-neural-network | 0 |
363,785 | 38,077,203 | How to use self join to reshape duplicate rows in Pandas? | <p>I have a duplicates rows and I want to concatenate them. They are like : </p>
<pre><code>ID Col1 Col2 Col3 ... Col46
-----------------------------------
id1 a1 b1 c1 ... x1
id2 a2 b2 c2 ... x2
id1 a1 b1 c1 ... y1
id3 a3 b3 c3 ... x3
id3 a3 b3 ... | <p>I think you need first create <code>groups</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><... | python|pandas|merge|reshape|self-join | 4 |
363,786 | 38,454,748 | selecting according to two condintions | <p>I can't figure it out why this does not work. The <code>df2</code> dataframe should contain all the data from df which match two conditions..</p>
<pre><code>df2 = df.loc[df['area'] == "north" & df['product'] == "a"]
</code></pre> | <p>Either</p>
<pre><code>df2=df.loc[df['area'] == "north"].loc[df['product'] == "a"]
</code></pre>
<p>or</p>
<pre><code>df2 = df[(df["area"] == "north") & (df["product"] == "a")]
</code></pre>
<p>Would do the job.</p> | python|pandas | 0 |
363,787 | 38,228,703 | How to optimize loading of batch on tensorflow? | <p>I have a problem with the very slow batch loading in tensorflow.
Each step in the training is reasonably fast but my function to load data is extremely slow.</p>
<p>I was wondering if there were any ways to make this faster or run it in the background when train operation is running so that the batch can be ready b... | <p>Input data preparation and training a model using the prepared data can be decoupled in TensorFlow using <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#queues" rel="nofollow">queues</a>. You can create a queue with <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_op... | python|numpy|optimization|tensorflow | 3 |
363,788 | 38,067,348 | Creating datetime in pandas from year and julian day | <pre><code> ad_name adl_name year JD
0 united_states_of_america colorado 2000 1
1 united_states_of_america colorado 2000 2
2 united_states_of_america colorado 2000 3
3 united_states_of_america colorado 2000 4
4 united_states_of_america colorado 2000 5
</code></pre>
... | <p>You need add to <code>year</code> column <code>JD</code> converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>:</p>
<pre><code>df['date'] = pd.to_datetime(df.year, format='%Y') + pd.to_timedelta(df.JD - 1, unit='d')
print (df)... | python|datetime|pandas|dataframe|time-series | 4 |
363,789 | 38,443,398 | Efficient way to look in list of lists? | <p>I am continuously creating a randomly generated list, <code>New_X</code> of size 10, based on 500 columns. </p>
<p>Each time I create a new list, it must be unique, and my function <code>NewList</code> only returns <code>New_X</code> once it hasn't already been created and appended to a <code>List_Of_Xs</code></p>
... | <p>So let me get this straight since the code doesn't appear complete:
1. You have an old list that is constantly growing with each iteration
2. You calculate a list
3. You compare it against each of the lists in the old list to see if you should break the loop?</p>
<p>One option is to store the lists in a set instea... | python|numpy | 1 |
363,790 | 38,156,265 | Getting 'av_interleaved_write_frame(): Broken pipe' error | <p>I am trying this blog post.I am new to python, numpy as well as FFMPEG. I could not figure out what causes this issue.</p>
<p><a href="http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/" rel="noreferrer">http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-py... | <p>It is a programming error as this <a href="https://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess">answer</a> suggests. FFMPEG tries to write to stout after stout is closed because python program finished running. a while loop solved this problem.</p>
<pre><code>while true:
#for line in... | python|python-2.7|numpy|ffmpeg|video-streaming | 3 |
363,791 | 38,075,171 | Dynamic function call, depneding on condition in tensorflow graph | <p>I'm trying to implement a <code>dynamic_rnn_decoder</code>. However, I get an exception, because after the second element the Tensors in the cell are already created. Thus I want to set <code>reuse=True</code> after the first iteration.
Is there a <code>op</code> which calls dynamically a function depending on a con... | <p>while_loop only calls the underlying body function once. not dynamically for every time step. if you're getting an error when getting the variable, it's because you also access the variable elsewhere in your code.</p>
<p>In this case, looks like it's because of your cond statement. this causes two calls to cell(... | tensorflow | 1 |
363,792 | 38,088,652 | Pandas: convert categories to numbers | <p>Suppose I have a dataframe with countries that goes as:</p>
<pre><code>cc | temp
US | 37.0
CA | 12.0
US | 35.0
AU | 20.0
</code></pre>
<p>I know that there is a pd.get_dummies function to convert the countries to 'one-hot encodings'. However, I wish to convert them to indices instead such that I will get <code>cc_... | <p>First, change the type of the column:</p>
<pre><code>df.cc = pd.Categorical(df.cc)
</code></pre>
<p>Now the data look similar but are stored categorically. To capture the category codes:</p>
<pre><code>df['code'] = df.cc.cat.codes
</code></pre>
<p>Now you have:</p>
<pre><code> cc temp code
0 US 37.0 ... | python|pandas|series|categorical-data|binning | 200 |
363,793 | 38,249,961 | Install pip for python 3.5 | <p><strong>SOLUTION</strong> My user did not own permissions to the pip directory, I reinstalled Python 3.5 using the <code>sudo -H</code> flag</p>
<p>I'm trying to install Tensorflow for python 3.5 using pip3 -- for reasons described in <a href="https://github.com/tensorflow/tensorflow/issues/3196#issuecomment-231114... | <p>Check: /usr/local/lib/python3.5/dist-packages</p>
<p>You'll either have Pip there or easy_install(part of Pythons setup tools), which can be used to install Pip:</p>
<pre><code>sudo apt-get install python3-setuptools
sudo python3.5 easy_install.py pip
</code></pre>
<p>Or you can try:</p>
<pre><code>python3.5 -m ... | python|ubuntu|installation|pip|tensorflow | 16 |
363,794 | 38,434,529 | Use pandas map or applymap or similar to process pairs of rows in a dataframe | <p>I'm trying to process a counter like that that counts miles in a car into the differences between counters:</p>
<p>Here is the input:</p>
<pre><code>Index, Counter
2016-06-01 13:00:00,225907.9
2016-06-01 14:00:00,225908.9
2016-06-01 15:00:00,225909.9
2016-06-01 16:00:00,225910.9
2016-06-01 17:00:00,22... | <p>It's unclear how you get your output based on your input but you can do this using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> which is vectorised and will be much faster for large datasets:</p>
<pre><code>In [15]:
df['Increase'] = df[... | pandas | 0 |
363,795 | 38,490,717 | Creating NaN values in Pandas (instead of Numpy) | <p>I'm converting a .ods spreadsheet to a Pandas DataFrame. I have whole columns and rows I'd like to drop because they contain only "None". As "None" is a <code>str</code>, I have:</p>
<p><code>pandas.DataFrame.replace("None", numpy.nan)</code></p>
<p>...on which I call: <code>.dropna(how='all')</code></p>
<p>Is th... | <p>You can use <code>float('nan')</code> if you really want to avoid importing things from the numpy namespace:</p>
<pre><code>>>> import pandas as pd
>>> s = pd.Series([1, 2, 3])
>>> s[1] = float('nan')
>>> s
0 1.0
1 NaN
2 3.0
dtype: float64
>>>
>>> s.dr... | python|pandas | 8 |
363,796 | 65,961,250 | AttributeError: 'Index' object has no attribute 'to_excel' | <p>There are plenty of similar questions. Here are two:</p>
<p><a href="https://stackoverflow.com/questions/61663329/python-error-attributeerror-nonetype-object-has-no-attribute-to-excel">Python Error: AttributeError: 'NoneType' object has no attribute 'to_excel'</a></p>
<p><a href="https://stackoverflo... | <p><code>df3.columns</code> is an index object (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.html" rel="nofollow noreferrer"><code>pandas.Index</code></a>), so while you replace <code>_</code> it returns an index object. Instead do this:</p>
<pre><code>import pandas as pd
ws = r'c:/... | python|excel|pandas | 1 |
363,797 | 66,323,301 | How to run one batch in pytorch? | <p>I'm new to AI and python and I'm trying to run only one batch to aim to overfit.I found the code:
<code>iter(train_loader).next()</code></p>
<p>but I'm not sure where to implement it in my code. even if I did, how can I check after each iteration to make sure that I'm training the same batch?</p>
<pre><code>train_lo... | <p>If you are looking to train on a single batch, then remove your loop over your dataloader:</p>
<pre><code>for i, data in enumerate(train_loader, 0):
inputs, labels = data
</code></pre>
<p>And simply get the first element of the <code>train_loader</code> iterator <em>before</em> looping over the epochs, otherwise... | python|deep-learning|pytorch|artificial-intelligence | 2 |
363,798 | 66,107,858 | Keyerror when looping over a data frame column | <p>I had a dataset, and I want to create a new data frame from a column in the original one. Chessdata is the original data frame and hizlisatranc is the one that I'm trying to create.
However, it raises a keyerror. I couldn't fix it. Can someone please help?</p>
<pre><code>for i in range(len(chessdata)):
a = chess... | <p>you can filter the df, with values in a range of value1 to value 2, so that only the rows that meet that condition are left. You can assign that to a new df like so:</p>
<pre><code>df_new = df_old[(df_old['column']>value1) & (df_old['column']<value2)]
</code></pre> | pandas|dataframe|loops|for-loop|keyerror | 0 |
363,799 | 66,098,849 | Convert Row in to DateTime DataTypes Pandas Dataframe | <p>I have a Dataframe that have a row that have date&time information not column, I want to convert it to DateTime Datatype. I was able to change the single row but could not be able to save it to dataframe. Below is my trial for the same. Please let me know missing part of code. Also not usre how to ignore the col... | <p>I think you should transpose your df to get it right:</p>
<pre><code>df1 = df.iloc[:,1:].T
df1.columns = df[0]
df1.Timestamp = pd.to_datetime(df1.Timestamp)
</code></pre>
<p>Result:</p>
<pre><code>0 A Timestamp B C D
1 1-2.1 2020-11-25 14:34:25 21 42 971
2 1-2.2 2020-11-25 17:3... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.