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 |
|---|---|---|---|---|---|---|
352,700 | 52,774,459 | Engines in Python Pandas read_csv | <p>In the document for <code>pd.read_csv()</code> method in pandas in python while describing the "sep" parameter there is a mention of engines such as C engine and Python engine. </p>
<p>The document link is :
<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer">https... | <p>The <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>pd.read_csv</code></a> documentation notes specific differences between 'c' (default) and 'python' engines. The names indicate the language in which the parsers are written. Specifically, the docs note:</... | python|python-3.x|pandas|csv|dataframe | 13 |
352,701 | 52,769,793 | Counting total values per month while plotting only yearly labels | <p>I have the following DataFrame : </p>
<pre><code> H T date
date
1990-08-26 11:30:00 38.0 11.6 1990-08-26
1990-08-26 11:30:00 63.0 11.3 1990-08-26
1990-08-26 11:30:00 87.0 10.9 1990-08-26
1990-08-26 11:30:00 111.0 10.6 1990-08-26
199... | <p>Some test data:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(444)
start = '1990-01-01'
end = '2017-12-31'
idx = pd.date_range(start, end, freq='30min')
# different number of repeats per 30-min tick
rpt = np.random.randint(1, 5, size=idx.size)
idx = np.repeat(idx, rpt)
df = pd.DataFrame({'... | python|python-3.x|pandas|matplotlib|pandas-groupby | 0 |
352,702 | 52,601,168 | Collapse Dataframe onto NaN values | <p>I have a pandas dataframe that computes values for certain integers in its index, and for other index integers displays NaN (intentional behavior). </p>
<p>I would like to collapse the dataframe so that it will "fall" on the NaNs, replacing them with all of the valid values.</p>
<p>An example is below:</p>
<pre><... | <p>Is this what you need ? </p>
<pre><code>df.apply(lambda x : sorted(x,key=pd.notnull))
Out[111]:
1 2 3
1 NaN NaN -0.248677
2 NaN NaN -0.058432
3 NaN NaN 0.036740
4 -0.037979 NaN 0.322239
5 0.007599 NaN 0.036711
6 0.007595 0.007599 0.03... | python|pandas|dataframe | 0 |
352,703 | 52,894,787 | Python Pandas Read multiple SAS files from a list into separate dataframes | <p>I'm reading a bunch of SAS files like so:</p>
<p><code>demography = pd.read_sas("demography.sas7bdat", encoding = 'latin-1')
adverse_event_ds = pd.read_sas("adverse_event_ds.sas7bdat", encoding = 'latin-1')
rpt10344 = pd.read_sas("rpt10344.sas7bdat", encoding = 'latin-1')
vaccine_administration = pd.read_sas("vacc... | <p>this is assigning to <code>dataset</code> on every iteration rather than creating the new variables (e. g. <code>demography</code>, <code>rpt10344</code>, etc).</p>
<p>i'd use a dataset dictionary as follows:</p>
<pre><code>dsd = {}
for dataset in datasets:
dsd[dataset] = pd.read_sas(dataset+".sas7bdat", encod... | python|pandas | 2 |
352,704 | 52,481,346 | .info() not displaying null values | <p>I have a dataframe and using df.info() I get the following output:</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Int64Index: 371899 entries, 0 to 8933
Data columns (total 2 columns):
col_a 371899 non-null object
col_b 371899 non-null object
dtypes: object(2)
memory usage: 8.5+ MB
</code></pre>
<... | <p>Probably, for some reason, the Pandas Dataframe is being imported with the columns being interpreted as Objects, and, as objects the null values are not null. Try to specify the columns as Floats with </p>
<pre><code>df['col_b'] = df['col_b'].astype(float)
</code></pre> | python|pandas|null | 0 |
352,705 | 52,722,934 | Using pandas date_range to label fiscal years does not work for most recent dates | <p>I am analyzing transactions by fiscal year and working with a dataframe that has datetime column and a separate column for the year. Our fiscal year runs July 1st, xxxx - June 30, xxxx. The code below works just fine for all dates except for any date that starts 7/1/2018 which would fall under 2018 - 2019 fiscal yea... | <p>You aren't providing enough bins. Though your max year is <code>2018</code> because you have dates that should be grouped with 2019, you need to increase the maximum year by 1. Similarly, you should subtract 1 from the minimum year.</p>
<pre><code>y_max = data.year.max() + 1
y_min = data.year.min() - 1
</code></pre... | python|python-3.x|pandas | 1 |
352,706 | 52,641,975 | Replace all non-unique values in numpy array by value not in dataset | <p>I am dealing with large (masked) 2D numpy arrays which originate from country wide raster datasets of 10 to 200 meter resolutions. The arrays are very large and can contain several millions of values.</p>
<p>I would like to perform the following operation on these kinds of arrays in the most efficient way possible:... | <p>You can use a simple</p>
<pre><code> out_array = np.arange(in_array.size).reshape(in_array.shape)
</code></pre> | python|arrays|numpy | 1 |
352,707 | 52,838,888 | Add a tensor only to a part of another tensor | <p>I have to add two tensors, one with a shape multiple of the other in the depth direction. Here an example</p>
<pre><code>t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)
</code></pre>
<p>I want to use something like <code>tf.add</code> to add the second ... | <p>Add the first '<em>column</em>' of <code>t1</code> with <code>t2</code> and then concat it with the rest columns of <code>t1</code>:</p>
<pre><code>t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)
tf.InteractiveSession()
tf.concat((t1[...,0:1] + t2, t1[.... | python|tensorflow | 2 |
352,708 | 52,889,798 | Obtain lengths of vectors without loading multiple .npy files | <p>I have around 2000 .npy files, each representing a 1-dimensional vector of floats with between 100,000 and 1,000,000 entries (both of these numbers will substantially grow in the future). For each file, I would like the length of the vector it contains. The following option would be possible but time consuming:</p>
... | <p>Using memmapped files will speed this up considerably.
By memmapping the file numpy only loads the header to get array shapes and datatype, while the actual array data is left on disk until needed.</p>
<pre><code>import numpy as np
# Load files using memmap
data = [np.load(f, mmap_mode='r')) for f in os.listdir(so... | python|file|numpy | 2 |
352,709 | 52,478,411 | How to efficiently filter a pandas dataframe and return a pandas series? | <p>The question seems simple and arguably on the verge of stupid. But given my scenario, it seems that I would have to do exactly that in order to keep a bunch of calculations accross several dataframes efficient.</p>
<p><strong>Scenario:</strong></p>
<p>I've got a bunch of pandas dataframes where the column names ar... | <p>You need opposite of <code>to_frame</code> - <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.squeeze.html" rel="nofollow noreferrer"><code>DataFrame.squeeze</code></a> - convert one column <code>DataFrame</code> to <code>Series</code>:</p>
<pre><code>colAA = df.filter(like = 'AA')
c... | python|pandas | 2 |
352,710 | 52,579,551 | Creating summary table on groupby dataframe based on condition | <p>I have a pandas dataframe df that looks like</p>
<pre><code>userid trip_id segmentid actual prediction
1 13 40 3 3
1 6 2 1 1
1 44 3 2 3
2 70 19 1 1
2 12 5 0 0
</co... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow noreferrer"><code>pd.crosstab</code></a> after creating a conditional array:</p>
<pre><code>flags = np.where(df['actual'].eq(df['prediction']), 'correct', 'incorrect')
res = pd.crosstab(df['userid'], fla... | python|pandas|dataframe|counter | 4 |
352,711 | 52,742,509 | Can I convert all the tensorflow slim models to tflite? | <p>I'm training tensorflow slim based models for image classification on a custom dataset. Before I invest a lot of time training such huge a dataset, I wanted to know whether or not can I convert all the models available in the <a href="https://github.com/tensorflow/models/tree/master/research/slim" rel="nofollow nore... | <p>Many Slim models can be converted to TFLite, but it isn't a guarantee since some models might have ops not supported by TFLite.</p>
<p>What you could do, is try and convert your model to TensorFlow Lite using <a href="https://www.tensorflow.org/lite/convert/python_api" rel="nofollow noreferrer">TFLiteConverter</a> ... | python|tensorflow|machine-learning|computer-vision|tensorflow-lite | 6 |
352,712 | 52,879,249 | Efficient intersection of grouped pandas column | <p>I have a tall pandas dataframe called <code>use</code> with columns <code>ID, Date, ...</code>. Each row is unique, but each ID has many rows, with one row ID per date. </p>
<pre><code>ID Date Other_data
1 1-1-01 10
2 1-1-01 23
3 1-1-01 0
1 1-2-01 11
3 1-2-01 1
1 1-3-01 9
2 ... | <p>Using <code>crosstab</code>, when the value is 0 should be the target row . using <code>df.eq(0).any(1)</code>. to find it </p>
<pre><code>df=pd.crosstab(use.ID,use.Date)
df
Out[856]:
Date 1-1-01 1-2-01 1-3-01
ID
1 1 1 1
2 1 0 1
3 1 ... | python|pandas | 2 |
352,713 | 52,867,016 | Opencv or Numpy-- replace a list of pixels in an image, efficiently | <p>Hi OpenCV or Numpy Gurus, </p>
<p>I've been searching to an answer to this, but I'm surprised to not find it here or elsewhere...</p>
<p>I have a black image, and I want to replace a list of pixels (quite a large list) with a certain value. In the future, the "certain value" will be a list of values, but for the ... | <p>In fact, you can directly use your tuple of coordinates to index your matrix: a simple <code>a[([2, 3], [3, 4])] = 20</code> gives the exact same result as your for loop here.</p> | python|numpy|opencv | 1 |
352,714 | 52,539,110 | Preprocess data for prediction in Google Cloud (Cloud Functions doesnt support Tensorflow) | <p>I use <code>Google Cloud Functions</code> to send data for prediction to the <code>Cloud ML Engine</code>.</p>
<p>Firstly, I need to preprocess the data before sending it to the <code>Cloud ML Engine</code>.</p>
<p>For preprocessing I use 2 tokenizers (<em>mwetokenizer</em> from <code>nltk</code> and <em>tf.keras.... | <p>You won't be able to do this with Cloud Functions until those libraries support Python 3.7. You'll need to use a different service that provides a Python 3.6 runtime, such as the <a href="https://cloud.google.com/appengine/docs/flexible/python/" rel="nofollow noreferrer">App Engine Flexible Environment</a> (which pr... | python|tensorflow|machine-learning|google-cloud-platform|google-cloud-functions | 2 |
352,715 | 52,472,881 | Keras Conv1d Input Shape/ Parameters for Stock Data | <p>I'm trying to test out Keras 1DConv CNNs to help predict time series/ stock data. Something like N stocks would have OHLCV data for n time-steps. As an example, for N=1 stock, I am trying to predict only the next period's close price. Say, using one stock, I have 100 periods with OHLCV values, so X.shape = (100, 5),... | <p>The Conv1D expects a 3D input.</p>
<p>You have a 2D input.</p>
<p>If you reshape like this</p>
<pre><code>x = x.reshape(batch, steps, channels)
</code></pre>
<p>please see <a href="https://keras.io/layers/convolutional/" rel="nofollow noreferrer">link</a> for more information.</p>
<p>It should work.</p>
<p>If ... | python-3.x|tensorflow|keras|conv-neural-network|keras-layer | 2 |
352,716 | 52,453,285 | Drop a dimension of a tensor in Tensorflow | <p>I have a tensor that have shape <code>(50, 100, 1, 512)</code> and i want to reshape it or drop the third dimension so that the new tensor have shape <code>(50, 100, 512)</code>.</p>
<p>I have tried <code>tf.slice</code> with <code>tf.squeeze</code>:</p>
<pre><code>a = tf.slice(a, [50, 100, 1, 512], [50, 100, 1, 5... | <p>Generally <code>tf.squeeze</code> will drop the dimensions. </p>
<pre><code>a = tf.constant([[[1,2,3],[3,4,5]]])
</code></pre>
<p>The above tensor shape is <code>[1,2,3]</code>. After performing squeeze operation,</p>
<pre><code>b = tf.squeeze(a)
</code></pre>
<p>Now, Tensor shape is <code>[2,3]</code></p> | python|tensorflow|slice|tensor | 12 |
352,717 | 52,872,239 | Can tf.scatter_update or tf.scatter_nd_update be used to update column slices of a tensor? | <p>I want to implement a function that takes in a variable as input, mutate some of its rows or columns and replaces them back in the original variable. I am able to implement it for row slices using tf.gather and tf.scatter_update but unable to do so for column slices since apparently tf.scatter_update only updates th... | <p>Here is a small demonstration of how to update rows or columns. The idea is that you specify the row and column indices of the variables where you want each element in the update to end up. That is easy to do with <a href="https://www.tensorflow.org/api_docs/python/tf/meshgrid" rel="nofollow noreferrer"><code>tf.mes... | python|tensorflow | 2 |
352,718 | 52,709,719 | Improve speed by creating dynamic columns in a Dataframe | <p>I am creating a Dataframe with the following information:</p>
<pre><code>import numpy as np
import pandas as pd
from time import time
start_time = time()
columns = 60
Data = pd.DataFrame(np.random.randint(low=0, high=10, size=(700000, 3)), columns=['a', 'b', 'c'])
Data['f'] = (Data.index % 60) + 1
Data['column_-... | <p>Using a profiler, you can see that the majority of the time is spent in <code>np.where</code>. Unfortunately there isn't much we can do about that right now.</p>
<p>The next-biggest time sink appears to be Pandas conversions, which are slow. So we can shave off some time making the code more streamlined (and more r... | python|python-3.x|pandas|numpy | 2 |
352,719 | 52,580,464 | TPU slower than GPU? | <p>I just tried using TPU in Google Colab and I want to see how much TPU is faster than GPU. I got surprisingly the opposite result.</p>
<p>The following is the NN. </p>
<pre><code> random_image = tf.random_normal((100, 100, 100, 3))
result = tf.layers.conv2d(random_image, 32, 7)
result = tf.reduce_sum(result)... | <p>Benchmarking devices properly is hard, so please take everything you learn from these examples with a grain of salt. It's better in general to compare specific models you are interested in (e.g. running an ImageNet network) to understand performance differences. That said, I understand it's fun to do this, so...</... | tensorflow|machine-learning|gpu|google-colaboratory|google-cloud-tpu | 8 |
352,720 | 52,542,344 | python pandas rename data frame | <p>The purpose of this code is to scrape a bunch of data tables with different lengths (different number of rows per table), turn them into pandas data frames, remove some unnecessary columns and fix the date.</p>
<p>All the above works ok but when I tried to rename a column I got an error.</p>
<p>Here is data sample... | <p>First of all, your multiple calls to <code>df.drop</code> are unnecessary, and makes reading the code more visually tiring. Change:</p>
<pre><code>df.drop(df.columns[-1], axis=1, inplace=True)
df.drop(df.columns[-1], axis=1, inplace=True)
df.drop(df.columns[-1], axis=1, inplace=True)
df.drop(df.columns[-1], axis=1,... | python|pandas|selenium | 0 |
352,721 | 52,455,883 | Merge changes Pandas types | <p>I'm using Python 3 (don't know if the info is relevant).
I have 2 Pandas DataFrames (coming from <code>read_csv()</code>): <code>Compact</code> and <code>SDSS_DR7_to_DR8</code>. Before merge, they contain types as follow : </p>
<pre><code>Compact.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2070 e... | <p><em><strong>Update:</strong></em> in Pandas 0.24, there now are <a href="https://pandas.pydata.org/docs/user_guide/integer_na.html" rel="nofollow noreferrer">Nullable integer data types</a>.</p>
<p>As of this writing, the Pandas does not seem choose the nullable int data type for the result of the merge. But it's po... | python-3.x|pandas | 4 |
352,722 | 52,771,800 | show create table return b"CREATE TABLE | <p>Same code in different mysql database instance</p>
<pre><code>sql_table_def = 'show create table {}.{}'.format(dbname,table_name)
df_table_def = pandas.read_sql_query(sql_table_def,self.conn)
create_table_sql = df_table_def.head(1)['Create Table'].values[0]
</code></pre>
<p>But sometimes the returned value is stra... | <p>The b prefix shows that it's a <a href="https://docs.python.org/3/library/stdtypes.html#bytes" rel="nofollow noreferrer"><code>bytes</code></a> object rather than a <a href="https://docs.python.org/3/library/stdtypes.html#str" rel="nofollow noreferrer"><code>str</code></a>.<br>
You can convert <code>bytes</code> to ... | python-3.x|pandas | 0 |
352,723 | 52,657,131 | Going from Pandas Dataframe to Javascript Array | <p>I need to create an array in an HTML file of the form:</p>
<pre><code><script>
var markers = [
[1, 2],
[3, 4]
];
</script>
</code></pre>
<p>I can get this array from either one of two sources: python via pandas or sql. I know how to get the list into a flat file or json, b... | <p>In Django example, you do this:</p>
<p>view.py</p>
<pre><code>data = df.to_dict(orient='records')
return render(request, 'XXX.html',{'data':data})`
</code></pre>
<p>in template:</p>
<pre><code>data = {{ data|safe }};
</code></pre> | javascript|json|pandas | 3 |
352,724 | 52,666,988 | How to invoke apply on multiple columns (including the result column) without looping | <p>For example, I have two columns A and B (as in pandas dataframe):</p>
<pre> A B
0 1 1
1 1 0
2 0 1
3 0 0
</pre>
<p>How do I calculate a column C based on A, B, and C_prev_row (its own calculated value from previous row), to get the below result:</p>
<pre> A B C
0 1 1 1
1 1 0 1
2 0 1 1
3 0 ... | <p>You need break down you logic behind the value C </p>
<pre><code>(df.A.iloc[1:].cumprod()*1).add((df.A.iloc[2:].cumprod()*df.B.iloc[1])+df.B,fill_value=0).fillna(1)
Out[983]:
0 1.0
1 1.0
2 1.0
3 0.0
dtype: float64
</code></pre>
<p>More Info</p>
<pre><code>C1=1
C2=A2*C1+B2
C3=A3*C2+B3=A3*A2*C1+A3*B2... | python|python-3.x|pandas|numba | 1 |
352,725 | 52,819,416 | Dividing a pandas groupby object into chunks | <p>I have a pandas DataFrame that I am grouping by columns ['client', 'product', 'data']. </p>
<pre><code>grouped_data = raw_data.groupby(['client', 'product', 'data'])
print(len(grouped_data))
# 10000
</code></pre>
<p>I want to split the resulting groupby object into two chunks, one containing roughly 80% of the gro... | <p>By using <code>np.split</code></p>
<pre><code>df['key']=df[['client', 'product', 'data']].apply(tuple,1)
g1,g2=np.split(df['key'].unique(),[2000])
df1=df[df['key'].isin(g1)]
df2=df[df['key'].isin(g2)]
</code></pre> | pandas|pandas-groupby | 3 |
352,726 | 52,650,646 | Changing the back ground color of rows in a dataframe using python styling | <p>I have a dataframe like this:</p>
<pre><code>name color parking_space
0 Terminal 1, 2 Green Lot 40
1 Terminal 4 Blue Lot 81
2 Terminal 5 Yellow Lot 59
3 Terminal 7 Orange Lot 45
4 Terminal 8 Red Lot 31
5 Long-Term ... | <p>So, once you solve the str/int comparison, with something like <code>int(row['parking_space'][:2])</code>, it looks like this has been solved in <a href="https://stackoverflow.com/questions/43596579/how-to-use-python-pandas-stylers-for-coloring-an-entire-row-based-on-a-given-col">this question</a>.</p>
<p>Using a n... | python|pandas|styling | 2 |
352,727 | 52,835,886 | Running my python loop on a df and print responses in df | <p>I have a dataframe in Pandas:</p>
<pre><code>In [10]: df
Out[10]:
Domain Use
0 graph.facebook.com 4242
1 news.bbc.co.uk 23423
2 news.more.news.bbc.co.uk 234432
3 profile.username.co 235523
4 offers.o2.co.uk 235523
5 subdomain.pyspark.org 23... | <p>This should solve the problem</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Domain':[' graph.facebook.com','news.bbc.co.uk ']})
df['new_domain']=df.Domain.str.split('.',1, expand=True)[1] # split on '.' then take second element
</code></pre> | python|python-3.x|pandas | 0 |
352,728 | 46,416,479 | How to dynamically create 3d numpy arrays from 2d numpy arrays using for loop | <p>I want to create a 3d numpy array form 2d numpy array using for loop.I tried in many different methods to create 3d arrays from 2d but each time its giving me errors. This is what I have done, the end array should have a dimension of <code>(10,3,3)</code>.</p>
<pre><code>#this is a sample code
arr=[]
for i in rang... | <p>You can append the <code>2d</code> arrays to the <code>arr</code> list using <code>list.append</code> method, and after you are done with the for loop, convert <code>arr</code> to <code>3d</code> array by wrapping it with <code>np.array</code>:</p>
<pre><code>arr = []
for i in range(10):
a = np.random.rand(3,3)... | python|numpy | 3 |
352,729 | 46,219,468 | proper date format for pandas datareader? | <p>can someone please explain how to input the proper date format for pandas datareader? it seems like i have tried both date formats in the past and they have worked. however, in the last few days these lines only output the last year's worth of data... </p>
<pre><code>import pandas_datareader.data as wb
import ... | <p>during the process of fixing this, i upgraded to the most current version of pandas (0.20.3) and pandas-datareader (0.5.0). that did not fix the code in the question. the problem appears to be trying to use google as the source. the code below runs correctly but uses yahoo as the source. however, it fails when t... | pandas|date|format|datareader | 0 |
352,730 | 46,481,361 | Creating a list of many ndarrays (different size) in python | <p>I am new to python. Do we have any similar structure like Matlab's <code>Multidimensional structure arrays</code> in <code>Python 2.7</code> that handles many ndarrays in a list. For instance, I have 15 of these layers (i.e. <code>layer_X, X=[1,15]</code>) with <code>different size but all are 4D</code>:</p>
<pre><... | <p>You can use a dictionary:</p>
<pre><code>layer_dict = {}
for X in range(1,16):
layer_dict['layer_' + str(X)] = np.ndarray(shape=(1, 1, 32, 64))
</code></pre>
<p>This allows to store arrays of various sizes (and any other datatypes to be precise), add and remove components. It also allows you to access your arr... | arrays|python-2.7|numpy|multidimensional-array | 4 |
352,731 | 46,506,082 | How to add weight factor to CountVectorizer | <p>I am pretty new to data science. I'm trying to solve nlp clustering problem using LDA. I've encountered with problem using <code>CountVectorizer</code> from <strong>sklearn</strong>. </p>
<p>I've got a Data Frame:</p>
<pre><code>df = pd.DataFrame({'id':[1,2,3],'word':[['one', 'two', 'four'],
... | <p>The essential function here is the <code>split()</code> method - from it, you can both turn your list of words into a list of strings, and also get the integers you want to assign to each string.</p>
<p><strong>The Final Answer:</strong> Here is a drop-in dictionary-making method and <code>apply()</code> calls to a... | python|pandas|machine-learning|scikit-learn | 1 |
352,732 | 46,603,052 | Difficulty with 'any' in NumPy | <p>I am using Python 3 and am trying to check if the sqrt of elements in array2 are in a. I am returning the boolean response.</p>
<p>I am receiving the error: </p>
<pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>My code:</p>
<pre><... | <p>I guess, return part is wrong. Try this:</p>
<pre><code>import numpy as np
def mems(a, b):
a = np.array(a)
b = np.array(b)
b_sqrt = np.sqrt(b)
return any(sqrt in a for sqrt in b_sqrt)
print(mems([1, 2, 3, 4, 5], [20, 56]))
print(mems([1, 2, 3, 4, 5], [16, 25, 17, 18]))
</code></pre>
<p>Output:</p... | python|python-3.x|numpy | 1 |
352,733 | 46,511,505 | How to merge multiindex column dataframe | <p>I want to merge static data with time varying data.</p>
<p>First dataframe</p>
<pre><code>a_columns = pd.MultiIndex.from_product([["A","B","C"],["1","2"]])
a_index = pd.date_range("20100101","20110101",freq="BM")
a = pd.DataFrame(columns=a_columns,index=a_index)#A
</code></pre>
<p>Second dataframe</p>
<pre><code... | <p>I think you need reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> and then create <code>df</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html" rel="nofollow norefer... | python|pandas | 2 |
352,734 | 46,382,866 | Tensorflow: Different activation values for same image | <p>I'm trying to retrain (read finetune) a <a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.py" rel="nofollow noreferrer">MobileNet</a> image Classifier.</p>
<p>The script for retraining given by tensorflow <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflo... | <p>When you build the mobilenet there is one parameter called <code>is_training</code>. If you don't set it to false the dropout layer and the batch normalization layer will give you different results in different iterations. Batch normalization will probably change very little the values but dropout will change them a... | python|machine-learning|tensorflow|conv-neural-network|batch-normalization | 0 |
352,735 | 46,386,914 | got error:Input contains NaN, infinity or a value too large for dtype('float64') | <pre><code> ## Load the data ##
train=pd.read_csv("../kagglehouse/train.csv")
test=pd.read_csv("../kagglehouse/test.csv")
all_data=pd.concat((train.loc[:,"MSSubClass":"SaleCondition"],test.loc[:,"MSSubClass":"SaleCondition"]))
NFOLDS = 5
SEED = 0
NROWS = None
ntrain = train.shape[0]
ntest = test.shape[0]
#creating ... | <p>You are not checking <code>all_data</code> correctly:</p>
<pre><code>np.isnan( all_data.all() )
np.isfinite( all_data.all() )
</code></pre>
<p>Are <strong>not</strong> how you should check your data.</p>
<p>You are applying <code>np.isnan()</code> and <code>np.isfinite()</code> to the output of <code>all_data.all... | python|python-2.7|pandas|numpy|scikit-learn | 3 |
352,736 | 46,578,708 | How to sum different rows of different keys in Pandas dataframe? | <p>I have this data frame:</p>
<pre><code>Col1 | Col2 | Col3 \n
A | 1 | 1 \n
B | 23 | 2 \n
C | 21 | 1 \n
</code></pre>
<p>Is it doable in Pandas to add, combine or sum A & B together so it will be like:</p>
<pre><code>Col1 | Col2 | Col3 \n
A | 24 | 3 \n
C | 21 | 1 \n
</code></pre>
<p>I... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow noreferrer"><code>replace</code></a> for same categories and then <code>groupby</code> + <code>sum</code>:</p>
<pre><code>df = df.groupby(df['Col1'].replace({'B':'A'})).sum().reset_index()
print (df)
Col... | python|pandas | 0 |
352,737 | 46,487,938 | Merge and delete duplicates | <p>I have two large datasets I want to merge which have a common column, "gene".</p>
<p>All entries are unique in df1</p>
<pre><code>in [85]: df1
Out[85]:
gene
0 Cdk12
1 Cdk2ap1
2 Cdk7
3 Cdk8
4 Cdx2
5 Cenpa
6 Cenpa
7 Cenpa
8 Cenpc1
9 Cenpe
10 ... | <p>I think one possible solution is create helper columns which count values of <code>gene</code> and then merge pairs - first <code>Cdk12</code> in <code>df1</code> with first <code>Cdk12</code> in <code>df2</code>, second <code>Cdk12</code> with second <code>Cdk12</code>,... . Unique values are merged 1 to 1, classic... | python|pandas|dataframe|merge | 3 |
352,738 | 46,427,603 | TensorFlow doesn't seem to install | <p>I have those warnings:</p>
<blockquote>
<p>2017-09-26 14:50:45.956966: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.</p>
<p>2017-09-26 14:50:45.956986: W tensorflow/co... | <p>Why are you saying it doesn't seem to install?</p>
<p>You are getting what you expected (Hello, Tensorflow!) but you are also getting these warnings. Regarding the warnings, they have been discussed here: <a href="https://stackoverflow.com/questions/47068709/your-cpu-supports-instructions-that-this-tensorflow-binar... | tensorflow|installation | 0 |
352,739 | 46,249,621 | Why TensorFlow in Go didn't find the optimizer as python? | <p>I am a newbie of <code>TensorFlow</code> in <code>Go</code>.</p>
<p>There are some doubts during my first traing demo. I just find one optimizer in Go's <code>wrappers.go</code>. </p>
<p>But i learn the demos of python,they has serveral optimizers. Like </p>
<pre><code>GradientDescentOptimizer
AdagradOptimizer
Ad... | <p>You <strong>can't</strong> train a Tensorflow model using Go.</p>
<p>The only thing you can do is load a pre-trained model and use it for the inference. </p>
<p>You can't because the Go implementation lacks the <code>Variable</code> support, therefore it's impossible to train anything at the moment.</p> | go|tensorflow | 0 |
352,740 | 46,279,527 | report_uninitialized_variables output explanation | <p>I was trying the following code to initialise uninitialised variables in tensorflow </p>
<pre><code>init_op = tf.variables_initializer([v for v in tf.global_variables() if v.name.split(':')[0] in set(sess.run(tf.report_uninitialized_variables()))])
sess.run(init_op)
</code></pre>
<p>However I kept getting errors r... | <p>The <code>b</code> in front of the name is because you're using python 3 and the string in the result from <code>report_uninitialized_variables()</code> is actually a <code>bytestring</code>.</p>
<p>In python 3, defining a string with <code>''</code> (e.g, <code>'Hello'</code>) creates a <em>unicode</em> string. Th... | python-3.x|tensorflow | 1 |
352,741 | 46,200,479 | tensorflow serving uninitialized | <p>Hello I want to initialize variable named result in the code below.
I tried to initialize with this code* when I tried to serving. </p>
<blockquote>
<p>sess.run(tf.global_variables_initializer(),feed_dict=
{userLat:0,userLon:0})</p>
</blockquote>
<p>I just want to initialize the variable.</p>
<p>The reaso... | <p>You can try to define the graph so that the output tensor preserves the shape (outer dimension) of the input tensor.</p>
<p>For example, something like:</p>
<pre><code>#server input data
userLoc = tf.placeholder(tf.float32, shape=[None, 2])
def calculate_dist(user_loc):
distanceList = []
for i in taxiData:
... | tensorflow|tensorflow-serving|google-cloud-ml-engine | 0 |
352,742 | 46,349,344 | Specific pandas columns as arguments in new column of df.apply outputs | <p>Given a pandas DataFrame as below:</p>
<pre><code>import pandas as pd
from sklearn.metrics import mean_squared_error
df = pd.DataFrame.from_dict(
{'row': ['a','b','c','d','e','y'],
'a': [ 0, -.8,-.6,-.3, .8, .01],
'b': [-.8, 0, .5, .7,-.9, .01],
'c': [-.6, .5, 0... | <p>The df.apply approach:</p>
<pre><code>df['rmse'] = df.apply(lambda x: mean_squared_error(x[['a','b','c']], x[['d','e','y']])**0.5, axis=1)
col a b c d e y rmse
row
a 0.00 -0.80 -0.60 -0.30 0.80 0.01 1.003677
b -0.80 0.00 0.50 0.7... | python|pandas|numpy|scikit-learn | 2 |
352,743 | 46,501,352 | Pandas Using String Contains to match values in 2 dataframes | <p>Lets say I have 2 dataframes with names of cities but with different formats. So, I want to match them based on their states, and the first four characters of each city name. A small example is as follows:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'city': ['NEW YORK', 'DALLAS', 'LOS ANGELES', 'SAN FRAN... | <p>Create a temporary <code>city4</code> column with 4 character to use <code>merge</code></p>
<pre><code>In [5247]: pd.merge(df1.assign(city4=df1.city.str[:4]),
df2.assign(city4=df2.city.str[:4]),
on=['city4', 'state']).drop('city4', 1)
Out[5247]:
city_x state value ... | python|pandas|dataframe | 1 |
352,744 | 46,485,691 | Zero-padding a 1-D tensor before or after each element. (TensorFlow) | <p>I have a 1-D tensor with <strong>N</strong> elements which is generated by interlacing 2 1-D vectors with <strong>N/2</strong> elements. How can I do this with TensorFlow?</p>
<p>For example, I want to generate [0, 1, 2, 3, 4, 5, 6, 7] from [0, 2, 4, 6] and [1, 3, 5, 7]. </p>
<p>I hope there could be a 1-line solu... | <p>You can stack <code>a</code> and <code>b</code> as columns, then reshape it to 1d:</p>
<pre><code>tf.reshape(tf.stack([a, b], axis=-1), [-1])
</code></pre>
<hr>
<pre><code>a = tf.constant([0, 2, 4, 6])
b = tf.constant([1, 3, 5, 7])
sess = tf.InteractiveSession()
interlace = tf.reshape(tf.stack([a, b], axis=-1), ... | python|tensorflow|tensor | 2 |
352,745 | 46,569,805 | Why do I get "nan" for Loss when I implement MNIST tensorflow code to my dataset | <p>My Project goal is to checkout weight map of neural network for my dataset.</p>
<p>I followed the <a href="https://www.oreilly.com/learning/not-another-mnist-tutorial-with-tensorflow" rel="nofollow noreferrer">MNIST example code</a> and worked fine.</p>
<p>MNIST dataset have 784(28*28) <code>pixel_data</code> inpu... | <p>Two suggestions: first initialize your weights to something other than zeros. For instance:</p>
<pre><code>W = tf.Variable(tf.truncated_normal(shape=[72, 4]))
</code></pre>
<p>Second, it is recommended that you use <code>tf.nn.softmax_cross_entropy_with_logits</code> rather than calculating this yourself. It is mo... | python-3.x|tensorflow|neural-network|mnist | 0 |
352,746 | 46,562,401 | Group python pandas dataframe per weeks (starting on Monday) | <p>I have a dataframe with values per day (see df below).
I want to group the "Forecast" field per week but with Monday as the first day of the week. </p>
<p>Currently I can do it via pd.TimeGrouper('W') (see df_final below) but it groups the week starting on Sundays (see df_final below)</p>
<pre><code>import pandas ... | <p>Use <code>W-MON</code> instead <code>W</code>, check <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offsets" rel="noreferrer">anchored offsets</a>:</p>
<pre><code>df_final = (df
.reset_index()
.set_index("Date")
.groupby(["Site","Product",pd.Grouper(freq='W-MON')])["For... | python|pandas|datetime|pandas-groupby | 9 |
352,747 | 46,480,098 | What is the difference between and array containing dot after the number e.g. [ 1. 2. ] and an array without dot e.g. [ 1 2 ]? | <p>I'm trying to import data from csv file and I get two different types of arrays when I use pandas' read function and numpy's getfromtxt resulting in two different arrays:</p>
<pre><code>[[ 1. 0. 1. ..., 1. 0. 0.]
[ 0. 1. 1. ..., 1. 0. 0.]
[ 0. 1. 1. ..., 1. 0. 0.]
...,
[ 0. 1. 1. ..., 1. 0. ... | <p>Try in Python shell:</p>
<pre><code>>>> type(1.)
<class 'float'>
>>> type(1)
<class 'int'>
</code></pre> | python|arrays|pandas|genfromtxt | 0 |
352,748 | 46,515,698 | Rounding to nearest min in a pandas dataframe | <p>I want to round the hh:mm:ss values in my TimeStamp col of the dataframe so that the seconds are always 00</p>
<p>Dataset:</p>
<pre><code> TimeStamp A B C
10:27:30 1.953036 2.110234 1.981548
10:28:30 1.973408 2.046361 1.806923
10:29:... | <p>Add one nanosecond to each time and then round.</p>
<pre><code>df['TimeStamp'] = (df['TimeStamp'] + pd.Timedelta(1)).dt.round('min')
0 10:28:00
1 10:29:00
2 10:30:00
3 10:31:00
Name: TimeStamp, dtype: timedelta64[ns]
</code></pre> | python|pandas|numpy | 1 |
352,749 | 46,500,581 | TypeError: 'numpy.ndarray' object is not callable when import a function | <p>Hi I am getting the following error.
TypeError: 'numpy.ndarray' object is not callable
I wrote a function module by myself,like this:</p>
<pre><code>from numpy import *
import operator
def creatDataset() :
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
... | <p>Since "group" is a numpy.array, you cannot call it like a function.
So "group()" will not work.
I assume, you want to see it's values, so you would have to use something like
"print(group)".</p> | python-3.x|numpy | 0 |
352,750 | 46,617,339 | couldn't Install TensorFlow Python dependencies | <p>I am installing tensorFlow from source by following the instructions mentioned in Tensorflow website. when I install TensorFlow Python dependencies using the command <code>sudo yum install python3-numpy python3-dev python3-pip python3-wheel</code> it gives me this error </p>
<pre><code> Loaded plugins: fastestmi... | <p>Try these instructions
<a href="https://edwards.sdsu.edu/research/installing-python3-4-and-the-scipy-stack-on-centos/" rel="nofollow noreferrer">https://edwards.sdsu.edu/research/installing-python3-4-and-the-scipy-stack-on-centos/</a></p>
<p>or you can install pip3 and install all the dependencies using pip3</p>
<... | python|linux|tensorflow | 0 |
352,751 | 46,193,100 | Find rows with list element that equals to something, in numpy array | <p>I have numpy array with lists:</p>
<pre><code>[(26, 6, 2, 4, 'Bridge', 1., 8, '2015-02-02')
(23, 6, 1, 4, 'Bridge', 1., 8, '2015-02-02')
(12, 6, 2, 4, 'Back', 1., 8, '2015-02-02')
(23, 6, 3, 4, 'Back', 1., 8, '2015-02-02')]
</code></pre>
<p>I need to filter numpy array by keeping only <em>lists</em> tha... | <p>lets the given numpy array be referenced by <code>ar</code></p>
<p>So,</p>
<pre><code>>>> ar = np.array([[26, 6, 2, 4, 'Bridge', 1., 8, '2015-02-02'],
... [23, 6, 1, 4, 'Bridge', 1., 8, '2015-02-02'],
... [12, 6, 2, 4, 'Back', 1., 8, '2015-02-02'],
... [23, 6, 3, 4, 'Back', 1., 8, '2015-02-02']])
... | python|arrays|numpy | 1 |
352,752 | 46,563,195 | Parsing Excel data with pandas - why is it skipping columns when renaming columns? | <p>I really hope its something simple im missing. I'm reading in excel workbooks using python pandas. When I rename my columns to be numbers 1:len(columns) it skips the first few columns.</p>
<p>It seems to only skip them if the cells don't have values in them. Even if the column doesn't have a value, i still want it t... | <pre><code>#dataframe have default columns names
df = pd.DataFrame({0:list('abcdef'),
1:[4,5,4,5,5,4],
2:[7,8,9,4,2,3]})
print (df)
0 1 2
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
#first column called index
print (df.index)
RangeIndex(start=0, stop=6,... | python|excel|pandas | 1 |
352,753 | 46,482,871 | Numerical operations on 2D array in python using numpy | <p>I have the below array. How can I apply numerical operation to each x,y as<br>
x*3+1,(y+2)*2 using numpy. </p>
<p>A = [[2,4],[1,5],[6,3],[],[],[],[].....[x,y]]</p>
<p>Thanks in advance</p> | <p>The obvious list approach:</p>
<pre><code>In [111]: A = [[2,4],[1,5],[6,3]]
In [112]: def foo(x,y):
...: return x*3+1,(y+2)*2
...:
In [113]: [foo(x,y) for x,y in A]
Out[113]: [(7, 12), (4, 14), (19, 10)]
</code></pre>
<p>Make an array, and pass columns to the function:</p>
<pre><code>In [114]: AA ... | python|numpy | 0 |
352,754 | 46,592,104 | Python Pandas: multi-index unstack taking forever | <p>I've read a DataFrame from a .csv file with the following columns:</p>
<pre><code>columns = ['Year', 'month', 'column1', 'column2','column3', 'column4', 'column5', 'column6', 'column7', 'column8','Value']
</code></pre>
<p>The dataframe has 116408 rows but after <code>df = df.drop_duplicates()</code> it now has 988... | <p>I believe you are unstacking the wrong levels. Because you have <code>append=True</code> when you set the index, the first value in your new index is whatever it was (you don't indicate what this index value is, so I am just assuming a continuous range starting at zero). The next two levels would then be <code>Yea... | python|pandas|dataframe | 3 |
352,755 | 46,428,855 | 'and' 'or' operator in if statement | <p>I've got a dataframe df as follow:</p>
<pre><code>Name Race(m) Date
Peter 2000 23/09/16
Mary 100 23/09/16
Mary 400 23/09/16
Mary 200 23/09/16
Mary 400 24/09/17
John 800 23/09/16
</code></pre>
<p>I wanna add a column [X] to indicate how many races still have to go... | <pre><code>import pandas as pd
df = pd.DataFrame(data=[["peter"],["peter"]], columns=["name"])
# count number of times each name occurs, put it in a dictionary
names = dict(df["name"].value_counts())
def num_races_left(name):
names[name]-=1
return names[name]
# for every name, look it up in the dict and reduce n... | python|pandas | 0 |
352,756 | 46,625,924 | Comparing dataframes by their column name and observations | <p>I have a function to compare two dataframes, and to return <code>True</code> if equal, and <code>False</code> if the column name and observations are not equal.</p>
<pre><code>def table_equal(A, B):
var_names = sorted(A.columns)
Y = A[var_names].copy()
Y.sort_values(by=var_names, inplace=True)
Y.set... | <p><strong>Problem</strong><br>
Clearly:</p>
<pre><code>A.equals(B)
False
</code></pre>
<p><strong>Solution</strong><br>
Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.align.html" rel="nofollow noreferrer"><strong><code>pd.DataFrame.align</code></strong></a></p>
<p>Rewrite your... | python|pandas|dataframe | 2 |
352,757 | 46,470,743 | How to efficiently compute a rolling unique count in a pandas time series? | <p>I have a time series of people visiting a building. Each person has a unique ID. For every record in the time series, I want to know the number of unique people visiting the building in the last 365 days (i.e. a rolling unique count with a window of 365 days).</p>
<p><code>pandas</code> does not seem to have a buil... | <p>I had 2 errors in the fast method <code>windowed_nunique</code>, now corrected in <code>windowed_nunique_corrected</code> below: </p>
<ol>
<li>The size of the array for memoizing the number of unique counts for each person ID within the window, <code>pid_cts</code>, was too small. </li>
<li>Because the leading an... | python|pandas|time-series|distinct-values|rolling-computation | 5 |
352,758 | 46,239,123 | Count unique values from one column across multiple dataframes | <p>Is it possible to count unique values from one column across multiple dataframes with pandas?</p>
<p><strong>Example</strong></p>
<p><strong>columnname</strong> in every <strong>dataframe</strong> which has to be searched for unique <strong>values = 'userid'</strong></p>
<p><code>df1: 1, 2, 3, 4
df2: 1, 2, 3
df3:... | <p>Access the <code>userId</code> column in all dataframes, then call <code>pd.concat</code> and <code>pd.Series.nunique</code>.</p>
<pre><code>df1
userId
0 1
1 2
2 3
3 4
df2
userId
0 1
1 2
2 3
df3
userId
0 5
1 6
2 7
series_list = [x['userId'] fo... | python|pandas|dataframe|unique | 1 |
352,759 | 46,452,487 | Better solution using NumPy | <p>Assume we have function which get on input 2D numpy array, matrix, and return product of diagonal elements.
I would like to apply such function to array of matrixes and obtain array of results. Of course, there is naive approach. For instance :</p>
<pre><code>def our_func():
...
array_of_matrixes = [...]
resul... | <p>The reason <code>np.apply_along_axis</code> or <code>np.vectorize</code> doesn't work reliably is that if your matrices have the same shape, numpy will flatten the array of matrices and will try to apply <code>our_func</code> to every single cell in each matrix, which isn't defined.</p>
<p>You could replace</p>
<p... | python|arrays|numpy | 1 |
352,760 | 46,542,572 | How to plot pie chart using data frame group by different range? | <p>My Code is:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
df=pd.read_csv("patient1.csv")
a=df.loc[df.Age<18,['Age']]
print(a)
b=df.loc[(df.Age >= 18) & (df.Age < 60),['Age']]
print(b)
c=df.loc[df.Age>=60,['Age']]
print(c)
d=pd.concat([a,b,c],keys=["... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="noreferrer"><code>cut</code></a> for create <code>range</code>s first. Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a>, aggregate ... | python|pandas|csv|matplotlib|dataframe | 12 |
352,761 | 58,282,204 | Merge values with missing Series Index with a main index | <p>Say I have an index:</p>
<pre><code>i = pd.Index(['apple', 'banana', 'orange'])
print(i)
Index(['apple', 'banana', 'orange'], dtype='object')
</code></pre>
<p>Now, I perform some groupby function and the result of the values is, <code>p</code>:</p>
<pre><code>p = pd.Series({'apple' : 1})
print(p)
apple 1
dty... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> by index values and <code>fill_value=0</code> for replace missing values:</p>
<pre><code>print (p.reindex(i, fill_value=0))
apple 1
banana 0
orange 0... | pandas | 2 |
352,762 | 58,254,732 | How to merge two DataFrames that have different lengths and index of one is a subset of the other but their datatypes are different? | <p>I need to merge these two DataFrames.</p>
<pre><code>+-------------------------------------+--+
| df1: | |
+-------------------------------------+--+
| Date Temperature Load | |
| 01-01-2019 25 400 | |
| 02-01-2019 32 487 | |
| 03-... | <p>Your <code>merge</code> command is correct and works perfectly:</p>
<pre><code>df1 = pd.DataFrame({'Date': ['01-01-2019', '02-03-2019'], 'Temperature': [25,32], 'Load': [400, 501]})
df2 = pd.DataFrame({'Date': ['02-03-2019', '14-04-2019'], 'Holiday': ['Mahashivratri', 'Good Friday']})
df1.merge(df2, on='Date', how=... | python-3.x|pandas|dataframe | 1 |
352,763 | 58,414,752 | Concat Columns of Dataframe in python? | <p>I have a data frame generate with the code as below:</p>
<pre><code># importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Category':['A', 'B', 'C', 'D'],
'Event':['Music Theater', 'Poetry Music', 'Theatre Comedy', 'Comedy Theatre'],
'Cost... | <p>The most general solution is convert all values to strings, use <code>join</code> and last <code>replace</code>:</p>
<pre><code>df['new'] = df.astype(str).apply('_'.join, axis=1).str.replace(' ', '_')
</code></pre>
<p>If need filter only some columns:</p>
<pre><code>cols = ['Category','Event','Cost']
df['new'] = ... | python|pandas | 1 |
352,764 | 58,491,104 | FCN with patches creates boundary | <p>I am trying to train a Unet model to do per pixel regression predictions on images. To do this, I separate my large image (1000x1000) to 200x200 pixel squares. Then use that to train an FCN model with a linear final layer. The loss function is MSE loss. In the prediction stage, I extract the same boxes but stitch it... | <p>It makes sense to have discontinuity near the boundary because there is no requirement for the network to have smooth predictions across boxes during the training.</p>
<p>I assume you have limited GPU memory, so you take only 200x200 pixels as input at a time; Thus, I would suggest the following two possible workar... | python|machine-learning|computer-vision|conv-neural-network|pytorch | 0 |
352,765 | 58,422,993 | Predict batches using Tensorflow Data API and Keras Model | <p>Suppose I have a dataset and a Keras Model. The dataset has been divided into batches using <code>batch()</code> in tf Dataset API. Now I am seeking an efficient and clean way to do batch predictions for all testing samples.</p>
<p>I have tried the following code and it works.</p>
<pre><code>batch_size = 32
datase... | <h1>TF >= 1.14.0</h1>
<p>You can just set <code>steps=None</code>. From the official documentation of <code>tf.keras.Model.predict()</code>:</p>
<blockquote>
<p>If x is a tf.data dataset and steps is None, predict will run until the input dataset is exhausted.</p>
</blockquote>
<p>Just make sure that your <code>da... | tensorflow|keras|tensorflow-datasets | 0 |
352,766 | 58,581,501 | Generate data with python based on column data | <p>I have a dataframe that looks like : </p>
<pre><code>I_Code Date_1 Date_2 s_count
FT-35447 01/09/2019 02/08/2019 6
FT-40664 01/09/2019 02/08/2019 6
FT-54185 01/09/2019 03/08/2019 3
FT-40664 01/09/2019 03/08/2019 3
FT-56984 02/09/2019 03/08/2019 3
FT-29238 02/09/2019 03/08/2... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for dupl... | python|pandas|numpy | 2 |
352,767 | 58,173,413 | Trouble turning comorbidity data into a table using Python and Pandas | <p>I'm trying to analyze the occurrence of comorbidity from a Kaggle dataset as a geeky training exercise. I've been able to get all the fifteen morbidities from the dataset. However, at this point I struggle to turn this into a dataframe or the likes.</p>
<p>My thoughts at this point are focused on creating a 15 x 15... | <p>For those who come across my question, after some brooding I came up with a solution;</p>
<pre><code>df_findings = pd.DataFrame(columns=findings, index=findings).fillna(0)
for finding in df_string:
finding = finding.split('|')
finding.sort()
if len(finding) > 1:
col_label = finding[0]
... | python|pandas|kaggle|chord-diagram | 0 |
352,768 | 58,306,643 | Pandas column reverse the values based on other column | <p>I want to reverse the values of a column based on a condition below,i tried lambda x::-1 but it didnt
Work as i expected.</p>
<p>Dataframe:</p>
<pre><code>UserA Order_id reversed_id
A 1 5
A 2 4
A 2. 4
A 2. 4
A... | <p>We can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rank.html" rel="noreferrer"><code>rank</code></a></p>
<pre><code>df.Order_id.rank(method='dense',ascending=False)
0 5.0
1 4.0
2 4.0
3 4.0
4 3.0
5 2.0
6 2.0
7 1.0
Name: Order_id, dtype: float64
</c... | python|pandas|list|lambda|pandas-groupby | 5 |
352,769 | 58,468,570 | How to get the TF-IDF of a certain word from a certain date? | <p>is it possible to calculate the tf-idf metric of a certain word from a certain date with python pandas?</p>
<p><br>
I want to display the tf-idf metric for the word <strong>dog</strong> using the dates <strong>2008-01-02</strong> and <strong>2008-01-05</strong>.</p>
<pre><code>index date comment ... | <p>You would need to use an NLP library like gensim. You can follow the first example at <a href="https://radimrehurek.com/gensim/models/tfidfmodel.html" rel="nofollow noreferrer">TF-IDF</a> page.</p>
<p>You'd basically want to use your 'comment' column as your corpus and then you can calculate the TF-IDF for each row... | python|pandas|scikit-learn|sklearn-pandas | 0 |
352,770 | 58,431,910 | Pandas - Append data to specific columns | <p>I need to append data from a list to a specific column.
I have 4 lists:</p>
<pre><code>orderNumber = ['123456789']
countryOfOrigin = ['United Kingdom']
sizeList = ['2', '4']
quantityList = ['10', '12']
</code></pre>
<p>I also have a CSV file with following headers:</p>
<pre><code>OrderNumber COO Size QTY
<... | <p>If possible use instead one element lists only scalars, create dictionary of scalars/lists and pass to <code>DataFrame</code> constructor - all lists has to be with same lengths:</p>
<pre><code>orderNumber = '123456789'
countryOfOrigin = 'United Kingdom'
sizeList = ['2', '4']
quantityList = ['10', '12']
d = {"Orde... | python|pandas | 3 |
352,771 | 58,472,659 | Tensorflow: Apply different function mapping to different axis of a tf array? | <p>I am new to tensorflow 1.14. Say I have an <code>n * dim</code> tf array: <code>X_tf</code>. I also have <code>dim</code> different numbers of <code>f</code> (as each of them imposes different <code>a</code> and <code>b</code>):</p>
<pre><code>def f(x, a, b):
return x + a + b
</code></pre>
<p>I would like to do ... | <p>Make use of <a href="https://www.tensorflow.org/versions/r1.14/api_docs/python/tf/stack" rel="nofollow noreferrer">tf.stack</a> to split your tensor in first axis and then make use of <a href="https://www.tensorflow.org/versions/r1.14/api_docs/python/tf/unstack" rel="nofollow noreferrer">tf.unstack</a> to join them ... | python|tensorflow | 0 |
352,772 | 58,572,274 | Why Can't I train the ANN for XNOR? | <p>I have made a simple NN for deciding the XNOR values with the Two Binary values in the Input layer.
I have the Numpy array of all the possible combinations with the lables.</p>
<p>Code :</p>
<pre><code>from keras.models import Sequential
from keras.layers import Dense
import numpy
data = numpy.array([[0.,0.,1.],[... | <p>Your architecture is just too simple for this function. If you use the architecture below and train for 100 epochs, you'll get accuracy = 1.</p>
<pre><code>model = Sequential()
model.add(Dense(20,input_dim = 2,activation = 'relu'))
model.add(Dense(20,activation = 'relu'))
model.add(Dense(1,activation = 'sigmoid'))
... | python|numpy|tensorflow|machine-learning|keras | 0 |
352,773 | 58,331,837 | Filter data in Tensorflow | <p>I have some column data in TensorFlow and I'd like to filter on one of the columns, like so:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import tensorflow.compat.v2 as tf
import tensorflow.compat.v1 as tfv1
tfv1.enable_v2_behavior()
csv_file = tf.keras.utils.get_file('heart.csv', 'http... | <p>This is because you apply the <code>filter</code> after the <code>batch</code>.
Hence, in the <code>lambda</code> expression, <code>x</code> is a batch with shape <code>(None,)</code> (pass <code>drop_reminder=True</code> to <code>batch</code> to get shape of <code>(20,)</code>), and not a sample. To fix it, you hav... | python|tensorflow|tensorflow-datasets|tensorflow2.0 | 2 |
352,774 | 58,382,240 | Combine Matrices row-wise by weighting them in Python | <p>I have <strong>N</strong> matrices with dimensions <strong>R</strong> x <strong>R</strong> and one 'Weight matrix' with dimension <strong>R</strong> x <strong>N</strong>.
Now I want to combine those <strong>N</strong> matrices row-wise by weighting them with the 'Weight matrix'. In the end I want a <strong>R</str... | <p>We can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p>
<pre><code>In [57]: A # 3D input array
Out[57]:
array([[[0.2, 0. , 0.8],
[0. , 0. , 1. ],
[0. , 0.2, 0.8]],
[[1. , 0. , 0. ],
[0. , ... | python|numpy|matrix | 2 |
352,775 | 58,469,384 | How to slice a pandas.DatetimeIndex? | <p>What is the best way to get dates between, say, <code>'2019-01-08'</code> and <code>'2019-01-16'</code>, from the <code>pandas.DatetimeIndex</code> object <code>dti</code> as constructed below? Ideally, some concise syntax like <code>dti['2019-01-08':'2019-01-16']</code>?</p>
<pre><code>import pandas as pd
dti = pd... | <p>You can do it with the <a href="https://pandas.pydata.org/pandas-docs/version/0.20.3/generated/pandas.DatetimeIndex.slice_indexer.html" rel="noreferrer">slice_indexer for DateTimeIndex</a></p>
<p><code>pandas.DateTimeIndex.slice_indexer(start, stop, step, [...])</code></p>
<p>It returns the indexes of the datetime i... | python-3.x|pandas|datetime | 8 |
352,776 | 58,408,092 | JupyterLab fig does not show. It shows blank result (but works fine on jupyternotebook) | <p>I am new to JupyterLab trying to learn.</p>
<p>When I try to plot a graph, it works fine on jupyter notebook, but does not show the result on jupyterlab. Can anyone help me with this?</p>
<p><strong>Here are the codes below:</strong></p>
<pre><code>import pandas as pd
import pandas_datareader.data as web
import t... | <p><strong>TL;DR:</strong></p>
<p>run the following and then restart your jupyter lab</p>
<pre><code>jupyter labextension install @jupyterlab/plotly-extension
</code></pre>
<p>Start the lab with:</p>
<pre><code>jupyter lab
</code></pre>
<p>Test with the following code:</p>
<pre><code>import plotly.graph_objects as go
f... | pandas|jupyter-notebook|jupyter-lab|candlestick-chart|alpha-vantage | 5 |
352,777 | 58,520,296 | Apply function Pandas DataFrame without Lambda paramater | <pre><code>df = pd.DataFrame([["Test", "Test123"]] * 3, columns=['A', 'B'])
def shorterstring(string, count):
return string[0:-count]
df["A"].apply(lambda x: x[0:2])
Out[614]:
0 Te
1 Te
2 Te
df["A"].apply(shorterstring(df["A"], 2))
TypeError: 'Series' object is not callable
</code></pre>
<p>I want ... | <p>With <a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow noreferrer"><code>functools.partial</code></a> feature:</p>
<pre><code>In [128]: from functools import partial
In [129]: df["A"].apply(partial(shorter... | python|pandas|apply | 3 |
352,778 | 58,248,367 | How to inverse transform models output? | <p>So I have a trained model, that was trained on a standardized dataset. When I try to use the model for testing on new data, that isn't in a dataset and that isn't standardized, it returns ridiculous values, because I can standardize the inputs, but I can't inverse transform the output as I did during training. What ... | <p>Use <code>sc.inverse_transform(predicted)</code></p> | python-3.x|scikit-learn|neural-network|deep-learning|sklearn-pandas | 0 |
352,779 | 58,292,049 | Unpacking **kwargs | <p>I am working on a project that involves a lot of database filtering using Pandas. So I wrote the following function:</p>
<pre><code>def filterList(df, dropL, col, criteria, reason="", strCont=False, isIN=False,
notEq=False, isEq=False, isNAN=False, isDup=False, useDropL=True,
... | <p>Since the filtering criteria are mutually exclusive, you should just use a single parameter that specifies the filtering method, rather than lots of boolean parameters.</p>
<pre><code>def filterList(df, dropL, col, filterType, reason="", useDropL=True,
dropCol=False, dropColDropList=False, useDropR... | python|python-3.x|pandas|keyword-argument | 0 |
352,780 | 58,514,651 | Is .data still useful in pytorch 1.3 stable and what is the meaning of it? | <p>Is .data still be used in the pytorch 1.3 stable, if so, could you please share the reference to me? Thx.</p>
<pre class="lang-py prettyprint-override"><code>t = torch.randperm(8)
t.data
</code></pre> | <p>From PyTorch v0.4.0, calling <code>y = x.data</code> still has similar semantics. So <code>y</code> will be a Tensor that shares the same data with <code>x</code>, is unrelated to the computation history of <code>x</code>, and has <code>requires_grad=False</code>.</p>
<p>However, <code>.data</code> can be unsafe in... | python-3.x|pytorch | 1 |
352,781 | 58,583,874 | Scipy Optimize Maximize with a dataframe | <p>I have a df consisting of monthly share prices. I was hoping to find the optimal buy price and sell price to maximize earnings (revenue - costs). From research, it appears Scipy Optimize is the best tool to use, however all the examples I've seen do not show it being used with a dataframe. </p>
<p>A previous <a hre... | <p>So I ended up finding a way to use scipy optimize with my dataset.</p>
<p>I wrote a predicate which would allow me to solve my field calculations. then I called it in another function which I used for my scipy optimization. </p>
<p>This is not a very good optimization solution, as I don't seem to get very far from... | python|pandas|scipy|scipy-optimize | 1 |
352,782 | 58,403,574 | how to join dataframes without losing their names | <p>how to join dataframes without losing their names</p>
<p>I have several dataframes in a list and by joining them I am losing the identification of each one because they have equal columns.</p>
<pre><code>ticker_list = ['SBSP3.SA', 'CSMG3.SA', 'CGAS5.SA']
pd_list = [pd.read_csv('{}.csv'.format(ticker)) for ticker i... | <p>Use <code>add_sufix</code> when reading.</p>
<pre><code>pd_list = [pd.read_csv(f'{ticker}.csv').add_suffix(ticker) for ticker in ticker_list]
</code></pre>
<hr>
<p>OR you can <code>concat</code> through <code>axis=0</code> and define the ticker as another columns</p>
<pre><code>pd_list = [pd.read_csv(f'{ticker}.... | python|pandas|dataframe | 1 |
352,783 | 58,467,047 | What is happening if I changed dropna to True/False | <p>if i write this code:</p>
<pre><code>train['id_03'].value_counts(dropna=False, normalize =True).head()
</code></pre>
<p>I am getting</p>
<pre><code>NaN 0.887689233582822
0.0 0.108211128797372
1.0 0.001461374335354
3.0 0.001131168083449
2.0 0.000712906831036
Name: id_03, dtype: float64
</code></pre>... | <p>I think the key is that you specified <code>normalize =True</code> It is: <code>"If True then the object returned will contain the relative frequencies of the unique values."</code> according to the documentations.</p>
<p>Before you removed Na's the Na's counts are used to calculate the relative frequencies, after ... | python|pandas | 2 |
352,784 | 58,604,000 | Function to downsample dataset not working for txt files | <p>I attempted to make a <code>function</code> that down-sample a dataset because sometimes the dataset becomes large and hard to handle.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def DownSampler(pre_filename, post_filename, dsfactor):
"""
DownSampler is a function that downsa... | <p>Following the suggestion from @molybdenum42, I added <code>encoding='iso-8859-1'</code> to <code>pd.read_csv</code>:</p>
<pre><code>df_og_csv = pd.read_csv(pre_filename, encoding='iso-8859-1)
</code></pre>
<p>It now works as expected with the files I have tested it with. </p>
<p>Thank you, @molybdenum42!</p> | python|pandas | 0 |
352,785 | 58,584,570 | PEP8 guidance for column names in pandas dataframe? | <p>Is there a standard naming convention that is suggestible for columns in Pandas Dataframes ?</p>
<p>As I looked around, this seems to be the most relevant question or answer on this topic: <a href="https://stackoverflow.com/questions/47964380/pandas-dataframe-column-naming-conventions">Pandas DataFrame column naming... | <p>It is really up to you how you name the columns as it is application- or problem specific. At least PEP8 does not care about this and a linter such as <a href="https://pypi.org/project/flake8/" rel="nofollow noreferrer">flake8</a> will not complain.</p> | python|pandas|pep8 | 0 |
352,786 | 58,277,932 | Keras - "ValueError: Error when checking target: expected activation_1 to have shape (None, 9) but got array with shape (9,1) | <p>I'm building a model to classify text into one of 9 layers, and am having this error when running it. Activation 1 seems to refer to the Convolutional layer's input, but I'm unsure about what's wrong with the input.</p>
<pre><code>num_classes=9
Y_train = keras.utils.to_categorical(Y_train, num_classes)
#Reshape dat... | <p>There are several typos and bugs in your code. </p>
<ol>
<li><p><code>Y_train = Y_train.reshape((100,9))</code></p></li>
<li><p>Since you reshape <code>X_train</code> to (100,150,1), I guess your input step is 150, and channel is 1. So for the <code>Conv1D</code>, (there is a typo in your code), <code>input_shape=(... | python|tensorflow|machine-learning|keras|keras-layer | 0 |
352,787 | 58,488,124 | Dynamic Column Data In Pandas Dataframe (Populated By Dataframe) | <p>I am really stuck on how to approach adding columns to Pandas dynamically. I've been trying to search for an answer to work through this, however, I am afraid when searching I may also be using the wrong terminology to summarize what I am attempting to do.</p>
<p>I have a dataframe returned from a query that looks... | <p>There are quite a few concepts you need at once here.</p>
<p>First you dont yet have the count. From your desired output I took you want it yearly but you can specify any time frame you want. Then just count with <code>groupby()</code> and <code>count()</code></p>
<pre><code>In [66]: df2 = df.groupby([pd.to_dateti... | python|python-3.x|pandas|dataframe | 1 |
352,788 | 58,372,787 | create hourly interval and loop through to get value_counts python pandas | <p>I have a dataframe with datetimeindex from 2019-04-25 15:00:00 until 2019-04-26 15:00:00</p>
<p>for each hour I want to find df["mode"].value_counts() to see how many mode counts there are each hour.</p>
<p>so between_time("08:00", "08:02"), between_time("09:00", "09:02"),between_time("10:00", "10:02"), and so on.... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.hour.html" rel="nofollow noreferrer"><code>DatetimeIndex.hour</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><... | python|pandas | 2 |
352,789 | 58,301,581 | Command line python and jupyter notebooks use two different versions of torch | <p>On my conda environment importing torch from command line Python and from a jupyter notebook yields two different results.</p>
<p>Command line Python:</p>
<pre><code>$ source activate GNN
(GNN) $ python
>>> import torch
>>> print(torch.__file__)
/home/riccardo/.local/lib/python3.7/site-packages/t... | <p>You need to sort of make the Anaconda environment recognized in Jupyter using </p>
<pre><code>conda activate myenv
conda install -n myenv ipykernel
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"
</code></pre>
<p>Replace <code>myenv</code> with the name of your environment. Later on... | python|jupyter-notebook|anaconda|pytorch|conda | 1 |
352,790 | 58,502,359 | Multiprocessing using csv+pandas+python | <p>I have written a code that would iterate over each csv in a folder, read it using data-frame and append it to a master df which would be later user. </p>
<pre><code>import glob
import os
import pandas as pd
import time
import multiprocessing as mp
from multiprocessing.dummy import Pool
constituent_df= pd.DataFram... | <p>I modified the way i wanted to process files in pool and got a working solution:</p>
<pre><code>def main():
'''
This module reads files present in the directory
And
'''
file_list=[]
constituent_df= pd.DataFrame()
start= time.time()
for file in glob.glob(os.path.join(os.getcwd(),'2... | python|pandas|multiprocessing | 0 |
352,791 | 58,470,877 | How to fix datatype mismatch to predict images using my trained model? | <p>I trained a CNN, but I'm unable to use it to make predictions.
All of my images are in a folder</p>
<pre><code>model = tf.keras.models.load_model("C:\Sid\CNNs\MoonRocks.h5")
import os
filepath = "C:\Sid\Projects\LunarMoonRocks\DataSet\Test Images"
for img in os.listdir(filepath):
img_path = os.path.join(filepa... | <p><code>decode_jpeg</code> is used to decode the contents of image file which is read in binary format. You have already read your image file using OpenCV and OpenCV reads the file in NumPy format. Had you made use of <a href="https://www.tensorflow.org/api_docs/python/tf/io/read_file" rel="nofollow noreferrer"><code>... | python|python-3.x|tensorflow|machine-learning|tf.keras | 1 |
352,792 | 58,570,749 | how to find the sum and average of multiple columns in pandas | <p>I have a dataframe with 4 columns . The dataframe looks like this: </p>
<pre><code> date sell price cost price discount
2019-10-13 2000 2000 0
2019-10-21 3000 3000 0
</code></pre>
<p>I need to find the total sum and average of 2 columns ... | <p>Use <code>DataFrame.agg</code>:</p>
<pre><code> new_df=df[['sell_price', 'cost_price']].agg(['sum','mean']).T.rename(columns={'sum':'total','mean':'Avg'})
print(new_df)
</code></pre>
<hr>
<pre><code> total Avg
sell_price 5000.0 2500.0
cost_price 5000.0 2500.0
</code></pre> | python|pandas|dataframe | 1 |
352,793 | 58,320,837 | Why am I getting a method object not iterable error on an iterrows function? | <p>I've gotten a bit of code to work, but when wanting the code to iterate through my pandas dataframe, it errors out. The code is supposed to open and MPO image file and save it as a jpeg. This works until I put the snippet in an <code>iterrows</code> call. </p>
<p>The error is as such:</p>
<pre><code>> -----... | <p>Try this:</p>
<pre><code>mpo_list.iterrows()
</code></pre>
<p>Brackets are missing in your version.</p> | pandas|iterator | 1 |
352,794 | 58,549,239 | How to resolve 'numpy.float64' object cannot be interpreted as an integer? | <p>I'm getting this error, can anybody help me? </p>
<blockquote>
<p>TypeError: <strong>'numpy.float64' object cannot be interpreted as an integer.</strong> </p>
</blockquote>
<pre class="lang-py prettyprint-override"><code> def stft(sig, frameSize, overlapFac=0.5, window=np.hanning):
win = window(frameSiz... | <p>The problem is probably with the <code>cols</code> variable. <code>np.ceil</code> returns a <code>np.float64</code>; yes it is an integer value, but still a float dtype. Reread the <code>np.ceil</code> docs.</p>
<pre><code>In [77]: np.ceil(1.23)
Out[77]: 2... | python|numpy | 1 |
352,795 | 58,349,665 | Can you please help me correct this valueerror: math domain error? | <p>I'm trying to calculate the loss function in Logistic Regression but end up getting a math error in it. can you please help me rectify this error?</p>
<pre><code>def loss(y,a):
L = (-y*math.log(a)-(1-y)*math.log(1-a)).mean()
return L
</code></pre> | <p>You are getting the error because you are trying to find the log of a negative number (i.e. <code>a</code> is becoming negative). From your equation, I infer <code>y</code> is the true value and <code>a</code> is the predicted value. And the predictions come for the eqution below:</p>
<p> &nb... | numpy|math|logistic-regression | 1 |
352,796 | 58,458,668 | How execute fuction sum() in a column with df concate with other df | <p>I am using concat to merge 5 equal df into one and get the total sum() of cost.</p>
<p>These values are not real, just an example of what df looks like</p>
<p>What I tried:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
g = {"id": "1515", "cost": "100"}
b = {"id": "1515", "cost": "100"}
... | <p>Your problem is that you're not reassigning your <code>astype</code> call back to your <code>DataFrame</code>:</p>
<pre><code>import pandas as pd
data = {
"id": ['1,515','1,515','1,515','1,515','1,515'],
"cost": ['1,000','1,000','1,000','1,000','1,000']
}
all_vendors = pd.DataFrame.from_dict(data)
all_vendor... | python|pandas|sum|concat | 2 |
352,797 | 58,394,879 | Comparing data frames with a level of error | <p>I have two dataframes as </p>
<p><strong>df_schematic</strong></p>
<pre><code> layer x y
0 18 -10850.0 -6550.0
1 18 -10850.0 -5750.0
2 18 -10950.0 -5850.0
3 18 -10950.0 -5450.0
4 31 -10850.0 -5350.0
5 14 -10850.0 -4950.0
6 17 2945.5 6550.0
2278 rows × 3 c... | <p>Make some experiments with <em>np.isclose</em>.</p>
<p>I mean the following scenario:</p>
<ul>
<li>Write a function, say <em>isClose</em>, comparing one pair of coordinates (x1, y1) with
another pair (x2, y2), from 2 source rows, something like
<code>np.isclose(x1, x2, atol=0.5) & np.isclose(y1, y2, atol=0.5)<... | python-3.x|pandas|dataframe|data-science | 1 |
352,798 | 58,293,213 | Why is it returning this command when it shouldn't? 'numpy.ufunc' object is not subscriptable | <p>I am currently trying to write a Code to define an equation where one Input is set under two conditions, but I am getting an error:</p>
<pre><code>def findV (v_a,x,k,sig_a):
taxcorp=0.2
taxdiv=0.2
Modelequity=(e_function(v_a=v_a,sig_a=sig_a, r=rf, k=k,C=Intexp,taxcorp=0.2,taxdiv=0.2)+20, taxcorp, taxdiv... | <p>It's an issue with the brackets you're using. See how in the error it's referring to subscripting, which is using <code>[]</code> instead of <code>()</code>.</p>
<pre><code>TypeError: 'numpy.ufunc' object is not subscriptable:
if np.logical_and[Model>0,Model<x]:
</code></pre>
<p>Using parentheses <code>(... | python|numpy|logical-operators|finance | 0 |
352,799 | 58,286,425 | Python dataframe with value 'NA' not fetching | <p>I am trying to read a excel with below data:</p>
<p><a href="https://i.stack.imgur.com/kEbQe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kEbQe.png" alt="enter image description here"></a></p>
<p>But when i tried to debug the dataframe its showing only:</p>
<p><a href="https://i.stack.imgur.... | <p>In <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer"><code>pd.read_excel</code></a> there's an argument for this called <code>na_values</code>.</p>
<p>Quoted from the documentation:</p>
<blockquote>
<p>Additional strings to recognize as NA/NaN.<... | python-3.x|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.