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 |
|---|---|---|---|---|---|---|
20,400 | 63,844,100 | Fetch max value column with rows condition | <p>I want to fetch the max value according to 2 columns in a pandas dataframe. I managed to do this according to 1 column but not 2.</p>
<p>For 1 column:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({"name": list("ABABCD"), "value": np.arange(6)})
maxes = df.gro... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transform</code></a> instead of <code>agg</code>. Using one or two columns is exactly the same, for two columns it will be as follows:</p>
<pre><code>df["maxvalue"] = df.... | python|pandas|pandas-groupby | 4 |
20,401 | 63,892,819 | Sum the count for each countries for that month per month | <p>I have a list a 2000 row dataset with a countries in lists followed by their count. I want to sum of all the counts by exploding the lists and grouping them together for each month, every month.</p>
<pre><code>df_grouped=df.pivot_table(index=('month','month_int', 'year'),values='views',aggfunc='max')
count period... | <p>Use <code>.explode()</code> and <code>.groupby()</code>. You need to <code>reset_index()</code> to make it a dataframe and pass <code>name='Countries Count'</code> or any name different than <code>Countries</code>; otherwise, you will get an error, since the column name already exists:</p>
<pre><code>df = (df.explod... | python|python-3.x|pandas | 0 |
20,402 | 64,079,625 | Beyond value_counts() | <p>I have a pandas dataframe including some <code>value</code>s and <code>count</code> for each:</p>
<pre><code>df = pd.DataFrame({'value':[1,2,3,11,12,13,21,22,23], 'count':[100,200,300, 1100,1200,1300, 2100,2200,2300]})
value count
1 100
2 200
3 300
11 1100
12 1200
13 1300
21 2100
22 2200
... | <p>You can use <code>pd.cut</code> to categorize the column <code>value</code> into discrete intervals based on window size, then groupby the column <code>count</code> using this binned column and aggregate using <code>sum</code>:</p>
<pre><code>w = 10
g = pd.cut(df['value'], np.r_[0:df['value'].max() + w : w], right=F... | python|pandas|dataframe | 3 |
20,403 | 64,128,487 | AttributeError:: 'module' object has no attribute 'SparseCategoricalCrossentropy' | <p>The code for the error in title is below. I googled several times but could find out what the reasons are:</p>
<pre><code>class MyLinearModel(Model):
def __init__(self):
super(MyLinearModel, self).__init__()
self.flatten = Flatten()
self.d1 = Dense(10, activation='softmax', name="dense1")
def ... | <p>The oldest version i could find that has a similar function is 1.13, here is the link <a href="https://github.com/tensorflow/docs/blob/r1.13/site/en/api_docs/python/tf/keras/losses/CategoricalCrossentropy.md" rel="nofollow noreferrer">https://github.com/tensorflow/docs/blob/r1.13/site/en/api_docs/python/tf/keras/los... | python|tensorflow|keras|attributeerror | 1 |
20,404 | 64,127,034 | Getting error (cause of indeces) when trying to print dictionary using pandas | <p>I am trying to use <code>Pandas</code> to display a dictionary</p>
<pre><code>import pandas as pd
</code></pre>
<p>I am getting the error message</p>
<pre><code>ValueError: If using all scalar values, you must pass an index
</code></pre>
<p>My dictionary looks like this</p>
<pre><code>{0: "Classifier: SVC(kerne... | <p>This is all you need</p>
<pre><code>pd.DataFrame(dictionary, index=[0])
</code></pre>
<p>Or if you want them as rows, just add a <code>.T</code>, like this</p>
<pre><code>pd.DataFrame(dictionary, index=[0]).T
</code></pre> | python|pandas|dictionary | 1 |
20,405 | 46,968,454 | Assign list to a single pandas dataframe column when using apply | <p>I have a column in pandas dataframe in the format : "A,B,C,D" and I would like to split store it as a list instead [A,B,C,D]. I am using the below code to do the conversion but I keep getting the following error : <strong><em>ValueError: Shape of passed values is (58110, 3), indices imply (58110, 36)</em></strong></... | <p><strong>Setup</strong> </p>
<pre><code>df = pd.DataFrame(dict(textlist=['a,b,c,d']))
df
textlist
0 a,b,c,d
</code></pre>
<hr>
<p>@jezrael's answer is perfect! No need to do anything different.</p>
<pre><code>df.assign(newcol=df.textlist.str.split(','))
</code></pre>
<p>However, your function (with one sl... | python|pandas | 1 |
20,406 | 47,066,858 | pandas.DataFrame.round doesn't seem to work on my DataFrames - Rounding issue causes extra data stored in csv files | <p>I've stumbled upon a small issue when using pandas DataFrame:</p>
<p>I have a big csv file (around 2Gb of data) containing the price of an asset and created using the <code>DataFrame.to_csv()</code> function of Pandas, and when I take a closer inspection of the code, my first lines look like this: </p>
<pre><code>... | <p>This has to do with the precision of floating point arithmetic; not all numbers can be represented exactly. If you want to set pandas to display numbers to 5 decimal places, you can do</p>
<pre><code>pd.set_options('display.float_format','{:.5f}')
</code></pre>
<p>but the internal representation will stay the same... | python|python-3.x|pandas|csv | 3 |
20,407 | 47,034,872 | Does np.zeros define a global variable | <p>This is my code</p>
<pre><code>import numpy as np
def f(x):
x += 3
return x
x_initial = np.zeros(3)
print(x_initial)
print(f(x_initial))
print(x_initial)
</code></pre>
<p>And it returns:</p>
<pre><code>[ 0. 0. 0.]
[ 3. 3. 3.]
[ 3. 3. 3.]
</code></pre>
<p>It seems like 'x_initial' is a global vari... | <p><code>x_initial</code> is a mutable object. Passing it to function <code>f()</code> and modifying it there will modify the object. It's the same as if you passed a list into a function and modified it:</p>
<pre><code>def f(l):
l.append('something extra')
l = []
f(l)
print(l)
f(l)
print(l)
</code></pre>
<p>Out... | python|numpy | 2 |
20,408 | 46,966,991 | k-Nearest Neighbors rundown | <p>I'm trying to follow an example on k-Nearest Neighbors and I'm not sure about the numpy command syntax. I'm supposed to be doing a matrix-wise distance calculation and the code given is</p>
<pre><code>def classify(inputVector, trainingData,labels,k):
dataSetSize=trainingData.shape[0]
diffMat=tile(inputVec... | <p>I hope the following will explain the working.</p>
<p>Numpy tile : <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html</a></p>
<p>Using this function, you are creating matrix from input vector ... | python|python-2.7|numpy|machine-learning | 0 |
20,409 | 46,661,373 | Neural Network gets stuck | <p>I am experimenting with classification using neural networks (I am using tensorflow).
And unfortunately the training of my neural network gets stuck at 42% accuracy.
I have 4 classes, into which I try to classify the data.
And unfortunately, my data set is not well balanced, meaning that:</p>
<ol>
<li>43% of the da... | <p>I will assume that you have already double, triple and quadruple checked that the data going in is matching what you expect.</p>
<hr>
<p>The question is quite open-ended, and even a topic for research. But there are some things that can help.</p>
<p>In terms of better training, there's two normal ways in which pe... | machine-learning|tensorflow|neural-network|deep-learning|conv-neural-network | 1 |
20,410 | 38,836,482 | Create a rolling custom EWMA on a pandas dataframe | <p>I am trying to create a rolling EWMA with the following decay= 1-ln(2)/3 on the last 13 values of a df such has :</p>
<pre><code>factor
Out[36]:
EWMA
0 0.043
1 0.056
2 0.072
3 0.094
4 0.122
5 0.159
6 0.207
7 0.269
8 0.350
9 0.455
10 0.591
11 0.769
12 1.000
</code></pre>
<p>I have a df of monthly ret... | <p>@piRSquared 's answer is a good approximation, but values outside the last 13 also have weightings (albeit tiny), so it's not totally correct.</p>
<p><code>pandas</code> could do rolling window calculations. However, amongst all the rolling function it supports, <code>ewm</code> is not one of them, which means we ha... | python|pandas | 6 |
20,411 | 38,939,221 | Simple TensorFlow Neural Network minimizes cost function yet all results are close to 1 | <p>So I tried implementing the neural network from:</p>
<p><a href="http://iamtrask.github.io/2015/07/12/basic-python-network/" rel="nofollow">http://iamtrask.github.io/2015/07/12/basic-python-network/</a></p>
<p>but using TensorFlow instead. I printed out the cost function twice during training and the error is appe... | <p>First of all: you have no hidden layer. As far as I remember basic perceptrons could possibly model the XOR problem, but it needed some adjustments. However, AI is just invented by biology, but it does not model real neural networks exactly. Thus, you have to at least build an MLP (<a href="https://en.wikipedia.org/... | python|machine-learning|neural-network|tensorflow | 1 |
20,412 | 38,725,011 | Iterating over multiindex dataframe (Python) and assigning dicts to index-value pairs | <p>I am at my wit's end with this... I have a dataframe of three columns (aff_id, mkt and bkgs) I grouped by two of them (aff_id and mkt) :</p>
<pre><code>df_gb_aff = df.groupby(["affiliate_id", 'mkt']).sum()
df_gb_aff.sort('bkgs', ascending=False, inplace=True)
</code></pre>
<p>to give me a multiindex dataframe that... | <p>Another solution with dict comprehension:</p>
<pre><code>d = {idx[1]: df_gb_aff.ix[idx][0] for idx in df_gb_aff.index}
print (d)
{'446bb566f202': 1206.589522,
'bcab9d6ec630': 1910.7071239999998,
'0e9013464c4c': 1203.5323100000001,
'dbe759c691eb': 1203.979908,
'b7d0dbd38376': 1374.9246840000001}
print (d['bcab... | python|pandas|group-by | 1 |
20,413 | 63,310,257 | How to check the value change between different rows in a dataframe and represent it in a new column? | <p>Everyone.</p>
<p>I'm new to python and pandas, that I met a problem that I need to check whether a value of a certain columns changed over time(different rows). I totally have no idea that how to solve this problem.</p>
<p>I create a simple sample to illustrate it clearly:</p>
<pre><code> df = pd.DataFrame({"... | <p>Your logic is quite involved, so I have built it up in stages</p>
<ol>
<li>temporary columns with <em>first</em> value and <em>count</em> of <em>product</em> per <em>year</em></li>
<li>then your core logic with is using <code>apply()</code> and fact have <em>first</em></li>
<li>build a filter condition that is logi... | python|pandas|numpy|dataframe | 1 |
20,414 | 67,704,574 | Divide dataframe column value by the total of the column | <p>My question might be too easy for many of you but since i'm a beginner with Python..</p>
<p>I want to have the % by value of a column containing 3 different possible values (1,0,-1) but by excluding one of the values in the column (which is -1).</p>
<p>I did this : <code>(df['col_name']).sum()/len(df.col_name)</code... | <p>For exclude values replace <code>-1</code> to missing values:</p>
<pre><code>df['col_name'].replace(-1, np.nan).sum()/len(df.col_name)
</code></pre>
<p>Or filter out <code>-1</code> values if need count lengths of filtered Series:</p>
<pre><code>np.random.seed(123)
df = pd.DataFrame({'col_name':np.random.choice([0,... | python|pandas|dataframe|formula|division | 2 |
20,415 | 67,846,014 | pandas how to filter and slice with multiple conditions | <p>Using pandas, how do I return dataframe filtered by value of 2 in 'GEN' column, value 20 in 'AGE' column and exclude columns with name 'GEN' and 'BP'? Thanks in advance:)</p>
<pre><code>AGE GEN BMI BP S1 S2 S3 S4 S5 S6 Y
59 2 32.1 101 157 93.2 38 4 4.8598 87 151
48 1 21.6 87 1... | <p>You can do this -</p>
<pre><code>cols = df.columns[~df.columns.isin(['GEN','BP'])]
out=df.loc[(df['GEN'] == 2) & (df['AGE'] == 20),cols]
</code></pre>
<p><strong>OR</strong></p>
<pre><code>out=df.query("'GEN'==2 and 'AGE'==20").loc[cols]
</code></pre> | pandas|filtering|slice | 1 |
20,416 | 67,759,276 | Find the first signal in a condition | <p>I have a data frame (df) with different "price"s and I want to compare these prices and make a decision.</p>
<p><code>df['Decision'] = np.where((df['price1'] > df['price2']) ,'sell',np.where((df['price1'] < df['price2']),'buy',np.nan))</code></p>
<p>My output is:</p>
<div class="s-table-container">
<... | <p>You can try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.idxmax.html#pandas-series-idxmax" rel="nofollow noreferrer"><code>idxmax</code></a>:</p>
<pre><code>df.loc[(df['price1'] > df['price2']).idxmax(), 'Decision'] = 'sell'
df.loc[(df['price1'] < df['price2']).idxmax(... | python|pandas|dataframe | 2 |
20,417 | 67,638,668 | Wrong encoding on CSV file in Python | <p>I am not sure if I am making this question correctly but here's my issue:</p>
<p>I have a .csv file (<a href="https://drive.google.com/file/d/1F79iKrXQTLGIaiRhdl5GXtqPMpcqcoAP/view?usp=sharing" rel="nofollow noreferrer">InjectionWells.csv</a>) that I need to split into columns based on commas. When I do it, it just ... | <p>As your csv files contain some non-ascii characters also, you need to pass a different encoding. utf-8 can't handle that.</p>
<p>I tried thisand it's working :-</p>
<pre><code>import pandas as pd
test_data2=pd.read_csv('InjectionWells.csv', sep=',', encoding='ISO-8859-1')
print(test_data2)
</code></pre>
<hr />
<p><a... | python|pandas|csv|jupyter-notebook|spyder | 1 |
20,418 | 31,768,292 | get the data and the masked values as 0? | <p>I have a masked array.
I can get back the data via array.data, but this does not filter the data trough the mask.</p>
<p>How can I can get the data, but in the place where there is mask to get zero.</p>
<hr>
<p>Here is what I got so far :</p>
<pre><code> ary.data * (~ary.mask).astype(byte)
</code></pre> | <p>use <code>numpy.ma.filled()</code>:</p>
<pre><code>import numpy as np
m = np.ma.masked_greater(np.random.rand(10), 0.5)
print np.ma.filled(m, 0)
</code></pre> | python|numpy|mask | 1 |
20,419 | 41,590,139 | In Pandas, using isin to match dataframe to other dataframe | <p>I have 2 dataframes:</p>
<p>local_PC_user_filer_OpCode_sum:</p>
<pre><code> client_op clienthostid eventSum feeling usersidid
0 5030 1 1 Happy 5
1 5030 1 2 Mad 5
2 5030 1 8 Sick 6
3 5030 ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a>:</p>
<pre><code>cols = ['usersidid', 'clienthostid']
a = local_PC_user_filer_OpCode_sum.set_index(cols)
print (df_old_enough_users.join(a, on=cols, lsuffix='_x')[loc... | python|pandas | 2 |
20,420 | 41,501,758 | Error in parsing, update multiple columns in 1 line | <p>Input to <code>pd.read_clipboard()</code></p>
<pre><code>Ratanhia ,30c x2, 200c x2
Aloe ,30c x2, 200c x2
Nitric Acid ,30c x2, 200c x 2
Sedum Acre ,200c x2, 30c x2
Paeonia ,200c x2, 30c x2
Sulphur ,200c x2, 30c x2
Hamamelis ,30c x1, 200c x1
Aesculus ,30c x1, 200c x1
</code></pre>
<p>Code:</p>
<pre><code>import... | <p>You need parameter <code>skipinitialspace</code>:</p>
<pre><code>df = pd.read_clipboard(sep=',',
names=['Medicine','power30c','power200c'],
skipinitialspace=True)
print (df)
Medicine power30c power200c
0 Ratanhia 30c x2 200c x2
1 Aloe 30c x2 ... | python|python-2.7|pandas | 2 |
20,421 | 41,284,251 | Box-plot in Pandas | <p>I have two csv files each of them has one column.
That column has shared information between them like PassengerId,Name,Sex,Age. etc.</p>
<p>I am trying to draw a graph box plot of the ages of the passengers distribution per title(Mr, Mrs etc.). I get an error. how to pass the error that the plot can be drawn ?</p... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> first, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> both <code>DataFra... | python|csv|pandas|boxplot | 2 |
20,422 | 68,768,477 | 4x4 matrix with 1's in the diagonals (like a cross) and 0's everywhere else, using python | <p>i am able to get the checkerboard pattern, the + pattern and the one with 1's on the border but i am not able to figure this out. Can somebody help?</p> | <p>If you're sticking with whole dimensions, then as <a href="https://stackoverflow.com/users/11751294/p%C3%A9ter-le%C3%A9h">@Péter Leéh</a> pointed out:</p>
<pre><code>>>> np.eye(n) + np.fliplr(np.eye(n))
array([[1., 0., 0., 1.],
[0., 1., 1., 0.],
[0., 1., 1., 0.],
[1., 0., 0., 1.]])
</co... | python|numpy | 0 |
20,423 | 68,750,135 | Is there a way I can get the new column value based on previous rows without using loop in Python? | <p>I have a data table which has two columns time in and time out as shown below.</p>
<pre><code>TimeIn TimeOut
01:23AM 01:45AM
01:34AM 01:53AM
01:43AM 01:59AM
02:01AM 02:09AM
02:34AM 03:11AM
02:39AM 02:48AM
02:56AM 03:12AM
</code></pre>
<p>I need to create a third column named 'Counter' which updates in a way that wh... | <p>I couldn't figure out an efficient way with native Pandas-methods. But if I'm not completely mistaken, a <a href="https://docs.python.org/3.8/library/heapq.html" rel="nofollow noreferrer">heap queue</a> seems to be an adequate tool for the problem.</p>
<p>With</p>
<pre><code>df =
TimeIn TimeOut
0 01:23AM 01:4... | python|pandas|dataframe|loops | 2 |
20,424 | 68,523,444 | assigning column range in csv file to variable using pandas | <p>I have a CSV file that has 30 columns
and I have two variables (X,y)
I want the variable y to get all the rows from column number 0
so I used</p>
<pre><code>df = pd.read_csv("dataset.csv" )
y = df[:0]
</code></pre>
<p>this gets only the header which I don't need</p>
<p>and I want the variable X to get all... | <p>I just stumbled across the answer
I should be using iloc , so it should be</p>
<pre><code>y = df.iloc[: , 0].values
X = df.iloc[ : , 4: 23 ].values
</code></pre> | python|pandas|dataframe|csv | 0 |
20,425 | 68,744,297 | How can I fill missing data in my dataframe faster for a big dataset, and without a SettingWithCopyWarning? | <p>I have a dataframe with the count of people per day and per location. Without any missing data, I expect to have 4 lines per day: 2 locations and 2 genders. Some data is missing and should be replaced by the mean count, but only if that location has data for that gender on the day before.</p>
<p>If data is missing f... | <p>One solution can be to re-generate the posible combinations of location, gender and day</p>
<pre><code>df = data.set_index(['location', 'gender', 'day'])
.reindex(pd.MultiIndex.from_product(
[['X', 'Y'], ['F', 'M'], range(1, 8)],
names=['location', 'gender', 'day']))
... | python|pandas | 1 |
20,426 | 68,684,697 | Python pandas read_csv() ParserError: unexpected end of data | <p>My csv file looks like this:</p>
<pre><code>"City","Name","Comment"
"A","Jay","Like it"
"B","Rosy","Well, good"
...
"K","Anna","Works "fine""
</code></pre>
<p>The expected output(datafra... | <p><strong>I believe the trick is to preprocess and then read the data</strong></p>
<pre class="lang-py prettyprint-override"><code>
import re
from io import StringIO
import pandas as pd
data = """
"City","Name","Comment"
"A","Jay","Like it"
&q... | python|pandas|csv | 1 |
20,427 | 36,369,969 | not able install pip hence pandas also in ubuntu | <p>I'm using ubuntu 15.10 and python 3.4</p>
<p>when <code>sudo apt-get install python-pip</code> it gives <strong>E: Unable to locate package pip</strong> and when using <code>sudo python get-pip.py</code>it throws an error message as <strong>The directory '/home/username/.cache/pip/http' or its parent directory is n... | <p>Try :</p>
<pre><code>sudo apt-get install python3-pip
</code></pre>
<p>Or to do this manually :</p>
<pre><code>curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
</code></pre>
<p>Refer Official <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow noreferrer">Document</a> for m... | python|ubuntu|numpy|pandas|pip | 0 |
20,428 | 53,292,178 | looking for Pandas.DateTimeIndex.is_dst() | <p>I have a DateFrame with a DateTimeIndex, i.e.</p>
<pre><code>import pandas as pd
dates = pd.date_range('2018-04-01', periods=96, freq='15T', tz='Australia/Sydney', name='timestamp')
df = dates.to_frame(index=False)
df.set_index(dates.name, inplace=True)
</code></pre>
<p>I want to create a column with an 0/1 indica... | <p>It have in <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.dst.html" rel="noreferrer"><code>pandas</code></a> </p>
<pre><code>df.index.map(lambda x : x.dst())
</code></pre>
<p>After a small change can yield the Boolean </p>
<pre><code>df.index.map(lambda x : int(x.dst().total_seco... | python|pandas | 7 |
20,429 | 53,128,352 | legend overlapping plot area in seaborn | <p><a href="https://i.stack.imgur.com/GjmkY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GjmkY.png" alt="enter image description here"></a></p>
<p>I made the plot above using seaborn but I am not able to place the legend outside plot properly. Please note that the legend is cut off on the right s... | <p>You have not specified a sample set for us to be able to test the implementation and generate the plot, but with a toy initialization, modifying <code>bbox_to_anchor</code> seems to do the trick. See <a href="https://matplotlib.org/users/legend_guide.html" rel="noreferrer">matplotlib's legend guide</a>.</p>
<p><cod... | python|pandas|seaborn | 6 |
20,430 | 65,545,918 | val_loss did not improve from inf + loss:nan Error while training | <p>I have a problem that occurs when I start training my model.
This error says that val_loss did not improve from inf and loss: nan.
At the beginning I thought it was because of the learning rate but now I'am not sure what it is because I've tried ceveral different learning rates and none of those worked for me.
I hop... | <p><em>Few Comments...</em></p>
<p>In these kind of situation, the most preferable is the trial and error approach. It seems like your parameters have diverged while training. Lots of possibilities could be the issue. Also, it seems like you are regularizing your network as well (dropouts, BatchNorm, etc)</p>
<h3>Sugge... | python|tensorflow|keras|python-3.8 | 1 |
20,431 | 65,708,947 | Change x-axis order of labels in Pandas / Matplotlib histogram? | <p>Suppose I have a Pandas dataframe with discrete values in a column.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = ['A']*2 + ['C']*3 + ['B']* 1
print(data)
# ['A', 'A', 'C', 'C', 'C', 'B']
my_df = pd.DataFrame({'mycolumn': data})
print(my_df)
# mycolumn
# 0 A
# 1 A
#... | <p>You can use <code>value_counts</code>, <code>loc</code> to define order, and <code>bar</code> plot:</p>
<pre><code>my_df.mycolumn.value_counts().loc[['C', 'A', 'B']].plot.bar()
</code></pre>
<p><a href="https://i.stack.imgur.com/OmE0v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OmE0v.png" alt=... | python|pandas|matplotlib | 7 |
20,432 | 65,601,310 | How to divide two large numpy matrix elemtwise without getting killed? | <p>I have two matrices A,B both of shape 150000 X 150000</p>
<p>I want to divide each element of A with each element of B, element wise.
The way I currently do it is -</p>
<pre><code>res=A/B
</code></pre>
<p>I do get the output for small matrices, but for large matrices as mine. The process gets killed. Any suggestion... | <p>you could try to use pandas and set the type of the values to something small memory wise, or at least check the memory allocated for a value, usually Python uses float64 or so, which is in some cases way too much.</p>
<p>use</p>
<pre><code>pd.to_numeric(s, errors='coerce')
</code></pre>
<p>or</p>
<pre><code>pd.to_... | python-3.x|pandas|numpy | 1 |
20,433 | 21,021,337 | Concatenate 2 dataframes with uneven lengths and no index | <p>How do you concatenate 2 dataframes with uneven lengths and no index</p>
<pre><code>y=[152,176,160,192,220,272,256,280,300,280,312,328]
df= pd.DataFrame({'a':y})
z=[np.nan, np.nan,176.,195.84, 217.8816, 241.242, 272.1758,
292.7523, 313.2483, 332.8503, 341.3608, 352.8076, 363.6765, 360.4414,
379.522]
d... | <p>Every pandas DataFrame has an index, even if you don't specify it explicitely. In that case the index is composed of integers from 0 to n:</p>
<pre><code>>>> df.index
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype=int64)
</code></pre>
<p>So if the DataFrames are in the right order, you can simpl... | python|pandas | 2 |
20,434 | 21,293,983 | Disabling DataFrame dimensions printing | <p>Pandas prints DataFrame dimensions at the last line after the DataFrame:</p>
<pre><code>import pandas as pd
print pd.__version__
print pd.DataFrame({'a':[1,2],'b':[3,4]})
</code></pre>
<p>Out:</p>
<pre><code>0.13.0
a b
0 1 3
1 2 4
[2 rows x 2 columns] <- dimensions
</code></pre>
<p>How to disabl... | <p>At the moment, I don't think you can, at least not without monkeypatching <code>DataFrame</code>. The magic happens in <code>DataFrame.__unicode__</code>:</p>
<pre><code>def __unicode__(self):
"""
Return a string representation for a particular DataFrame
Invoked by unicode(df) in py2 only. Yields a Uni... | python|pandas | 3 |
20,435 | 20,984,266 | Dispersing Random Sampling in CSV through Python | <p>I have a (large) directory CSV with columns [0:3] = Phone Number, Name, City, State.</p>
<p>I created a random sample of 20,000 entries, but it was, of course, weighted drastically to more populated states and cities.</p>
<p>How would I write a python code (using CSV or Pandas - I don't have linecache available) t... | <p>There are many ways to implement this, but the abstract algorithm should be something like this.</p>
<p>First, to create a new CSV that meets your second critera about each state being drawn with equal probability, draw each row as follows. </p>
<p>1) From the set of states, draw a state (each state is drawn with ... | python|python-2.7|csv|random|pandas | 2 |
20,436 | 2,841,567 | Python optimization problem? | <p>Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho.</p>
<p>Here's the code (that I've managed to optimize a bit in the latter part):</p>
<pre><code>im... | <p>Interference patterns are fun, aren't they?</p>
<p>So, first off this is going to be minor because running this program as-is on my laptop takes a mere twelve and a half seconds.</p>
<p>But let's see what can be done about doing the first bit through numpy array operations, shall we? We have basically that you wa... | python|optimization|numpy|for-loop|physics | 5 |
20,437 | 63,375,398 | Create new pandas row as a result of combination of text values from different rows which has same value in other pandas column | <p>I would like to create a new pandas data-frame as a result of concatenating text values which has the same value in other column. So for instance, I got the following dataframe:</p>
<pre><code>example_dct = {
"text": {
"0": "this is my text 1",
"1": "this is my ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> on <code>article_id</code> and use a custom lambda function that produces all possible combinations of <code>length=2</code> of strings in <code>text</co... | python|pandas|dataframe | 2 |
20,438 | 63,686,752 | Python pandas dataframe groupby columns error no apply member | <p>I am using pandas to get the average price and total quantity of a dataset.
The code works, but I get the following error message:</p>
<p><strong>Instance of 'DataFrameGroupBy' has no 'apply' member</strong> for the line</p>
<p><em>summary_Report = df.groupby('name').apply(f1)</em></p>
<pre><code>import pandas as pd... | <p>The code is running absolutely fine for me. But there can be a few potential issues -</p>
<ol>
<li>You have used groupby as a variable name and overwritten the pandas method. Please restart the kernel and run again and it should not throw this error again.</li>
<li>You are working with an experimental version or out... | python|pandas | 0 |
20,439 | 21,747,305 | Working with map in python | <p>I'm trying to figure out the way to properly use map in python so that I can multi-thread my program by Pool.map. Basically I'm running into issues trying to understand how functional python works. I have: </p>
<pre><code>import numpy as np
def maptest(foo,bars):
print foo * bars
main():
matA = np.eye(2)
... | <p>The [None, None] is coming from printing the map call (note that your maptest function prints!).</p>
<p>Now, the reason that it prints those multiple arrays is that you are mapping your function across all of mapA. mapA is actually a two-element array, and map applies your function to <em>each</em> element of the a... | python|numpy|map|functional-programming | 5 |
20,440 | 21,899,555 | circle detection in open cv using python | <p>I was trying to detect circles from a black background with red circular kind objects.</p>
<pre><code>import cv2
import cv2.cv as cv
import numpy as np
img = cv2.imread('extracted.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,... | <p>There is a small correction to be made in your code.</p>
<p>You are loading image in grayscale, and then again converting it to grayscale using <code>cv2.cvtColor</code> which is invalid operation.</p>
<p>Alternatively, OpenCV provides a <a href="https://github.com/Itseez/opencv/blob/master/samples/python2/houghci... | python|opencv|numpy | 26 |
20,441 | 24,567,078 | How to remove the date information in a column, just keep time | <p>I am using pandas dataframe. there is a specific column has time information.</p>
<p>the raw data likes this:</p>
<pre><code>5:15am
5:28am
6:15am
</code></pre>
<p>so I need to convert the raw data into datetime format:</p>
<pre><code>format = '%I:%M%p'
dataset['TimeStamp'] = pd.to_datetime(dataset['TimeStamp'],f... | <p>The following will convert what you have to datetime.time() objects:</p>
<pre><code>dataset['TimeStamp'] = pd.Series([val.time() for val in dataset['TimeStamp']])
</code></pre>
<p>Output</p>
<pre><code> TimeStamp
0 05:15:00
1 05:28:00
2 06:15:00
</code></pre> | python|pandas | 11 |
20,442 | 30,083,872 | How to pass arrays into Scipy Interpolate RectBivariateSpline? | <p>I am creating a Scipy Interpolate RectBivariateSpline as follows:</p>
<pre><code>import numpy as np
from scipy.interpolate import RectBivariateSpline
x = np.array([1,2,3,4])
y = np.array([1,2,3,4,5])
vals = np.array([
[4,1,4,4,2],
[4,2,3,2,6],
[3,7,4,3,5],
[2,4,5,3,4]
])
rect_B_spline = RectBivari... | <p>Yes, the documentation is perhaps a bit weak here. The default call that you are using expects that x and y define grid points. Like the original call to create the spline fit, these need to be in strictly ascending order. It will then return the full grid of spline interpolations.</p>
<p>If you instead use RectB... | python|numpy|scipy|interpolation | 5 |
20,443 | 30,184,702 | Cythonise a pandas loop | <p>Can anyone help show me how convert this loop into cython to improve performance. I get you need to create static types using cdef for performance but what else is required:</p>
<p>If I have a dataframe df with column 'a'.</p>
<pre><code> for i in range(0, len(df.a)-1):
if (i < len(df.a)-1):
y= i ... | <p>Without trying to comment on whether you could write this better in Pandas without using Cython (I don't know, but it's certainly worth trying), the steps you'd need to do are:</p>
<ol>
<li><code>cdef</code> the iteration indices <code>i</code> and <code>y</code> as integers: <code>cdef int i,y</code> (the cdefs go... | python|pandas|cython | 1 |
20,444 | 53,520,911 | how to truncate certain columns to X number of characters? | <p>I have a dataframe with some columns having large sentences. </p>
<p>How do I truncate the columns to say 50 characters max? </p>
<p>current df:</p>
<pre><code>a b c
I like data science 1 2
</code></pre>
<p>new truncated df for ONLY column <code>a</code>:</p>
<pre><code>a ... | <p>For a specific column:</p>
<pre><code>df['a'] = df['a'].str[:50]
</code></pre> | python|python-3.x|pandas | 1 |
20,445 | 53,403,439 | Creating a simple webpage with Python, where template content is populated from a database (or a pandas dataframe) based on query | <p>I use python mainly for data analysis, so I'm pretty used to pandas. But apart from basic HTML, I've little experience with web development.</p>
<p>For work I want to make a very simple webpage that, based on the address/query, populates a template page with info from an SQL database (even if it has to be in a data... | <p>You can start with flask, It is easy to setup and lots of good resources online,
Start with this minimal web app <a href="http://flask.pocoo.org/docs/1.0/quickstart/" rel="nofollow noreferrer">http://flask.pocoo.org/docs/1.0/quickstart/</a></p>
<p>Example snippet</p>
<pre><code>@app.route('/database')
def database... | python|django|pandas | 0 |
20,446 | 53,796,187 | How to get coordinate of only one item in numpy array | <p>So this is my code. I don't want to get all the coordinates of pixel values below 210 because I want to perform some operation on them and possibly adjust the condition depending on outcome of that operation.</p>
<pre><code>filename = "/home/User/PycharmProjects/Test/files/1366-000082.png"
image = Image.open(filen... | <p>You can use enumerate() to get value indexes:</p>
<pre><code>def get_image_data():
for row_number, row in enumerate(image_data):
for column_number, cell in enumerate(row):
if condition:
# I need only coordinate of cell here
print(row_number, column_number)
</c... | python|numpy | 1 |
20,447 | 53,391,618 | Tensor Tensor("predictions/Softmax:0", shape=(?, 1000), dtype=float32) is not an element of this graph | <p>I am trying to follow a <a href="https://machinelearningmastery.com/use-pre-trained-vgg-model-classify-objects-photographs/" rel="nofollow noreferrer">simple tutorial</a> on how to use a pre-trained VGG model for image classification. The code which I have: </p>
<pre><code>from keras.applications.vgg16 import VGG16... | <p>Seems that Keras is not thread safe so you need to initialize the model in each thread. A fix is calling: _make_predict_function()</p>
<p>It did work for me. Here is a clean example:</p>
<pre><code>from keras.models import load_model
def load_model():
model = load_model('./my_model.h5')
model._make_predict_fu... | python|tensorflow|keras | 3 |
20,448 | 17,457,329 | split data frame based on integer index | <p>In pandas how do I split Series/dataframe into two Series/DataFrames where odd rows in one Series, even rows in different? Right now I am using</p>
<pre><code>rng = range(0, n, 2)
odd_rows = df.iloc[rng]
</code></pre>
<p>This is pretty slow.</p> | <p>Use slice:</p>
<pre><code>In [11]: s = pd.Series([1,2,3,4])
In [12]: s.iloc[::2] # even
Out[12]:
0 1
2 3
dtype: int64
In [13]: s.iloc[1::2] # odd
Out[13]:
1 2
3 4
dtype: int64
</code></pre> | pandas | 28 |
20,449 | 19,838,008 | Vectorizing loops in NumPy | <p>I am trying to vectorize a loop iteration using NumPy but am struggling to achieve the desired results. I have an array of pixel values, so 3 dimensions, say (512,512,3) and need to iterate each x,y and calculate another value using a specific index in the third dimension. An example of this code in a standard loop ... | <p>Your vectorized solution is correct.</p>
<ul>
<li>in your for loop <code>temp</code> is a scalar value that will take only the last value</li>
<li>use <code>np.sqrt</code> istead of <code>math.sqrt</code> for vectorized inputs</li>
<li>you should not use <code>array</code> as a variable since it can shadow the <cod... | python|arrays|numpy|vectorization | 1 |
20,450 | 15,913,908 | python numerically solving an equation with no sign change between the upper and lower bound | <p>I am trying to solve an equation but I am unable to use <code>brentq</code> since there is no sign change. How could I find the value of <code>r</code>?</p>
<pre><code>>>> import numpy as np
>>>
>>> def f(r):
return 0.1 + 1 / (2 * r ** 2) - 2 / (3 * np.sqrt(r ** 3))
</code></pre> | <p>I think there is sign change, but you can solve it by <code>fsolve</code>:</p>
<pre><code>from scipy.optimize import fsolve
import numpy as np
def f(r):
return 0.1 + 1 / (2 * r ** 2) - 2 / (3 * np.sqrt(r ** 3))
r = fsolve(f, 1)
f(r)
</code></pre>
<p>result:</p>
<pre><code>r = 2.22213541
</code></pre>
<p><s... | python|numpy|python-3.x | 1 |
20,451 | 16,027,625 | AttributeError: 'module' object has no attribute 'percentile' | <p>I use this function to calculate percentile from <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html" rel="nofollow noreferrer">here</a>:</p>
<pre><code>import numpy as np
a = [12, 3, 45, 0, 45, 47, 109, 1, 0, 3]
np.percentile(a, 25)
</code></pre>
<p>But I get this error :</p>
... | <p>The <code>percentile</code> function was added in <a href="https://github.com/numpy/numpy/blob/maintenance/1.5.x/numpy/lib/function_base.py" rel="noreferrer">version 1.5.x</a>. You will need to upgrade to at least that version.</p>
<p>Did you try:</p>
<pre><code>sudo pip install numpy==1.7.1 --upgrade
</code></pre... | python|numpy|percentile | 9 |
20,452 | 71,895,083 | Pandas - Subtraction in column pairs | <p>For a given column pair I'd like to calculate the difference between them two.</p>
<p>df</p>
<pre><code>customer_id total_spent_21_q4_ total_spent_22_q1_ time_spent_online_21_q4_ time_spent_online_22_q1_
132 394 439 29 32
222 482 ... | <p>You can remove the following renaming column header line</p>
<pre class="lang-py prettyprint-override"><code>df_2.columns = df_2.columns.str.extract('(\d+)', expand=False)
</code></pre>
<p>Then rename the <code>diff_table</code> columns before <code>reset_index</code> based on the integer in your original column hea... | python|pandas | 1 |
20,453 | 72,015,160 | Iterate a column to create a dictionary and create a data frame | <p>I am trying to for iterate a column to achieve the count of each word in a sentence.</p>
<p>I have a column:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>words</th>
</tr>
</thead>
<tbody>
<tr>
<td>"one two three four four six"</td>
</tr>
<tr>
<td>"seven eight nine ten e... | <pre class="lang-py prettyprint-override"><code>from collections import Counter
# get a list of lists with sentences
sentences = df['words'].values.tolist()
# split the sentences into the words and flatten the list
words = [i for j in sentences for i in j.split()]
# get counts of each unique word
counts = Counter(words... | python|pandas|list|dataframe|dictionary | 0 |
20,454 | 71,970,900 | Integrate strip or trim in python script | <p>Thanks so much for reading my post, I hope someone can help me with that, I have a script to connect to my database and extract several tables and convert them to JSONL format ( all with pandas ), my script:</p>
<pre><code>import pyodbc
import fileinput
import csv
import pandas as pd
import json
import os
import sys... | <p>You should be able to do this right between two of your lines:</p>
<pre class="lang-py prettyprint-override"><code> df_o = df.astype(str)
df_o = df_o.applymap(lambda x: x.strip() if isinstance(x, str) else x)
df_o.to_json(filename_json, orient = "records", lines = bool, date_format = "iso&... | python|pandas|python-requests|trim|strip | 0 |
20,455 | 16,710,999 | Extracting rows for a Pandas dataframe in Python | <p>I have imported a simple query log into a pandas dataframe in Python (see image), and would like to know what the most efficient way is to extract all of the rows that contain any given keyword that is contained in the 'Keyword' column.</p>
<p>I could iterate over the dataframe - but have a feeling there might be a... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods" rel="noreferrer"><code>str.contains</code></a>, for example:</p>
<pre><code>In [1]: df = pd.DataFrame([['abc', 1], ['cde', 2], ['efg', 3]])
In [2]: df
Out[2]:
0 1
0 abc 1
1 cde 2
2 efg 3
In [3]: df[... | python|pandas|dataframe | 5 |
20,456 | 19,090,070 | pylab histogram get rid of nan | <p>I have a problem with making a histogram when some of my data contains "not a number" values. I can get rid of the error by using <code>nan_to_num</code> from numpy, but than i get a lot of zero values which mess up the histogram as well.</p>
<pre><code>pylab.figure()
pylab.hist(numpy.nan_to_num(A))
pylab.show()
</... | <p>Remove <code>np.nan</code> values from your array using <code>A[~np.isnan(A)]</code>, this will select all entries in <code>A</code> which values are not <code>nan</code>, so they will be excluded when calculating histogram. Here is an example of how to use it:</p>
<pre><code>>>> import numpy as np
>>... | python|numpy|matplotlib|histogram|nan | 40 |
20,457 | 19,050,386 | Installing Numpy on Fedora 19 with pip | <p>I tried to install Python 2.7 <code>Numpy</code> module on Fedora 19 using <code>pip</code>:</p>
<pre><code>sudo pip install numpy
</code></pre>
<p>But I have the following error:</p>
<pre><code>"Cannot compile 'Python.h'. Perhaps you need to "\
SystemError: Cannot compile 'Python.h'. Perhaps you need to install... | <pre><code>sudo yum install python-devel
</code></pre>
<p>And then it shall work flawlessly.</p> | python|numpy|pip|fedora | 4 |
20,458 | 55,198,049 | Using Numpy where to place conditions on Pandas DataFrame while taking Cumulative Sum | <p>I am trying to place a condition on one of the columns in Pandas Dataframe and based on that condition I want to take cumulative sum of another column in the Dataframe. To be more clear here is the example: Suppose my DataFrame <code>df</code> as:</p>
<pre><code>+-----------+--------------+-----+-------------+
| ... | <p>Check with <code>groupby</code> and <code>cumsum</code> </p>
<pre><code>df.groupby((df.dir==df.dir.shift()).eq(0).cumsum()).daily_return.cumsum()
0 -0.000681
1 -0.002181
2 -0.005203
3 0.005776
4 -0.003772
5 -0.008132
Name: daily_return, dtype: float64
</code></pre>
<p>If only keep the last one ,using ... | python|pandas|numpy|dataframe | 1 |
20,459 | 55,512,414 | How to groupby and filter for strings in python pandas dataframe | <p>I would like to filter based on a string condition.</p>
<p>My dataframe looks like this:</p>
<p><a href="https://i.stack.imgur.com/aR3b5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aR3b5.png" alt="dataframe"></a></p>
<p>I want to group by Id, and filter for groups that consist of both words... | <p>The error you get is because <code>.mode</code> is a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mode.html" rel="nofollow noreferrer">method</a> on the DataFrame. Use <code>["mode"]</code> instead.</p>
<p>To filter the groups correctly you want to test whether "set" is appea... | python|pandas|filter | 2 |
20,460 | 55,260,093 | how to count number of all child under every p1 id in pandas? id and parent id are given | <p>here is some part of the data table </p>
<p>Df2</p>
<pre><code> id title parent_id
0 11 p1 11
1 12 p1 11
2 13 p2 12
3 14 p2 12
4 15 p2 13
5 16 p2 13
6 17 p3 13
</code></pre>
<p>This df2 problem should give output like</p>
<... | <p>You can use the crosstab function:</p>
<p><strong>Step 1: Create DataFrame</strong></p>
<pre><code>import pandas as pd
import numpy as np
d = {'id': [11, 12, 13, 14, 15, 16, 17], 'title': ['p1','p1','p2', 'p2', 'p2', 'p2', 'p3'],'parentid':['11','11','12', '12', '13', '13', '13']}
df = pd.DataFrame(data=d)
</code>... | python|pandas|statistics|data-science|data-analysis | 2 |
20,461 | 55,356,929 | How can I use Shapely to detect all points that are closer than N meters? | <p>Say I've got a list of points (the coordinates are in meters):</p>
<pre><code>points = [(1, 1), (2, 2), (-1, 3), ..., (1000, 1000)]
</code></pre>
<p>And I want to use Shapely library to return all the points (from <code>points</code>) that are within <code>N</code> meters radius to some specified origin e.g., <cod... | <p>Fast calculations for lots of data are best handled with numpy. Instead of creating shapely objects from the coordinates and use the built in distance function, it is much easier (for points!, not for polygons) to calculate the distance using a numpy array. If you want to do the same for lines and polygons and use t... | python|numpy|shapely | 4 |
20,462 | 9,990,789 | How to force zero interception in linear regression? | <p>I have some more or less linear data of the form:</p>
<pre><code>x = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 20.0, 40.0, 60.0, 80.0]
y = [0.50505332505407008, 1.1207373784533172, 2.1981844719020001, 3.1746209003398689, 4.2905482471260044, 6.2816226678076958, 11.073788414382639, 23.248479770546009, 3... | <p>As @AbhranilDas mentioned, just use a linear method. There's no need for a non-linear solver like <code>scipy.optimize.lstsq</code>.</p>
<p>Typically, you'd use <code>numpy.polyfit</code> to fit a line to your data, but in this case you'll need to do use <code>numpy.linalg.lstsq</code> directly, as you want to set ... | python|numpy|scipy|statistics|linear-regression | 51 |
20,463 | 56,579,536 | Whats the difference between `arr[tuple(seq)]` and `arr[seq]`? Relating to Using a non-tuple sequence for multidimensional indexing is deprecated | <p>I am using an ndarray to slice another ndarray.
Normally I use <code>arr[ind_arr]</code>. <code>numpy</code> seems to not like this and raises a <code>FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use arr[tuple(seq)] instead of arr[seq]</code>.</p>
<p>What's the difference be... | <p><code>meshgrid</code> returns a list of arrays:</p>
<pre><code>In [50]: np.meshgrid([1,2,3],[4,5],indexing='ij')
Out[50]:
[array([[1, 1],
[2, 2],
[3, 3]]), array([[4, 5],
[4, 5],
[4, 5]])]
In [51]: np.meshgrid([1,2,3],[4,5],index... | numpy|numpy-ndarray | 2 |
20,464 | 56,602,423 | create plot and save plot same name as CSV file | <p>This code will create a 3d scatter plot using matplotlib and I am trying to figure out how to save a PNG with the same name as the CSV file I am using to create the pandas dataframe.</p>
<p>I can save the PNG same name as the .py file with this:</p>
<p><code>output_filename = os.path.splitext(__file__)[0] + '.png'... | <p>Since you are explicitly specifying the name of the csv file while reading it, why can't you simply do the following. Remember, comment out the <code>plt.show()</code> before saving the figure. Read <a href="https://stackoverflow.com/questions/21875356/saving-a-figure-after-invoking-pyplot-show-results-in-an-empty-f... | python|pandas|matplotlib | 0 |
20,465 | 56,441,190 | Zero padding pandas column | <p>I have the following dataframe, in which col_1 is type integer:</p>
<pre><code>print(df)
col_1
100
200
00153
00164
</code></pre>
<p>I would like to add two zeros, if the number of digits is equal to 3:</p>
<pre><code>final_col
00100
00200
00153
00164
</code></pre>
<p>I tried with:</p>
<pre><code>df.col_1 = df... | <p>Another way using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.pad.html" rel="noreferrer"><code>series.str.pad()</code></a>:</p>
<pre><code>df.col_1.astype(str).str.pad(5,fillchar='0')
</code></pre>
<hr>
<pre><code>0 00100
1 00200
2 00153
3 00164
</code></pre>
... | python|pandas|numpy | 12 |
20,466 | 56,686,854 | How to save the output of a while loop within a for loop in Python? | <p>I have a for-while-loop combination to check value differences for person-year observations. The entire things gives me a boolean list as outcome which I need for further analysis. </p>
<p>I tried several versions of <code>append</code>, none was working.</p>
<p>Here is <strong>my data</strong>:</p>
<pre class="l... | <p>IIUC use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a>, <a href="https:... | python|pandas|loops | 2 |
20,467 | 56,596,759 | Accessing a Numpy Matrix from C as a 3D array | <p>I have noticed that it is possible to create a borrowed/stolen reference to a (3D) numpy array of floats using <code>PyArray_AsCArray</code> as following:</p>
<pre><code>...
float ***matrix_c;
npy_intp dims[3] = {X, Y, Z};
PyArray_Descr *descriptor = PyArray_DescrFromType(NPY_FLOAT32);
PyArray_AsCArray(&matrix_... | <p>Found out quite an easy way to solve this, so I will post it just in case anyone else struggles with this.</p>
<p>I tried solving it through a pointer of 2D structures, but in the end, all which I needed was a cast to a pointer to 3D structures:</p>
<pre><code>PyObject *matrix_object;
PyArg_ParseTuple(args, "O", &... | python|c|arrays|numpy|3d | 1 |
20,468 | 26,193,548 | Query about np.log in Numpy | <p>This is probably a trivial question, but I've been struggling with it for a while. For some reason, when I used the line of code below I get the Error <code>RuntimeWarning: divide by zero encountered in log print np.log(69/74)</code>. I can't figure out why this is the case.</p>
<pre><code>np.log(69/74)
</code></pr... | <p>Because you are doing integer division</p>
<pre><code>>>> 69/74
0
</code></pre>
<p>As <code>float</code> you get</p>
<pre><code>>>> 69.0/74.0
0.9324324324324325
</code></pre> | python|numpy | 2 |
20,469 | 26,281,204 | Check indexes in 3D numpy array | <p>I'm trying to write code that will play a dice game called <a href="http://en.wikipedia.org/wiki/Pig_(dice_game)" rel="nofollow">Pig</a> through the command line with a person against the computer</p>
<p>For the computer's player, I am using a 3D numpy array to store a game strategy based on the information current... | <p>It looks like you're making a small logic error.</p>
<blockquote>
<p>I have this code to set up the array:</p>
<pre><code>AI_1_strategy = numpy.zeroes((100,100,100))
for i in range(10, 100):
for j in range(10, 100):
for k in range(10, 100):
AI_1_strategy[i, j, k] = 1
</code></pre>
<... | python|arrays|numpy|indexing | 0 |
20,470 | 26,385,843 | Python, how to merge 2 pandas DataFrame | <p>Lets say I have two differents pandas Dataframe with different index
for example:</p>
<p>df1:</p>
<pre><code>email | other_field
_________________________________________
email1@email.com | 2
email2@email.com | 1
email3@email.com | 6
</code></pre>
<p>... | <p>You can just <code>concat</code> in this case:</p>
<pre><code>In [70]:
pd.concat([df1,df2],axis=1)
Out[70]:
email other_field new_field
0 email1@email.com 2 1
1 email2@email.com 1 7
2 email3@email.com 6 4
</code></pre>
<p>You could el... | python|pandas|merge|dataframe | 2 |
20,471 | 66,788,478 | AttributeError: 'ArgDef' object has no attribute 'handle_data' | <p>I am trying to run this example from tensorflow.org on my local machine <a href="https://www.tensorflow.org/tutorials/text/classify_text_with_bert" rel="nofollow noreferrer">1</a>, but gives me the following error:</p>
<p>AttributeError: 'ArgDef' object has no attribute 'handle_data'.</p>
<p>The problem appears in l... | <p>The version of tensorflow was 2.4, I made a typo unfortunately.</p>
<p>But I overcame the problem by adding the following lines of code:</p>
<pre><code>os.environ["TFHUB_CACHE_DIR"] = "gs://my-bucket/tfhub-modules-cache"
Bert_Model_Path = '______path to the downloaded model_______'
bert_layer = h... | python|tensorflow|nlp|tensorflow-hub | 0 |
20,472 | 66,950,375 | I try to implement vggnet, but it does not be trained well | <p>I am new at CNN.
I try to train vggnet.</p>
<p>class Net(nn.Module) :</p>
<pre><code>def __init__(self) :
super(Net, self).__init__()
self.conv = nn.Sequential (
#1
#####
nn.Conv2d(3,64,3, padding=1), nn.ReLU(inplace=True),
nn.Conv2d(64,64,3, padding=1),nn.ReLU(inplace=Tru... | <p>Your loss value <code>6.9077</code> is equal to <code>-log(1/1000)</code>, which basically means your network produces random outputs out of all possible 1000 classes.</p>
<p>It is a bit tricky to train VGG nets from scratch, especially if you do not include batch-norm layers.</p>
<p>Try to reduce the learning rate ... | python|pytorch|conv-neural-network|training-data|vgg-net | 0 |
20,473 | 47,412,496 | Why does python numpy std() make unwanted spaces? | <p><a href="http://blogattach.naver.net/9f0a8335221415a38c6c0e3b06e39fe14313ec3b/20171121_33_blogfile/tkdgur946_1511264695731_Odbo04_csv/car3.csv" rel="nofollow noreferrer">'car3.csv' file download link</a></p>
<pre><code>import csv
num = open('car3.csv')
nums = csv.reader(num)
nums_list = []
for i in nums:
nums_l... | <p>That is not a spacing problem. What all you need to do is to save the output of the standard deviation. Then, you can access each value like this: </p>
<pre><code> std_arr = np.std(nums_arr, axis=0) # array which holds std of each column
# now, you can access them by indexing:
print(std_arr[0]) # output here is... | python|numpy | 0 |
20,474 | 47,474,155 | What is causing my Python program to run out of memory using opencv? | <p>I wrote a program to read images using Python's opencv and tried to load 3 GB images, but the program aborted.
There is 32 GB of memory on my PC, but when I run this program it will run out of it. What is the cause?</p>
<p>The error message is not issued and the PC becomes abnormally heavy. I confirmed it with Ubun... | <p>Reasons for running out of memory:</p>
<ul>
<li><p>Image file size and the size of corresponding array in memory are different. Images, e.g., PNG and JPEG formats, are compressed. The size of a corresponding uncompressed BMP image is more relevant here. Also, <code>ndarray</code> holds some meta-information that ma... | python|image|numpy|opencv|memory | 1 |
20,475 | 68,367,726 | Can I plot a point at an equal distance from a line in python? | <p>So far in my code I have:</p>
<pre><code>enter code here import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# DATA
L = 0.1 #m, length of arm of cross
t = L/2 #m, thickness
# VECTORS OF COORDINATES OF THE CROSS
X = np.array([L, t/2, t/2, -t/2, -t/2, -L, -L, -t/2, -t/2, t/2, t/2, L, L])
Y = ... | <p>I would recommend using a scatter plot and defining the x and y values of the points you want to plot.</p>
<p><a href="https://i.stack.imgur.com/Gr6gf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gr6gf.png" alt="enter image description here" /></a></p>
<pre><code>import numpy as np
import matp... | python|numpy|matplotlib | 1 |
20,476 | 68,126,025 | filter out rows of a dataframe containing a specific string | <p>I have a massive dataframe. The dataframe has column patient.drug. This column contains list of dictionaries as its elements.
I want to filter out all the rows that containn 'NIFEDIPINE' word in patient.drug column.</p>
<p>The dataframe is very large. Here is a sample of it.</p>
<pre><code> ... | <p>Suppose you have this layout of column:</p>
<p>Search string 'NIFEDIPINE' found on the 2nd and 4th entries:</p>
<pre><code>data = {'patient.drug':
[[{'drugcharacterization': '1', 'medicinalproduct': 'PANDOL'}],
[{'drugcharacterization': '2', 'medicinalproduct': 'NIFEDIPINE'}],
[{'drugcharacterizati... | python|pandas|dataframe|data-science | 1 |
20,477 | 1,066,758 | find length of sequences of identical values in a numpy array (run length encoding) | <p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p>
<p>The events I'm interested in are when the distance i... | <p>Fully numpy vectorized and generic RLE for any array (works with strings, booleans etc too).</p>
<p>Outputs tuple of run lengths, start positions, and values.</p>
<pre><code>import numpy as np
def rle(inarray):
""" run length encoding. Partial credit to R rle function.
Multi data... | python|matlab|numpy|matplotlib | 72 |
20,478 | 59,374,819 | Is groupby from pandas commutative? | <p>I would like to know if the rows selected by:</p>
<pre><code>groupby(['a', 'b'])
</code></pre>
<p>are the same as the rows selected by:</p>
<pre><code>groupby(['b', 'a'])
</code></pre>
<p>In this case the order of the rows doesn't matter.</p>
<p>Is there any case in which <code>groupby</code> does not fulfill ... | <p>Per <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html" rel="noreferrer">definition</a> and the logic applied when using <code>groupby</code> in <code>pandas</code>, it will always be commutative:</p>
<blockquote>
<p>A groupby operation involves some combination of splitting the object,... | python|pandas|commutativity | 8 |
20,479 | 44,987,224 | How to drop first row using pandas? | <p>I've searched at other questions related to dropping rows but could not find one that worked:</p>
<p>I have a CSV file exported from the tool screaming frog that looks like this:</p>
<pre class="lang-none prettyprint-override"><code>Internal - HTML | | |
--------------- | --------------|-... | <p>You can add <code>header</code> as a parameter in the first call, to use column names and start of data :</p>
<pre><code>a = pandas.read_csv("internal_html.csv", encoding="utf-8", header=1)
</code></pre> | python|pandas | 8 |
20,480 | 44,984,765 | Avoiding exhausting GPU resources in convNN Tensorflow | <p>I'm trying to run a hyperparameter optimization script, for a convNN using Tensorflow.
As you may know, TF handling of the GPU-Memory isn't that fancy(don't think it will ever be, thanks to the TPU). So my question is how do I know to choose the filter dimensions and the batchsize, so that the GPU-memory don't get... | <p>Actually, this will take only about 44MB of memory, mostly taken by the output.</p>
<ul>
<li>Your input is <code>20x128x128x3</code></li>
<li>The convolution kernel is <code>4x4x3x32</code></li>
<li>The output is <code>20x128x128x32</code></li>
</ul>
<p>When you sum up the total, you get</p>
<pre><code>(20*128*12... | tensorflow|out-of-memory|gpu|conv-neural-network | 1 |
20,481 | 45,270,632 | DataFrame apply function based on multiple column and set value for multiple columns as well | <p>I have DataFrame as below:</p>
<pre><code>df = pd.DataFrame((np.random.randn(5,4)*10).astype(int), columns=list('abcd'))
def cal(a, b):
if a + b > 5:
return a+b, a-b
</code></pre>
<p>how could I apply this function to df, the two variables cal take would be df['a'] and ['b'], the output a+b, a-b wil... | <p>You can vectorize this using mask:</p>
<pre><code>vals = pd.concat((df['a'] + df['b'], df['a'] - df['b']), axis=1).values
df[['c', 'd']].mask(df['a'] + df['b'] > 5, vals)
Out:
c d
0 6 3
1 -12 3
2 12 -14
3 21 -31
4 15 -21
</code></pre>
<p>where the original df is</p>
<pre><code>df
Out:
a b... | python|pandas|dataframe | 4 |
20,482 | 45,124,766 | Cannot Import Python Packages on Linux | <p>I ran this in the terminal to install all the packages for a machine learning project.</p>
<p><code>sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose</code></p>
<p>It says the packages are already their newest version. When I run <code>... | <p>In order to get to know the version in python,</p>
<p><code>import numpy
print numpy.__version__</code></p>
<p>numpy.version gives the path.</p> | python|linux|python-2.7|numpy|python-import | 1 |
20,483 | 57,134,984 | Compute KL divergence between rows of a matrix and a vector | <p>I have a matrix (numpy 2d array) in which each row is a valid probability distribution. I have another vector (numpy 1d array), again a prob dist. I need to compute KL divergence between each row of the matrix and the vector. Is it possible to do this without using for loops?</p>
<p><a href="https://stackoverflow.c... | <p>The function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html" rel="nofollow noreferrer"><code>scipy.stats.entropy</code></a> can, in fact, do the vectorized calculation, but you have to reshape the arguments appropriately for it to work. When the inputs are two-dimensional arr... | python|numpy|scipy | 1 |
20,484 | 57,279,231 | Comparing datetime in pandas | <p>I want to return a "YES" in a new column if a datetime in another column is after a given datetime, in this case, July 1 of this year.</p>
<pre><code>source_df['Request Date']
0 2018-03-16 16:29:18
1 2019-05-07 17:40:16
2 2019-06-03 12:35:18
3 PENDING
</code></pre>
<pre class="lang-py prettypri... | <p>See <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html" rel="nofollow noreferrer">Time series / date functionality</a> for an overview of pandas date and time functionality.</p>
<pre><code>def check_request_date(x):
try:
return 'YES' if pd.to_datetime(x[:10]) > pd.to_dat... | python|pandas | 0 |
20,485 | 57,148,326 | Use multiple csv files as test and training set for CNN | <p>I am writing a code to detect minerals from their Raman Spectra data using CNN. I have data (RRUFF dataset) for different minerals written into different csv/text files each consisting of 2 columns: Intensity and corresponding Raman Shift value of the mineral. </p>
<p>How should I use these multiple files for train... | <pre><code>def merge_data(csv_files, columns, output_file):
df = pandas.DataFrame(columns=columns)
for file in csv_files:
df = df.append(pandas.read_csv(file), sort=False)
return df
</code></pre>
<p>Now, call the function <code>df = merge_data(['file1.csv', file2.csv], ['column1', 'column2'], 'al... | python|csv|tensorflow|keras|conv-neural-network | 0 |
20,486 | 57,286,729 | Pandas: while loop before a for loop until a certain condition is respected | <p>I have a dataframe, filled_orders, like that:</p>
<pre><code> price amount side fees timestamp
0 0 2 bids 0 2019-06-25 12:24:46.570000
1 3 2 asks 0 2019-06-25 12:22:46.570000
2 2 4 bids 0 2019-06-25 12:22:46.570000
3 5 1 asks ... | <p>Based on your sample data and desired output, couldn't you just: </p>
<pre class="lang-py prettyprint-override"><code>df.loc[df['side'].isin(['bids', 'asks'])].tail(1)
</code></pre>
<pre><code> price amount side fees timestamp
4 1 4 asks 0 2019-06-26 12:24:46.570000
</code></pre> | python|pandas | 1 |
20,487 | 46,085,091 | Transform a set of pandas columns in one operation, rather than multiple ones? | <p>So I have a set of columns in a dataframe that all need to be converted into strings (from floats), and then truncated to the first 11 characters. I can do this just fine with one column at a time, but how can I do it for five or six at once?</p>
<p>Here is what I have working:</p>
<pre><code>df_combined['FileX']... | <p>How about something like this: </p>
<pre><code>df.apply(lambda x: x.astype('str').apply(lambda y: y[:10]))
</code></pre>
<p>The first apply is on each column (converting the column to <code>str</code>), the second apply is on each entry of the column that truncates.</p> | python|pandas | 1 |
20,488 | 46,018,000 | Reasons of slowness in numpy.dot() function and how to mitigate them if custom classes are used? | <p>I am profiling a numpy dot product call. </p>
<pre><code>numpy.dot(pseudo,pseudo)
</code></pre>
<p><code>pseudo</code> is a numpy array of custom objects. Defined as:</p>
<pre><code>pseudo = numpy.array(
[[PseudoBinary(1), PseudoBinary(0), PseudoBinary(1)],
[PseudoBinary(1), PseudoBinary(0), Ps... | <p>Pretty much <em>anything</em> you do with object arrays is going to be slow. None of the reasons NumPy is usually fast apply to object arrays.</p>
<ul>
<li>Object arrays cannot store their elements contiguously. They must store and dereference pointers.
<ul>
<li>They don't know how much space they would have to al... | python|performance|numpy|matrix | 2 |
20,489 | 23,188,343 | Python savetxt write as int | <p>I am trying to write an array out to a text file and I want each element to be written as an <code>int</code> type.</p>
<p>I am using </p>
<pre><code>np.savetxt(outfile_name, array, comments = '')
</code></pre>
<p>to write out the file. I converted <code>array</code> from <code>float</code> to <code>int</code> us... | <p>Have you tried specifying a format, per <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="noreferrer">the documentation</a>? </p>
<pre><code>np.savetxt(outfile_name, array, fmt="%d", comments='')
# ^ format as signed decimal integer
</code></pre>
<p... | python|arrays|file-io|numpy | 9 |
20,490 | 35,415,148 | Using numpy.tile to repeat 2D arrays | <p>I have 3 arrays:</p>
<pre><code>e = np.array(range(3,100))
dRdE = np.load('arr_25.npy')
</code></pre>
<p>The npy file contains an array with random values but is of the same length as e. I then take the outer product of <code>dRdE</code> with another array.</p>
<pre><code>s = np.array(range(1,100))
dRdE = np.oute... | <p>I asked about variable length sublists because that is a clear indicator that some sort of iteration is required. There aren't many <code>numpy</code> operations that produce a list or tuple of differing length arrays.</p>
<p>Looking into <code>tile</code> a bit more (it's not something I use everyday), I don't th... | python|arrays|numpy|repeat|tile | 0 |
20,491 | 35,464,815 | Iterate over all possible numpy binary arrays with restrictions using python | <p>I'm trying to iterate over all possible binary arrays of size mxn but with some restrictions. As you know the set of arrays becomes extreme as m and n increase (2^(m*n) arrays). I have written some code that will iterate over all of these possibilities. </p>
<pre><code>mxn = np.arange(m*n).reshape(m,n)
for i in ... | <p>Since the matrix is of size <code>m*n</code>, the second restriction will be automatically met if the first one is satisfied.</p>
<p>Since each row has at most 1 element to be none zero, there are only <code>n+1</code> choices for a row. Given there is <code>m</code> rows, the possible number of combinations for su... | python|arrays|numpy | 1 |
20,492 | 28,754,265 | pandas read_hdf with 'where' condition limitation? | <p>I need to query an <code>HDF5</code> file with <code>where</code> clause with 3 conditions, one of the condition is a list with a length of 30:</p>
<pre><code>myList = list(xrange(30))
h5DF = pd.read_hdf(h5Filename, 'df', where='index=myList & date=dateString & time=timeString')
</code></pre>
<p>The que... | <p>This is answered <a href="https://stackoverflow.com/questions/15895837/hdfstore-table-select-and-ram-usage">here</a></p>
<p>This is a defect in that <code>numpy/numexpr</code> cannot handle more than 31 operands in the tree. An expression like <code>foo=[1,2,3,4]</code> in the where of the <code>HDFStore</code> gen... | python|pandas|hdf5|pytables | 5 |
20,493 | 50,990,350 | dataframe to rdd python / spark / pyspark | <p>i'm using a somewhat old pyspark script.
and i'm trying to convert a dataframe df to rdd.</p>
<pre><code>#Importing the required libraries
import pandas as pd
from pyspark.sql.types import *
from pyspark.ml.regression import RandomForestRegressor
from pyspark.mllib.util import MLUtils
from pyspark.ml import Pipelin... | <p><code>df = pd.read_json("events.json")</code>: your df is not a pyspark DataFrame, it is a Pandas DataFrame so it has no rdd attribute.</p>
<p>To create a pyspark DataFrame from a json, use <code>df = sqlContext.jsonFile('events.json')</code></p> | python|pandas|apache-spark|pyspark | 2 |
20,494 | 50,868,686 | Using Pandas; not sure whether to use map or add with these dataframes | <p>I have two data frames that were read from excel.</p>
<pre><code>df1
SRD CIVF Test Case
0 9530\n3678\n549 CIV-016
1 9979\n9980 CIV-040
2 5231\n4455 CIV-177
df2
SRD SRD CR
0 549\n9980 CR181
1 4455 CR170
2 5231\n9979 CR190
</code></pre>
<p>For... | <p>Unless there is a good reason to keep <code>SRD</code> values buried in strings in single rows, I would convert <code>df1</code> and <code>df2</code> so that each row has a single <code>SRD</code> value. Then you can merge on <code>SRD</code>:</p>
<pre><code># Split all strings between '\n' into their own columns
s... | excel|pandas | 0 |
20,495 | 51,098,303 | How to make a legend for all bars in matplotlib barplot | <p>I want to make a legend for all bars in my barplot. I have already extracted the labels for all bars, but somehow legend()z only creates a line for the first one and not the second one. </p>
<p>How should I proceed? I was thinking that I maybe have to extract the colors of the bars manually as well, but I don't kno... | <p>Set the color by hand and use mpaches</p>
<pre><code>import matplotlib.patches as mpatches
df.Completeness.value_counts().plot(kind='bar')
complete = mpatches.Patch(color='red', label='Complete')
partial = mpatches.Patch(color='blue', label='Partial')
plt.legend(handles=[complete, partial])
</code></pre> | python|python-3.x|pandas|matplotlib | 0 |
20,496 | 50,834,192 | Assign increasing number based on common number in a column | <p>There is a column in my dataset that looks like that:</p>
<pre><code>col1
100
100
100
101
101
102
102
103
103
103
103
104
104
</code></pre>
<p>I want to create a column that gives an increasing number per group. Specifically, where is <code>100</code> in the <code>col1</code> there will be <code>01</code>. The nex... | <p>I think you're looking for this.</p>
<pre><code>df['nc'] = df.groupby('col1').cumcount()+1
</code></pre>
<p>Which gives:</p>
<pre><code> col1 nc
0 100 1
1 100 2
2 100 3
3 101 1
4 101 2
5 102 1
6 102 2
7 103 1
8 103 2
9 103 3
10 103 4
11 104 1
12 104 2
</code></p... | python|pandas|group-by | 4 |
20,497 | 50,688,468 | Python SQLAlchemy pyodbc.Error: ('HY000', 'The driver did not supply an error!') | <p>Hi Everyone I Am working right now with Pandas and MSSQL. I have bene working ok but recently after an SQlalchemy update i am getting the following error when I am trying to upload information into the DB via df.to_sql</p>
<p>pyodbc.Error: ('HY000', 'The driver did not supply an error!')</p>
<p>My connection is... | <p>OK this was a "silent error for a known bug in pandas 23, downgrading to v22 makes the error go away and you can upload 1000+ rows.</p>
<p>this is being worked out on </p>
<p><a href="https://github.com/pandas-dev/pandas/issues/21103" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/21103</a>... | python|sql-server|pandas|sqlalchemy|pyodbc | 2 |
20,498 | 33,114,637 | Apply unique twice in groupby dataframe | <p>I have a dataframe <code>df</code> that looks like this:</p>
<pre><code>key_1, key_2, country
12, a, US
12, a, US
12, b, US
12, c, NZ
23, d, PE
23, e, PE
23, e, PE
31, f, RO
31, f, RO
42, g, VI
</code></pre>
<p>I'm interested in 2 dataframes (please provide one procedure for each dataframe) that fulfill the follow... | <p>After a few hours digging around I finally managed to do it myself. Anyone with a better solution is welcome to answer!</p>
<p>I've tried the following code on my real dataframe and it works. </p>
<p>As @Alexander pointed out correctly, "both of your desired dataframes are built on the same set of data: rows with ... | python-2.7|pandas | 1 |
20,499 | 33,439,617 | pandas: type conversion returning incorrect value | <p>I have a DataFrame which looks like this:</p>
<pre><code>Values Total
Values
cbase 2019
</code></pre>
<p>Here's a better look at the value:</p>
<pre><code>>>> df.values
[[ 2019.]]
>>> df.dtypes
Values
Total float64
dtype: object
</code></pre>
<p>Now I would like to ensure that t... | <p>I think this is a rounding-for-representation thing; your value in the Pandas object is actually very slightly under 2019. For example:</p>
<pre><code>>>> v = np.nextafter(2019, 0)
>>> v
2018.9999999999998
</code></pre>
<p>If you put this value <code>v</code> in a DataFrame; it rounds to 2019 for... | python|pandas|dataframe|casting|floating-point | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.