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 |
|---|---|---|---|---|---|---|
10,500 | 24,812,760 | How do I find what index a True value is located at in an array contaning True and False values? | <p>I have an np.array with True and False values in it. Something along the lines of this:</p>
<pre><code>full=[False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, True, False, False,
False,... | <p>you can use <code>argmax(arr)</code> for the index of the first <code>True</code> value.</p>
<p>As pointed out by @Alok, if the result is zero you must then check if the first element of <code>arr</code> is <code>False</code>.</p> | python|python-2.7|numpy | 1 |
10,501 | 30,191,807 | Formatting datetime variables give missing time values as 00:00:00. Using Python | <p>I am currently using python trying to split a datetime column into 2, one for Date and one for time and also have the column properly formatted.</p>
<p><strong>ORIGINAL DATASET</strong></p>
<pre><code>INCIDENT_DATE
12/31/2006 11:20:00 PM
12/31/2006 11:30:00 PM
01/01/2007 00:25
01/01/2007 00:10
12/31/2006 11:30:00 ... | <p>Add <code>ambiguous =‘NaT’</code> to <code>pd.DatetimeIndex</code>. If that doesn't work, you could always patch the values using something like</p>
<pre><code>crimeall['TIME'] = [np.NaN if t.isoformat()=='00:00:00' else t for t in crimeall['TIME']]
</code></pre> | python|datetime|pandas | 1 |
10,502 | 53,531,820 | Keras: notImplementedError/RuntimeError when using fit_generator | <p>I am having troubles with keras and tensorflow, using the following code:</p>
<pre><code>from tensorflow.keras.layers import Activation, Conv2D
from tensorflow.keras import Model
from data import DataGenerator
from config import train_datapath, test_datapath
training_generator = DataGenerator(train_datapath)
val... | <p>You're not creating a model anywhere. </p>
<p>You need: </p>
<pre><code>model = Model(inputTensors, outputTensors)
</code></pre>
<p>Or at least at some point in your class <code>super(model,self).__init__(inputTensors,outputTensors)</code>.</p>
<p>Ideally:</p>
<pre><code>def createModel():
inputs = Input(... | python|tensorflow|keras | 1 |
10,503 | 53,730,670 | Dynamically create variables in python | <p>I have a list of images that I am repeatedly calling the same functions for:</p>
<pre><code>first_image = load_image("test1.jpg")
first_image_encoding = pic_encoding(first_image)[0]
second_image = load_image("test2.jpg")
second_image_encoding = pic_encoding(second_image)[0]
</code></pre>
<p>After which I need to ... | <p>Creating variables dynamically adds excessive overhead of handling them, instead you could directly append to list like so:</p>
<pre><code>encoding_arr = []
for root, dirs, files in os.walk(img_dir):
for f in files:
encoding_arr.append(pic_encoding(load_image(f))[0])
</code></pre> | python|arrays|python-3.x|numpy | 1 |
10,504 | 53,452,755 | pandasql: count occurrences of pairs | <p>I was trying to count the number of matches that A and B have ever played,
the dataset looks like this:</p>
<p><img src="https://i.stack.imgur.com/OkWgk.png" alt="This is how the data looks like in Notebook"></p>
<p>so the number of matches team1 and team 29 have played is 2 as they each once were HomeTeam and Awa... | <p>Put the teams in a common order so the grouping isn't sensitive to whether they're home or away.</p>
<pre><code>SELECT GREATEST(HomeTeamID, AwayTeamID) AS team1, LEAST(HomeTeamID, AwayTeamID) AS team2, COUNT(*) as num_matches
FROM games
GROUP BY team1, team2
</code></pre> | sql|sqldf|pandasql | 0 |
10,505 | 15,906,153 | Pandas Trial Repetioin indexing | <p>I have a data set where pictures were presented 3 times and measurements were taken for each presentation. Prospectively I would like to normalize the values for each picture (based on the 3 repetitions - so 3 numbers) and run an ANOVA on the categories: first presentation, second presentation, third presentation (f... | <p>If you have a DataFrame <code>df</code>, you can set your <code>image name</code> and <code>measurement id</code> fields as an index then sort. That will order the data how you want.</p>
<pre><code>df2 = df.set_index("pic_name", "meas_id").sort()
</code></pre>
<p><code>groupby</code> and <code>pivot</code> are go... | indexing|dataframe|pandas | 2 |
10,506 | 15,974,631 | Maximum Recursion Occurs, what went wrong in Keller Box? | <p>This is the non syntax error code, but i cant seem to fix the recursion error. need some help here. the algorithm based on matlab, i've read the tutorial on matlab but i can seem to figure out which part did i miss.</p>
<pre><code>import numpy as npy
blt = int(raw_input("Input the boundary layer thickness = "))
d... | <p>The infinite recursion will occur in these two functions:</p>
<pre><code>def alfa(j,k):
return AJ(j,k) - (BJ(j,k)*gamma(j,k))
def gamma(j,k):
return npy.matrix.I((alfa(g,k))*CJ(g,k))
</code></pre>
<p>Each of which calls the other one under any circumstances. So, <code>alfa</code> calls <code>gamma</code> ... | python|numpy | 1 |
10,507 | 12,530,381 | Numpy indexing using array | <p>I'm trying to return a (square) section from an array, where the indices wrap around the edges. I need to juggle some indexing, but it works, however, I expect the last two lines of codes to have the same result, why don't they? How does numpy interpret the last line? </p>
<p>And as a bonus question: Am I being woe... | <p>The problem is that <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">advanced indexing</a> is triggered if:</p>
<blockquote>
<p>the selection object, <em>obj</em>, is [...] a tuple with at least one sequence object or ndarray</p>
</blockquote>
<p>The easie... | multidimensional-array|numpy | 4 |
10,508 | 72,001,898 | Is it possible to reverse an image if we did a dot product between noise and the image? | <p>I did dot product of the image with a noise.</p>
<p>import numpy as np<br>
np.random.seed(100)<br>
x = grayscale.shape[0]<br>
y = grayscale.shape[1]<br>
noise = np.random.rand(x,y)<br>
noise_dot_img = grayscale.dot(noise)<br>
plt.imshow(noise_dot_img, cmap = "gray")<br></p>
<p><a href="https://i.stack.imgur.com/0uFL... | <p>I think you should share some more information about what exactly you are trying to achieve here.</p>
<p>In any case, you actually can get your image back in this specific example, by inverting the noise matrix and multiplying with it the noisy image:</p>
<pre><code>inv = np.linalg.inv(noise)
restored_img = noise_do... | python|numpy | 0 |
10,509 | 71,992,442 | Modify function to use percentage risk instead of fixed amount | <p>How do I modify this function to use a percentage risk instead of current fixed <code>risk_per_trade</code> of 50?</p>
<p>I would like to start with 1000 and use 5 percent.</p>
<p><strong>Function to modify:</strong></p>
<pre><code>def tradingStats(win_loss_series,risk_per_trade):
df = pd.DataFrame(win_loss_seri... | <p>Just change the column to a multiplier rather than an additive amount, and use <code>cumprod()</code>.</p>
<p>e.g.</p>
<pre class="lang-py prettyprint-override"><code>def tradingStats(win_loss_series, risk_percent_per_trade=5, starting_amount=1000):
df = pd.DataFrame(win_loss_series, columns=["win"])
... | pandas | 1 |
10,510 | 17,755,764 | Python beginner -- change shape of a matrix | <p>I have the following img object</p>
<pre><code>img.shape = (480,640,3)
</code></pre>
<p>How do I make <code>img</code> just <code>(480,640)</code> (i.e. lose the <code>,3</code>)?</p> | <p>If you want the first third, you want</p>
<pre><code>newimg = img[..., 0]
</code></pre>
<p>If you'll never need the other two thirds again, but you'll be keeping the first third around for a while, you may want</p>
<pre><code>img = img[..., 0].copy()
</code></pre>
<p>so you don't keep the other parts of the arra... | python|numpy | 2 |
10,511 | 56,626,552 | Compare two dataframe columns for matching percentage | <p>I want to compare a data frame of one column with another data frame of multiple columns and return the header of the column having maximum match percentage.</p>
<p>I am not able to find any match functions in pandas. First data frame first column :</p>
<pre><code>cars
----
swift
maruti
wagonor
hyundai ... | <p>Try to use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer">isin</a> function of pandas DataFrame. Assuming df is your first dataframe and words is a list :</p>
<pre><code>In[1]: (df.isin(words).sum()/df.shape[0])*100
Out[1]:
cars 100.0
bi... | python|string|pandas|dataframe|compare | 3 |
10,512 | 56,572,732 | Tensorflow object detection API AvgNumGroundtruthBoxesPerImage is always zero (no ground truth labels shown) | <p>As per the title - I can run a training job using the object detection API, but when I look at the loss curve, it's far too smooth. At the eval stage after 1 epoch, the ground truth images are shown in Tensorboard, but no boxes are drawn on them. I have no negative examples in my dataset, so all the images should ha... | <p>Turns out my class labels in each TFRecord had a newline at the end. This took more effort to discover than I'm willing to admit!</p>
<p>I had a .names file I was reading in, e.g.</p>
<pre><code>cat
dog
horse
</code></pre>
<p>except it's not that, it's:</p>
<pre><code>cat\n
dog\n
horse\n
</code></pre>
<p>and wh... | python|tensorflow | 0 |
10,513 | 56,687,437 | Save TensorFlow state (weights) while running | <p>I've got a python program that is running fitting over a model.
I didn't implements a saver so i'm wondering if there's a method to recover the weights directly from memory (maybe from a temp file?) while the fitting is running</p> | <p>I think that should be possible using the command, <code>tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)</code>.</p>
<p>Code for extracting/recovering weights of a model without Saving the Model is shown below. </p>
<pre><code>import tensorflow as tf
import numpy as np
X_ = tf.placeholder(tf.float64, [None, 5... | python|tensorflow | 0 |
10,514 | 26,058,792 | Correct fitting with scipy curve_fit including errors in x? | <p>I'm trying to fit a histogram with some data in it using <code>scipy.optimize.curve_fit</code>. If I want to add an error in <code>y</code>, I can simply do so by applying a <code>weight</code> to the fit. But how to apply the error in <code>x</code> (i. e. the error due to binning in case of histograms)?</p>
<p>My... | <p><code>scipy.optmize.curve_fit</code> uses standard non-linear least squares optimization and therefore only minimizes the deviation in the response variables. If you want to have an error in the independent variable to be considered you can try <code>scipy.odr</code> which uses orthogonal distance regression. As its... | python|numpy|scipy|curve-fitting | 27 |
10,515 | 67,157,289 | Access aws elastic search role based using python elastic search package | <p>I am using <a href="https://github.com/deepset-ai/haystack" rel="nofollow noreferrer">deepset/haystack</a> and communicating with elastic search. Using OpenDistroElasticsearchDocumentStore method works fine with username,pasword access to aws elastic search. Doesnt seem to work with role based access when deployed i... | <p>Do you mean IAM based access on AWS like <a href="https://elasticsearch-py.readthedocs.io/en/v7.12.0/index.html?highlight=aws#running-on-aws-with-iam" rel="nofollow noreferrer">this</a>? We just recently merged a feature that might help you here (<a href="https://github.com/deepset-ai/haystack/pull/965" rel="nofollo... | python|elasticsearch|huggingface-transformers|aws-elasticsearch|haystack | 1 |
10,516 | 66,832,669 | Memory leak with en_core_web_trf model, Spacy | <p>there is a Memory leak when using pipe of en_core_web_trf model, I run the model using GPU with 16GB RAM, here is a sample of the code.</p>
<pre><code>!python -m spacy download en_core_web_trf
import en_core_web_trf
nlp = en_core_web_trf.load()
#it's just an array of 100K sentences.
data = dataload()
for index, r... | <p>Lucky you with GPU - I am still trying to get thru the (torch GPU) DLL Hell on Windows :-). But it looks like Spacy 3 uses more GPU memory than Spacy 2 did - my 6GB GPU may have become useless.</p>
<p>That said, have you tried running your case without the GPU (and watching memory usage)?</p>
<p>Spacy 2 'leak' on la... | memory-leaks|nlp|pytorch|gpu|spacy-3 | 1 |
10,517 | 66,802,110 | Optimizing/Parallel Computing a simple but big loop based on Pandas | <p>I have this simple loop which processes a big dataset.</p>
<pre><code>for i in range (len(nbi.LONG_017)):
StoredOCC = []
for j in range (len(Final.X)):
r = haversine(nbi.LONG_017[i], nbi.LAT_016[i], Final.X[j], Final.Y[j])
if (r < 0.03048):
SWw = Final.CUM_OCC[j]
St... | <p>Before talking about parallelization, you can work on optimizing your loop. The first way would be to iterate over the data instead of incremental values over the length and then access the data each time:</p>
<pre><code>#toy sample
np.random.seed(1)
size_nbi = 20
size_Final = 100
nbi = pd.DataFrame({'LONG_017':np.... | python|pandas|parallel-processing | 2 |
10,518 | 47,137,187 | How to group by and count values in my DataFrame? | <p>I have this DataFrame:</p>
<pre><code>df = pd.DataFrame(columns=["App","Feature1", "Feature2","Feature3",
"Feature4","Feature5",
"Feature6","Feature7","Feature8"],
data=[["SHA",0,0,1,1,1,0,1,0],
["LHA",1,0,1,1,0,1,1,0],... | <p>Use:</p>
<pre><code>#remove column App, compare and get sum of Trues
a0 = df.drop('App', 1).eq(0).sum()
#a0 = df.set_index('App').eq(0).sum()
#alternative with select only Feature columns
#a0 = df.filter(like='Feature').eq(0).sum()
#alternative with select all columns without first
a0 = df.iloc[:, 1:].eq(0).sum()... | python|pandas | 1 |
10,519 | 47,520,885 | Reading csv into dataframe and changing date reformat to dd/mm/yyyy | <p>I am reading a .csv into a data-frame index by date using the following code:</p>
<pre><code>def getCSVData(rawStaticDataPath):
pattern = 'Overview-trade-pos'+'.csv'
staticPath = rawStaticDataPath
with open(staticPath+pattern,'rt') as f:
csv=pd.read_csv(f,engine='c',header=0,index_col='date'... | <p>We using <code>strftime</code></p>
<pre><code>df.index=df.index.strftime('%m/%d/%Y')
df
Out[300]:
val
01/04/2016 BBG.XTKS.9716.S
01/04/2016 BBG.XTKS.9065.S
01/04/2016 BBG.XTKS.7966.S
01/04/2016 BBG.XTKS.3774.S
01/04/2016 BBG.XTKS.5110.S
</code></pre> | python|pandas | 2 |
10,520 | 68,394,836 | Pandas, recording a continuous average | <p>I'm writing a program takes in data that is linked with time, I want to be able to average the values of the data if there are more than one points of data per minute. The data points also have different devices that they record data for and cannot be mixed. I'm using a pandas dataframe and the points of data coming... | <p>You might want to clean your data first and possibly create a new column if the data ready to be analyzed, and then include some logics to compare where data should calculate average or not in your algorithm, could you share a sample of you data and any algorithm you may have.</p> | python|python-3.x|pandas|dataframe|average | 0 |
10,521 | 68,151,158 | Pandas not listing every single unique value in a column | <p>I am trying to list every single unique value in a single column, so I can copy and paste them. But, when I do it, it only seems to list the first 1000 unique values in my column.</p>
<p>When I count the number of unique values in my column, I get 2038:</p>
<pre><code>df['Emojis'].nunique()
2038
</code></pre>
<p>Th... | <p>You can create a second data frame where you have removed all duplicate function.
For example:</p>
<pre><code>df_unique = df.drop_duplicates()
for i in df_unique.index:
print(df_unique['Emojis'][i])
</code></pre>
<p>Here is the documentation:
<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame... | python|pandas|dataframe|emoji | 0 |
10,522 | 49,926 | Open source alternative to MATLAB's fmincon function? | <p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html" rel="noreferrer"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <... | <p>Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently)</p>
<ul>
<li>L... | python|matlab|numpy|numerical|scientific-computing | 33 |
10,523 | 59,358,124 | Changing color for overlapping scatters in seaborn | <p>I want to visualize a prediction method with the help of seaborns <code>lmplot</code>, I have the following example:</p>
<pre><code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
d = {'col1': [1, 2, 1, 1], 'col2': [3, 4, 3, 4], 'col3': [1, 1, 0, 0]}
df = pd.DataFrame(data=d)
sns.lmplot('... | <p>Change marker styles:</p>
<pre><code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
d = {'col1': [1, 2, 1, 1], 'col2': [3, 4, 3, 4], 'col3': [1, 1, 0, 0]}
df = pd.DataFrame(data=d)
sns.lmplot('col1', 'col2', data =df, hue='col3', fit_reg=False, scatter_kws={"s": 200, "alpha":.7}, marker... | python|pandas|seaborn | 2 |
10,524 | 59,272,939 | RLLib - Tensorflow - InvalidArgumentError: Received a label value of N which is outside the valid range of [0, N) | <p>I'm using RLLib's PPOTrainer with a custom environment, I execute <code>trainer.train()</code> two times, the first one completes successfully, but when I execute it for the second time it crashed with an error: </p>
<blockquote>
<p>lib/python3.7/site-packages/tensorflow_core/python/client/session.py",
line 138... | <p><a href="https://github.com/ray-project/ray/issues/6136#issuecomment-552766521" rel="nofollow noreferrer">This</a> comment really helped me:</p>
<blockquote>
<p>FWIW, I think such issues can happen if NaNs appear in the policy
output. When that happens, you can get out of range errors.</p>
<p>Usually it's ... | python|tensorflow|ray|rllib | 3 |
10,525 | 59,048,278 | how to convert JSON data into dataframe? | <p>I got a JSON data like this:</p>
<pre><code>jsonData = {
"0":{
"columnA":"a",
"columnB":"b"
},
"1":{
"columnA":"c",
"columnB":"d"
}
}
</code></pre>
<p>how do I convert it into a data frame like this:</p>
<pre><code> rowData
0 {"columnA":"a","columnB":"b"}
1 {"columnA":"c","colum... | <p>For me working your solution nice:</p>
<pre><code>jsonData = {
"0":{
"columnA":"a",
"columnB":"b"
},
"1":{
"columnA":"c",
"columnB":"d"
}
}
df = pd.DataFrame({'rowData': jsonData})
print (df)
rowData
0 {'columnA': 'a', 'columnB': 'b'}
1 {'columnA': 'c', 'column... | python|json|pandas|dataframe | 1 |
10,526 | 59,171,948 | Tensorflow 2.0 not installing on pipenv with Heroku | <p>I have the pipenv lock working for django with tf, but it won't proceed to install on the heroku server.</p>
<pre><code>An error occurred while installing tensorflow==2.0.0! Will try again.
</code></pre>
<p>I'm wishing the server could have 2.0 tensorflow installed, but it fails and there's no prior help.</p>
<pr... | <p>Tensorflow only supports from python 3.4 up to python 3.7 (as March 2020). You can find more info in the [system requirements page][1] of the documentation.</p>
<p>Make sure that in your Pipfile you have the following:</p>
<pre><code>[requires]
python_version = "3.7"
</code></pre>
<p>If that is not the case, remo... | python|tensorflow | 0 |
10,527 | 56,999,493 | Tensorflow: GPU Acceleration only happens after first run | <p>I've installed CUDA and CUDNN on my machine (Ubuntu 16.04) alongside <code>tensorflow-gpu</code>.</p>
<p><strong>Versions used:</strong> CUDA 10.0, CUDNN 7.6, Python 3.6, Tensorflow 1.14</p>
<hr>
<p>This is the output from <code>nvidia-smi</code>, showing the video card configuration.</p>
<pre><code>| NVIDIA-SMI... | <p><a href="https://stackoverflow.com/questions/56999493/tensorflow-gpu-acceleration-only-happens-after-first-run/57023579#comment100532663_56999493">robert-crovella's comment</a> made me look into the XLA thing, which helped me find the solution.</p>
<p>Turns out the GPU is mapped to a Tensorflow device in two ways: ... | python|tensorflow|gpu|nvidia | 2 |
10,528 | 57,081,937 | Pandas dataframe outputting as text rather than standard format | <p>I am using pandas to work with an excel file and create a dataframe from that. It's able to read the file, but when i print the resulting dataframe it's showing up in a text format which is a lot different from the normal one we are used to.</p>
<p>This is how i'm reading the excel file and printing it:</p>
<pre><... | <p>The 'pretty'format is only outputted when 'print' isn't called. Try:</p>
<pre><code>locations = pd.read_excel('file.xlsx')
locations
</code></pre> | python|pandas|dataframe|output | 1 |
10,529 | 57,183,977 | Broken structured to unstructured numpy array conversion in 1.16.0 | <p>I want to convert NumPy structured array with columns of the same (np.float) type to unstructured array in Numpy 1.16.0.</p>
<p>Previously I did it like this: </p>
<pre><code>array = np.ones((100,), dtype=[('user', np.object), ('item', np.float), ('value', np.float)])
array[['item','value']].view((np.float, 2))
</... | <p>With 1.16 there was a major change in the handling of multifield views. You need to use <code>rf.repack_fields</code> to get earlier behavior.</p>
<pre><code>In [277]: import numpy.lib.recfunctions as rf
In [287]: arr = np.ones(3, dtype='O,f,f') ... | python|numpy|structured-array | 1 |
10,530 | 56,989,136 | Pandas sequence string match on rows and get the best match rows ids | <p>Suppose that we have the following pandas dataframe</p>
<pre><code>import pandas as pd
data_dic = {
"values": ['jk4', '293','814' ,'er b3', '1', " sas", '<', '37', '/',3, '5651 + sdfv 84083', '+', '814 gfj67 340f', "sas " ,'293', '<', 'df gfdh', ' .', ':9271', '1', '3-', '=', '5', '293', "sas "],
"row... | <p>well, here goes my try.</p>
<p>I calc the strongest match just by counting matching chars,
I go on all possible concatenations, and pick the best one based on that score.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from itertools import product
data_dic = {
"values": ['jk4', '293',... | python|python-3.x|pandas | 1 |
10,531 | 28,590,626 | Python/Pandas: How to quickly pivot datetimeindex on date and time? | <p>I have a huge pandas timeseries which looks like:</p>
<pre><code>2011-02-18 08:05:00-05:00 94.00
2011-02-18 08:10:00-05:00 94.75
2011-02-18 08:15:00-05:00 94.00
2011-02-18 08:20:00-05:00 94.25
2011-02-18 08:25:00-05:00 93.25
2011-02-18 08:30:00-05:00 93.25
2011-02-18 08:35:00-05:00 94.00
2011-0... | <p>You could try pandas pivot(). </p>
<p>s = your series name</p>
<pre><code>pd.pivot(index=s.index.date,columns=s.index.time,values=s)
</code></pre> | python-2.7|datetime|numpy|pandas|cython | 1 |
10,532 | 51,104,939 | Python matrix swapping columns using numpy | <p>This is my Y matrix I am trying to swap the columns (to make the columns [1,2,3,4,5] be in the place of [5,4,3,2,1])
But, this changes the numbers' accuracy</p>
<p>This is Y</p>
<pre><code>> array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
> [ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
... | <p>Don't loop here, simply use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html" rel="nofollow noreferrer"><strong><code>np.flip</code></strong></a></p>
<pre><code>x = np.array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
[ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
... | python|numpy|matrix|swap|floating-accuracy | 0 |
10,533 | 20,709,855 | Iterate over matrices in numpy | <p>How can you iterate over all 2^(n^2) binary n by n matrices (or 2d arrays) in numpy? I would something like:</p>
<pre><code>for M in ....:
</code></pre>
<p>Do you have to use <code>itertools.product([0,1], repeat = n**2)</code> and then convert to a 2d numpy array?</p>
<p>This code will give me a random 2d binary... | <p>Note that <code>2**(n**2)</code> is a big number for even relatively small n, so your loop might run indefinetely long.</p>
<p>Being said that, one possible way to iterate matrices you need is for example</p>
<pre><code>nxn = np.arange(n**2).reshape(n, -1)
for i in xrange(0, 2**(n**2)):
arr = (i >> nxn) ... | python|numpy | 4 |
10,534 | 33,367,878 | Is there a numpy.there? | <p>I was wondering whether there is a opposite of <code>numpy.where</code> (going from booleans to indices) which goes from indices to booleans; for example <code>numpy.there</code>.</p>
<p>A possible implementation could use scipy's sparse matrices:</p>
<pre class="lang-py prettyprint-override"><code>from scipy.sp... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow"><code>np.arange</code></a> to simulate such a behaviour, like so -</p>
<pre><code>def ... | python-3.x|numpy|scipy | 3 |
10,535 | 6,253,729 | kmeans with L1 distance in python | <p>Given an NxM feature vectors as numpy matrix. Is there any routine that can cluster it by Kmeans algorithm using L1 distance (Manhattan distance)?</p> | <p>Here is one Kmeans algorithm using L1 distance (Manhattan distance). For generality,the feature vector is represented as a list, which is easy to convert to a numpy matrix. </p>
<pre><code> import random
#Manhattan Distance
def L1(v1,v2):
if(len(v1)!=len(v2):
print “error”
return -1... | python|numpy|k-means | 5 |
10,536 | 66,549,867 | compare two dataframe by specific column and return the rows not exist in another | <p>I am trying to comparing datafram df1 with df2 by column cust_id, and get all rows that not in df1</p>
<pre><code>df1
name cust_id
1 cxa c1001
2 cxb c1002
3 cxc c1003
4 cxd c1004
df2
name cust_id qty
1 cxa c1001 10
2 cxb c1002 20
3 cxc c1003 10
4 cxd c1004 15
5 cxe ... | <p>If you only want to see rows from df2 with cust_id which does not appear in df1 (and value in 'name' column does not matter), you can do:</p>
<pre><code>df2[~df2['cust_id'].isin(df1['cust_id'])]
</code></pre>
<p>Output:</p>
<pre><code> name cust_id qty
5 cxe c1005 20
6 cxf c1006 20
</code></pre> | python|pandas|dataframe | 3 |
10,537 | 66,573,974 | Verify Median Value with Area Under the Curve Calculation | <p>I want to calculate the area under this curve for confirmation that the size is correct. How would one go about doing this?</p>
<p>I have a frequency plot below. The package utilized for this median calculation is here: <a href="https://github.com/nudomarinero/wquantiles" rel="nofollow noreferrer">https://github.com... | <p>You're looking for a cumulative sum of the normalised area and the first point where this sum is >= 0.5.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import cumtrapz
# generate some heavy-tail data
np.random.seed(0)
y, x = np.histogram(np.random.gumbel(size=100000), ... | python|numpy|median|area | 0 |
10,538 | 66,717,576 | convert deeply nested JSON response to pandas dataframe | <p>I'm kinda pretty new to data science. I'm working on a project where I'm collecting data from an API call that returns the following JSON response :</p>
<pre><code>{
"jsonrpc": "2.0",
"result": {
"class": "dataset",
"dimension": {
"ST... | <p>After normalizing json like you do, you could perhaps use "explode" (transforms each element of a list-like to a row) on each column:</p>
<p><code>df.explode('size').reset_index(drop=True)</code></p> | python|json|pandas|dataframe|json-rpc | 0 |
10,539 | 66,425,158 | Interpolate date in pandas | <p>I have a data frame with a date column. There are almost 7k rows and 10 of them are NaN. So I wanted to interpolate the date. I checked out the documentation and they used <code>.interpolate()</code>. However, when I tried that, I was not getting the desired result.</p>
<p>One sample row:</p>
<pre><code>0 Novemb... | <p>You don't get to do usual arithmetic operators on <code>datetime</code> type, e.g. multiplication/division. So you don't get to interpolate the dates linearly. One option is to convert the dates into float by subtracting a time stamp, then dividing by a period:</p>
<pre><code>first_date=pd.to_datetime('1900-01-01')
... | python|pandas|dataframe|interpolation|nan | 2 |
10,540 | 66,602,357 | Filter data by column using user input value in python | <p>I wanted to filter the data from a CSV file based on a value from the column SN. The column value is given by the user itself. I am using the below code but the same returns no values. Can someone please correct this? . The issue is in the line is_data = (data['SN'] == SN) The code works fine when I replace the SN w... | <p><code>input()</code> returns a string and you are comparing it to integers. You should cast <code>SN</code> to integer:</p>
<pre><code>data = pd.read_csv("sample.csv") is_data = (data['SN'] == int(SN))
</code></pre> | python|pandas|filter | 0 |
10,541 | 66,498,515 | Algorithms of Joining arrays in numpy | <p>I'm new in numpy, I understand the methods of "Joining arrays" in lower shape such as (n1, n2) beacause we can visualize, like a matrix.</p>
<p>But I don't undestand the logic in higher dimensions (n0, ...., n_{d-1}) of course I can't visualize that. To visualize I usually imagine a multidimensional array ... | <p>Let's see I can illustrate some basic array operations.</p>
<p>First make a 2d array. Start with a 1d, [0,1,...5], and reshape it to (2,3):</p>
<pre><code>In [1]: x = np.arange(6).reshape(2,3)
In [2]: x
Out[2]:
array([[0, 1, 2],
[3, 4, 5]])
</code></pre>
<p>I can join 2 copies of <code>x</code> along the 1s... | numpy|numpy-ndarray | 1 |
10,542 | 66,344,728 | What's under the hood of numpy's 'mean' function such that it works faster than built in python methods? | <p>I've been exploring the performance differences between numpy functions and the normal built-in functions of Python, and I want to know how numpy functions are so optimized such that there's almost a 100x speed up.
Below is some code that I wrote to highlight the execution time differences between <b> numpy mean() <... | <p>Make a numpy array:</p>
<pre><code>In [130]: a=np.arange(10000)
</code></pre>
<p>Apply the <code>numpy</code> sum function:</p>
<pre><code>In [131]: timeit np.sum(a)
16.2 µs ± 22.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p><code>mean</code> is a bit slower, since it has to divide b... | python|numpy | 0 |
10,543 | 16,233,851 | Python Numpy Array indexing | <p>I am having a small difficulty with Numpy indexing. The script gives only the index of the last array three times when it supposed to give index of three different arrays (F_fit in the script). I am sure it is a simple thing, but I haven't figured it out yet. The 3_phases.txt file contains these 3 lines</p>
<pre><c... | <p>You are redefining <code>F_cont</code> each time you go through your <em>first</em> loop. By the time you get to your second loop (with all the <code>_2</code> values) you only have access to the <code>F_cont</code> from the last <code>row</code>.</p>
<p>To fix this, move your <code>_2</code> definitions above you... | python|numpy | 2 |
10,544 | 57,497,687 | Pandas dataframe groupby multiple years rolling stat | <p>I have a pandas dataframe for which I'm trying to compute an expanding windowed aggregation after grouping by columns. The data structure is something like this:</p>
<pre><code>df = pd.DataFrame([['A',1,2015,4],['A',1,2016,5],['A',1,2017,6],['B',1,2015,10],['B',1,2016,11],['B',1,2017,12],
['A',1,2015... | <p>There's been no activity on this question, so I'll post the solution I found.</p>
<pre><code>mn = df.groupby(by=['Typ','ID']).dat.expanding().median().reset_index().set_index('level_2')
mylast = lambda x: x.iloc[-1]
mn = mn.join(df['Year'])
mn = mn.groupby(by=['Typ','ID','Year']).agg(mylast).reset_index()
</code></... | python|pandas|windowing | 0 |
10,545 | 57,555,301 | Read multiple jsons from one file | <p>I am working with <code>python</code> and I have a file (<code>data.json</code>) which contains multiple jsons but the whole of it is not a json.</p>
<p>So the file looks like that:</p>
<pre><code>{ "_id" : 01, ..., "path" : "2017-12-12" }
{ "_id" : 02, ..., "path" : "2017-1-12" }
{ "_id" : 03, ..., "path" : "2017... | <p>Idea is use <code>read_csv</code> with no exist separator in data and then convert each value of column to <code>dictionary</code>:</p>
<pre><code>import pandas as pd
import ast, json
from io import StringIO
temp=u"""{ "_id" : 1, "path" : "2017-12-12" }
{ "_id" : 2, "path" : "2017-1-12" }
{ "_id" : 3, "path" : ... | python|json|pandas | 1 |
10,546 | 57,482,643 | Select distinct names from all letters in alphabet | <p><strong>Background</strong></p>
<p>I have the following sample df:</p>
<pre><code>df = pd.DataFrame({'Name' : ['ANT J DOE', 'ANT J DOE', 'ANT J DOE', 'ANT J DOE',
'ANDREW THE', 'AMANDA TO', 'AZARA HEBREW', 'BARNY GUM',
'BORIS CHE', 'BORIS CHE', 'BORIS CHE',... | <p>This is kinda hacky and I'm sure there are better alternatives, but it works:</p>
<pre><code>> df['first'] = df['Name'].astype(str).str[0] # add a column with first letter
> print( df.drop_duplicates('Name'). \ # select distinct names
groupby('first'). \ # group by first le... | python-3.x|string|pandas | 3 |
10,547 | 24,195,825 | Group By & Aggregate List of Dictionaries in Python | <p>I have a list of dictionaries which I need to aggregate in Python:</p>
<pre><code>data = [{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 10},
{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 50},
{"startDate": ... | <p>Just to demonstrate that sometimes python is perfectly fine to do this kind of stuff in:</p>
<pre><code>In [11]: from collections import Counter
from itertools import groupby
In [12]: data = [{"startDate": 123, "endDate": 456, "campaignName": "abc", "campaignCfid": 789, "budgetImpressions": 10}, {"startDa... | python|list|dictionary|pandas | 5 |
10,548 | 73,092,306 | How to fill (based on the index of a dataframe) an empty column | <p>I'm trying to add the column 'Information' to my dataframe (df3) and filling it with string values ('True' if the index is 0 and 'False', otherwise). The problem is pandas put <code>'False'</code> in every single row, even in the ones having an index 0 (see the output below).</p>
<h2>Input :</h2>
<pre><code>import p... | <p>Change the for loop with this snippet</p>
<pre class="lang-py prettyprint-override"><code>
df3['Information']= df3.index.map(lambda x: x==0)
</code></pre>
<p>What happen in the for loop is you actually make a new column based on a scalar. Note that you typed</p>
<pre class="lang-py prettyprint-override"><code>
df3[... | python|pandas | 1 |
10,549 | 72,953,697 | Text to column task in Python | <pre><code>;
;
ACHTUNG;Dies ist das Ergebnis einer Testversion. Alle Ergebnisse ohne Gewaehr.
;Bei Rueckfragen oder Unstimmigkeiten wenden Sie sich an aron.proebsting@mwtest.de;
;
;
;
PSD4_Status;|;
PSD5_Status;|;
mux;<-;PSD6_CAN;PSD6_Status;
PSD6_Status;|;
cycle_state;<-;PSD6_Status;PSD5_Status;PSD4_Status;
PsdE... | <p>Do you have to keep every row in your csv file? This will be a slight problem because you do not have enough delimiters per row to account for each column. This code will open your file, check how many delimiters each row needs, add the appropriate number of delimiters, save the new csv file with those delimiters, t... | python|pandas|csv | 1 |
10,550 | 72,860,959 | Determine number of entrants and exits in each year in panel data | <p>I have three data frames with the same variables for the same firms but corresponding to different years (2016, 2017, 2018). The ID variable corresponds to a firm ID.</p>
<pre><code>df2016 = pd.DataFrame({"ID": [99,101,102,103,104], "A": [1,2,3,4,5], "B": [2,4,6,8,10], "year":... | <p>You can use:</p>
<pre><code>df = pd.concat([df2016, df2017, df2018], ignore_index=True)
g = df.groupby('ID')['year']
df['entry'] = g.diff(1).ne(1).astype(int)
df['exit'] = g.diff(-1).ne(-1).astype(int)
print(df)
# Output
ID A B year entry exit
0 99 1 2 2016 1 1
1 101 2 4 2016 1... | pandas|multi-index|panel-data | 2 |
10,551 | 73,022,731 | Cannot covert dictionary data to integer | <p>Hello I created an application using pandas to read an csv file and return the file removing all negative numbers in python that works, I am trying to implement this in a http api interface using flask and for some reason gives this type error and I cannot figure out why. I have tried converting the array slice to ... | <p>There's some confusion because you're re-using the variable name <code>data</code> as both a list and a DataFrame, and as the name of the function. I recommend you give them different names to help track the differences, perhaps <code>data_list</code>, <code>data_df</code>, and <code>data_func</code>. Reusing varia... | python|pandas|flask | 1 |
10,552 | 73,123,529 | How to calculate the delta for the first and each subsequent second in one minute? | <p>I have a csv file that looks something like this (~400.000 lines)
It has every second from 10 to 19 pm and they are duplicated a lot</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Time</th>
<th style="text-align: left;">Value</th>
</tr>
</thead>
<tbody>
<tr>
<t... | <p>IIUC,</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
['10:00:00', 6],
['10:00:00', 5],
['10:00:00', 2],
['10:00:00', 4],
['10:00:01', 6],
['10:00:01', 2],
['10:00:01', 9],
['10:00:04', 4],
['10:00:04', 5],
['10:00:04', 1],
['10:01:00',... | python|pandas | 1 |
10,553 | 73,013,060 | Why can't I use the == operator when comparing to "NaN"? | <p>Trying to get my head around this...</p>
<pre><code>a = float("NaN")
a == float("NaN")
</code></pre>
<p>Out: False</p>
<pre><code>np.isnan(a)
</code></pre>
<p>Out: True</p> | <p>"NaN" means that it isn't equal to anything. So {thing1 which is NaN} == {thing2 which is NaN} will always be "False" because NaN is not equal to anything, including itself.</p> | python|numpy | 0 |
10,554 | 10,753,528 | numpy array creating with a sequence | <p>I am on my transitional trip from MATLAB to scipy(+numpy)+matplotlib. I keep having issues when implementing some things.
I want to create a simple vector array in three different parts. In MATLAB I would do something like:</p>
<pre><code>vector=[0.2,1:60,60.8];
</code></pre>
<p>This results in a one dimensional a... | <p>Well NumPy implements MATLAB's array-creation function, <em>vector</em>, using <em>two</em> functions instead of one--each implicitly specifies a particular axis along which <em>concatenation</em> ought to occur. These functions are:</p>
<ul>
<li><p><strong>r_</strong> (row-wise concatenation) and</p></li>
<li><p><... | python|arrays|numpy|scipy|sequence | 17 |
10,555 | 70,688,363 | Using Statsmodel and the ARIMA model to forecast but running into issues | <p>I'm trying to learn how to forecast data based on the ARIMA model that is in the library Statsmodel, but I keep running into issues. Currently i'm just trying to line up my prediction next to the actual to test my model but i cant get the ARIMA model results to cooperate</p>
<pre><code>import statsmodels.api as sm
... | <p>First of all, you try to save what a function is returning, in this case you expect three values. One for <code>fc</code>, one for <code>se</code> and one for <code>conf</code>. The problem is that the function <code>.forecast()</code> returns the prediction as a single object. You try to unpack a single object, but... | python|pandas|matplotlib|statsmodels|arima | 0 |
10,556 | 42,638,209 | Dealing with duplicates Python | <p>I'm working with a case data CSV file. I am running into a problem wherein one of the columns named <code>case_number</code> there are multiple case number repeats. Is there a way to delete the duplicates without losing any of the information related to those rows that will be dropped. </p>
<p>In other words, merge... | <p>You should use <code>pd.read_csv('filename.csv')</code> to create your DataFrame, but for this simplified example, I'll just create one out of a dictionary:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'x':[1,1,1,2,1,2,2], 'y':['a','b','c','d','e','f','g']})
df = df.groupby('x')['y'].apply(lambda i: ', '.j... | python|pandas | 2 |
10,557 | 42,799,450 | How to duplicated or drop the row with condition in Python | <p>I have unbalanced data frame, I try to make data balanced first before unstack data, the key point is <code>len(df.Question == "Q007_C02")</code> is number of row of new data, so if any levels of <code>df.Question</code> greater than number of row of <code>df.Question == "Q007_C02"</code>, I take only the first row ... | <p>Here's a solution that works for your sample data.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Question":["Q007_A00","Q007_B00","Q007_C01","Q007_C01","Q007_C01","Q007_C01","Q007_C01","Q007_C01","Q007_C01","Q007_C02","Q007_C02","Q007_C02","Q007_C02","Q007_C02"],
"Key": ["Y","N",1,4,5,2,8,9... | python|pandas | 1 |
10,558 | 42,652,573 | Python Dataframe - Keep data as string while loading from_csv | <p>from_csv picks up a '04' as one of the values and converts it to a string. How do I make sure that all columns being picked up are as string? I would want to avoid handling individual columns as there are 114 columns and I do not want to go thru the exercise of analyzing while columns are impacted.</p> | <p>If you want all columns to be <code>str</code> then pass <code>dtype=str</code> to <code>read_csv</code>:</p>
<pre><code>df = pd.read_csv(file_path, dtype=str)
</code></pre>
<p>will preserve any leading zeroes</p>
<p>Example:</p>
<pre><code>In [54]:
t="""a,b
001,230
01,003"""
df = pd.read_csv(io.StringIO(t), dty... | python|pandas|dataframe|import-from-csv | 5 |
10,559 | 27,011,903 | How to sort a Series or DataFrame by a given index order? | <p>Suppose I have a Series like this:</p>
<pre><code>In [19]: sr
Out[19]:
a 1
b 2
c 3
d 4
dtype: int64
In [20]: sr.index
Out[20]: Index([u'a', u'b', u'c', u'd'], dtype='object')
</code></pre>
<p>Instead of sorting lexicographically, I would like to sort this series based on a custom order, say, <code>cd... | <p>You can do this in number of different ways. For Series objects, you can simply pass your preferred order for the index like this:</p>
<pre><code>>>> sr[['c','d','a','b']]
c 3
d 4
a 1
b 2
dtype: int64
</code></pre>
<p>Alternatively, both Series and DataFrame objects have a <code>reindex</code>... | python|sorting|pandas|dataframe | 8 |
10,560 | 39,392,021 | pandas.value_counts for NA | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>pandas.value_counts</code></a>
works for numeric arrays with <code>None</code>:</p>
<pre><code>> s = pd.Series([1,2,1,None])
> vc = s.value_counts(dropna=False)
> vc
1.0 2
2.0 1
Na... | <p>I was also surprised to see that <code>cv[np.nan]</code> does not work, but this does: <code>vc.loc[np.nan]</code></p> | python|pandas|types | 0 |
10,561 | 19,743,525 | Is there a way to prevent numpy.linalg.svd running out of memory? | <p>I have 1 million 3d points I am passing to <code>numpy.linalg.svd</code> but it runs out of memory very quickly. Is there a way to break down this operation into smaller chunks?</p>
<p>I don't know what it's doing but am I only supposed to pass arrays that represent a 3x3, 4x4 matrix? Because I have seen uses of it... | <p>If you have an MxN in your case 1000000x3 matrix<code>numpy.linalg.svd</code> does not require M==N. In fact this is precisely where the SVD can come in to compute things like rank and pseudo inverse. Methods such as linalg.inv require a square (and full rank) matrix to have a defined result. </p>
<p>@Saullo Cas... | python|numpy|matrix|linear-algebra|svd | 1 |
10,562 | 33,694,602 | Script is fine, but will not run as imported module | <p>With this script/module, XRateDKKUSD_test.py, I can successfully fetch the exchange rate DKK pr USD.</p>
<pre><code>import pandas as pd
import pandas.io.data as web
import datetime
def xRate_pd(years,modus,start=datetime.datetime(2000,1,1),end=pd.Timestamp.utcnow()):
global xrate, xratedate, df_xrate
days... | <p>Your script has no issues with being imported as a module. You are passing in a different <em>type</em> of object for the <code>years</code> argument.</p>
<p>When you call the code from the <code>if __name__ == '__main__':</code> guard, you pass in <code>years</code> as a float:</p>
<pre><code>xRate_pd(modus='trad... | python|python-3.x|pandas|currency-exchange-rates | 4 |
10,563 | 33,783,328 | pandas - groupby and filtering for consecutive values | <p>I have this dataframe <code>df</code>:</p>
<pre><code>U,Datetime
01,2015-01-01 20:00:00
01,2015-02-01 20:05:00
01,2015-04-01 21:00:00
01,2015-05-01 22:00:00
01,2015-07-01 22:05:00
02,2015-08-01 20:00:00
02,2015-09-01 21:00:00
02,2014-01-01 23:00:00
02,2014-02-01 22:05:00
02,2015-01-01 20:00:00
02,2014-03-01 21:00:0... | <p>Finally I could come up with the solution :) .</p>
<p>to give you an idea of how custom function works , simply it subtracts the value of the month from it's preceding value , the result should be <code>one</code> of course , and this should happen twice , for example if you have a list of numbers <code>[5 , 6 , 7]... | python|pandas|dataframe|time-series | 2 |
10,564 | 23,666,412 | Comparing date in one row to date in subsequent row in Pandas | <p>I'm trying to drop rows of a dataframe based on whether they are duplicates, and always keep the more recent of the rows. This would be simple using <code>df.drop_duplicates()</code>, however I also need to apply a <code>timedelta</code>. The row is to be considered a duplicate if the <code>EndDate</code> column is ... | <p>I've managed to get the following code to work, but I'm sure it could be improved.</p>
<pre><code>df = df.sort(['ID','EndDate'])
df['Duplicate'] = (df['EndDate'].shift(-1) - df['EndDate']) - datetime.timedelta(182) < 0
df['Duplicate'] = df['Duplicate'] & (df['ID'].shift(-1) == df['ID'])
df = df[df['Duplicate... | python|pandas|timedelta | 0 |
10,565 | 23,644,100 | How do I view a series into table form in Python | <p>I am trying to view a series in a table form like this:</p>
<p>test:</p>
<pre><code>SYM ABC
PRICE NaN
HD1 NaN
HD2 100
BD1 12
BD2 10
SZ1 20
Name: 2014-03-13 00:30:01.643000, dtype: object
</code></pre>
<p>I want to ... | <p>Well, I would probably convert it to a dataframe with the <code>to_frame</code> method and then transpose it (example, using a slighty different series):</p>
<pre><code>>>> print s
close 187.56
high 187.73
low 187.54
open 187.70
volume 1922600.00
Name: 2014-05-09 00:... | python|pandas | 2 |
10,566 | 22,879,200 | how to display the values in Entry in tkinter? | <p>I wanted to know how to display the integer and double values in the text box. As I have to calculate mean values of an image, and I want those values to be displayed in the text box in the GUI. </p>
<p>When I tried with my code I got an error:</p>
<pre><code>AttributeError: numpy.ndarray object has no attribute s... | <p><code>blue</code> is a local name in your function, shadowing your global <code>IntVar</code> reference <code>blue</code>.</p>
<p>Rename one or the other.</p> | python|user-interface|numpy|tkinter | 1 |
10,567 | 22,874,420 | pandas.read_sql processing speed | <p>I need for further processing the result set of a MySQL query as a dataframe. The SQL table contains about 2 million rows and 12 columns (Data size = 180 MiB).
I'm running OS X 10.9 with 8 GB memory. Is it normal that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="noreferre... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/io.html#performance-considerations" rel="nofollow noreferrer">Pandas documentation</a> shows that <code>read_sql()</code>/<code>read_sql_query()</code> takes about 10 times the time to read a file compare to <code>read_hdf()</code> and 3 times the time of <code>r... | python|pandas | 2 |
10,568 | 29,754,080 | Numpy/scipy deprecation warning for "rank" | <p>I have some python code which uses numpy and have run this successfully for a year or more. I suddenly got the following error last week:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py:2507: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instea... | <p>From the <a href="https://docs.scipy.org/doc/numpy/release.html#rank-function" rel="nofollow noreferrer">release notes</a> of NumPy 1.9.0:</p>
<blockquote>
<h2><code>rank</code> function</h2>
<p>The rank function has been deprecated to avoid confusion with <code>numpy.linalg.matrix_rank</code>.</p>
</blockqu... | python|python-2.7|numpy|scipy|deprecation-warning | 6 |
10,569 | 62,462,098 | How to restructure/reformat Pandas dataframe containing images to be fed into Tensorflow's model.fit()? | <p>In preprocessing a set of images to be fed into a Tensorflow convolutional neural network, I have created a Pandas dataframe with two columns.</p>
<p>The first contains 13200, 1/255-rescaled images(specifically their file paths to their respective train/test and class directories) filled into the dataframe such tha... | <p>tf.keras.layers.Conv2D layer expects input of shape <code>4+D</code> tensor with shape: <code>batch_shape + (channels, rows, cols)</code> if data_format='channels_first' or <code>4+D</code> tensor with shape: <code>batch_shape + (rows, cols, channels)</code> if data_format='channels_last'.
Make sure your X_train be ... | python|tensorflow|machine-learning|scikit-learn|computer-vision | 0 |
10,570 | 62,081,792 | Mean average precision metrics for evaluation multilabel object detection model | <p>My goal is to evaluate model performance on test dataset for <strong>object detection task</strong>. Model was trained on dataset with 6 classes with Tensorflow Object Detection API. For some class there are 20 samples of objects and for some it can be only one sample. So data is imbalanced for both train and test s... | <p>Mean average precision will still work. As you can see, it is mean average precision, so, since precision will be averaged over all classes their number won't matter.</p> | python|tensorflow|object-detection|object-detection-api | 0 |
10,571 | 62,146,572 | Labeling by date in two data frames | <pre><code>df1
name date
A 14-04-05
A 14-05-08
A 14-08-09
A 15-01-05
B 18-07-05
B 18-08-09
B 18-10-02
C 19-01-03
C 19-02-04
C 19-03-30
D 16-04-01
D 16-08-04
</code></pre>
<pre><code>df2
name startdate
A 14-07-07
B 18-09-09
C 19-03-15
D 16-06-28
</code></pre>
<p>Record ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> for add new column and then compare by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.gt.html" rel="nofollow noreferrer"><co... | python|pandas|dataframe|label | 2 |
10,572 | 62,357,684 | Astropy Spectrum1D recovering arrays from spectrum | <p>I have to work with an Astropy Spectrum1D array:</p>
<pre><code> spectrum = Spectrum1D(spectral_axis= wavelength, flux = field_strength)
</code></pre>
<p>I need to recover the wavelengths and field_strength to standard numpy arrays so that I can manipulate them (this has to be done outside "spectrum" in numpy f... | <p>From <a href="https://docs.astropy.org/en/stable/units/#getting-started" rel="nofollow noreferrer">https://docs.astropy.org/en/stable/units/#getting-started</a>:</p>
<blockquote>
<p>You can get the unit and value from a Quantity using the unit and
value members</p>
</blockquote>
<pre><code>spectrum.flux.value
... | numpy|astropy|astronomy|spectrum | 1 |
10,573 | 62,143,055 | How numpy printoptions will work with images? | <p>I was trying to print an image to analyze, if there are some changes in the pixel intensities if the images are forged. Anyways my doubt is related with the numpy.printoptions.
I was trying below code and numpy.printoptions was not working:
<a href="https://i.stack.imgur.com/72mDp.png" rel="nofollow noreferrer">Ima... | <p>From the diagram you have given in "Image of code snippet" link, it seems printoptions print the values in both cases, incase if the values needs to be printed properly (displaying all values), u could use,</p>
<pre>
with np.printoptions(linewidth=200):
ok = np.copy(src[:, :, 1])
print(ok)
</... | python|python-3.x|numpy|tensorflow|computer-vision | 0 |
10,574 | 62,215,453 | Python Pandas Iterate over columns and also update columns based on apply conditions | <p>I am trying to update dataframe columns based on consecutive columns values.<br>
If columns say col1 and col2 has >0 and <0 values, then same columns should get updated as col2=col1 + col2 and col1=0 and also counter +1 (gives how many fixes has been done throughout the column).</p>
<p>Dataframe look like: </p>
... | <p>Here is an approach without loops:</p>
<pre><code>c = df.gt(0) & df.shift(-1,axis=1).lt(0)
out = (df.mask(c.shift(axis=1).fillna(False),df+df.shift(axis=1))
.mask(c,0).assign(Fix=c.sum(1)))
print(out)
</code></pre>
<hr>
<pre><code> id col0 col1 col2 col3 col4 col6 col7 col8 col9 col10 Fix... | python|pandas|dataframe | 3 |
10,575 | 62,087,598 | tensorflow keras model predicts similar value for every test | <p>I'm trying to do a binary classification with an RNN with tensorflow. The labels of m y training and test data are 0 and 1. When I try to use my RNN on my finished model, it returns almost the same predictions for every single sample:</p>
<pre><code>model.predict(holdout_x[400:500])
array([[-4.116061 , -1.3410028]... | <p>In theory, there could be various reasons. However, there's one thing in this example that definitely requires clarification. </p>
<p>Sparse categorical crossentropy is expecting you to feed probabilities (values from 0 to 1) for the predictions, unless you instantiate it with <code>from_logits=True</code>. Your la... | tensorflow|keras | 1 |
10,576 | 62,158,316 | Iterate over all rows in dataframe and check all column values are in list | <p>I have a dataframe with 7 columns and ~5.000 rows. I want to check that all the column values in a row are in my list and if so either add them to a new dataframe OR remove those where all values do not match, i.e. remove <em>false</em> rows (w/e is the easiest);</p>
<pre><code>for row in df:
for columns in row:... | <p>If I understood correctly, you can solve this by using <code>apply</code> with a lambda expression like:</p>
<pre><code>df.loc[df.apply(lambda row: all(value in MyList for value in row), axis=1))]
</code></pre> | python|pandas | 1 |
10,577 | 51,487,275 | Dataframe index from string to date | <p>I have a large dataframe (df) where the start looks like:</p>
<pre><code>date,number
2015-12-28,161
2015-12-29,225
2015-12-30,197
2016-06-06,217
2016-06-07,301
2016-06-08,317
2016-06-09,338
2016-06-10,308
2016-10-24,108
2016-10-25,142
2016-10-26,162
2016-10-27,165
2016-10-28,141
2016-01-04,193
2016-01-05,249
2016-01... | <p>Use <code>parse_dates</code> parameter in <code>pd.read_csv</code>.</p>
<p>MCVE:</p>
<pre><code>from io import StringIO
csvfile = StringIO("""date,number
2015-12-28,161
2015-12-29,225
2015-12-30,197
2016-06-06,217
2016-06-07,301
2016-06-08,317
2016-06-09,338
2016-06-10,308
2016-10-24,108
2016-10-25,142
2016-10-26... | python|pandas|parsing | 1 |
10,578 | 51,521,171 | Efficient row-wise comparisons between two dataframes | <p>I am comparing two dataframes in a row wise fashion.</p>
<p>For each row in <code>data</code>, I want to check if there is a matching row in <code>reference</code>.</p>
<p>For a match to be considered as true, some conditions must be fullfiled:</p>
<ol>
<li>I want the same number of non-null values in both row (s... | <p>Your loops may be avoided through use of <code>df.apply</code>. <code>itertuples</code> is slow and should only be used when absolutely necessary. </p>
<pre><code># index-setting not technically required, but makes the
# rest of the code simpler
data = data.set_index('name')
reference = reference.set_index('name')... | arrays|python-3.x|numpy|dataframe|vectorization | 1 |
10,579 | 51,254,067 | How to make a rectangular matrix square on pandas dataframe | <p>I have a matrix on the following form (not necessarily square):</p>
<pre><code> A B C D
A 0 0.2 0.3 0.5
E 0.2 0.6 0.9 0.2
D 0.5 0.3 0.6 0
F 0.1 0.4 0.5 0.3
</code></pre>
<p>And I would like to turn it into a square matrix as follows</p>
<pre><code> A B C D E F
A 0 0.2... | <p>Just as you thought you can definitely do this pretty concisely in Pandas.</p>
<p>One way is by using the very nice <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer">combine_first</a> method.</p>
<pre><code>result = df.combine_first(df.T)... | python-3.x|pandas|numpy|dataframe | 5 |
10,580 | 48,356,278 | Pandas: drop_duplicates().fillna(0) not filling zeroes | <p>I'm trying to drop duplicates from a series and then fill the NaNs with 0. Should be pretty straightforward, but when I chain the two functions together, I still get <code>NaN</code> where I would expect <code>0.0</code>.</p>
<pre><code>df = pd.DataFrame({'a':[1,1,2,3,3,4], 'b':[10,20,30,40,50,60]})
df['a'] = df['... | <p>Because <code>drop_duplicates</code> removes elements, your result is of smaller size than the dataframe you're assigning back to. This causes index mismatches.</p>
<p>Alternatively, use <code>mask</code>/<code>where</code> with <code>duplicated</code> - </p>
<pre><code>df['a'] = df['a'].mask(df['a'].duplicated(),... | python|pandas|duplicates|nan | 3 |
10,581 | 48,215,969 | Usage of argmax from tf.nn.max_pool_with_argmax tensorflow | <p>I am trying to use the argmax result of <code>tf.nn.max_pool_with_argmax()</code> to index another tensor. For simplicity, let's say I am trying to implement the following:</p>
<pre><code>output, argmax = tf.nn.max_pool_with_argmax(input, ksize, strides, padding)
tf.assert_equal(input[argmax],output)
</code></pre>
... | <p>I found a solution using <code>tf.gather_nd</code>and it works, although it seems not so elegant. I used the function <code>unravel_argmax</code>that was posted <a href="https://github.com/tensorflow/tensorflow/issues/2169%20here" rel="nofollow noreferrer">here</a>.</p>
<pre><code>def unravel_argmax(argmax, shape):... | python|tensorflow|indexing|convolution|max-pooling | 2 |
10,582 | 70,824,476 | numpy bring values in a range | <p>Is there a more elegant way of bringing values in a numpy array in the range 0-50?</p>
<pre><code>x = np.array([-5, 6, 24, 51, 50, 40])
array([-5, 6, 24, 51, 50, 40])
x = np.where(x < 0, 0, x)
x = np.where(x > 50, 50, x)
array([ 0, 6, 24, 50, 50, 40])
</code></pre> | <pre><code>In [49]: x = np.array([-5, 6, 24, 51, 50, 40])
</code></pre>
<p>A couple of alternatives:</p>
<pre><code>In [50]: np.clip(x,0,50)
Out[50]: array([ 0, 6, 24, 50, 50, 40])
In [52]: np.minimum(np.maximum(x,0),50)
Out[52]: array([ 0, 6, 24, 50, 50, 40])
</code></pre> | python-3.x|numpy | 3 |
10,583 | 71,017,107 | Python row wise operation without loops | <p>Solved:
Thanks to the help of @mozway I solved my problem.
Basically merged the df's, grouped them up and combined them into one column + deleted the duplicates.</p>
<pre><code>df2 = df2.merge(df1, how='left', left_on=df2["code2_firstTwoDigits"], right_on=df1["code"])
df2['code'] = df2.groupby(['... | <p>The exact logic of the output is unclear, but you want <code>merge</code> and <code>groupby</code>+<code>agg</code>:</p>
<pre><code>(df1.merge(df2, left_on=df1['code']//100, right_on='code2_firstTwoDigits', suffixes=('', '_2'))
.groupby('code2_firstTwoDigits')
.agg({'code_Values': 'sum',
'code': li... | python|pandas|dataframe|series | 0 |
10,584 | 71,067,733 | Using regex in python for a dynamic string | <p>I have a pandas columns with strings which dont have the same pattern, something like this:</p>
<pre><code>{'iso_2': 'FR', 'iso_3': 'FRA', 'name': 'France'}
{'iso': 'FR', 'iso_2': 'USA', 'name': 'United States of America'}
{'iso_3': 'FR', 'iso_4': 'FRA', 'name': 'France'}
</code></pre>
<p>How do I only keep the name... | <p>As you have dictionaries in the column, you can get the values of the <code>name</code> keys:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'col':[{'iso_2': 'FR', 'iso_3': 'FRA', 'name': 'France'},
{'iso': 'FR', 'iso_2': 'USA', 'name': 'United States of America'},
... | python|regex|pandas | 3 |
10,585 | 71,027,249 | How do I use the length of another column in Pandas as a slice argument | <p>I am trying to remove rows from a dataframe where the first sequence of letters in the <code>Ref</code> column are equal to the <code>Product</code> column.</p>
<p>For example, for the input:</p>
<pre><code>+---------+---------------+
| Product | Provision Ref |
+---------+---------------+
| DVX | DVX9251 ... | <p>Try this:</p>
<pre><code>filtered = df[df.groupby('Product', sort=False).apply(lambda g: g['Provision Ref'].str.startswith(g['Product'].iloc[0])).tolist()]
</code></pre>
<p>Output:</p>
<pre><code>>>> filtered
Product Provision Ref
0 DVX DVX9251
2 TV TV12369
</code></pre>
<p>More reada... | python|pandas|dataframe|slice | 2 |
10,586 | 71,023,630 | Loading a pretrained model in PyTorch, error:object not callable | <p>I am trying to load the <code>Efficientnet-b6</code> weights using <code>PyTorch</code> and <code>Fastai</code>:</p>
<pre><code>PATH = '../input/EffnetB6/efficientnet_b6.pth'
model = torch.load(PATH)
</code></pre>
<p>The above model is part of another model:</p>
<pre><code>class EARUnet(nn.Module):
def __init__(... | <p>Given the restrained context, I suspect that the problem resides in <code>model</code>, probably containing an <code>OrderedDict</code> of the EfficientNet model state dict, while the EARUnet expects the EfficientNet <code>nn.Module</code>.</p>
<p>You should instead, try something like:</p>
<pre class="lang-py prett... | python|pytorch|fast-ai | 1 |
10,587 | 70,802,992 | Having trouble putting data into a pandas dataframe | <p>I am new to coding, so take it easy on me! I recently started a pet project which scrapes data from a table and will create a csv of the data for me. I believe I have successfully pulled the data, but trying to put it into a dataframe returns the error "Shape of passed values is (31719, 1), indices imply (31719... | <p>You are creating a dataframe with 692 rows with 23 columns as a new dataframe. However looking at the rows array, you only have 1 dimensional array so shape of passed values is not matching with indices. You are passing 692 x 1 to a dataframe with 692 x 23 which won't work.</p>
<p>If you want to create with the data... | python|pandas|dataframe | 0 |
10,588 | 51,757,209 | How does TensorFlow know which variables to change for optimization? | <p>Code taken from:-<a href="http://adventuresinmachinelearning.com/python-tensorflow-tutorial/" rel="noreferrer">http://adventuresinmachinelearning.com/python-tensorflow-tutorial/</a></p>
<pre><code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("M... | <p>The answer by Cory Nezin is only partially correct, and could lead to wrong assumptions!</p>
<p>You actually <em>do</em> specify which parameters are optimized (=trainable), namely by doing this:</p>
<pre><code># now declare the weights connecting the input to the hidden layer
W1 = tf.Variable(tf.random_normal([78... | tensorflow|neural-network | 3 |
10,589 | 51,636,337 | How to deploy a Keras CNN Model to webservice? | <p>I am currently in the process of trying to deploy a Keras Convolutional Neural Network for a webservice.</p>
<p>I had tried converting my saved keras hdf5 model to a tensorflow.js model and deploying that but it slowed down the client-side app as the model is relatively robust and thus, takes a large amount of spac... | <p>You can export a trained Keras model and serve it with <a href="https://www.tensorflow.org/serving/" rel="nofollow noreferrer">TensorFlow Serving</a>. TF Serving allows to host models and call them via either gRPC or REST requests. You could deploy a flask app with an endpoint that accepts an image, wraps it as a pa... | python|tensorflow|request|keras|google-cloud-ml | 2 |
10,590 | 42,075,777 | Pandas series Max value for column based on index | <p>I am trying to extract the max value for a column based on the index. I have this series:</p>
<pre><code>Hour Values
1 0
1 3
1 1
2 0
2 5
2 4
...
23 3
23 4
23 2
24 1
24 9
24 2
</code></pre>
<p>and am looking to add a n... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html">transform('max')</a> method:</p>
<pre><code>In [61]: df['Max Value'] = df.groupby('Hour')['Values'].transform('max')
In [62]: df
Out[62]:
Hour Values Max Value
0 1 0 3
1 1 ... | python|pandas|dataframe|group-by | 7 |
10,591 | 42,106,461 | How to get started with TensorFlow? | <p>How to get start TensorFlow, is there any book to read?
I'm good at java programming, and have some background of machine learning. I'd like to find a book or a course about TensorFlow. Is there any recommendation?</p> | <p>Though this page its not the right place to ask such question , A programmer should get answer wherever possible</p>
<p>You can get some of the tutorials that could be taken as initiation for your study at the very its own website <a href="https://www.tensorflow.org/tutorials/" rel="nofollow noreferrer">https://www... | machine-learning|tensorflow | 0 |
10,592 | 64,537,981 | Python3.9 pandas save pivotted data frame as a proper csv | <p>I have this csv:</p>
<pre><code>Label,Visits,Actions,Maximum actions in one visit,Total time spent by visitors (in seconds),Bounces,Visits with Conversions,Unique visitors (daily sum),Users (daily sum),Metadata: segment,Metadata: referrer_type, cmpgn_group2, cmpgn_group3
Search Engines,4386,5836,15,351989,3547,0,409... | <p>The reason is <code>pivot_table</code> creates multi-index DataFrames. You can collapse them into a single index like this:</p>
<pre><code>df2 = pd.pivot_table(df, values=['Visits'], columns=['Label'], index=' cmpgn_group2', aggfunc=np.sum)
df2.columns = df2.columns.map('_'.join)
df2.to_csv('ex1.csv')
</code></pre>
... | python|pandas|dataframe|csv|pivot | 1 |
10,593 | 64,412,470 | Defining loss function in Keras as element wise multiplication with negation of every second element | <p>I am trying to define my own cost function in Keras running on top of Tensorflow. While having <code>y_true = [a0, a1, a2, a3, ..., an]</code> and <code>y_pred = [b0, b1, b2, b3, ..., bn]</code> as ground truth and predictions, respectively, I want to define the cost function as: <code>cost = a0*b0 - a1*b1 + a2*b2 -... | <p>I expect the following <code>cost_function</code> to work; in essence, we make a trick and select the odd and even indices; we multiply only the <code>y_true</code> and <code>y_pred</code> counterparts considering their oddity.</p>
<p>Then we use the <code>tf.math.reduce_sum()</code> in order to actually compute the... | tensorflow|machine-learning|keras|neural-network | 1 |
10,594 | 64,364,462 | Pandas Groupby & Pivot | <p>I have a pandas <code>df</code> setup as the following:</p>
<pre><code> product salesperson positionHours levelHours
0 soap john 10 25
1 nuts john 15 27
2 soap doug 12 29
3 nuts doug 11 ... | <p>There's going to be a multitude of ways you can do this. First couple that come to mind:</p>
<p>Melt, then pivot:</p>
<pre><code>(df.melt(["product", "salesperson"], var_name="measurement")
.pivot(index=["product", "measurement"], columns="salesperson", va... | python|pandas | 7 |
10,595 | 47,607,315 | ModuleNotFoundError: No module named 'pandas._libs.tslibs.timedeltas' | <p>I'm a learner of Python. There is a problem on executing my script.
It shows <code>failed to execute script</code> while packing by Pyinstaller due to </p>
<blockquote>
<p>ModuleNotFoundError: No module named 'pandas._libs.tslibs.timedeltas'.</p>
</blockquote>
<p>How can I solve it?</p>
<p><img src="https://i.... | <p>Navigate to your pyinstaller folder, within your Python folder - where it was installed. It might be a path similar to this:</p>
<pre><code>C:\Users\yourName\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\PyInstaller\hooks
</code></pre>
<p>In this folder, find the file named <code>hook.pandas.py</code... | python-3.x|pandas|pyinstaller | 1 |
10,596 | 47,550,615 | View specific fields as ndarray with numpy >= 1.13 | <p>Data is in a structured array:</p>
<pre><code>import numpy as np
dtype = [(field, float) for field in ['x', 'y', 'z', 'prop1', 'prop2']]
data = np.array([(1,2,3,4,5), (6,7,8,9,10), (11,12,13,14,15)], dtype=dtype)
</code></pre>
<p>For some operations, the positions are accessed as a single nx3 array, for example:</... | <p>Checking on numpy 1.13 the announced change doesn't appear to have happened yet. So let's simulate the future:</p>
<p>The future behavior will presumably be not to copy the data but to create a dtype that has only the fields you want, but the <code>itemsize</code> of the original dtype. So there will be gaps in eac... | python|numpy|scipy | 2 |
10,597 | 49,052,231 | Run object detection evaluation protocols (tensorflow) | <p>I want to run one of the tensorflow object detection evaluation protocols [1]. I am new with it, and from the webpage I cannot understand where I would have to add the metrics_set configuration. Ex: </p>
<pre><code>EvalConfig.metrics_set='pascal_voc_detection_metrics'
</code></pre>
<p>I tried changing the value in... | <p>I think "8" is just a placeholder - it's the 8th entry in the <code>eval.proto</code> file. </p>
<p>When you run an evaluation job (eval.py), this <code>metrics_set</code> you specify is used as the protocol by which to compute the metrics on the data set specified in <code>eval_input_reader</code>. The results are... | tensorflow|object-detection | 3 |
10,598 | 49,054,338 | Aggregate rows in a Pandas Data Frame based off two columns | <p>Hi, I want to know if it's possible to do the following calculation in a panda data frame in python. I have a single data frame with the below columns</p>
<pre><code> city zone b_s total
0 cardiff 1 buy 1000
1 cardiff 1 sell 500
2 cardiff 2 buy 100
3 bristol 1 buy 200
... | <p>This is what I think you are looking to achieve:</p>
<pre><code>import pandas as pd, numpy as np
df.loc[df['b_s'] == 'sell', 'total'] *= -1
df = df.groupby(['city', 'zone'], as_index=False)['total'].sum()
df['b_s'] = np.where(df['total'] >= 0, 'buy', 'sell')
# city zone total b_s
# 0 bristol 1 ... | python|pandas | 1 |
10,599 | 49,225,962 | How to convert row values to attributes (columns) in pandas | <p>I have a dataset in pandas with column pid (patient id), and code (drug code), sorted in rows as the example shows. I need to convert them to 1 patient/row, and list all the drugs as attributes for each patient.</p>
<p>What I have now:</p>
<pre><code>pid code
1 Az
1 Bn
2 Az
2 Bn
2 C4
3 Bn
3 C... | <p>IIUC <code>crosstab</code></p>
<pre><code>pd.crosstab(df.pid,df.code).replace({1:'y',0:'n'})
Out[231]:
code Az Bn C4 Dx E
pid
1 y y n n n
2 y y y n n
3 n y y y n
4 y y n y y
5 n n y y y
</code></pre> | python|pandas|dataframe|attributes | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.