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 |
|---|---|---|---|---|---|---|
18,800 | 60,654,425 | Closing a figure in python | <p>I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message: </p>
<pre><code>RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may co... | <p>Replace <code>fig.close()</code> with <code>plt.close(fig)</code>, <a href="https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html" rel="noreferrer"><code>close</code></a> is a function defined directly in the module.</p> | python|pandas|matplotlib | 6 |
18,801 | 60,344,271 | Python function stop working after some iterations | <pre><code>from yahoo_fin.stock_info import *
n=0
Ptf_opp_2=[]
lenght_2=len(Ptf_opp)
def step2():
for n in range(0,lenght_2):
Bs=get_balance_sheet(Ptf_opp[n])
tca=Bs.loc[Bs.get('Breakdown').str.match('Total Current Assets')]
tl=Bs.loc[Bs.get('Breakdown').str.match('Total Liabilities')]
... | <p>Don't do: <code>from yahoo_fin.stock_info import *</code></p>
<p>Do: <code>from yahoo_fin import stock_info</code></p>
<p><code>stock_info.get_balance_sheet</code> then identifies where the function it is coming from</p>
<p>I'm going to guess you are hitting a rate limit on the use of the API, provided that funct... | python|pandas|loops|finance|quantitative-finance | 0 |
18,802 | 59,748,831 | Torch - Interpolate missing values | <p>I have a stock of tensor images of a form NumOfImagesxHxW that includes zeros. I am looking for a way to interpolate the missing values (zeros) using the information in the same image only (no connection between the images). Is there a way to do it using pytorch? </p>
<p>F.interpolate seems to work only for reshapi... | <p>EDIT: Turns out the below does not answer the OP as it does not provide a solution to track gradients for back-propagation. Still leaving it as it can be used as part of a solution. </p>
<p>One way is to convert the tensor to numpy array and use scipy interpolation, e.g. <code>scipy.interpolate.LinearGridInterpolat... | pytorch|interpolation | 0 |
18,803 | 32,238,751 | How to fix a segmentation fault when passing an array of int? | <p>I have a Rust (1.2) library and I want to use its functions from Python (3.4) using Rust's FFI. I'm on OSX 10.10 Yosemite.</p>
<p>Almost all my functions take a mutable slice reference as the input:</p>
<pre><code>pub fn myfunction<T>(array: &mut [T]) { ... }
</code></pre>
<p>I then expose this function... | <p>You should only use <code>Vec::from_raw_parts</code> with data that has been allocated in Rust code with Rust’s allocators. Anything else is truly unsafe.</p>
<p>I expect that Python uses malloc, but Rust uses jemalloc. If jemalloc is instructed to free an address that was not allocated by jemalloc, it will, I beli... | python|numpy|segmentation-fault|rust|ffi | 5 |
18,804 | 40,767,076 | customizing facetgrid xticks and labels in seaborn | <p>how can the properties of ticklabels be customized inside a <code>FacetGrid</code> in seaborn? in the example below i wanted to change the fontsize of only the x-axis ticklabels:</p>
<pre><code>import matplotlib.pylab as plt
import seaborn as sns
df1 = pandas.DataFrame({"x": np.random.rand(100),
... | <p>You can simplify the loop by using the <code>flatten</code> method. I have also added a way to format in scientific notation. <code>.0e</code> means scientific notation with 0 decimals.</p>
<pre><code>import matplotlib.ticker as tkr
for ax in g.axes.flatten():
ax.set_xticklabels(ax.get_xticklabels(), fontsize=... | python|numpy|matplotlib|seaborn | 2 |
18,805 | 40,410,210 | TensorFlow 2-gpu slower then single gpu | <p>I have two gpu (TitanX (Pascal) and GTX 1080). I am trying
to run single-thread graph computation. The graph is two separate matrix multiplication chains (each assigned to corresponding gpu).</p>
<p>Here is the code that I'm using:</p>
<p>import tensorflow as tf
import numpy as np
import random
import ... | <p>There's significant delay when launching kernel for the first time on a GPU, possibly caused by PTXAS compilation. This delay can be on the order of seconds and accumulates when you use more than 1 GPUs, so in your case the run is slower because time is dominated by an extra "initial kernel launch". One way to bench... | tensorflow | 2 |
18,806 | 61,860,578 | keras implementation of a parallel convolution layer | <p>learning keras and cnn in general, so tried to implement a network i found in a paper, in it there is a parallel convolution layer of 3 convs where each conv apply a different filter on the input, here how i tried to solve it:</p>
<pre><code>inp = Input(shape=(32,32,192))
conv2d_1 = Conv2D(
filters = 32,
... | <p>Unless you add the padding to match the array shapes, <code>Concatenate</code> will not be able to match them. Try running this</p>
<pre><code>import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, Concatenate
inp = Input(shape=(32,32,192))
conv2d_1 = Conv2D(
filters = 32,
kern... | tensorflow|keras|conv-neural-network|caffe | 0 |
18,807 | 57,876,530 | How do I scrape only the first column and href link of this websites HTML table into a pandas dataframe? | <p><a href="http://www.annualreports.com/Companies?search=" rel="nofollow noreferrer">Website in question</a>. I want to <strong>scrape</strong> that table in the middle and just want the first column (the Company name) plus its href link.</p>
<p>For example here, I just want to <strong>scrape</strong> all the data bet... | <p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type" rel="nofollow noreferrer">nth-of-type</a> to restrict to first column (<code>td</code>). As the nodes have both the <code>href</code> of interest and the text you can use a tuple within the list comprehension to retrieve both from sa... | python|html|pandas|web-scraping | 2 |
18,808 | 57,779,324 | use values in dictionary to replace values in column | <pre><code>import pandas as pd
df= pd.DataFrame({'Data':['Hey this is 123456 Jonny B Good',
'This is Jonny B Good at 511-233-1137',
'Wow that is Alice N Wonderland A999b',
'Yes hi: Mick E Mouse 1A25629Q88 or ',
... | <p>You could generate and use regular expressions, like this:</p>
<pre><code>df['New']= df['Data']
for key, value in d.items():
regex='({alternatives})'.format(alternatives='|'.join(value))
df.loc[df['E_ID']==key, 'New']= df.loc[df['E_ID']==key, 'New'].str.replace(regex, '@@@')
</code></pre>
<p>The result ... | python-3.x|string|pandas|dictionary|replace | 0 |
18,809 | 57,869,149 | post training quantization for mobilenet V1 not working | <p>I am trying to convert mobilenet V1 .pb file to quantized tflite file. I used the below command to do the quantization:</p>
<pre><code> tflite_convert \
--output_file=/home/wc/users/Mostafiz/TPU/models/mobilnet/test2_4thSep/mobilenetv1_test5.tflite \
--graph_def_file=/home/wc/users/Mostafiz/TPU/models/mobilnet... | <p>The dummy quantization may not work properly as we need to guess the default_max and defual_min values for activation functions. </p>
<p>As Sudarsh mentioned in the comment, we should do a post training full integer quantization to convert .pb to INT8 tflite file.</p>
<p>you can follow this link to start with - <a... | tensorflow|quantization|uint8t | 0 |
18,810 | 55,114,691 | How to reverse .astype(str) in pandas dataframe? | <p>I had to remove duplicate rows in my dataframe which had list values in it.</p>
<p>So I used </p>
<pre><code>pd_data['douban_info_string'] = pd_data['douban_info'].astype(str)
</code></pre>
<p>Where 'douban_info_string' had list values.</p>
<p>But now I need this list to compare with list of another data fr... | <p>Use <code>apply</code> with an if statement:</p>
<pre><code>df = pd.DataFrame({'info':[[1,2,3], [4,5,6], 'str224']})
df['info_str'] = df['info'].astype(str)
print(df['info_str'][0])
print(type(df['info_str'][0]))
print(df['info_str'].apply(lambda x: x if x in df['info'].tolist() else pd.eval(x))[0])
print(type(df['... | python|python-3.x|pandas|dataframe | 0 |
18,811 | 55,084,119 | Applying Pandas Function to rows and columns simultaneously for Confidence Interval Calculations | <p>I am new to python programming.
I am trying to determine outliers in my data set. I have converted the data set to a pandas data frame and then applying the IQR principle.
After that I want to replace my OUTLIERS by zero and then calculate the mean and standard deviation as the outliers as skewing the mean and SD.<... | <p>Try this:</p>
<pre><code>m=df.filter(like='Store').lt(df.Lower_Limit,axis=0)|df.filter(like='Store').\
gt(df.Upper_limit,axis=0)
df.update(df.where(~m,0).filter(like='Store'))
print(df)
ID Store1 Store2 Store3 Min Max Lower_Limit Upper_limit
0 123 ... | python|pandas|dataframe|outliers|iqr | 1 |
18,812 | 54,779,527 | Editing an array not working in a for-loop | <p>I'm working with a list that contains several nested arrays as elements. Each array represents a set of points to be plotted as a frame in an animated scatter plot. Each frame contains the previous frame as a subset, plus a random number of new points so that in the animation, the scatter plot grows in number of poi... | <p>So it turns out that the way my array was organized was causing tons of problems when trying to change anything in it. </p>
<p>Originally, it was organized like this:</p>
<pre><code>frames = []
for i in range(10):
frames.append(np.random.random((i, 4)))
</code></pre>
<p>For some reason, editing the elements o... | python|numpy|numpy-ndarray | 0 |
18,813 | 55,045,523 | How to get only last output of sequence model in Keras? | <p>I trained a Many-to-Many sequence model in Keras with <code>return_sequences=True</code> and <code>TimeDistributed</code> wrapper on the last Dense layer:</p>
<pre><code>model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=50))
model.add(LSTM(100, return_sequences=True))
model.add(TimeDistribut... | <p>If, for whatever reason, you need only the last timestep during inference, you can build a new model which applies the trained model on the input and returns the last timestep as its output using the <code>Lambda</code> layer:</p>
<pre><code>from keras.models import Model
from keras.layers import Input, Lambda
inp... | python|tensorflow|machine-learning|keras|deep-learning | 2 |
18,814 | 54,704,896 | Selective replacement of NaN using column values | <p>I have a dataframe:</p>
<pre><code> GType BNM XXCV COO
0 CAT1 WERT NaN NaN
1 CAT3 FRGT NaN NaN
2 CAT3 NaN NaN NaN
3 CAT2 NaN NaN NaN
</code></pre>
<p>I need to selectively replace the <code>NaN</code>s either with space or text <code>"vvv"</code> using the <code>GType</code>.</p>
<p>I ... | <p>this should do the trick</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'GType': ['CAT1', 'CAT3', 'CAT3', 'CAT2'],
'BNM': ['WERT', 'FRGT', None, None],
'XXCV': [None, None, None, None],
'COO': [None, None, None, None],
})
to_nan_xxcv = (df.XXCV.isnull()) & (df.GType.isin(['CAT1', 'CAT2... | python|pandas|dataframe | 0 |
18,815 | 54,941,113 | Select specific columns | <p>I've a scientist dataframe</p>
<pre><code> radius date spin atom
0 12,50 YYYY/MM 0 he
1 11,23 YYYY/MM 2 c
2 45,2 YYYY/MM 1 z
3 11,1 YYYY/MM 1 p
</code></pre>
<p>I want select for each row, all rows where the difference between the radius i... | <p>I am assuming that the datatype of the <code>radius</code> column is a <code>tuple</code>. You can keep the <code>diff_radius</code> method like</p>
<pre><code>def diff_radius(x):
a, b = x
return a-b
</code></pre>
<p>Then, you can use <code>loc</code> method in pandas to select the rows which matches the c... | python|pandas|selection | 1 |
18,816 | 54,729,309 | How to merge multiple rows of timestamps and objects into line items for data pre-processing? | <p>Hi Stack Overflow community!</p>
<p>As you can see from the screenshot below, I have a dataframe of crimes in my neighbourhood, which has multiple timestamps and types of crime for each day.
<img src="https://i.imgur.com/KCt133j.png" alt="dataframe"></p>
<p>I am trying to create additional dataframe by merging th... | <p>This question is not related to the columns, you can solve it by just using the index.<br><br />
At first, group your data just by each day.</p>
<pre><code># I created a demo df
grouped = df.groupby(pd.Grouper(freq='D')).count()
print(grouped)
</code></pre>
<pre><code> CRIME
2019-01-01 2
2019-01-02 ... | python|python-3.x|pandas|dataframe|time-series | 3 |
18,817 | 49,649,215 | Pandas - image to DataFrame | <p>I want to convert an RGB image into a DataFrame, so that I have the co-ordinates of each pixel and their RGB value.</p>
<pre><code> x y red green blue
0 0 0 154 0 0
1 1 0 149 111 0
2 2 0 153 0 5
3 0 1 154 0 9
4 1 1 ... | <p>Try using <code>np.indices</code> unfortunately it ends up with a array where the coordinate is the first dimension, but you can do a bit of <code>np.moveaxis</code> to fix that.</p>
<pre><code>colourImg = Image.open("test.png")
colourPixels = colourImg.convert("RGB")
colourArray = np.array(colourPixels.getdata()).... | python|image|pandas | 8 |
18,818 | 49,356,743 | How to train TensorFlow's deeplab model on Cityscapes? | <p>Is it possible to train the current deeplab model in TensorFlow to reasonable accuracy using 4 GPUs with 11GB? I seem to be able to fit 2 batches per GPU, so am running a total batch size of 8 across 4 clones.</p>
<p>Following the <a href="https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/city... | <p>It seems I needed a much larger step length than the default. 1e-2 gives results closer to the published results, with batch size 15 and a smaller crop window size.</p> | tensorflow | 1 |
18,819 | 73,198,519 | Why free GPU is not utilisable? | <p>I run a deep learning program in PyTorch using <code>nn.DataParallel</code>. Since I have eight GPUs available. I am passing <code>device_ids=[0, 1, 2, 3, 4, 5, 6, 7]</code>.</p>
<p>My program runs on the first seven GPUs [0, 1, 2, 3, 4, 5, 6] but not on the last GPU, whose index is 7.</p>
<p>I have no clue on the r... | <p>I found the solution from <a href="https://discuss.pytorch.org/t/nn-dataparallel-doesnt-automatically-use-all-gpus/55467/9" rel="nofollow noreferrer">this</a></p>
<p>I am using the batch size of 7. So it is using only 7 GPUs, and if I change it to eight, it is using all the GPUs.</p> | pytorch|gpu | 0 |
18,820 | 35,289,773 | Cannot convert a partially converted tensor in TensorFlow | <p>There are many methods in TensorFlow that requires specifying a shape, for example truncated_normal:</p>
<pre><code>tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
</code></pre>
<p>I have a placeholder for the input of shape [None, 784], where the first dimension is None be... | <p>You just need to feed it in as a single example but in the batched shape. So that means adding an extra dimension to the shape e.g.</p>
<pre><code>batch_size = 32 # set this to the actual size of your batch
tf.truncated_normal((batch_size, 784), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
</code><... | python|tensorflow | 32 |
18,821 | 67,186,141 | Conditional Join for on range | <p>I'm trying to join df 1 and 2 on the basis if the df 1's entry_time column have a values in range of +30 or -30 from the entry_time values in df2</p>
<p>CurrentlyI'm using this code my memory runs out:</p>
<pre><code>original_entry_time = df1.entry_time.head()
entry_time = df2.entry_time.values
i, j = np.where((ori... | <p>Let us try <code>merge_asof</code></p>
<pre><code>out = pd.merge_asof(df1,df2, on = 'entry_time',direction = 'nearest',tolerance = 30)
index_x entry_time index_y Price
0 1 60 1 120
1 2 100 2 70
2 3 120 2 70
3 4 170 ... | python|pandas|join | 2 |
18,822 | 67,338,553 | Extract tensor shape as integers with unknown first dimension | <p>I have a function where it takes as input a tensor X. I would like to extract the 2nd, 3rd and 4th dimension sizes from a Tensor whose first dimension is unknown:</p>
<p>I wrote the following code but it does not work:</p>
<pre><code>x = Input(shape=(128, 128, 1))
def function1(x):
sz = tf.shape(x)
row = in... | <p>You can use <code>get_shape()</code>.</p>
<pre><code>print(x.get_shape().as_list())
</code></pre> | python|tensorflow|keras|tensor | 1 |
18,823 | 34,753,378 | Matplotlib Plot time series with colored points Pandas (Python) | <p>I'm trying to plot time series data where there are multiple points at each time. I want to have <code>time</code>on the x axis, <code>Amount</code> on the y axis and then color each point by ID i.e. where <code>ID = 344</code> they would all have the same color etc.</p>
<p>Below is example data i'm using. I'm sure... | <p>Read the docs and look at examples for scatter within pylab or matplotlib</p>
<pre><code>import pylab as pl
fig= pl.figure( figsize=(5,5) )
ax = fig.add_subplot(111)
ax.scatter(df.index, df.Amount, s=20, c=df.ID)
</code></pre>
<p>This can be customized to meet your needs.</p> | python|pandas|matplotlib|plot|timeserieschart | 5 |
18,824 | 60,195,575 | Heroku failed to find application app error | <p>Trying to deploy my dash plotly dashboard on Heroku but getting this error:</p>
<pre><code>2020-02-12T20:06:28.207580+00:00 heroku[web.1]: Starting process with command `gunicorn app:server`
2020-02-12T20:06:34.455328+00:00 heroku[web.1]: State changed from starting to up
2020-02-12T20:07:03.644528+00:00 app[web.1]... | <p>I resolved this issue by adding this line to my app.py</p>
<pre><code>server = app.server
</code></pre> | python|pandas|heroku|plotly-dash | 0 |
18,825 | 60,256,740 | Python: Remove exponential in Strings | <p>I have been trying to remove the exponential in a string for the longest time to no avail. </p>
<p>The column involves strings with alphabets in it and also long numbers of more than 24 digits. I tried converting the column to string with .astype(str) but it just reads the line as "1.234123E+23". An example of the ... | <pre><code>b = "1.234123E+23"
str(int(float(b)))
</code></pre>
<p>output is '123412299999999992791040'
no idea how to do it in pandas with mixed data type in column</p> | pandas | 0 |
18,826 | 60,224,216 | How to Calculate change between rows in Pandas Data Frame | <p>Suppose I have a daily sales record column. And from it I want to create two new columns. That keep track of the change from a month a go. For each day on the record. How would I go about doing this in Pandas Data frame. new to pandas and stuck here.
here is a sample data set </p>
<p><a href="https://i.stack.imgur... | <p>you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html" rel="nofollow noreferrer">pandas.DataFrame.diff</a> </p>
<pre><code>df['new_col'] = df.sales.diff(periods=30)
</code></pre>
<p>this will find the difference of current row and 30 rows above (this may or may ... | python|pandas | 1 |
18,827 | 65,186,386 | TensorFlow: Alternative to tf.stack() operation | <p>The TensorFlow supports stack operation as follows:
"Stacks a list of rank-R tensors into one rank-(R+1) tensor".</p>
<p>My question is, can we use other operations( like tf.concat, or tf.expand_dims) or anything else and emulate the behavior of tf.stack? My intention is to skip using tf.stack</p> | <p>You can achieve this using <code>tf.concat</code> operation and with <code>tf.expand_dims</code>,below is an example of it.</p>
<p><strong>Using Stack:</strong></p>
<pre><code>t1 = tf.constant([1,2,3])
t2 = tf.constant([4,5,6])
tf.stack((t1,t2),axis=0)
</code></pre>
<p><strong>Result :</strong></p>
<pre><code><... | tensorflow|deep-learning|neural-network|pack | 1 |
18,828 | 46,632,888 | How to get stacked bars in python plotly | <p>While this code:</p>
<pre><code>import plotly
from plotly.graph_objs import *
import pandas as pd
import datetime
date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']
date_dt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'), date)
attribute = ['a', 'b', 'a', 'a', 'b']
json_file ... | <p>I managed to do something, but it is quite tedious. Here's the code and the result:</p>
<pre><code>import plotly
from plotly.graph_objs import *
import matplotlib.pyplot as plt
import pandas as pd
import datetime
date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']
date_dt = map(lambda ... | python|pandas|plotly | 1 |
18,829 | 46,733,674 | Pandas - Pivot Multiple Categorical Columns | <p>I have a dataframe as such:</p>
<pre><code>name = ['fred','fred','fred','james','james','rick','rick','jeff']
actionfigures = ['superman','batman','flash','greenlantern','flash','batman','joker','superman']
cars = ['lamborghini', 'ferrari','bugatti','ferrari','corvette','bugatti','bmw','bmw']
pets = ['cat','dog','b... | <p><code>melt</code> and <code>pivot</code></p>
<pre><code>test.melt('name').assign(new=1).pivot('name','value','new').fillna(0)
Out[239]:
value batman bird bmw bugatti cat corvette dog ferrari fish flash \
name
fred 1.0 1.0 ... | python|pandas|pivot-table | 4 |
18,830 | 46,685,395 | How to train and test tensorflow CNN on files residing at local computer | <p>I am new to python and tensorflow. I am trying to use a convolutional neural network algorithm implemented in tensorflow. What is need to do is to train and test my own dataset instead of MNIST dataset.
Currently program is using:</p>
<pre><code>def main(unused_argv):
# Load training and eval data
mnist = tf.co... | <p>You can use the command below to train and eval the model by use of <a href="http://ronnie.ai" rel="nofollow noreferrer">ronnie.ai framework</a></p>
<pre><code>eResult = CNNModel.trainNeval(trainData, evalData, designer.modelDef, 200, 50, 1, evalSteps=1)
</code></pre> | python|tensorflow | -1 |
18,831 | 46,724,398 | memory issue creating huge numpy (interrupted by signal 9: SIGKILL) | <p>I have an huge csv and i have to create a numpy array for the same argument in a certain column (the type ara about 10) but i have a problem with my list: it's too big and python goes down:</p>
<pre><code> def mem():
file = pd.read_csv(file_csv)
x = []
y = []
path_prec = 0
for index, row in file... | <p>You could create a NumPy's <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.memmap.html" rel="nofollow noreferrer"><code>memmap</code></a> object.</p>
<p>According to its documentation, this will: </p>
<blockquote>
<p>Create a memory-map to an array stored in a binary file on disk.</p>
... | arrays|numpy|sigkill | 1 |
18,832 | 32,657,654 | Python Pandas Groupby a List of Lists | <p>I am new to Python and am trying to combine the functionality that I have created in two separate programs that are working for me.</p>
<p>The goal is to group values by various descriptions and then average values of the data set by date. I have successfully done this using Pandas Groupby.</p>
<p>One of the desc... | <p>Pandas will easily groupby a boolean list. Thus, all you need to do is get a list of if each row is nearby or not. The easiest way to do this is with a list comprehension:</p>
<pre><code>df = pandas.DataFrame({'value': [3,2,3,6,4,1], 'location': ['a', 'a', 'b', 'c', 'c', 'c']})
nearby_locations = ['a','b']
is_nea... | python|list|numpy|pandas|group-by | 0 |
18,833 | 32,657,856 | MLK as holiday in USFederalHolidayCalendar | <pre><code>from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
import pandas as pd
import datetime as dt
BDAY_US = CustomBusinessDay(calender=USFederalHolidayCalendar())
bus_dates =pd.date_range(start=dt.datetime(2015,1,1), end=dt.datetime(2015,1,20), freq=... | <p>This was a result of a typo.</p>
<pre><code>BDAY_US = CustomBusinessDay(calendar=USFederalHolidayCalendar())
</code></pre>
<p>Is the correct version and the resulting series of business days don't have MLK in it which is what I wanted.</p> | pandas | 0 |
18,834 | 32,765,322 | What's the correct way of using reduceByKey in Spark using Python | <p>I'm new to apache spark and don't know if I'm misunderstanding reduceByKey or am encountering a bug. I'm using the spark-1.4.1-bin-hadoop1 build, due to
issues with the python Cassandra interface in spark-1.4.1-bin-hadoop2.</p>
<p>reduceByKey(lambda x,y: y[0]) returns the first value of the last tuple,
but reduceBy... | <p>Using pyspark:</p>
<pre><code>>>> t1=[
... [12.095850944519043, 111.84786987304688, 41252.0, 7469.0, 16.0],
... [12.094693183898926, 111.84053802490234, 40811.0, 7444.0, 16.0],
... ]
>>> t1
[[12.095850944519043, 111.84786987304688, 41252.0, 7469.0, 16.0],[12.094693183898926, 111.840538024902... | python|numpy|apache-spark|pyspark|pyhdf | 1 |
18,835 | 38,814,692 | can't set Attr as {type, list(type)} when create op in tensorflow | <p>seems that <code>Attr("Tout: {list(type), type}")</code> is not allowed in tensorflow op creation.</p>
<pre><code>F tensorflow/core/framework/op.cc:160] Check failed: ::tensorflow::Status::OK() == (RegisterAlreadyLocked(deferred_[i])) (OK vs. Invalid argument: Unrecognized type string 'type' from Attr("Tout: {type,... | <p>The TensorFlow <a href="https://github.com/tensorflow/tensorflow/blob/32bd3d024f33e920a67a1081bc0ae0048350fdee/tensorflow/core/framework/op_def.proto" rel="nofollow"><code>OpDef</code></a> type system doesn't currently support arguments (or outputs) whose types may be either a list of types or a single type. Instead... | tensorflow | 0 |
18,836 | 38,828,331 | Select multiple sections of rows by index in pandas | <p>I have large DataFrame with GPS path and some attributes. A few sections of the path are those which I need to analyse. I would like to subset only those sections to a new DataFrame. I can subset one section at the time but the idea is to have them all and to have an original index.</p>
<p>The problem is similar to... | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="noreferrer"><code>np.r_</code></a> to concatenate the slices:</p>
<pre><code>In [16]: df.loc[np.r_[11:13, 17:20]]
Out[16]:
A B
11 1 b
12 2 c
17 7 h
18 8 i
19 9 j
</code></pre>
<p>Note, however, that
<cod... | python|pandas|slice | 11 |
18,837 | 38,516,664 | Anti-Join Pandas | <p>I have two tables and I would like to append them so that only all the data in table A is retained and data from table B is only added if its key is unique (Key values are unique in table A and B however in some cases a Key will occur in both table A and B). </p>
<p>I think the way to do this will involve some sort... | <p><code>indicator = True</code> in <code>merge</code> command will tell you which join was applied by creating new column <code>_merge</code> with three possible values: </p>
<ul>
<li><code>left_only</code></li>
<li><code>right_only</code></li>
<li><code>both</code></li>
</ul>
<p>Keep <code>right_only</code> and <co... | python|pandas|dataframe|merge|anti-join | 64 |
18,838 | 63,078,416 | how to compare two dataframes to infer third dataframe | <pre><code>df_base =
time_id object_id gt_class hp_class
0 1 a CAR ""
1 1 b CAR ""
2 2 c PERSON PERSON
3 2 d PERSON PERSON
4 2 e CAR ""
df_... | <p>The data:</p>
<pre><code>df_base = pd.DataFrame.from_dict({'time_id':[1,1,2,2,2], 'object_id':['a','b','c','d','e'], 'gt_class':['CAR', 'CAR', 'PERSON', 'PERSON', 'CAR'],
'hp_class':['','','PERSON','PERSON','']})
df_feature = pd.DataFrame.from_dict({'time_id':[1,1,2,2,2], 'object_id':['a','b','c','d','e... | pandas|dataframe|grouping | 2 |
18,839 | 63,277,026 | Loop through date and assign value as week number | <p>I have a Dataframe with a date column. I would like to create a new column and assign value for every 7 days as week 1, week 2... I have learned that <code>df.iloc[::7, :]</code> will do the loop but how to assign values to the new column. Thank you.</p>
<pre><code>Date Week
1/1/2020 1
2/1/2020 1
3/1/20... | <p>For general solution subtract minimal date, convert timedeltas to days and use integer division by <code>7</code> with adding <code>1</code>:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
df['Week'] = df['Date'].sub(df['Date'].min()).dt.days // 7 + 1
print (df)
Date Week
0 2020... | python|pandas | 2 |
18,840 | 67,725,385 | group by on dataframe pandas with python | <p>I am using python and I have a dataframe pandas :</p>
<pre><code>unique_col | code | Col3 | ... | Col4
1 | A | aa | ... | aaa1
2 | A | bb | ... | aaa2
3 | A | cc | ... | aaa3
4 | B | dd | ... | aaa4
5 | B | ee | ... | aaa5
6 | B | ff... | <p>You can use <code>groupby.last()</code> (or <code>.max()</code>, and make sure you sort your dataframe first with the column you want to get the max value of, i.e. <code>unique_col</code>:</p>
<pre><code>df.sort_values(by=['unique_col']).groupby('code').last().reset_index()
code unique_col Col3 Col4
0 A ... | python|pandas|dataframe | 1 |
18,841 | 67,927,669 | Is there any method to replace specific data from column without breaking its structure or spliting | <p>Hi there i am trying to figure out how to replace a <strong>specific data of csv</strong> file. i have a file which is base or <em>location data</em> of <em>id's.</em>
<a href="https://store8.gofile.io/download/5b031959-e0b0-4dbf-aec6-264e0b87fd09/service%20block.xlsx" rel="nofollow noreferrer">https://store8.gofile... | <p>If I understand correctly, you simply need to specify the separator <code>;</code></p>
<pre><code>>>> df.to_csv(‘test.csv’, sep=‘;’, index_label=False)
</code></pre> | python|excel|pandas|dataframe|numpy | 1 |
18,842 | 67,788,862 | Create a list that represents all the possible paths an individual can take | <p>The below dataframe represents presumed residence of a set of individuals:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'PRESUMED_RESIDENCE':['SJDR1', 'LD1', 'LD2', 'TR1', 'TR2', 'SVM']})
df
</code></pre>
<p>I need to create a list that contains all the possible trajectories that an individual can take - h... | <p>Use <code>more_itertools.powerset</code> which will result in list of tuples so convert it into list of list using <code>map()</code></p>
<pre><code>import more_itertools
vals = df["PRESUMED_RESIDENCE"].to_list()
out = list(more_itertools.powerset(vals))[1:]
MOTIFS = list(map(list, out))
</code></pre>
<pre... | python|pandas | 1 |
18,843 | 67,921,586 | Python and pandas: How to use df.loc to make a new column based on conditions? | <p>*see edits below</p>
<p>I have a dataframe that contains 6 columns and I am using pandas and numpy to edit and work with the data.</p>
<pre><code>id calv1 calv2 calv3 calv4
1 2006-08-29 2007-08-29 2008-08-29 2009-08-29
2 NaT NaT NaT NaT
3 2006-08-29 ... | <p>So long the values are datetime (and NaT are missing values, not string), you can use:</p>
<pre><code>df['no_calv'] = df.notna().sum(axis = 1)
</code></pre>
<p>To get:</p>
<pre><code>id calv1 calv2 calv3 calv4 no_calv
1 2006-08-29 2007-08-29 2008-08-29 2009-08-29 4
2 NaT NaT... | python|pandas|dataframe | 3 |
18,844 | 67,913,138 | Replacing dataframe column list values with values from another dataframe | <p>I am trying to replace data in one of the dataframe while comparing different columns with another data frame with values like below.
I need to map the 'members' column in df1 with 'uid' column in df2 and get the corresponding ipv4-address for one member.</p>
<p>Dataframe 1:</p>
<div class="s-table-container">
<tabl... | <p>If you are filtering just to the rows you need on df1 and df2, you can do</p>
<pre><code>ips = df2['ipv4-address'].tolist()
</code></pre>
<p>and then set</p>
<pre><code>df1['members'] = ips
</code></pre>
<p>otherwise you'll have to use a little more logic to get the right rows to update</p> | python|python-3.x|pandas|dataframe | 0 |
18,845 | 32,034,237 | How does NumPy's transpose() method permute the axes of an array? | <pre><code>In [28]: arr = np.arange(16).reshape((2, 2, 4))
In [29]: arr
Out[29]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
In [32]: arr.transpose((1, 0, 2))
Out[32]:
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
... | <p>To transpose an array, NumPy just swaps the shape and stride information for each axis. Here are the strides:</p>
<pre><code>>>> arr.strides
(64, 32, 8)
>>> arr.transpose(1, 0, 2).strides
(32, 64, 8)
</code></pre>
<p>Notice that the transpose operation swapped the strides for axis 0 and axis 1. ... | python|arrays|numpy|transpose | 248 |
18,846 | 41,280,489 | Concatenate data frames by column values | <p>How I can merge following two data frames on columns <code>A</code> and <code>B</code>: </p>
<pre><code>df1
A B C
1 2 3
2 8 2
4 7 9
df2
A B C
5 6 7
2 8 9
</code></pre>
<p>And with result to get only results of those two matching rows.</p>
<pre><code>df3
A B C
2 ... | <p>You can concatenate them and drop the ones that are not duplicated:</p>
<pre><code>conc = pd.concat([df1, df2])
conc[conc.duplicated(subset=['A', 'B'], keep=False)]
Out:
A B C
1 2 8 2
1 2 8 9
</code></pre>
<hr>
<p>If you have duplicates,</p>
<pre><code>df1
Out:
A B C
0 1 2 3
1 2 8 2
2 4 ... | python|pandas|dataframe | 4 |
18,847 | 41,547,753 | How to convert a dataframe to sparse matrix with mixed column types? | <p>I have a data frame of following format:</p>
<pre><code>df:
key f1 f2
k1 10 a, b, c
k2 20 b, d
k3 15 NaN
</code></pre>
<p>The column f2 has a bag of words as values. I want to convert this data frame into a sparse matrix, as distinct words in f2 run to a few thousands. The end result I am e... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>str.get_dummies</code></a> and <a hr... | python|pandas|scipy|scikit-learn|sparse-matrix | 2 |
18,848 | 27,752,746 | df.plot seems not to work in Pandas? | <p>I am a python beginner. I meet an issue that I cannot do the plot function. But I have no idea how to fix it?</p>
<p>I am not sure if I miss something in my steps.</p>
<p><strong>The environment:</strong>
win 7
Anaconda 2.1</p>
<p><strong>Code:</strong>
In [1]:</p>
<pre><code>import pandas as pd
In [2]:
df ... | <p>It seems like you are using ipython notebook.</p>
<p>If it is the case, executing <code>%matplotlib inline</code> should solve your problem.</p> | matplotlib|pandas|plot|anaconda | 1 |
18,849 | 61,200,660 | Predictive model expecting 3 dimension but the array with shape don't match | <p>I'm using this formula to predict stock price in Jupyter:</p>
<pre><code>import keys
import datetime
from binance.client import Client
import pandas as pd
client = Client(keys.APIKey, keys.SecretKey)
symbol= 'BTCUSDT'
BTC= client.get_historical_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_30MINUTE, start_... | <p>LSTM models expect input dim = 3: (#samples, timestamp, features).<br>
So for example, if you have 7505 audio files, each has 100 timestamp, each timestamp has 578 features - the train set should be with the current shape: (3,100,578).<br>
Your input shape is (#samples, features), so reshape it to be 3 dimensional -... | python|python-3.x|tensorflow|keras|jupyter-notebook | 1 |
18,850 | 61,542,232 | How to edit title size and position in pandas plot() method when subplots=True? | <p>I am comparing sales data from 9 shops:</p>
<p><a href="https://i.stack.imgur.com/PStBM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PStBM.png" alt="enter image description here"></a></p>
<p>However the title is very small, and seems to be inside the chart. I can't figure out how to change th... | <p>The overall chart label is controlled with <code>plt.gcf().suptitle()</code>.</p>
<p>Then, in order to put the title outside the plots you can do this (from here: <a href="https://stackoverflow.com/a/45161551/42346">https://stackoverflow.com/a/45161551/42346</a>):</p>
<pre><code>plt.gcf().tight_layout(rect=[0, 0.0... | python|pandas|matplotlib | 2 |
18,851 | 68,510,066 | How to plot a 3dimensional tensor as a tube with different colors | <p>Let's assume that we have a numpy array <code>traj</code> with shape <code>(64,64,64)</code> and each element of this tensor may be either -1 or +1. I want to plot it into a three dimensional cube, where blue color stands for -1 and red color for +1. How I can do that?</p>
<p><strong>p.s.</strong> <em>To have a phys... | <p>You can achieve this by creating a figure with a three-dimensional axes enable (<code>projection='3d'</code>) and using <a href="https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.voxels" rel="nofollow noreferrer">ax.voxels</a> parameter <code>facecol... | python|python-3.x|numpy|matplotlib | 1 |
18,852 | 68,559,239 | Weird rounding using numpy.floor() to every 0.02 | <p>I'm having trouble working out how to round some data up to every 0.02. Here's my code:</p>
<pre><code>def cpt_rnd(x):
return np.floor(x*50)/50
x = np.array([32.16, 32.18, 32.2, 32.22])
d = cpt_rnd(x)
print(d)
</code></pre>
<p>Which returns:</p>
<pre><code>[32.14, 32.18, 32.2, 32.22]
</code></pre>
<p>And is m... | <p>This happens due to the finite resolution of floating-point numbers on a computer leading to slightly inaccurate results when you perform arithmetic operations on them (<a href="https://en.wikipedia.org/wiki/Round-off_error#Roundoff_error_caused_by_floating-point_arithmetic" rel="nofollow noreferrer">Roundoff error ... | python-3.x|numpy|rounding | 2 |
18,853 | 68,782,529 | R sapply in a for loop equivalent in Python | <p>I have a code that I have to translate from R to python.
However I'm not very familiar with sapply equivalents in python.
This portion of code combines a for loop and sapply.</p>
<p>Here's the code:</p>
<pre><code>for ( j in 1:nrow(df)) {
train <- df$train_nbr[j]
data <- matrix(nrow= 1 ,ncol=length(num))
... | <p>An efficient Python version, which is equivalent to the R version posted by user2554330, is</p>
<pre class="lang-py prettyprint-override"><code> result = (df.train == df.z) | (df.train.str[2:4] != df.z.str[2:4])
</code></pre> | python|r|pandas | 0 |
18,854 | 68,835,409 | Return a Boolean value in a new column if two columns are equal and a third column is True | <p>I want to create a new column in which stores boolean values when two columns (one and two) present the same value and another column (three) presents the value True.</p>
<pre><code>If column three == True AND column two == column one ---> column four = True
If column three == false ---> column four = Na
If... | <p>Use <code>np.select</code>:</p>
<p>Input data:</p>
<pre><code>>>> df
One Two Three
0 0 0 True
1 0 1 True
2 0 1 False
</code></pre>
<pre><code>df['Four'] = np.select([df['Three'] & df['One'].eq(df['Two']),
df['Three'] & df['One'].ne(df['Two'])],
... | python|pandas | 1 |
18,855 | 36,454,802 | How to display Pandas array with Cyrillic in Matplotlib | <p>I am building a tool that reads a uft-8 encoded text file with Pandas and displays the field on Matplotlib. Think of it as a poor man's telemetry display for training purposes. I am having an issue that the code is not displaying fields that are in Cyrillic but it is able to display other fields from the txt file. T... | <p>Read back your utf8 encoded file by passing the <code>encoding=</code> argument to the <code>read_table</code> function:</p>
<pre><code>data = pd.read_table(filename, sep="\s+", encoding="utf-8")
</code></pre> | python|pandas|matplotlib | 1 |
18,856 | 36,405,677 | Caffe feature extraction is too slow? caffe.Classifier or caffe.Net | <p>I have trained a model with images.
And now would like to extract the <code>fc-6</code> features to <code>.npy</code> files.
I'm using <code>caffe.set_mode_gpu()</code>to run the <code>caffe.Classifier</code> and extract the features.</p>
<p>Instead of extracting and saving the feature per frame.
I save all the fe... | <p>I found the best answer here in <a href="http://sites.duke.edu/rachelmemo/2015/05/21/setup-a-network-in-caffes-python-wrapper/" rel="nofollow noreferrer">this post.</a></p>
<p>Till now I had used a</p>
<pre><code>net = caffe.Classifier(model_prototxt, model_trained,
mean=np.array([128, 128... | python|numpy|optimization|caffe|pycaffe | 4 |
18,857 | 65,717,683 | Geographic points extend beyond expected boundary | <p>I have a point geometry of US locations contained in a GeoDataFrame.
I want to plot this as a scatterplot over the US map.
My code is:</p>
<pre><code>import numpy as np
import geopandas as gpd
import libpysal
import contextily as ctx
import matplotlib.pyplot as plt
from shapely.ops import cascaded_union
gdf = gpd.G... | <p>The plot looks good. I guess you want to exclude the points outside conterminous USA. Those points are clearly in Hawaii, Alaska, and Canada.</p>
<p>From your geodataframe with <code>point</code> geometry, <strong>gdf</strong>, and with <code>polygon</code> geometry, <strong>boundary</strong>, you can create a prope... | geolocation|gis|geospatial|geopandas | 1 |
18,858 | 65,503,536 | uploading csv file into Django model | <p>I'm working on a Django app and need to import a CSV file into the Django model.</p>
<p>What's the proper way to get around this?</p>
<p>I was planning to use <code>pandas</code> to read the CSV and then saving into models with <code>bulk_create</code>. But not sure if there will be any performance issues as the dat... | <p>Visit <a href="https://concisecoder.io/2019/04/19/avoid-memory-issues-with-djangos-bulk_create/" rel="nofollow noreferrer">https://concisecoder.io/2019/04/19/avoid-memory-issues-with-djangos-bulk_create/</a></p>
<pre class="lang-py prettyprint-override"><code>from itertools import islice
from my_app.models import My... | python|django|pandas | 0 |
18,859 | 65,768,237 | How to improve CNN model reaching loss plateau? | <p>I am using TensorFlow in Python 3 to create a CNN that creates a multi class (i.e. expected output is 3 probabilities out of 92) based on a vector of photon energies shape(20, 1).
My model below is a result of multiple iterations and gradually increasing complexity.</p>
<p>However, the model seems to consistently re... | <p>You might try using an adjustable learning rate. The Keras callback <code>ReduceLROnPlateau</code> makes this easy to do. Documentation is <a href="https://keras.io/api/callbacks/reduce_lr_on_plateau/" rel="nofollow noreferrer">here.</a> Set the callback to monitor validation loss. My recommended code is shown below... | python|python-3.x|tensorflow|keras|conv-neural-network | 2 |
18,860 | 63,671,163 | Keras custom loss function huber | <p>I wrote huber loss using Keras backend functions and this works well:</p>
<pre><code>def huber_loss(y_true, y_pred, clip_delta=1.0):
error = y_true - y_pred
cond = K.abs(error) < clip_delta
squared_loss = 0.5 * K.square(error)
linear_loss = clip_delta * (K.abs(error) - 0.5 * clip_delta... | <p>I like to debug custom functions by graphing them using a program like Desmos. <a href="https://www.desmos.com/calculator/rlxkemtzxu" rel="nofollow noreferrer">I graphed the Huber Loss using your implementation and it looks like how it should</a>.</p>
<p><a href="https://www.desmos.com/calculator/lfy3su6ac9" rel="no... | python|tensorflow|machine-learning|keras|loss-function | 1 |
18,861 | 63,496,687 | 2D histogram plot from data file | <p>How can you make a 2d histogram (or surface) plot out of a given 2d numpy array where the first index is the label for the 'x' dimension, the 2nd index for the 'y' dimension and the third is the value to be plotted? Example:</p>
<pre><code>[[4.80000e+01 5.12000e+02 8.03447e+03]
[4.80000e+01 2.56000e+02 9.24963e+03]... | <p><code>plt.tricontourf(d[:,0], d[:,1], d[:,2])</code> creates filled contours from <code>x</code>, <code>y</code> and <code>z</code> data which aren't organised as a grid.</p>
<p><code>plt.hist2d(d[:,0], d[:,1], weights=d[:,2])</code> creates a 2d histogram where the weight of each <code>x,y</code> is given by <code>... | python|numpy|matplotlib | 1 |
18,862 | 63,405,447 | <class ‘decimal.ConversionSyntax’> errors when importing data from a CSV file using Python (tried using CSV and Pandas) | <p>I have a CSV file from a small business that represents their records for about 70,000 orders spread out over about 30 years. My goal is to store this data in a Django project with a DecimalField in the model setup to receive the import.</p>
<p>Before trying to store the data in Django I'm first trying to import thi... | <p>You can use <code>chardet</code> to detect the encoding.</p>
<pre><code>import chardet
with open('csv_of_text.csv','rb') as fraw: # "rb" = bytes mode
file_content = fraw.read()
chardet.detect(file_content)
</code></pre> | python|django|pandas|csv | 0 |
18,863 | 63,604,609 | What happens internally and raises ValueError while using bitwise and comparison operators with numpy arrays? | <pre><code>import numpy as np
arr = np.array([3, 4, 6, 15, 25, 38])
print(arr > 5 & arr <= 20)
"""Output
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(arr > 5 & arr <= 20)
ValueError: The truth value of an array with more than ... | <p><code>&</code> has a <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow noreferrer">higher precedence</a> than <code><=</code>, so this is being run as <code>arr > (5 & arr) <= 20</code> <a href="https://docs.python.org/3/reference/expressions.html#compa... | python|numpy|expression|bitwise-operators|comparison-operators | 1 |
18,864 | 63,474,460 | How to count pandas.Series range when groupie followed by value_counts() | <p>I have the data like this:</p>
<pre><code>year = ['2010', '2011-2014', '2013', '2012-2016', '2018-present', '2019', '2015-present', '2015']
products = ['A', 'B', 'C', 'D', 'B', 'E', 'F', 'A']
rating = [4, 2, 2, 3, 1, 1, 2, 2]
data = pd.DataFrame({'Products': products, 'Year': year, 'Rating': rating})
</code></pre>
... | <p>Use <code>explode</code>:</p>
<pre><code># Extract the range information from the Year column
y = data['Year'].str.extract('(?P<From>\d+)-?(?P<To>\d+|present)?')
y['To'] = y['To'].combine_first(y['From']).replace({'present': '2020'})
y = y.astype('int')
y['Range'] = y.apply(lambda row: range(row['From'],... | python|pandas|group-by | 3 |
18,865 | 30,098,482 | Pandas creates DataFrame with first header column in it's own row | <p>I am working with the <a href="http://gdeltproject.org/" rel="nofollow noreferrer">GDELT dataset</a> am having issues creating a pandas <code>DataFrame</code> using <code>pd.DataFrame.from_csv(path_to_data, sep=",")</code> which seems to load the data fine except except for the fact that the first header column is s... | <p>Don't use <code>from_csv</code> it's no longer maintained, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>In [244]:
t="""Source,Actor1Type1Code,Actor1Type2Code,Actor1Geo_CountryCode,Target,Actor2Type1... | python|pandas|csv|gdelt | 3 |
18,866 | 53,708,927 | No changes to original dataframe after applying loop | <p>I have a list of dataframes such that </p>
<pre><code>df_lst = [df1, df2]
</code></pre>
<p>I also created a function which removes the rows with '0' in the dataframe:</p>
<pre><code>def dropzeros(df):
newdf = df[df['x']!=0.0]
return newdf
</code></pre>
<p>I tried applying this through a loop and placed a... | <p>That's because the variable <code>df</code> in your <code>for</code> loop does not <em>reference</em> a value in your list. You are creating a variable <code>df</code> afresh each iteration of your loop.</p>
<p>You can assign via <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow nor... | python|python-3.x|pandas|loops|dataframe | 1 |
18,867 | 53,676,740 | remove rows from dataframe where contents could be a choice of strings | <p>so i can do something like:</p>
<pre><code>data = df[ df['Proposal'] != 'C000' ]
</code></pre>
<p>to remove all Proposals with string C000, but how can i do something like:</p>
<pre><code>data = df[ df['Proposal'] not in ['C000','C0001' ]
</code></pre>
<p>to remove all proposals that match either C000 or C0001 (... | <p>You can try this,</p>
<pre><code>df = df.drop(df[df['Proposal'].isin(['C000','C0001'])].index)
</code></pre>
<p>Or to select the required ones,</p>
<pre><code>df = df[~df['Proposal'].isin(['C000','C0001'])]
</code></pre> | python|pandas | 1 |
18,868 | 53,733,566 | Compute a new set of columns based on two different sets of columns | <p>I am trying to compute a new set of columns based on two sets of columns in pandas. Here is sample code I am using. It produces ValueError: Columns must be same length as key</p>
<pre><code>dates = pd.date_range('1/1/2000', periods=100, freq='M')
dft = pd.DataFrame(np.random.randn(100, 4),index=dates, columns=['... | <p>Adding <code>.values</code> , since pandas will check index and columns value when do the dataframe divide , then using <code>DataFrame</code> constructor re-format the result and <code>concat</code> back </p>
<pre><code>C=pd.DataFrame(data=dft[list_A].values/dft[list_B].values,columns=list_C,index=dft.index)
pd.... | python|pandas | 1 |
18,869 | 53,739,790 | Pandas OFFSET and MATCH function with two dataframes | <p>I have this excel formula that needs to be applied on a pandas dataframe </p>
<p><code>=IF(OFFSET(list!$B$1,MATCH($X1,list!$A:$A,0)-1,0)=0,"",OFFSET(list!$B$1,MATCH($X1,list!$A:$A,0)-1,0))</code></p>
<p>dataframe: <strong>list</strong></p>
<pre><code>A B C
24309 Pepsi US
45768 McDona... | <p>the easiest and most efficient way is to apply a mask over the values. Here you could find a sample dataframe: </p>
<pre><code>df1 = pd.DataFrame({
"Date" : ['2013-11-22', '2013-10-24', '2013-09-24', '2013-02-15'],
"Fruit" : ['Banana', 'Orange', 'Apple', 'Celery'],
"Num" : [22.1, 8.6, 7.6, 10.2],
"Color" : ['Yello... | python|pandas|dataframe|excel-formula | 0 |
18,870 | 53,443,796 | Count number of elements in a column greater than x but smaller than y | <p>I am trying to count the number of elements in column <code>'xyz'</code> which are smaller than <code>x</code> but larger than <code>y</code>.</p>
<pre><code>a= df['xyz']
df[1/3 < a < 2/3].count()
</code></pre>
<p>However, this gives me:</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambi... | <p>Subsetting your dataframe is not necessary. Just sum a Boolean series:</p>
<pre><code>res = df['xyz'].between(1/3, 2/3, inclusive=False).sum()
</code></pre>
<p>Chained comparisons such as <code>x < a < y</code> work with regular Python scalars, not with Pandas objects, which require vectorised operations.</p... | python|pandas|series | 2 |
18,871 | 17,663,433 | plot of multiple arrays | <p>I have imported and processed multiple datasets in numpy/python- from the datasets I can created several arrays with the data -
for the sake of argument let's say 3 arrays;
A
B
C
now I want to plot the data: </p>
<p>currently I chose each array,
and plot the data - this is fine, but when I have 18 arrays, then it... | <p>My mistake, and as #debianplebian suggested the problem was with the followup code -
I actually needed to define colors within the high level loop - I failed to do so and when the 2nd iteration reached the color it stuck</p> | python|arrays|numpy|matplotlib | 1 |
18,872 | 15,728,070 | Copying Data Between 3D Numpy Arrays Where A Condition Is True | <p>I'd like to copy data from one 3D array to another 3D array at the indices where a condition is true for a different 2D array. All three arrays have the same first two dimensional shapes (x,y coords).</p>
<p>I thought it'd be something like,</p>
<pre><code>a[c == cond] = b[c == cond]
</code></pre>
<p>But in this ... | <p>If you are on a new numpy version, use <code>np.copyto</code>.</p> | python|multidimensional-array|numpy|indexing | 2 |
18,873 | 12,372,899 | Bug in pandas.Series/DataFrame.fillna limit? | <p>I've been trying to fill a DataFrame and Series using <code>fillna</code> with the <code>value</code> and <code>limit</code> keywords. The <code>limit</code> is respected when not including <code>value</code>, but as soon as including <code>value</code> the limits are no longer respected. Here's an example using a D... | <p>This is actually by design. The <code>limit</code> keyword is designed to go with the <code>method</code> keyword because you have to specify the ordering (i.e., forward-fill or back-fill) and you don't have that with <code>value</code>.</p> | python|pandas | 3 |
18,874 | 71,923,607 | 'val_accuracy' and 'accuracy' missing in fitted model history Tensorflow (YOLO) | <p>Im trying to retrain YOLOv4 model with custom dataset. It supposed to detect and predict car body type such as sedan, suv, etc.</p>
<p>here is the training function:</p>
<pre><code>def model_train(data_dir:str, model_dir:str, version:str, epochs:int = 100, class_path:str = '', annot_path:str = ''):
model_filenam... | <p>The <a href="https://github.com/taipingeric/yolo-v4-tf.keras/blob/master/models.py#L83" rel="nofollow noreferrer">compilation of the model</a> is done as follows:</p>
<pre class="lang-py prettyprint-override"><code>self.training_model.compile(optimizer=optimizers.Adam(lr=1e-3),
loss={'yol... | python|tensorflow | 0 |
18,875 | 71,859,221 | Pandas loop into variables adding suffix and transforming original column | <p>I would like to loop into some variable name and the equivalent column with an added suffix "_plus"</p>
<pre><code>#original dataset
raw_data = {'time': [2,1,4,2],
'zone': [5,1,3,0],
'time_plus': [5,6,2,3],
'zone_plus': [0,9,6,5]}
df = pd.DataFrame(raw_data, columns = ['t... | <pre><code>raw_data = {'time': [2,1,4,2],
'zone': [5,1,3,0],
'time_plus': [5,6,2,3],
'zone_plus': [0,9,6,5]}
df = pd.DataFrame(raw_data, columns = ['time','zone','time_plus','zone_plus'])
# Take every column that doesn't have a "_plus" suffix
cols = [i for i in list(df.columns) if &quo... | python|pandas|dataframe|loops | 2 |
18,876 | 18,954,752 | Python/Pandas filter out unique rows from DataFrames | <p>I tow or three DataFrames that have duplicated rows.</p>
<pre><code>In [31]: df1
Out[31]:
member time
0 0 2009-09-30 12:00:00
1 0 2009-09-30 18:00:00
2 0 2009-10-01 00:00:00
3 1 2009-09-30 12:00:00
4 1 2009-09-30 18:00:00
5 2 2009-09-30 12:00:00
6 3 2009-09-3... | <p>Do a inner join on <code>member</code> and <code>time</code> columns:</p>
<pre><code>>>> df1.merge(df2, on=['member', 'time'], how='inner')
member time
0 0 2009-09-30 12:00:00
1 0 2009-09-30 18:00:00
2 1 2009-09-30 12:00:00
3 2 2009-09-30 12:00:00
</code></pre>
<p... | python|pandas | 3 |
18,877 | 55,471,227 | How to run apache beam locally? | <p>I'm trying to run a python apache beam script on my local machine to do some simulation. I have put 'DirectRunner' in my options. However the p.run() gives me an error "TypeError: Receiver() takes no arguments"</p>
<p>Any ideas why this would occur ? I'm using Spyder as IDE.</p>
<p>EDIT: Here is an example of code... | <p>You do not need to specify 'DirectRunner' as an argument, if you do not specify any runner i.e. leave it blank, it defaults to running using the DirectRunner.
This should run fine. </p>
<pre><code> p = beam.Pipeline()
(p | 'ReadMessage' >> beam.io.textio.ReadFromTextWithFilename('input/inputs.json')
... | python-3.x|pandas|google-cloud-platform|apache-beam | 1 |
18,878 | 9,948,042 | Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)? | <p>Elementwise multiplication of two vectors is no problem if they both have the same shape, say both (n,1) or both (n,). If one vector has shape (n,1) and the other (n,), though, the <code>*</code>-operator returns something funny.</p>
<pre><code>a = np.ones((3,1))
b = np.ones((3,))
print a * b
</code></pre>
<p>The ... | <p>Slice the vectors in a way that makes their shape match:</p>
<pre><code>a[:, 0] * b
</code></pre>
<p>or</p>
<pre><code>a * b[:, None]
</code></pre> | python|arrays|numpy | 19 |
18,879 | 56,805,214 | KeyError: 6 when adding labels to a regplot | <p>I have a dataframe with the following columns: 'Project', 'Hours', 'Revenue', 'Rate'</p>
<p>I try to build a regplot with Rate on X-axis and Revenue on the Y-axis and add Project name label to the dots at my regplot. Here is my code:</p>
<pre><code>ax=sns.regplot(x = 'Revenue', y = 'Rate',data= df_hours_revenue, c... | <p>If you want to access Series' item by its position, you should be using <code>.iloc</code>, e.g.:</p>
<pre><code>df_hours_revenue.Revenue.iloc[line]
</code></pre>
<p>Read more <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">here</a>.</p> | pandas|matplotlib|seaborn | 0 |
18,880 | 56,661,072 | Re-order row data | <p>Based on this question <a href="https://stackoverflow.com/questions/55570389/cant-re-order-columns-data">Can't Re-Order Columns Data</a>, how to do it for the <code>dataframe</code> row? because I have a problem, not in the column order but the row order.</p>
<p>my data looks like this:</p>
<pre><code> B1 ... | <p>you can use <a href="https://pypi.org/project/natsort/" rel="nofollow noreferrer"><code>natsort</code></a></p>
<pre><code>import natsort as ns
df.reindex(ns.natsorted(df.index))
</code></pre>
<hr>
<pre><code> B1 B2
B1 1 1
B2 1 1
B3 1 1
B10 1 1
B11 1 1
B12 1 1
B20 1 1
B21 1 ... | python|pandas|csv|row | 3 |
18,881 | 56,443,925 | How do I format large numbers(int) in pandas dataframe? | <p>I have a balance sheet of a company with large number which, I want to format into a small number, I have this number:</p>
<pre><code>55888000000
</code></pre>
<p>which I need to convert into:</p>
<pre><code>$55.88
</code></pre>
<p>I Have tried this:</p>
<pre><code>pd.options.display.float_format = '{:,.2f}'.f... | <p>Given a dataframe called <code>df</code>: </p>
<pre><code>>>> df = pd.DataFrame({'co1': {'a':55888000000, 'b':3495000000},
'co2': {'a':33888000000, 'b':11495000000}})
>>> df
co1 co2
a 55888000000 33888000000
b 3495000000 11495000000
</code></pre>
<p... | python|pandas|dataframe|formatting | 0 |
18,882 | 26,127,778 | Remove DF Rows Based on a CSV File (Pandas,Python3) | <p>Right now, I am trying to create a function that removes rows based on certain criteria that are outlined within an excel file. This excel file (bad words2) contains word pairs that should be removed from within the DF and looks like this:</p>
<pre><code>header
the man
is a
</code></pre>
<p>The second part of my ... | <p>Some thoughts:</p>
<ol>
<li>The final two operations return a new DataFrame. I.e. they do not modify the DataFrame in-place. You need to assign the result of those operations to something, e.g. <code>df</code>.</li>
<li>And then if you do the above, the variable <code>df</code> is not available for assignment withi... | python-3.x|pandas | 1 |
18,883 | 26,403,884 | Speed up for loop with numpy | <p>How can this next for-loop get a speedup with numpy? I guess some fancy indexing-trick can be used here, but i have no idea which one (can einsum be used here?).</p>
<pre><code>a=0
for i in range(len(b)):
a+=numpy.mean(C[d,e,f+b[i]])*g[i]
</code></pre>
<p>edit:
<code>C</code> is a numpy 3D array of shape comp... | <p>You can do the following trick:</p>
<pre><code>C[d, e][:, np.add.outer(f, b)].dot(g).diagonal().mean()
</code></pre>
<p>improving even more, by prematurely taking the elements that will form the diagonal:</p>
<pre><code>C[d, e][np.arange(len(d))[:, None], np.add.outer(f, b)].dot(g).mean()
</code></pre> | python|arrays|performance|optimization|numpy | 3 |
18,884 | 26,420,593 | Subtracting two columns of decimals in pandas | <p>aI have a dataframe which contains two columns of decimals and i would like to subtract one column from the other one. However, when i try to do something like this:</p>
<pre><code>df['diff'] = df['a'] - ['b']
</code></pre>
<p>i get </p>
<pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'str'
</c... | <p>Just use np.float64 instead of decimal.Decimal</p> | python|pandas | 0 |
18,885 | 67,041,036 | Way to turn dates into a date range in pandas? | <p>If you have a list of dates based on a condition ex:</p>
<pre><code>df
date random_values
2020-03-01 1
2020-03-02 2
2020-03-03 2
2020-04-01 8
2020-04-02 9
2020-04-03 10
2020-05-01 ... | <p>Assuming <code>df.date</code> is a proper <code>datetime</code> column and you've queried your desired <code>dates</code>:</p>
<pre class="lang-py prettyprint-override"><code>df.date = pd.to_datetime(df.date)
dates = df.date.where(df.random_values >= 8)
</code></pre>
<p>You can <a href="https://pandas.pydata.org/... | python|pandas|dataframe | 3 |
18,886 | 67,118,578 | How to clear the row named "Unnamed" in pandas which is merged with all the rows? | <p>I wanna work on this dataset but as you can see in the image, I see an unnamed row which is before the index[0]. But when I check the first row to delete it, I see that it kinda merges with the data in the index [0] in dataFrame. So i tried deleting the first row but then it still merged with next row and then I sea... | <p>It looks like you have a column you do not want, and that's why you see its value on every row you look at.</p>
<p>To validate that the case you can look at your DataFrame's columns by (the second column should be the column you do not want):</p>
<pre><code>df.columns
</code></pre>
<p>If that's really the case you c... | python|pandas | 0 |
18,887 | 66,881,794 | cannot import name 'get_config' from 'tensorflow.python.eager.context' | <p>I was trying to fit my model into history, but my code didn't work. The initial error was</p>
<pre><code>"Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
[[node sequential/conv2d/Conv2D (defined at &... | <p>You are trying to run <code>Tensorflow 1.x</code> code in <code>Tensorflow 2.x</code>, which is causing this error.</p>
<p>You need to install <code>Tensorflow 1.x</code> in your system along with the compatible <code>python version 3.7</code> as per this <a href="https://www.tensorflow.org/install/source_windows#gp... | python|tensorflow|machine-learning | 0 |
18,888 | 66,831,653 | How can I divide a column count total (sum) by a dollar amount using python and pandas? | <p>I am attempting to count colA totals then am needing to divide that total (5550) by $127,200 to get the cost per item.</p>
<p>How can I do this?</p>
<p>I have tried the following:</p>
<pre><code>print('\n Cost per item: ' +str(df.colA.sum() / (cost)))
</code></pre>
<p>I am getting an error of unsupported operand typ... | <p>Can you try to remove the parenthesis from <code>cost</code>?</p>
<pre><code>print('\n Cost per item: ' +str(df.colA.sum() / cost))
</code></pre>
<p>You may be converting the <code>cost</code> into a tuple</p>
<p>Edit: You also need to make sure that <code>colA</code> is indeed a column of integers and not strings.<... | python|python-3.x|pandas|dataframe | 0 |
18,889 | 66,908,393 | Finding the average of values in a column and create a new dataframe that distributes the average | <p>I want to replace existing values in a column with the average values of the same column using python, preferably. I want to distribute the payments equally to all the months from the first month of payment until the last month. The average monthly payments should be distributed per cust_id and sub_id.</p>
<p>Paymen... | <p>As noted in the comments your answer for cust_id=2 and sub_id='C' appears to be inconsistent with your requirements, so I go by the latter.</p>
<p>First, we aggregate dates into a min,max and payments into a sum:</p>
<pre><code>df2 = df.groupby(['cust_id','sub_id']).agg({'date':[min,max], 'payment':sum})
df2.columns... | python|sql|pandas|average | 1 |
18,890 | 66,783,997 | CNN Classifier only guesses one thing - PyTorch | <p>I'm trying to make a model predict the race of a 75x75 image's ethnicity, but when ever I train the model, the accuracy always stays completely still at 53.2%. I didn't realize why until I actually ran it on some of photos. It turned out, that no matter what the photo was, it would always predict 'other'. I'm not en... | <p>The number of layers and the dataset size don't explain this behavior for this example. Your CNN is behaving as a constant function, so far I don't know why, but these might be some clues:</p>
<ol>
<li>Since you have separated your data by label into folders, if you are training your model using only one of those fo... | python|pytorch|conv-neural-network|classification | 1 |
18,891 | 47,242,694 | AttributeError: module 'sklearn.datasets' has no attribute 'load_titanic' | <p>I am trying to load the file titanic and I face the following problem. My code is:</p>
<pre><code>from sklearn import datasets
titanic = datasets.load_titanic()
</code></pre>
<p>I get the following:</p>
<pre><code>AttributeError: module 'sklearn.datasets' has no attribute 'load_titanic'
</code></pre>
<p>While I ... | <p><a href="http://scikit-learn.org/stable/datasets/index.html#toy-datasets" rel="nofollow noreferrer">According to the documentation</a>, there is no toy dataset <code>load_titanic()</code> for the current stable version (<code>scikit-learn v0.19.1</code>) - which version are you using? You get the version via <code>s... | python-3.x|python-3.6|attributeerror|sklearn-pandas | 4 |
18,892 | 47,233,911 | How can I join two dataframes together | <p>My first data frame has various columns one of which contains ID column and my second data frame has various columns one of which contains a No so I have found the link between the two. However how can I link these together using the number to assign the postcode information from data frame 2 to the correct practic... | <p>IIUC, I think what you are looking for is 'left_on' and 'right_on' parameters in merge:</p>
<pre><code>df1.merge(df2, left_on='Practice', right_on='Prac No')
</code></pre>
<p>Output:</p>
<pre><code> ID_x Practice Items Cost ID_y Prac No Dr Postcode
0 0 5 10 2001.0 1 5 ... | python|python-2.7|pandas|dataframe|jupyter-notebook | 1 |
18,893 | 47,288,642 | Tensorflow Regression is predicting insanely wrong values | <p>I am currently doing an exercise for university.
The task is to change a given classification to regression.
I did all the changes to the data's preprocessing and the network, so the regression is executed.</p>
<p>But when I try to test the network's prediction, there are insanely wrong values predicted.</p>
<p>Th... | <p>I could fix the problem, by normalizing the given data.</p> | python|tensorflow|regression|linear-regression | 0 |
18,894 | 10,920,318 | numpy beginner: writing an array using numpy.savetxt | <p>I have a numpy histogram that I would like to output as a tab-delimited text file. My code is below: </p>
<pre><code>targethist = np.histogram(targetlist, bins=ilist)
print targethist
np.savetxt('ChrI_dens.txt',targethist,delimiter='\t')
</code></pre>
<p>targetlist and ilist are long lists of integers. I get the f... | <p>I think that the problem is that the second argument to <code>savetxt</code> must be "array-like". Your input is not "array-like". e.g.</p>
<pre><code>print (len(targethist[0]))
print (len(targethist[1]))
</code></pre>
<p>Notice the lengths aren't the same? If the lengths were the same, numpy could convert it t... | python|numpy|histogram|csv | 4 |
18,895 | 68,208,503 | Merge rows based on value (pandas to excel - xlsxwriter) - addition | <p><a href="https://stackoverflow.com/questions/61217923/merge-rows-based-on-value-pandas-to-excel-xlsxwriter/61228294?noredirect=1#comment120527781_61228294">Following up this question</a></p>
<p>I would like to ask if we could merge rows from multiple columns, i.e.</p>
<p><a href="https://i.stack.imgur.com/RQ8SF.png"... | <p>IIUC:</p>
<p>Firstly:</p>
<pre><code>df=pd.read_excel('filename.xlsx')
#read excel file in pandas
</code></pre>
<p>try via <code>set_index()</code> and <code>to_excel()</code></p>
<pre><code>df.set_index(df.columns[:-1].tolist()).to_excel('filename.xlsx',header=None)
#OR(Since you don't provide data as text so not s... | pandas | 3 |
18,896 | 68,148,306 | Panada groupby, then apply function to compare consecutive values(starting bottom to top) for increase, new column to be created stating true/false | <blockquote>
<p>Here is my data. Q - Y/Y Eps is the quarter growth compared to last
years quarter.
I want to create a new column named 'Increase Eps Growth' that has true and false
values base on whether Q - Y/Y Eps is increasing. The stocks symbols must be
grouped based on symbol and the comparison must start from the... | <p>You can try:</p>
<p>via <code>groupby()</code> and <code>transform()</code>:</p>
<pre><code>df['Increase Eps']=(df.groupby(by='Symbol')['Q - Y/Y Eps']
.transform(lambda x:x.shift(-2) > x.shift(-1)))
</code></pre>
<p><strong>OR</strong></p>
<p>via via <code>groupby()</code> and <code>apply()<... | pandas|dataframe|pandas-groupby | 0 |
18,897 | 68,266,108 | Efficiently handling multiple For Loops and If Statements in Python | <p>I am working with two dataframes. One containing the pair of unique keys and the other having values of those unique keys. There are almost 5.8million pairs.</p>
<p>Dataframe 1 - <code>pair_df</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">key1</th>
<th ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by <code>Series</code> created from <code>key_value_df</code> by set <code>key</code> to <code>index</code>:</p>
<pre><code>s = key_value_df.set_index('key')['value']
... | python|pandas | 1 |
18,898 | 68,185,442 | String replacement of column names in python | <p>I have a data frame <code>df</code> that contains 15 columns (See below)</p>
<p><code>A_phase_1</code>,<code>A_phase_2</code>,<code>A_phase_3</code>,<code>A_phase_4</code>,<code>A_phase_5</code>, <code>B_phase_1</code>,<code>B_phase_2</code>,<code>B_phase_3</code>,<code>B_phase_4</code>,<code>B_phase_5</code>, <code... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>.filter()</code></a> to filter the columns to delete. Then, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.map.html" rel="nofollow noref... | python|pandas|replace|apply | 2 |
18,899 | 68,102,732 | pandas.concat ignores keys when ignore_index=True, is this a bug? | <p>When I do <code>pd.concat((df1, df2), keys=('A', 'B'), ignore_index=True)</code> it ignores the keys. I couldn't find any mention of this in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">documentation</a>, am I missing something or is this a bug... | <p>You might need to add a reset_index() after concatenatinng</p>
<pre><code>print(pd.concat((df1, df2), keys=('A', 'B'), ignore_index=False).reset_index(drop=True, inplace=True))
</code></pre> | python|pandas|concatenation | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.