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 |
|---|---|---|---|---|---|---|
361,000 | 59,882,702 | Python pandas when sorting table, choose ascending/decending based on value of a column? | <p>I have a df with these columns: time, username, aisle_id, seat_id. </p>
<p>I want to sort the table by: </p>
<p>1st: time, ascending, </p>
<p>2nd: username ascending, </p>
<p>3rd: aisle_id ascending, </p>
<p>4th: seat_id, ascending when aisle_id is odd number, and descending when aisle_id is even.</p>
<p>I tri... | <p>You can groupby by time, username and aisle_id, and then sort values by seat_id within each group based on the values of aisle_id. </p>
<p>To sort within groups, create function func():</p>
<pre><code>def func(x):
if (x["aisle_id"].iloc[0]%2 == 0):
ans = x["seat_id"].sort_values(ascending=False)
el... | python|pandas|function|numpy|sorting | 2 |
361,001 | 59,705,605 | How to store each dataframes row value in a string and execute URL | <p>I have the following dataframe:</p>
<pre><code> symbol
0 https://nseindia.com/api/historical/cm/equity?symbol=ACC&series=["EQ"]&from=07-01-2020&to=11-01-2020
1 https://nseindia.com/api/historical/cm/equity?symbol=ADANIENT&series=["EQ"]&from=07-01-2020&to=11-01-2020
2 https://nse... | <blockquote>
<ol>
<li>How to iterate dataframe and store Dataframe row value in text/string without index so I can execute above code</li>
</ol>
</blockquote>
<p>You could extract the values of a column and store them in a <code>np.array</code> like this <code>a = df['symbol'].values</code>. After that you coul... | python|python-3.x|pandas | 0 |
361,002 | 59,859,989 | Change column to multi-index by using one column as a new level | <p>I've got a DataFrame:</p>
<pre><code>df = pd.DataFrame.from_dict({'Close': {1: 14.03, 3: 14.02, 0: 79.88, 2: 80.31},
'High': {1: 14.3, 3: 14.33, 0: 80.22, 2: 81.19},
'Low': {1: 14.03, 3: 13.99, 0: 79.39, 2: 80.25},
'Open': {1: 14.18, 3: 14.25, 0: 79.79, 2: 80.97},
'Volume': {1: 1656782.0, 3: 2249159.0, 0: 14162... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unsta... | python|pandas | 4 |
361,003 | 59,477,301 | compare value of the current index to the value of next index in Pandas df | <p>I'm trying to compare the value of the current index to the value of the next index in my pandas data frame. I'm able to access the value with <code>iloc</code> but when I write an if condition to validate the value. It gives me an error.</p>
<p>Code I tried:</p>
<pre><code>df = pd.DataFrame({'Col1': [2.5, 1.5, 3 ... | <p>You are getting the error becauce</p>
<p><code>df.iloc[k]</code> gives you a <code>pd.Series</code>. </p>
<p>You can use say <code>df.iloc[k,0]</code> to get the <code>Col1</code> value</p> | python|pandas|dataframe | 0 |
361,004 | 59,766,748 | Find local mimimum in 2D np.array in Python | <p>I have this two columns array :</p>
<pre><code>A | 1
A | 2
A | 3
B | 4
B | 5
B | 6
</code></pre>
<p>where A, B are constants. What I want is to find the mimimum value of each parameter A and B, so the result of this operation would be an other 2D array like this one : </p>
<pre><code>A | 1
B | 4
</code></p... | <p>What you are looking for is the optional keyword <code>axis</code> in the function <code>np.min</code>. It allows you to compute the minimum of the array column-wise.
The use of <code>np.min</code> is also better than using <code>np.amin</code> since it allows you to perform one less step before the result (you imme... | python|arrays|numpy|sorting | 0 |
361,005 | 59,582,378 | Filtering pandas dataframe to restrict within a given range of dates | <p>I have a pandas data frame that looks like this </p>
<pre><code>2684 A878 2015-01-01 False M13
2685 A878 2015-01-01 False M50
2686 A879 2015-01-01 False M96
5735 A879 2015-01-02 False M19
... ... ... ... ...
89487 A879 2015-01-30 False M38
89488 A879 2015-01-30 Fals... | <p>How about</p>
<pre><code>import datetime as dt
REFERENCE_DATE = dt.date(2015, 1, 15)
df["date"] = pd.to_datetime(df["date"])
df[
df["date"].dt.date.between(
REFERENCE_DATE - dt.timedelta(days=5), REFERENCE_DATE - dt.timedelta(days=2)
)
& df["code"].eq("A879")
]
</code></pre>
<p>?</p> | python|pandas|dataframe | 1 |
361,006 | 59,582,111 | Why image (numpy array) is convert to string before encoding into tfrecord file? | <p>Recently, I'm working on decoding image (let's say a bitmap format) into a tfrecord file</p>
<p>But, I'm wondering about the reason </p>
<p>Why do we need to convert numpy array data into a string type</p>
<p>before the data is been written into tfrecord file?</p>
<p>like </p>
<pre><code>from PIL import Image
.... | <p>To read data efficiently it can be helpful to serialize your data and store it in a set of files (100-200MB each) that can each be read linearly. This is especially true if the data is being streamed over a network. This can also be useful for caching any data-preprocessing.</p>
<p>Edit:
This comes in handy when yo... | python|numpy|tensorflow | 2 |
361,007 | 59,862,598 | Importing non-square adjacency matrix into Networkx python | <p>I have some data in pandas dataframe form below, where the columns represent discrete skills and the rows represent discrete jobs. A 1 is present only if the skill is required by the job, otherwise 0.</p>
<pre><code> skill_1, skill_2,
job_1 1, 0,
job_2 0, 0,
job_3 1, ... | <p>You have a <a href="https://en.wikipedia.org/wiki/Bipartite_graph" rel="nofollow noreferrer">bipartite graph</a>. Networkx can create this network from your original (bi)adjacency matrix using <a href="https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.bipartite.matri... | python|pandas|numpy|networkx|graph-theory | 2 |
361,008 | 59,643,570 | Tensorflow training accuracy and loss different from evaluation of the same dataset | <p>I try to train a Tensorflow model with two classes.
My Trainingsdata is balanced (~11k images for both classes).
I am using Tranferlearning and try to continue on the InceptionV3 Model with the following code:</p>
<pre><code>BUFFER_SIZE = 1000
BATCH_SIZE = 32
def get_label(file_path, class_names):
# convert the ... | <p>Ok, after a few more hours of reseach i might have the Problem.
InceptionV3 uses </p>
<pre><code>def preprocess_input(x):
x /= 255.
x -= 0.5
x *= 2.
return x
</code></pre>
<p>as preprocess function. And i am only doing the x/=255 part wich is not enough. The difference of the accuracy might be beca... | python|tensorflow|machine-learning|keras|deep-learning | 0 |
361,009 | 59,588,556 | Android(kotlin), how getting assets file path? (at pytorch mobile) | <p>I'm trying PyTorch Mobile tutorial by kotlin. I want to load module, "model.pt" in assets file. But no idea to load module in assets file.</p>
<p><strong>Java</strong> (written in PyTorch Mobile Tutorial "hello world")</p>
<pre><code>Module module = Module.load(assetFilePath(this, "model.pt"));
</code></pre>
<p><... | <p>Declare this function:</p>
<pre><code>fun assetFilePath(context: Context, asset: String): String {
val file = File(context.filesDir, asset)
try {
val inpStream: InputStream = context.assets.open(asset)
try {
val outStream = FileOutputStream(file, false)
val buffer = ... | android|kotlin|pytorch | 5 |
361,010 | 59,656,313 | How to share weights and not biases in Keras Dense layers | <p>I'm trying to create a model for ordinal regression as explained by this <a href="https://arxiv.org/abs/1901.07884" rel="nofollow noreferrer">paper</a> . A major part of it is sharing weights in the final layer but not the bias in order to obtain rank monotonicity(Basically to ensure P[Y>N] must always be greater th... | <p>One of the ways you can achieve this is by defining a custom <code>bias</code> layer, and here is how you could do this.
PS: Change input shapes/ initializer according to your need.</p>
<pre><code>import tensorflow as tf
print('TensorFlow:', tf.__version__)
class BiasLayer(tf.keras.layers.Layer):
def __init__(... | python|tensorflow|keras|deep-learning|neural-network | 3 |
361,011 | 59,815,491 | Does PyTorch loss() and backpropagation understand lambda layers? | <p>I've been working with a resnet56 model from the code provided here: <a href="https://github.com/akamaster/pytorch_resnet_cifar10/blob/master/resnet.py" rel="nofollow noreferrer">https://github.com/akamaster/pytorch_resnet_cifar10/blob/master/resnet.py</a>. </p>
<p>I noticed that the implementation is different fro... | <p><strong>"I was wondering if PyTorch's backpropagation algorithm using loss() can account for the lambda layer and shortcut in the code provided."</strong></p>
<p>PyTorch has no problem with backpropagating through lambda functions. Your LambdaLayer is just defining the forward pass of the Module as the evaluation o... | pytorch|backpropagation|resnet|autograd | 1 |
361,012 | 59,861,580 | Pandas df reorder rows and columns according to integer index list | <p>I have the following structure for my data frame: </p>
<pre><code> col1 col2 col3
myindex
apple A B C
pear Ab Bb Cb
turtle A1 B1 C1
</code></pre>
<p>Now I get two lists, one with reordered column indices, one with reordered row indices, but as integers, for e... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer"><code>DataFrame.iloc</code></a> and because python counts from <code>0</code> convert list to arrays and subtract <code>1</code>:</p>
<pre><code>rowindices = [3,1,2]
colindices = [1,3,2]
df = df.iloc... | python|pandas|dataframe | 6 |
361,013 | 59,685,269 | Find most frequent element/row in list of lists | <p>I have a list of lists of the form:</p>
<pre><code>my_list = [[8, [16, 32], [32, 16, 8], 0],
[16, [16, 32], [32, 16, 8], 0],
[16, [32, 64], [32, 16, 8], 0],
[8, [16, 32], [32, 16, 8], 0]]
</code></pre>
<p>and I would like to extract the most frequent item, namely:</p>
<pre><code>m... | <p>Using Pandas</p>
<pre><code>>>> s = pd.Series(map(str, my_list))
>>> s.value_counts()
[8, [16, 32], [32, 16, 8], 0] 2
[16, [32, 64], [32, 16, 8], 0] 1
[16, [16, 32], [32, 16, 8], 0] 1
</code></pre>
<p>To get the most frequent element:</p>
<pre><code>s.value_counts().index[0]
</code></... | python-3.x|list|numpy | 1 |
361,014 | 59,742,526 | Python numpy array Generate Array (Month Data) from array (Yearly Data) | <p>I have a array for yearly date </p>
<pre><code>#the first value for year 2000
#Last one for year 2001
a = [45,25]
</code></pre>
<p>can you help me to generate this result for month values.</p>
<pre><code>B=[ 45/12,45/12,45/12,45/12,45/12,45/12,45/12,45/12,45/12,45/12,45/12,45/12,25/12,25/12,25/12,
25/12,25/12,25... | <p>Not sure if I understood you corretly, but here goes:</p>
<pre class="lang-py prettyprint-override"><code>yearly_values = ... # Put your yearly_values array here
# monthly_values[year_index, month_index]
monthly_values = np.full(12, 1 / 12) * yearly_values[:, np.newaxis]
# If you want a flat array as result
mont... | python|arrays|numpy|insert | 1 |
361,015 | 59,857,291 | How to change from date format from object ( 16-04-2017 ) to DateTime format of (2017-04-16) in pandas? | <p><a href="https://i.stack.imgur.com/QbFKr.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>How to change from date format from object ( 16-04-2017 ) to DateTime format of (2017-04-16) in pandas</p> | <p>Use to_datetime() e.g </p>
<pre><code>import pandas as pd
pd.to_datetime(df[date_field],format='%Y-%m-%d', errors='coerce')
</code></pre> | pandas | 0 |
361,016 | 59,676,082 | Python function returning objects insted of values | <p>I have a python class, and this class has functions as follows
:</p>
<pre><code>import numpy as np
class output_hidden:
def feature(self,x1,y1):
feature=np.array([x1,y1])
return feature
def weights(self):
self.weights = np.random.rand(2,1)
return weights
object_1=output_hi... | <p>you need to use return self.weights (since weights isn't defined)</p>
<pre><code>import numpy as np
class output_hidden:
def feature(self,x1,y1):
feature=np.array([x1,y1])
return feature
def weights(self):
self.weights = np.random.rand(2,1)
return self.weights
object_1=out... | python|python-3.x|numpy|data-structures | 0 |
361,017 | 59,537,601 | Force python script on GPU | <p>Is there a way to force a Python script on GPU? In my code I use tensorflow and keras, and I have already the tensorflow-gpu version, but my code runs on CPU anyway. I'd like to know if there is a way to force the running on GPU independently on Tensorflow, Numpy or others. </p> | <p>For TensorFlow (but not python in general) there is a good description of how to do this here: <a href="https://www.tensorflow.org/guide/gpu" rel="nofollow noreferrer">https://www.tensorflow.org/guide/gpu</a></p>
<p>To force a function to be performed on a specific processor (CPU or GPU) use the TensorFlow call to ... | python|tensorflow | 1 |
361,018 | 59,844,608 | Accessing columns without name and deleting certain data from dataframe | <p>I have a dataframe which has 14 columns and it does not have any headers in it. The first column is date and I need to delete all rows which is older than 25 months from now and does not contain any date. </p>
<pre><code> 44.93442 -79.37061 Tow 36 45.06541 -79.43384 R103 2053 ... | <p>You can use <code>iloc</code> accessor to operate on the column:</p>
<pre><code># convert month to days
n_days = 25 * 30
# both will return a boolean series
t1 = df.iloc[:,0].apply(lambda x: (x - pd.to_datetime('today')).days).gt(n_days)
t2 = df.iloc[0].isna()
# remove unwanted dates
df1 = df.loc[t1 & t2]
</c... | python|pandas|dataframe|datetime | 0 |
361,019 | 59,534,544 | Difference between Series & Data Frame | <p>If we perform <code>value_counts</code> function on a column of a Data Frame, it gives us a Series which contains unique values' counts.</p>
<p>The <code>type</code> operation gives <code>pandas.core.series.Series</code> as a result. My question is that what is the basic difference between a <strong>Series</strong>... | <p>You can think of Series as a column in a DataFrame while the actual DataFrame is the table if you think of it in terms of sql</p> | python|pandas|dataframe|series | 2 |
361,020 | 59,831,211 | neighbours of a cell in matrix pytorch | <p>I am trying to get neighbours of a cell of matrix in pytorch using below part of code.
it works correctly but it is very time consumming.
Have you any suggestion to to get it faster</p>
<pre><code>def neighbour(x):
result=F.pad(input=x, pad=(1, 1, 1, 1), mode='constant', value=0)
for m in range(1,x.size(0)+... | <p>If you are only after the mean of the 9 elements centered at each pixel, then your best option would be to use a 2D convolution with a constant 3x3 filter:</p>
<pre class="lang-py prettyprint-override"><code>import torch.nn.functional as nnf
def mean_filter(x_bchw):
"""
Calculating the mean of each 3x3 neighbo... | matrix|pytorch | 3 |
361,021 | 59,889,754 | I am creating an AI Chatbot which repeatedly displays the error: Expected Bytes, descriptor found | <p>The following code is the first few steps of building a chatbot using deep learning, I have tensorflow, cUDDN, CUDA installed but it still displays the same error. I have followed the video tutorials on youtube and downloaded all packages needed over two times just to be sure but it still doesnt get out of this spec... | <p>This error seems to be TensorFlow installation issue.</p>
<p>Also, your code only reads a JSON file. If that's only what you want, you could remove import of <code>tflearn</code> & <code>tensorflow</code> packages. </p>
<p>If you want to use these packages later, then I would suggest checking your TensorFlow i... | python|visual-studio|tensorflow|deep-learning | 0 |
361,022 | 59,718,834 | Name error: Image to text error in python | <p>I am working on developing code to convert image to text using the below code. I see the below error while executing the code. I dont really understand what is causing the issue. Can any one help me to identify the issue.</p>
<pre><code>
from PIL import Image
import PIL.Image
from pytesseract import image_to_strin... | <p>The code should be like this:</p>
<pre class="lang-py prettyprint-override"><code>from PIL import Image
import pytesseract
from pytesseract import Output
img = Image.open('Sample.png')
pytesseract.pytesseract.tesseract_cmd = 'C:\AppData\Local\Tesseract-OCR\tesseract.exe'
print(pytesseract.image_to_string(img))
</... | python|pandas|spyder|python-tesseract | 0 |
361,023 | 59,849,236 | number is a string in a csv? | <p>I have just read several answers about the frequently asked error message, </p>
<p><code>TypeError: '>=' not supported between instances of 'str' and 'int</code></p>
<p>The problem is that all of them were based on the input() command. My problem is that I am trying to compare values in a csv file, as shown her... | <p>Since no one posted a separate answer, I here repost Ben Pap's comment as the answer that worked:</p>
<p>Is complete_data_pd a dataframe? and math_score a column? If so you can just do this to get your percent_math_mavens: </p>
<pre><code>len(complete_data_pd[complete_data_pd['math_score'] >= 70])/total_student... | pandas|csv|int | 0 |
361,024 | 59,795,511 | Dataframe values conditional on multiple values | <p>I have the following df in pandas:</p>
<pre><code>person year A B
AA 1998 5
AA 1999 10
AA 2000 15
XB 2010 100
CY 1980 3
CY 1981 9
CY 1982 36
CY 1983 72
MJ 2017 120
MJ 2018 240
</code></pre>
<p>I'd like to iterate over each <em>person</em> in the ... | <pre><code>dfshift = df.groupby('person')['A'].transform(lambda x: x.shift())
df['B'] = (df['A']/dfshift)*100
df['B'].fillna(0, inplace = True)
person year A B
0 AA 1998 5 0.0
1 AA 1999 10 200.0
2 AA 2000 15 150.0
3 XB 2010 100 0.0
4 CY 1980 3 0.0
5 ... | python|pandas|dataframe | 3 |
361,025 | 59,608,026 | How to export cleaned data from a jupyter notebook, not the original data | <p>I have just started to learn to use Jupyter notebook. I have a data file called 'Diseases'. </p>
<p><strong>Opening data file</strong></p>
<pre><code>import pandas as pd
df = pd.read_csv('Diseases.csv')
</code></pre>
<p><strong>Choosing data from a column named 'DIABETES', i.e choosing subject IDs that have diabe... | <p>You forget assign back filtered DataFrame, here to <code>df1</code>:</p>
<pre><code>import pandas as pd
df = pd.read_csv('Diseases.csv')
df1 = df[df.DIABETES >1]
df1.to_csv('diabetes-filtered.csv')
</code></pre>
<p>Or you can chain filtering and exporting to file:</p>
<pre><code>import pandas as pd
df = pd.r... | python|pandas|jupyter-notebook | 4 |
361,026 | 59,728,513 | pandas string values are not getting proper format | <p>Before reading into pandas my data looks like in sas dataset</p>
<pre><code>Name
Alfred
Alice
</code></pre>
<p>After reading into pandas data is getting as </p>
<pre><code>Name
b'Alfred'
b'Alice'
</code></pre>
<p>Why I am getting the data is different? Steps followed:</p>
<ol>
<li>Import pandas as pd</li>
<li... | <p>SAS files need to be imported with special encoding</p>
<pre><code>df=pd.read_sas(r'C:/ProgramData/Anaconda3/Python_local/class.sas7bdat',format='sas7bdat', encoding='iso-8859-1')
</code></pre> | python|pandas|sas | 0 |
361,027 | 59,756,532 | Reading a big csv file into dataframe | <p>I have a large csv file (of 13 GB) that I wish to read into a dataframe in Python. So I use: </p>
<pre><code>txt = pd.read_csv(r'...file.csv', sep=';', encoding="UTF-8", iterator = True, chunksize=1000)
</code></pre>
<p>It works just fine, but the data is contained in a <strong>pandas.io.parsers.TextFileReader</st... | <p>Try to take a look to this <a href="https://stackoverflow.com/questions/59730803/best-way-to-use-big-csv-file-as-lookup-to-fill-data-in-dataframe/59731587#59731587">answer</a>, in particular <a href="https://examples.dask.org/dataframes/01-data-access.html#Tuning-read_csv" rel="nofollow noreferrer">dask read_csv</a>... | pandas|csv|parsing|stringio | 0 |
361,028 | 59,504,630 | Decimal module is not working with Numpy or Scipy | <p>I want to use Decimal module.</p>
<pre><code>getcontext().prec = 3
d1 = Decimal("0.1")
a = float(0.20052)
b = str(a)
d2 = Decimal(b)
q = d1+d2
print(q) ###0.301
</code></pre>
<p>and</p>
<pre><code>getcontext().prec = 1
d1 = Decimal("0.1")
a = float(0.20052)
b = str(a)
d2 = Decimal(b)
q = d1+d2
print(q)##0.3
</cod... | <blockquote>
<p>... the result has not changed.</p>
</blockquote>
<p>There is a conceptual gap, here.</p>
<p>Changing <code>prec</code> of the current <a href="https://docs.python.org/3/library/decimal.html#decimal.getcontext" rel="nofollow noreferrer">context</a>
changes how e.g. <code>__add__( ... )</code> behave... | python-3.x|numpy|decimal | 1 |
361,029 | 59,757,561 | Efficient way to multiply each elements of numpy 1d array and 3d Array | <p>I want to multiply each elements of 1dArray and each matrices of 3dArray without <code>for</code> loop.</p>
<pre><code>arr1d2=np.array([1,2])
arr3d222=np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
# Correct Solution is below
for i1 in range(len(arr1d2)):
print(arr1d2[i1]*arr3d222[i1])
</code></pre>
<p>I try to find... | <p>You can use <code>np.newaxis</code> so that the number of dimensions match:</p>
<pre><code>arr1d2[:, np.newaxis, np.newaxis] * arr3d222
</code></pre> | python|numpy | 3 |
361,030 | 59,778,248 | modifying an ssd net in tensorflow | <p>If I were using Keras, Modifying the architecture would be straight forward modification of the network layers:</p>
<pre><code> x = Conv2D(32, (3, 3), padding="same")(inputs)
x = Activation("relu")(x)
x = Conv2D(32, (3, 3), padding="same")(x)
x = Activation("relu")(x)
x = MaxP... | <p>It looks like the actual model has been abstracted away to<br>
<a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py</a></p>
<p>Though I would ima... | tensorflow|keras|neural-network|architecture|tensorflow-ssd | 0 |
361,031 | 59,823,495 | INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, 2 root error(s) found | <p>I am trying to run a object detection model using tensorflow objection detection API. My purpose for running object detection is trying to solve captcha problem using object detection. I following the one tutorial for that.
System configuration:
virtual machine on Azure
GPU - nivida tesla k80
RAM - 56
tensorflow ver... | <p>You get this error when the tensors passed to <code>tf.concat</code> are of different dimensions. Below is the code to reproduce the error you are facing.</p>
<p><strong>Code to reproduce the error -</strong></p>
<pre><code>import tensorflow as tf
t1 = tf.constant([[1, 2, 3], [4, 5, 6]])
t2 = tf.constant([[7, 8, 9... | python|tensorflow|gpu|faster-rcnn | 0 |
361,032 | 59,882,714 | Python generating a list of dates between two dates | <p>I want to generate a list of dates between two dates and store them in a list in string format. This list is useful to compare with other dates I have. </p>
<p>My code is given below: </p>
<pre><code>from datetime import date, timedelta
sdate = date(2019,3,22) # start date
edate = date(2019,4,9) # end date
d... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="noreferrer"><code>pandas.date_range()</code></a> for this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas
pandas.date_range(sdate,edate-timedelta(days=1),freq='d')
</code></pre>
<hr />
<pre... | python|pandas|dataframe | 94 |
361,033 | 59,493,445 | How can I punish certain outputs more than others in a keras model? | <p>I have a keras model with multiple (8) output neurons, that all go through a softmax activation function. My dataset, which consists of around 300.000 datapoints, is however largely filled with data where just having the first output neuron at 1 and all the others at 0 allows the neural network to score a high accur... | <p>In the <code>fit</code> method, there is a <code>class_weight</code> parameter used to give weights to each class (output neuron). </p>
<p>So, use it. Read the <a href="https://keras.io/models/sequential/" rel="nofollow noreferrer">documentation</a></p>
<blockquote>
<p><strong>class_weight:</strong> Optional dic... | python|tensorflow|keras|neural-network | 4 |
361,034 | 59,699,835 | Histogram Correlation Specific Column | <p>I have a csv file that has 36 columns, I wanted to keep one column constant and find the histogram correlation between it and the rest of the 35 columns remaining but I could not figure out how to choose that individual column</p>
<p>I have made a prototype csv file that consists of 4 columns and 4 rows.
<a href="h... | <p>According to the the documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html" rel="nofollow noreferrer"><code>corr</code></a>:</p>
<p>The returned df is a correlation matrix. You have to select specific rows & columns to visualize.</p>
<p>So, by updating... | python|pandas|jupyter-notebook|anaconda|correlation | 1 |
361,035 | 59,550,221 | output and feeb_dict inside session FailedPreconditionError (see above for traceback): Attempting to use uninitialized value | <p>I am converting the <a href="https://github.com/AITTSMD/MTCNN-Tensorflow" rel="nofollow noreferrer">MTCNN tensorflow</a> into tensorflow tensorRT</p>
<p>When I run <a href="https://github.com/AITTSMD/MTCNN-Tensorflow/blob/master/test/camera_test.py" rel="nofollow noreferrer">camera_test.py</a></p>
<p>I get this er... | <p>Just after <a href="https://github.com/AITTSMD/MTCNN-Tensorflow/blob/master/Detection/detector.py?#L65" rel="nofollow noreferrer">the following line</a></p>
<pre class="lang-py prettyprint-override"><code>self.sess = tf.Session( config=tf.ConfigProto(allow_soft_placement=True, gpu_options=tf.GPUOptions(allow_growth... | python-3.x|tensorflow|tensorrt | 1 |
361,036 | 59,868,887 | IndexError: Invalid Index for Scalar Variable NumPy | <p>So I tried to convert an image to an array with PIL and NumPy. Then I tried to iterate through a file and get all the images from it and then see how many red, green and blue pixels it has to see what is the main color of the image and I tried this:</p>
<pre><code>import numpy as np
import os
import time
from PIL i... | <p>So to summarize it in an answer:
With the following code I have no problem running it:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import os
import time
from PIL import Image
def load_image(image: str):
img = Image.open(image)
img.load()
return img
def image_to_array(image... | python|arrays|numpy|python-imaging-library|index-error | 0 |
361,037 | 32,159,869 | How to make user defined functions for binned_statistic | <p>I am using scipy stats package to take statistics along the an axis, but I am having trouble taking the percentile statistic using <code>binned_statistic</code>. I have generalized the code below, where I am trying taking the 10th percentile of a dataset with x, y values within a series of x bins, and it fails.</p>... | <p>The problem with the function you defined is that it takes no arguments at all! It needs to take a <code>y</code> argument that corresponds to your sample, like this:</p>
<pre><code>def percentile10(y):
return(np.percentile(y,10))
</code></pre>
<p>You could also use a <code>lambda</code> function for brevity:</... | python|numpy|statistics|scipy | 9 |
361,038 | 32,149,739 | TypeError: cannot concatenate a non-NDFrame object, when time series mungling | <p>Have a time series ts (dataframe.to_dict())</p>
<pre><code>{'latitude': {Timestamp('2014-10-20 15:21:56.571000'): 48.145553900000003,
Timestamp('2014-10-20 15:24:00.789000'): 48.145584300000003,
Timestamp('2014-10-20 15:26:00.911000'): 48.145497599999999,
Timestamp('2014-10-20 15:33:57.764000'): 48.1455486999... | <p>I think you want to <code>agg</code> (aggregate), not <code>apply</code>, as for each of your group, you want 1 returning value:</p>
<pre><code>In [185]:
print ts.groupby(pd.TimeGrouper(freq='10Min')).agg(my_func)
latitude longitude speed
2014-10-20 15:20:00 36.567360 36.567360 36.56... | python|pandas | 2 |
361,039 | 32,247,922 | How do I find the region borders in an image using python? | <p>So I have two numpy arrays- the first is a 3D RGB image. The second is a 2D grid representing the regions in the image (my images generally have around 7 to 20 regions) where each region is represented by an integer.</p>
<p>The the 2D grid looks something like this:</p>
<pre><code>[
[0,0,0,1],
[0,0,1,1],
[2,2,2,... | <p>Talking about the algorithm you can use to detect boundaries between regions pro grammatically
You can use any of the edge detector kernels and apply them on your 2d grid to detect differences horizontally or vertically if the outcome is zero then both pixels belong to the same region if the answer is non-zero then ... | python|image|numpy|boundary | 2 |
361,040 | 32,587,183 | Collapsing entries with duplicate index values in DataFrame | <pre><code>import pandas as pd
bids = [100, 101, 101, 102]
offers = [101, 102, 102.25, 103]
data = {'bids': bids, 'offers': offers}
index = [0, 1, 1, 2]
df = pd.DataFrame(data=data, index=index)
print df
bids offers
0 100 101.00
1 101 102.00
1 101 102.25
2 102 103.00
</code></pre>
<p>How can I reindex... | <p>You can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html#pandas.DataFrame.reset_index" rel="nofollow"><code>reset_index</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html#pandas.DataFrame.drop_d... | python|pandas | 2 |
361,041 | 32,337,380 | Count data types in pandas dataframe | <p>I have <code>pandas.DataFrame</code> with too much number of columns.</p>
<p>I call:</p>
<pre><code>In [2]: X.dtypes
Out[2]: VAR_0001 object
VAR_0002 int64
...
VAR_5000 int64
VAR_5001 int64
</code></pre>
<p>And I can't understand what types of data I... | <p>To answer your first question do the following:</p>
<pre><code>df.dtypes.value_counts()
</code></pre>
<p>Example:</p>
<pre><code>In [4]:
df = pd.DataFrame({'a':[0], 'b':['asds'], 'c':[0]})
df.dtypes
Out[4]:
a int64
b object
c int64
dtype: object
In [5]:
df.dtypes.value_counts()
Out[5]:
int64 2
ob... | python|pandas | 24 |
361,042 | 32,375,885 | Altering a global var within function - more specifically a pandas series | <p>thanks in advance to anyone looking to enlighten me here a little bit since I have been struggling for a solid couple of hours :-(</p>
<pre><code>def pullQueue(eventQueue, barLength):
# Setting start and End times for extractions
startExtract = dt.time(8, 00, 00, 0)
endExtract = dt.time(22, 00, 00, 0)
... | <p>The method pandas.Series.append doesn't change the original series in-place, it returns a new series, so all you need to do is:</p>
<p><code>ts = ts.append(pd.Series([event.ask], index=[event.time]))</code></p> | python|pandas|while-loop | 1 |
361,043 | 40,569,538 | Find max value and the corresponding column/index name in entire dataframe | <p>I want to select the maximum value in a dataframe, and then find out the index and the column name of that value.
Is there a way to do it?</p>
<p>Say, in the example below, I want to first find the max value (<code>31</code>), and then return the index and column name of that value <code>(20, R20D)</code></p>
<pre... | <p>If you call <code>a.max(axis=0)</code> you get a series of the max on each column:</p>
<pre><code>R05D 3
R10D 7
R20D 31
dtype: int64
</code></pre>
<p>If you call <code>max</code> on that series you get it's maximum so:</p>
<pre><code>a.max(axis=0).max()
#31
</code></pre>
<p>gives you the maximum value... | python|pandas|dataframe|max | 9 |
361,044 | 40,506,390 | Pandas - 'Series' object has no attribute | <p>I need to use a lambda function to do a row by row computation. For example create some dataframe</p>
<pre><code>import pandas as pd
import numpy as np
def myfunc(x, y):
return x + y
colNames = ['A', 'B']
data = np.array([np.arange(10)]*2).T
df = pd.DataFrame(data, index=range(0, 10), columns=colNames)
</code... | <p>When you use <code>df.apply()</code>, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using <code>series[label]</code>.</p>
<p>So this should work:</p>
<pre><code>df['D'] = (df.apply(lambda x: m... | python|pandas | 25 |
361,045 | 40,481,606 | How to prevent pandas dataframe to shirk string value to [...] after appending ? | <p>I use list of list to create dataframe in short with this code below, but I got result of df with <code>"..."</code> value after put the value in dataframe for example : </p>
<p><a href="http://shakespeare.mit.edu/allswell/allswell.1" rel="nofollow noreferrer">http://shakespeare.mit.edu/allswell/allswell.1</a>...</... | <p>It is only display problem. You need <code>display.max_colwidth</code> set to some higher <code>int</code>, e.g. <code>100</code>, see <a href="http://pandas.pydata.org/pandas-docs/stable/options.html#available" rel="nofollow noreferrer"><code>available options</code></a>:</p>
<pre><code>#temporaly set max_colwidth... | python|string|pandas|dataframe|truncate | 2 |
361,046 | 40,749,442 | Add matrices with different labels and different dimensions | <p>I have two large square matrices ( in two CSV files). The two matrices may have a few different labels and different dimensions.
I want to add these two matrices and retain all labels. How do I do this in python?</p>
<p>Example:</p>
<p>{a, b, c ... e} are labels. </p>
<pre><code> a b c d ... | <p>use the <code>add</code> method with the parameter <code>fill_value=0</code></p>
<pre><code>X.add(Y, fill_value=0).fillna(0)
</code></pre>
<p><a href="https://i.stack.imgur.com/9o7gS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9o7gS.png" alt="enter image description here"></a></p> | python|pandas|matrix | 1 |
361,047 | 40,498,532 | Tensorflow efficient per-pixel gradient computation | <p>I'm reimplementing the paper <a href="https://arxiv.org/pdf/1603.06041v2.pdf" rel="nofollow noreferrer" title="Learning Image Matching by Simply Watching Video">Learning Image Matching by Simply Watching Video</a> using tensorflow and I'm facing some serious performance issues when grabbing the gradients from the ne... | <p>Here are my ideas:</p>
<ol>
<li>Try to visualize the learning graph, e.g. through <a href="https://www.tensorflow.org/versions/r0.11/how_tos/graph_viz/index.html" rel="nofollow noreferrer">tensorboard</a> and <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/train.html#SummaryWriter" rel="nofollow ... | python|tensorflow|deep-learning|gradient | 0 |
361,048 | 40,347,592 | Can we see the Send nodes and the Receive nodes in the tensorflow GraphDef? | <p>Can we see the <em>Send</em> nodes and the <em>Receive</em> nodes in the tensorflow GraphDef, or by using python API?</p>
<p>I try the following code</p>
<pre><code>import tensorflow as tf
with tf.device("/gpu:0"):
x = tf.constant(1.0)
with tf.device("/gpu:1"):
y = tf.constant(2.0)
with tf.device("/cpu:0"... | <p>The send and recv nodes are only added to the graph on the first time you try to execute the graph, in a call to <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/client.html#Session.run" rel="nofollow noreferrer"><code>tf.Session.run()</code></a>... and, indeed, the set of send and recv nodes that ... | python|tensorflow | 4 |
361,049 | 40,545,302 | Use Tensorflow trained models as a service | <p>I just started with tensorflow. I was able to successfully train it for a data set that I created. Now the question is that how will I be able to use this model to make predictions. I want to make it as a REST service, to which I will be able to pass some values and get the predictions as response. Any helpful links... | <p>Have you seen Cloud ML on GCP? It might be exactly what you're looking for.<br>
<a href="https://cloud.google.com/ml/" rel="nofollow noreferrer">https://cloud.google.com/ml/</a></p>
<p>You might need to make a few tweaks to the architecture of your model - like variable batch sizes and adding inputs/outputs to coll... | google-app-engine|tensorflow|tensorflow-serving | 2 |
361,050 | 40,619,429 | How to avoid slow for(): loops, when using Pandas dataframe? | <pre><code>for i in range( 1, len( df ) ):
if df.loc[i]["identification"] == df.loc[i-1]["identification"] and df.loc[i]["date"] == df.loc[i-1]["date"]:
df.loc[i,"duplicate"] = 1
else:
df.loc[i,"duplicate"] = 0
</code></pre>
<p>This simple for loop runs really slow when processing a dataframe of ... | <p>Try to use a vectorized approach instead of looping:</p>
<pre><code>df['duplicate'] = np.where((df.identification == df.identification.shift())
&
(df.date == df.date.shift()),
1,0)
</code></pre> | python|loops|pandas|for-loop | 3 |
361,051 | 40,621,240 | GPU + CPU Tensorflow Training | <p><strong>Setup</strong></p>
<hr>
<p>I have a network, one whose parameter is a <strong>large-embedding matrix (3Million X 300 sized)</strong>, say embed_mat. </p>
<p>During training, for each mini-batch, I only update a <strong>small subset</strong> of the vectors from embed_mat (max 15000 vectors) which are chose... | <p>Try visualizing on tensorboard where each of your ops is placed. In the "graph" tab you can color by "device". Ideally the embedding variable, the embedding lookup, and the embedding gradient update should be in the CPU, while most other things should be in the GPU.</p> | tensorflow | 1 |
361,052 | 40,738,934 | Pandas 0.19: Attribute error "unknown property color_cycle" still exists while performing boxplot | <p>Unlike what has been said <a href="https://stackoverflow.com/questions/33995707/attributeerror-unknown-property-color-cycle">here</a>, the <code>AttributeError: Unknown property color_cycle</code> is still persistent in the newest Pandas version (<code>0.19.0-1</code>).</p>
<p>In my case, I have a dataframe similar... | <p>I've verified myself that one needs to have <code>pandas 0.19.0-1</code> <strong>together</strong> with <code>matplotlib 1.5.1-8</code> to not experience this error.</p> | python|pandas|boxplot|attributeerror | 1 |
361,053 | 40,612,804 | Subtract multiple columns based on foreign key in pandas | <p>I'm trying to calculate the difference between an object and it's benchmark. I have a dataset containing daily records for all of the objects and their corresponding values that looks like this:</p>
<pre><code>obj_df
date id value_a value_b value_c value_d benchmark_id
01/21/2015 abc 10 41 ... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>sub</code></a>, then add columns <code>id</code> and <code>benchmark_id</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofol... | python|pandas | 4 |
361,054 | 40,538,337 | Python: print dictionary to csv, each key value in a new line | <p>I have the following data</p>
<pre><code>{'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
</code></pre>
<p>and I want to print it to a csv file as following:</p>
<pre><code>index similar markets
1 [0,2] ['A','C']
2 [1,2] ['B','C']
3 ... | <pre><code>import csv
a = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
keys = ['index', 'similar', 'markets']
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.writer(f)
w.writerow(keys)
w.writerows(zip(*[a[key] for key... | python|python-2.7|pandas | 4 |
361,055 | 40,642,018 | How can I define a custom kernel function for sklearn.svm.SVC? | <p>I am trying to make a stock prediction system in Python using scikit-learn. Here is my code:</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from sklearn import svm,preprocessing
from sk... | <p>You need to pass the kernel function itself as the <code>kernel=</code> parameter rather than just the function name, i.e.:</p>
<pre><code>clf = svm.SVC(kernel=mykernel)
</code></pre>
<p>rather than</p>
<pre><code>clf = svm.SVC(kernel="mykernel")
</code></pre> | numpy|machine-learning|scikit-learn|svm | 4 |
361,056 | 40,676,205 | cross platform numpy.random.seed() | <p>The <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html#numpy.random.RandomState" rel="noreferrer">docs</a> say:</p>
<blockquote>
<p>Compatibility Guarantee A fixed seed and a fixed series of calls to
‘RandomState’ methods using the same parameters will always produce
t... | <p>As per sascha’s comment, random numbers are platform independent.</p> | python|linux|windows|numpy|random | 4 |
361,057 | 40,667,736 | Calculate chi-sqaure between pairs of columns | <p>I am wanting to calculate a chi-squared test statistic between pairs of columns in a pandas dataframe. It seems like there must be a way to do this in a similar fashion to <code>pandas.corr</code></p>
<p>if I have the following data frame</p>
<pre><code>df = pd.DataFrame([['a', 'x', 'a'],
['b',... | <h1>Alternate Method 1</h1>
<p>Another way to find chi-squared test statistic between pairs of columns along with heatmap visualisation:</p>
<pre><code>def ch_calculate(df):
factors_paired = [(i,j) for i in df.columns.values for j in df.columns.values]
chi2, p_values =[], []
for f in factors_paired:
... | python|pandas|scipy | 0 |
361,058 | 40,338,152 | numpy: detect consecutive 1 in an array | <p>I want to detect consecutive spans of 1's in a numpy array. Indeed, I want to first identify whether the element in an array is in a span of a least three 1's. For example, we have the following array a:</p>
<pre><code> import numpy as np
a = np.array([1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1,... | <p>We could solve it with a combination of <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_dilation.html" rel="nofollow"><code>binary dilation</code></a> and <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_erosion.... | python|arrays|numpy | 2 |
361,059 | 18,595,583 | numpy on cluster via ssh | <p>For my studies I have to use a cluster to which I am logged on via SSH. I want to use a python script using numpy modules. Unfortunately the numpy version seems to be to old and doesn't include all needed modules. How can I get access to a newer numpy without sudo rights? </p> | <p>If <code>pip</code> is installed on the cluster, then just install numpy under your home directory on the cluster:</p>
<pre><code>pip install --user numpy
</code></pre> | python|numpy|ssh|cluster-computing | 1 |
361,060 | 18,341,851 | Cleaner way to store store data using dictionary | <p>I am wondering if there is a cleaner way to store the follwoing:</p>
<pre><code>arr1 = arr[arr1inds]
arr2 = arr[arr2inds]
arr3 = arr[arr3inds]
arr4 = arr[arr4inds]
arr5 = arr[arr5inds]
arr6 = arr[arr6inds]
arr7 = arr[arr7inds]
</code></pre> | <p>Go two-dimensional:</p>
<pre><code>arr2d = []
arr2d[1] = arr[arr1inds]
arr2d[2] = arr[arr2inds]
arr2d[3] = arr[arr3inds]
...
</code></pre> | python|numpy | 1 |
361,061 | 18,743,397 | Python Numpy : np.int32 "slower" than np.float64 | <p>I would like to understand a strange behavior of python.
Let us consider a matrix <code>M</code>with shape <code>6000 x 2000</code>. This matrix is filled with signed integers. I want to compute <code>np.transpose(M)*M</code>. Two options:</p>
<ul>
<li>When I do it "naturally" (i.e. without specifying any typing), ... | <p>No, integer multiplies aren't cheaper. But more on that later.
Most likely (I am 99% sure) <code>numpy</code> calls <code>BLAS</code> routine under blankets, which can be as efficient as 90% of peak CPU performance. There aren't special provisions for <code>int</code> matrix multiplies, most likely it is done in P... | python|numpy|floating-point|int32 | 7 |
361,062 | 18,457,333 | How do I interate through a paired list when using map and lambda? | <p>I'm stuck on how to iterate through a paired list while i'm using the map and lambda functions. I want to create a series of histograms based on a central location and the distances of selected locations (x,y) to the center and the number of times a particular distance appears, but I keep getting an index out of r... | <p>Came up with this:</p>
<pre><code>def detect_peaks(arrayfinal):
average=numpy.average(arrayfinal)
local_max = arrayfinal > average
return local_max
def dist(distances, center, n):
distance=numpy.linalg.norm(n-center)
distances.append(distance)
def histotest():
peaks = numpy.where(detect_pe... | python|map|numpy|lambda | 0 |
361,063 | 18,727,600 | Writing .npy (numpy binary format) from java | <p>Is there a library to create npy file in java?</p>
<p>I'm looking for a method to write large matrices in java, to be read using python code.</p>
<p>npy seems like a good option, as it doesn't add additional dependencies in the python side, and the format is documented.</p>
<p>I considered hdf5 format, but the de... | <p>We've encountered the same problem a while ago and implemented both NPY and <a href="http://docs.scipy.org/doc/numpy/neps/npy-format.html#conventions" rel="noreferrer">NPZ</a> formats in Kotlin as part of the <a href="https://github.com/JetBrains-Research/npy" rel="noreferrer"><code>npy</code></a> library.</p>
<p>T... | java|python|serialization|numpy | 10 |
361,064 | 61,825,870 | load model.json for tensorflowjs in reactjs not working | <p>I'm trying to load a model.json file with it's weights.bin from the root directory in my react app.</p>
<p>When I call an example I found online from storage.googleapis.com it works but loading from my root doesn't. </p>
<p>The contents of App.js in my react app...</p>
<pre><code>import React from "react";
import... | <p>The file URI scheme <code>file://url</code> is only for loading model server side. To load the model in the browser, the user can be prompted to select the model topology(model.json) and weight files. The <a href="https://js.tensorflow.org/api/latest/#loadLayersModel" rel="nofollow noreferrer">doc</a> contains an ex... | javascript|reactjs|tensorflow.js | 3 |
361,065 | 61,947,237 | Broadcasting with ragged tensor | <p>Define <code>x</code> as:</p>
<pre><code>>>> import tensorflow as tf
>>> x = tf.constant([1, 2, 3])
</code></pre>
<p>Why does this normal tensor multiplication work fine with broacasting:</p>
<pre><code>>>> tf.constant([[1, 2, 3], [4, 5, 6]]) * tf.expand_dims(x, axis=0)
<tf.Tensor: s... | <p>The problem will be resolved if you add <code>ragged_rank=0</code> to the Ragged Tensor, as shown below:</p>
<pre><code>tf.ragged.constant([[1, 2, 3], [4, 5, 6]], ragged_rank=0) * tf.expand_dims(x, axis=0)
</code></pre>
<p>Complete working code is:</p>
<pre><code>%tensorflow_version 2.x
import tensorflow as tf
x... | python|tensorflow|array-broadcasting|ragged | 1 |
361,066 | 61,924,147 | How do I add two new columns on the basis of the values of multiple other columns in a pandas dataframe? | <p>I am trying to add two columns to an existing dataframe based on the values of a few other columns. My dataframe looks like this:</p>
<p><code>df = pd.DataFrame({'Type':['A', 'A', 'A', 'B','',''], 'Type1':['A', 'A', '', 'B','',''], 'Type2':['A','B','B','B','A',''], 'Score':[1, 2, 3, 1, 0 ,0], 'Score1':[2, 1, 0, 1, ... | <pre><code>m1 = (df[['Type', 'Type1', 'Type2']] == 'A')
m2 = (df[['Type', 'Type1', 'Type2']] == 'B')
scores = df[['Score', 'Score1', 'Score2']]
df['Score_A'] = pd.DataFrame(np.where(m1, scores, np.nan)).mean(skipna=True, axis=1).fillna(0)
df['Score_B'] = pd.DataFrame(np.where(m2, scores, np.nan)).mean(skipna=True, axi... | python|pandas|dataframe | 2 |
361,067 | 61,710,810 | Getting error while replacing "NaN" values using 'SimpleImputer' | <p>I have tried every way of replacing these values but failed!
I'm performing this on the famous 'Titanic' dataset!
Here's a glimpse of the data:</p>
<pre><code>Survived Pclass Sex Age SibSp Fare Embarked
0 0 3 male 22.0 1 7.2500 S
1 1 1 female 38.0 1 71.2833 C
2 1 3 female ... | <p>The problem is pretty simple, the <code>transform</code> function takes 2D matrix. So, all you have to do is put square brackets on <code>stats["Age"]</code> when using <code>transform</code> just like so:</p>
<pre><code>imputer.transform([ stats['Age'] ])
</code></pre>
<p>Also, I suggest using <code>fit_transform... | python|python-3.x|pandas|dataframe | 0 |
361,068 | 61,963,181 | Replacing only some rows in the same column | <p>Given a column:</p>
<pre><code>name
Jules
Jules
Jules
Jules
Vince
</code></pre>
<p>I need to replace only the top-half of ocurrences of <code>Jules</code> for <code>Quentin</code></p>
<p>Such as:</p>
<pre><code>name
Quentin
Quentin
Jules
Jules
Vince
</code></pre>
<p>How do I replace only some values in a give... | <p>It is rather straightforward:</p>
<pre><code># where name is Jules
is_jules = df['name'].eq('Jules')
# total `Jules` in `name`
num_jules = is_jules.sum()
# first half `Jules`
first_half = is_jules.cumsum().le(num_jules//2)
df.loc[is_jules & first_half, 'name'] = 'Quentin'
</code></pre>
<p>Output:</p>
<pre>... | python|pandas|dataframe | 1 |
361,069 | 61,619,101 | How to create a column that has the same value per group in Python Pandas? | <p>I currently have a Pandas Dataframe with lots of stock tickers in my first column. They are time series so each Tickers appears more than once. In my second column I have a CUSIP code, but this code only appears in the row where the ticker appears first, all the next rows do not contain this CUSIP code. I would like... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html#pandas-dataframe-ffill" rel="nofollow noreferrer"><code>ffill</code></a> - To fill NA/NaN values using the specified forward method.</p>
<pre><code>>>> df.ffill()
0 1 2 ... | python|pandas|pandas-groupby | 0 |
361,070 | 61,817,896 | Fill panda columns with conditions | <p>I'm trying to fill a column C with conditions: if the value of column B is None, then fill column C with the value of column A. If column B is not None, then fill column C with the value 3</p>
<p><strong>I tried:</strong></p>
<pre><code>import pandas
df = pandas.DataFrame([{'A': 5, 'B': None, 'C': ''},
... | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with test <code>None</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>Series.isna</code></a>:</p... | python|pandas | 3 |
361,071 | 61,659,698 | How to view the total unqiue values for each cloumns if total unique value is less than a specific no. in my dataset | <p>i am working on Heart Disease Prediction data and i want to know the unqiue values for each column</p>
<p>first i took total unique feature in my data is </p>
<pre><code>framinghamDF.nunique()
output-
male 2
age 39
education 4
currentSmoker 2
cigsPerDay ... | <p>Filter index values of <code>Series</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>s = framinghamDF.nunique()
out = s.index[s < 4].tolist()
#alternative
out = s[s < 4].index.... | pandas | 1 |
361,072 | 61,901,128 | Calculate length of list pandas dataframe where cell value is a list | <p>Given such a data frame df:</p>
<pre><code>id elements
1 Ba, Ca
2 Th
3 Ag, Au, Ca, Mg, V
4 Au, Ca
</code></pre>
<p>I would like to calculate a column that has the number of items in the elements list. For example:</p>
<pre><code>id elements count
1 Ba, Ca 2
2 ... | <p>Let us try <code>count</code> the sep </p>
<pre><code>df['ct']=df.elements.str.count(',')+1
</code></pre> | python|pandas | 1 |
361,073 | 61,801,384 | Keep maximum value per group including repetitions | <p>Let's say I have a dataframe like this:</p>
<pre><code> a b c
0 x1 y1 9
1 x1 y2 9
2 x1 y3 4
3 x2 y4 2
4 x2 y5 10
5 x2 y6 5
6 x3 y7 6
7 x3 y8 4
8 x3 y9 8
9 x4 y10 11
10 x4 y11 11
11 x4 y12 11
</code></pre>
<p>I first want to do a grouped sort of column <code>c</code... | <p>You could <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> column <code>a</code> and find the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.max.html" rel="nofollow no... | python|pandas | 5 |
361,074 | 61,857,713 | Weighted time aggregation of pandas dataframe defined by two categorical columns | <p>Consider the following dataframe of time series data about the daily production of three factories : f1, f2 and f3 of a company that only has two products: A and B. Missing data about a factory on a given day for a given product should be considered as a 0.</p>
<pre><code>import datetime
d = {
1: {'date': datet... | <p>From what you have, you can unstack the factory and products to get those 0s to populate. You should also probably do a resample in case there are days where no products are made (I changed the Jan 4 to Jan 6 in this example):</p>
<pre><code>df2 = dff.groupby(['date','Factory','Product']).sum().unstack([1,2], fill_... | python|pandas|aggregate | 3 |
361,075 | 61,728,969 | pandas groupby, difference between top and bottom group members | <p>Assume I have <code>df</code>:</p>
<pre><code>df = pd.DataFrame({'ID': ['a', 'b', 'b', 'b', 'c', 'c'],
'V1': [1,2,3,4,5,6],
'V2': [7,8,9,19,11,12]})
</code></pre>
<p>I want to create a new column <code>V3</code>, indicating the difference between <code>V2</code> for the "top" gr... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <code>first</code> and <code>last</code> and subtract by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Serie... | python|pandas|dataframe|group-by | 3 |
361,076 | 61,933,897 | pandas : an array of Series by reducing a large Serie | <p>I've got one Serie of int, like this one :</p>
<pre><code>ages = pd.DataFrame(np.array([100, 107,99,98,65,45,32,18,66,69, 74,83,81,67, 101, 94, 52,90]), columns=["age"])
</code></pre>
<p>My goal is create several Series in an array. Each serie should include only the values in an interval.</p>
<p>For example, arr... | <p>One way to solve this is <code>pd.cut</code> and <code>groupby()</code>:</p>
<pre><code>bins = pd.cut(ages['age'], bins=range(0,100))
for r, d in ages.groupby(bins)['age']:
print(r)
print(d)
</code></pre> | python|arrays|pandas|numpy | 1 |
361,077 | 62,019,212 | Tensorflow input pipeline using text | <p>in the last weeks I tried to get the input pipeline running with tf.records under tensorflow (tf 2.0.1). From a CSV sentences are loaded and a record is generated:</p>
<pre><code>import tensorflow as tf
import pathlib
import sys
import csv
PATH_PARENT = str(pathlib.Path(__file__).parent.absolute())
if PATH_PARENT.... | <p>You get this error in tensorflow version <code>2.0.1</code> when you don't pass the <code>labels</code> in your data. In the below example, I am writing dummy <code>Input</code> values using <code>TFRecordWriter</code> and later reading it using <code>TFRecordDataset</code> and passing it to the model. </p>
<p>If y... | python|tensorflow|keras | 1 |
361,078 | 61,713,271 | pandas groupBy dataframe with original indexes from dataframe preserved | <p>Input:</p>
<pre><code>import pandas as pd
data = [['Delhi', 'A', 10], ['Delhi', 'B', 12], ['Delhi', 'C', 9], ['Delhi', 'D', 11], ['Mumbai', 'A', 21], ['Mumbai', 'B', 13], ['Mumbai', 'C', 19], ['Mumbai', 'D', 23]]
df = pd.DataFrame(data, columns = ['Name', 'Group', 'Val'])
df
Out[4]:
Name Group Val
0 Delh... | <p>Try this :</p>
<pre><code>df.loc[df.groupby('Name').Val.idxmax(),['Name','Val']]
Name Val
1 Delhi 12
7 Mumbai 23
</code></pre> | python|pandas|dataframe|pandas-groupby | 3 |
361,079 | 61,914,413 | How does BatchNormalization work on an example? | <p>I am trying to understand batchnorm.
My humble example</p>
<pre><code>layer1 = tf.keras.layers.BatchNormalization(scale=False, center=False)
x = np.array([[3.,4.]])
out = layer1(x)
print(out)
</code></pre>
<p>Prints</p>
<pre><code>tf.Tensor([[2.99850112 3.9980015 ]], shape=(1, 2), dtype=float64)
</code></pre>
<... | <p>Two problems here.</p>
<p>First, batch norm has two "modes": Training, where normalization is done via the batch statistics, and inference, where normalization is done via "population statistics" that are collected from batches during training. Per default, keras layers/models function in inference mode, and you ne... | tensorflow|machine-learning|neural-network|batch-normalization | 1 |
361,080 | 62,003,480 | Python Numpy - Aggregate numpy array for multiple groups | <p>I have an array like this:</p>
<pre><code>([(1, 1, 10),
(1, 1, 20),
(1, 2, 10),
(2, 1, 30),
(2, 1, 40),
(2, 2, 20)],
dtype=[('id', '<i8'), ('group', '<i8'), ('age', '<i8')])
</code></pre>
<p>And I would like to aggregate this array, grouped bu 'id' and 'age', getting the mean for age. </p>
<p... | <p>You can divide your bincount with weights to bincount without weights to get means.</p>
<pre><code>import numpy as np
a = np.array([(1, 1, 10),
(1, 1, 20),
(1, 2, 10),
(2, 1, 30),
(2, 1, 40),
(2, 2, 20)],
dtype=[('id', '<i8'), ('group', '<i8'), ('age', '<i8')])
ans, indices = np.unique(a[['i... | python|numpy|aggregate|grouping | 2 |
361,081 | 61,978,195 | Pandas html to df - commas in numbers | <p>I'm newbie in Python. I need to download some tables from Polish language webpages.
I have problem with commas in numbers because it seems that Pandas delete them?
For example:</p>
<pre><code>import pandas as pd
x = pd.read_html('https://www.gpw.pl/wskazniki', encoding='utf-8', decimal=",")[1]
</code></pre>
<p>Th... | <p>The issue is with the thousands separator, which also defaults to common. </p>
<p>To read the data and parse it correctly, use: </p>
<pre><code>pd.read_html('https://www.gpw.pl/wskazniki',encoding = 'utf-8', decimal=',', thousands='.')[1]
</code></pre>
<p>The result is:
<a href="https://i.stack.imgur.com/2AP8v.p... | python|pandas|dataframe | 2 |
361,082 | 61,900,138 | PyTorch "Caught IndexError in DataLoader worker process 0", "IndexError: too many indices for array" | <p>I am trying to implement a detection model based on "finetuning object detection" official tutorial of PyTorch.
It seemed to have worked with minimal data, (for 10 of images). However I uploaded my whole dataset to Drive and checked the index-data-label correspondences. There are not unmatching items in my setup, I... | <p>I faced the same issue while trying training on Dataset of length 785 with corresponding Dataloader with batch size of 8.</p>
<p>Making Dataset length divisible by the batch size <strong>solved</strong> the issue</p> | python|machine-learning|deep-learning|pytorch | 6 |
361,083 | 61,699,826 | delete row from one dataframe and append it to another of same number of columns | <p>This seems like a simple question but i can't figure it out
how to remove lines from one data frame and add them to another with simple numeric indexing:</p>
<pre><code>do with iter 1, 2, ...
from: --------------
>>> df2 = pd.DataFrame([[5, 6], [7, 8], [9,10]])
>>> df2
0 1
0 5 6
1 7 8
2... | <pre><code>rows = data.iloc[0:3, :] # Select rows from 0 to 3
data = data.drop([0,1,2], axis=0) # delete rows 0 to 3 here axis=0 is for rows
temp = pd.DataFrame(rows, columns=list(...)) #create new df with selected rows
data2.append(temp) # append new df to second df
</code></pre>
<p>Hope this helps. Please refer t... | python|pandas|dataframe | 2 |
361,084 | 62,029,506 | Problem with Friends of Tracking Code NOOB [PYTHON] | <p>I am learning with python code and I have some issues:</p>
<p><a href="https://github.com/Slothfulwave612/Football-Analytics-Using-Python/blob/master/03.%20Analyzing%20Event%20Data/pass_map.py" rel="nofollow noreferrer">https://github.com/Slothfulwave612/Football-Analytics-Using-Python/blob/master/03.%20Analyzing%2... | <p>So it's combining all the matches onto 1 because the figure is "drawing" on top of the previous one. There's a few other things you need to change too.</p>
<ol>
<li>The away team will not always be Real Madrid, so make that dynamic</li>
<li>Adjust that in the figure text text so it's not always "<code>vs. Real Madr... | python|pandas|dataframe | 0 |
361,085 | 61,876,751 | How to sum values associates to categories from different dataframes using python/pandas? | <p>I am new to python and I have a simple problem, I guess</p>
<pre><code>+---------------------------+-------+
| Dataframe 1 | |
+---------------------------+-------+
| Category | Value |
| A | 1 |
| B | 10 |
+-------------+... | <p>Try this:</p>
<pre><code>pd.concat([df1,df2]).groupby('category').sum()
</code></pre>
<p>Output:</p>
<pre><code> value
category
A 2
B 5
C 10
</code></pre> | python|pandas|numpy | 2 |
361,086 | 61,976,215 | Text recognition with tensorfow | <p>I'm new to tensorflow and played around with the hand written numbers MNIST set.
I'd like to do my own project that recognises text instead of numbers but can't find a good tutorial.</p>
<p>Is it the same principle as numbers but instead of 10 layers at the end I have to use 26? Or include upper and lowercase and s... | <p>You're looking for an OCR model, a simple CNN can't detect text from scanned images, you need to segment them first which can be completed based on the language script.</p>
<p>You can start with <code>tesseract</code>. There is a python wrapper named pytesseract.</p>
<pre><code>import pytesseract
from PIL import I... | tensorflow|keras|ocr | 1 |
361,087 | 61,774,167 | Summing up column values in python using pandas library | <pre><code>a b
1 5
1 1
2 4
1 3
2 1
</code></pre>
<p>I want to sum up 1's in <code>a</code> column and 1's in <code>b</code> column and use this sum as number of size in bubble plot. How should I do it? Numbers are in range 1-5 and I have to do it for all possibilities for ex. 1,1 1,2 1,3 1,4 1,5 and d... | <p>If you want to know how many rows are 1,1; how many are 1,2; ...; how many are 5,5, then groupby is going to be your friend.</p>
<pre class="lang-py prettyprint-override"><code>df.groupby(['a','b']).count()
</code></pre> | python|pandas|matplotlib | 1 |
361,088 | 61,945,518 | Remove all whitespace in the header of a dataframe in pandas | <p>I have the following dataframe:</p>
<pre><code> eff, par 0, par 1, par 2, par 3, par 4, par 5, par 6, par 7, par 8, par 9, par10, par11, par12, par13, par14
-0.133,0.989,0.554,5.524, NaN,0.000,0.702,0.... | <p>You can use rename:</p>
<pre><code>df.rename(columns=lambda x: x.strip())
</code></pre> | python|string|pandas|header|whitespace | 3 |
361,089 | 61,610,792 | Combinations of a dataframe column and index | <p>So I have a dataframe with a list of particle trajectories with lat/lon pairs, the mass of the particle, and a cell bin to which the particle is inside at that particular time.</p>
<pre><code> lon lat mass cell_bins
time trajectory ... | <p>I think you need aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with counts by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="n... | python|pandas | 2 |
361,090 | 61,694,836 | How do I extract the first and last entry made by an employees during shift in pandas | <p>Edit: I'm very sorry for the confusion, it's clear I haven't explained it well, I need to save the first and last entry for every person for every day in my csv. </p>
<pre><code>Basically what I have is:
3/4/2020 8:29 Ali
3/4/2020 8:35 Vlad
3/4/2020 11:47 Vlad
3/4/2020 11:47... | <pre><code>df.Date=pd.to_datetime(df.Date)#Coaerce Date to Datetime
df.set_index(df.Date, inplace=True)#Set Date as index
df2=df.groupby(df.Name).Date.agg(['first', 'last']).stack().reset_index()#Groupby and extract names and dates
df2.columns=['Name', 'ShiftSignIn', 'Date']
</code></pre>
<p><a href="https://i.stack.i... | python|pandas|csv | 2 |
361,091 | 62,018,263 | Is there any function equivalent to np.unique for generic object in Python | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique()</code></a> can return indices of first occurrence, indices to reconstruct, and occurrence count. Is there any function/library that can do the same for any Python object?</p> | <p>Not as such. You can get similar functionality using different classes depending on your needs.</p>
<p><code>unique</code> with no extra flags has a similar result to <a href="https://docs.python.org/3/library/functions.html#func-set" rel="nofollow noreferrer"><code>set</code></a>:</p>
<pre><code>unique_value = se... | python|algorithm|numpy|unique | 1 |
361,092 | 61,886,615 | how do i assign top 2, middle 2 and bottom 2 values with extra in the given data frame | <p>In the given below data frame. i want to insert a new column with extra and assign, top 2, middle two and below two values as "Extra"
df</p>
<pre><code>A_No B_Wt
39 184.66
40 193.11
46 197.82
2 203.82
12 205.27
9 208.11
3 208.49
14 208.70
</code></pre>
<p>Out put</p>
... | <p>I believe you can use join positions for top2, middle2 and bottom2 together and then set values to new column:</p>
<pre><code>lend = len(df)
mid = lend // 2
pos = np.r_[0:2, mid-1:mid+1, lend-2:lend]
df.loc[df.index[pos], 'Group'] = 'Extra'
print (df)
A_No B_Wt Group
0 39 184.66 Extra
1 40 193.11 ... | python-3.x|pandas|numpy|dataframe | 1 |
361,093 | 61,808,768 | Changing ticks on Jupyter Notebooks from csv | <p>I've been trying to change the tick label of my axis. I've imported them from a csv, and have changed the label, but I can't change the tick. I'm just starting out, so if I have any of the terms wrong just let me know. My code is outlined below.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
da... | <p>Well, I feel like a fool. I was formatting my graph wrong.
Where I had </p>
<pre><code>plt.plot(uk.date_epicrv)
plt.plot(uk.CumCase)
</code></pre>
<p>I should have used </p>
<pre><code>plt.plot(uk.date_epicrv, uk.CumCase)
</code></pre>
<p>I was trying to plot both graphs on the x-axis. Closing the question now,... | python|pandas|matplotlib|jupyter-notebook | 1 |
361,094 | 61,902,630 | Python Pandas Style to every nth row | <p>I'm working on a Python project w/ Pandas and looking to implement a style to every Nth row. I've been able to select every Nth row using iloc but cannot get the style to work with a basic function. Here's my example in context:</p>
<pre><code>data = [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
df = pd.DataFrame(data)
df
</c... | <p>I would apply on <code>axis=0</code> in case <code>df</code> is not index by <code>rangeIndex</code>:</p>
<pre><code>def highlight_everyother(s):
return ['background-color: yellow; color:blue' if x%2==1 else ''
for x in range(len(s))]
df.style.apply(highlight_everyother)
</code></pre>
<p>Output:... | python|pandas|dataframe|pandas-styles | 0 |
361,095 | 61,950,738 | Using numpy.testing functions with unittest | <p>I am using <code>numpy.testing.assert_almost_equal</code> in a unittest environment - but I am not sure what the right way to combine numpy and unittest is.</p>
<p>My first approach was to use assertTrue from unittest in combination with a <code>is None</code> comparison like so:</p>
<pre><code>from unittest impor... | <p>If you are in a <code>unittest</code> enviroment, your second try is perfectly ok. If you don't want the pylint warnings, you can make static functions from the methods:</p>
<pre class="lang-py prettyprint-override"><code>from unittest import TestCase
import numpy as np
class TestPredict(TestCase):
@staticmeth... | python|numpy|python-unittest | 2 |
361,096 | 61,993,458 | How to unnest elements of a list that are dictionaries into dataframe (using the first values of it as prefixes) | <p>I am currently studying python (using pandas) for dealing with data analysis. I did a few courses on DataCamp and tried to apply what I've learned into a real problem: I wanted to monitor covid-19 cases in Canada.</p>
<p>For that I am getting the data from an Apify API which returns a json that I then create a data... | <ul>
<li>Given the following dataframe where one column (<code>infectedByRegion</code>) is a list of dictionaries</li>
</ul>
<h2>List of dicts for <code>infectedByRegion</code></h2>
<pre class="lang-py prettyprint-override"><code>data = [{'region': 'Canada', 'infectedCount': '6258', 'deceasedCount': '61'},
... | python|json|pandas | 1 |
361,097 | 61,844,103 | How can I resize Olivetti Dataset images 64x64 to 32x32 ?? I am getting error | <pre><code>batch_boyut = 2
train_loader = torch.utils.data.DataLoader(
X_egitim, batch_size=batch_boyut)
val_loader = torch.utils.data.DataLoader(
X_val, batch_size=batch_boyut)
class CNNModule(nn.Module):
def __init__(self):
super(CNNModule, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5... | <p>I assume your input shape is <code>320 x 1 x 64 x 64</code>.</p>
<p>I think you need to understand what is the output shape of convolution and max-pool operations. In your model, you have 2 CNN layers, followed by the max-pooling layer.</p>
<p>First CNN and max-pool layer:</p>
<pre><code>x = self.pool(f.relu(self... | python|dataset|pytorch|conv-neural-network | 0 |
361,098 | 61,680,111 | Improvement on copy array elements numpy | <p>I have a question regarding variable assignation and memory allocation in a simple case.</p>
<p>Imagine that I am initialising a state vector <code>x</code>, with initial value <code>x0</code>. I am then making iterative updates on that state vector with buffer array <code>X</code> and after each iteration, I store... | <p>I am not entirely sure I understand what you want to do, but maybe <code>numpy.append()</code> is what you are looking for:</p>
<pre><code>import numpy as np
np.random.seed(11)
x = np.array([1.])
for i in range(10):
x = np.append(x, np.random.normal())
print(x)
</code></pre> | python|arrays|numpy | 1 |
361,099 | 61,734,953 | Convert emty list `[]` to `[0]` pandas dataframe | <p>Sample data</p>
<pre><code> A
0 []
1 [1, 3]
2 [5, 7]
3 []
</code></pre>
<p>Desired output:</p>
<pre><code> A
0 [0]
1 [1, 3]
2 [5, 7]
3 [0]
</code></pre>
<p>How can i replace null list to <code>[0]</code>?
I tried <code>df.A.replace([],[0])</code> and <code>df.apply(lambda x:x ... | <p>use an apply on the series and assign back to <code>df.A</code></p>
<pre><code>df = pd.DataFrame({'A': [[], [1, 3], [5, 7], []]})
df.A = df.A.apply(lambda x: [0] if x == [] else x)
df
# outputs
A
0 [0]
1 [1, 3]
2 [5, 7]
3 [0]
</code></pre> | python|pandas|replace | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.