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 |
|---|---|---|---|---|---|---|
17,000 | 45,842,932 | Pandas drop duplicates with partially completed data in each row and combine data | <p>I have a dataframe with duplicate IDs but the data is partially completed in multiple areas. </p>
<pre><code>df = pd.DataFrame([[1234, 'Customer A', '123 Street', np.nan, np.nan],
[1234, 'Customer A', np.nan, '333 Street', np.nan],
[1234, 'Customer A', '12345 Street', np.nan, np.nan],
... | <p>Here's one approach using <code>apply</code> and create new columns, using <code>dict</code> creation for <code>pd.Series</code></p>
<pre><code>In [1057]: cols = ['Billing Address', 'Shipping Address']
In [1058]: (df.groupby(['ID', 'Customer'])
.apply(lambda g: pd.Series({'%s %s' % (x, i+1): v[x]
... | python|pandas | 3 |
17,001 | 23,313,260 | Do Python functions copy the input parameters to the function? | <p>I have the following example in Python:</p>
<pre><code>import numpy as np
import timeit
# array size
m = 3000
# square array
a = np.random.rand(m, m)
# column vector
b = np.random.rand(m)
# solve
ti = timeit.default_timer()
x = np.linalg.solve(a, b)
tf = timeit.default_timer()
# solve function
def solver(a, b)... | <p>The speed difference is likely due to some memory caching of the contents of <code>a</code> and <code>b</code> that the second call to <code>linalg.solve</code> takes advantage of.</p>
<p>And to answer the question, objects in python are passed by reference, so the only differencein the cost of passing arguments i... | python|python-3.x|numpy|timeit | 1 |
17,002 | 11,707,586 | How do I expand the output display to see more columns of a Pandas DataFrame? | <p>Is there a way to widen the display of output in either interactive or script-execution mode?</p>
<p>Specifically, I am using the <code>describe()</code> function on a Pandas <code>DataFrame</code>. When the <code>DataFrame</code> is five columns (labels) wide, I get the descriptive statistics that I want. However... | <p><strong>Update: Pandas 0.23.4 onwards</strong></p>
<p>This is not necessary. Pandas autodetects the size of your terminal window if you set <code>pd.options.display.width = 0</code>. (For older versions see at bottom.)</p>
<p><code>pandas.set_printoptions(...)</code> is deprecated. Instead, use <code>pandas.set_opti... | python|pandas|printing|column-width | 1,300 |
17,003 | 28,466,772 | Filling date gaps in pandas dataframe | <p>I have Pandas DataFrame (loaded from .csv) with Date-time as index.. where there is/have-to-be one entry per day.
The problem is that I have gaps i.e. there is days for which I have no data at all.
What is the easiest way to insert rows (days) in the gaps ? Also is there a way to control what is inserted in the colu... | <p>You'll could resample by day e.g. using mean if there are multiple entries per day:</p>
<pre><code>df.resample('D', how='mean')
</code></pre>
<p>You can then <code>ffill</code> to replace NaNs with the previous days result.</p>
<p><em>See <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#up-and... | python|datetime|csv|pandas|pad | 12 |
17,004 | 50,779,252 | Creating a numpy array with dimension, mean, and variance as parameters? | <p>How do I create a numpy array with the dimensions, mean, and variance as parameters? I see there is a <code>numpy.random.randn</code> function which allows the user to specify dimensions, but that function assumes a mean of 0 and variance of 1.</p>
<p>I am okay with the mean 0 part, but I want to be able to specify... | <p>You may be looking for <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html#numpy-random-normal" rel="nofollow noreferrer"><code>numpy.random.normal</code></a>. For example:</p>
<pre><code>import numpy as np
arr = np.random.normal(loc=1, scale=0.50, size=(500, 500))
print(... | python|arrays|numpy|random | 4 |
17,005 | 50,854,611 | Pandas groupby multiple columns, sum and append answer as new column to the original dataframe | <p>I have the following dataframe:</p>
<pre><code>In [1]:
import pandas as pd
pd.DataFrame({"AAA":["x1","x1","x1","x1"],
"BBB":["y1","y1","y1","y2"],
"CCC":["t1","t2","t3","t1"],
"DDD":[10,11,18,17]})
Out[1]:
AAA BBB CCC DDD
0 x1 y1 t1 10
1 x1 y1 t2 11
2 x1 y1... | <p>One way is to use:</p>
<pre><code>df['AAA_BBB sum'] = df.groupby(['AAA', 'BBB'])['DDD'].transform(lambda x: x.sum())
</code></pre>
<p>This gives:</p>
<pre><code> AAA BBB CCC DDD AAA_BBB sum
0 x1 y1 t1 10 39
1 x1 y1 t2 11 39
2 x1 y1 t3 18 39
3 x1 ... | python|pandas|dataframe | 5 |
17,006 | 50,784,144 | How to set iteration depth when interating numpy array with e.g. nditer? | <p>supose I have the following array, representing the structure of an rgb image:</p>
<pre><code>[[[ 0, 1, 2], [ 3, 4, 5]]
[[ 6, 7, 8], [ 9, 10, 11]]
[[12, 13, 14], [15, 16, 17]]]
</code></pre>
<p>How can I iterate over the pixels, e.g. [0, 1, 2] then [3, 4, 5], and receive the coresponding index?
With numpys... | <p>If I understood your question correctly you could just use a simple nested loop</p>
<pre><code>A = np.array([[[ 0, 1, 2], [ 3, 4, 5]],
[[ 6, 7, 8], [ 9, 10, 11]],
[[12, 13, 14], [15, 16, 17]]])
for i in range(A.shape[0]):
for j in range(A.shape[1]):
print(i, j, A[i,j,.... | python|numpy|opencv | 4 |
17,007 | 50,998,868 | Implement MSSQL's partition by windowed clause in Pandas | <p>I’m in the process of moving a <code>MSSQL</code> database to <code>MYSQL</code> and have decided to move some stored procedures to <code>Python</code> rather than rewrite in <code>MYSQL</code>. I am using Pandas 0.23 on Python 3.5.4.</p>
<p>The old <code>MSSQL</code> base uses a number of windowed functions. So fa... | <p>I am pretty sure the transform function can help.</p>
<pre><code>df.groupby('Col1'')['Val'].transform(lambda x: x.rolling(3, 2).mean())
</code></pre>
<p>where e.g. the value 3 is the step of the rolling window, and 2 is the minimum number of periods.</p>
<p>(Just don't forget to sort your data frame before applyi... | python|sql-server|pandas | 3 |
17,008 | 20,441,335 | Python: "IndexError: invalid index into a 0-size array" | <p>Obviously, there are loads of threads concerning index errors. But I couldn't find one that helped me out.</p>
<p>I use numpy.loadtxt to read in a function f(a,b).</p>
<pre><code>a, b, f = np.loadtxt(filename, delimiter=' ', usecols=(0,1,2), unpack=True)
</code></pre>
<p>To get a 2d plot I found a solution in ano... | <p>Thanks to seberg's advice, I found the mistake (and I also found old stackoverflow account): </p>
<pre><code>a, b, f = np.loadtxt(filename, delimiter=' ', usecols=(0,1,2), unpack=True)
</code></pre>
<p>I imported the wrong columns from the file. One happened to be constant. So I got nrows=0. And grid was the 0-siz... | python|arrays|numpy|indexing | 1 |
17,009 | 66,657,701 | Insert values in list in DataFrame cell based on string in another cell | <p>I have a pandas DataFrame df containing three columns where one is largely empty. In the first column I have a list of agreements where some of them have similar names. I want to insert a list of values in the empty column if the value in the agreements column starts with a certain string.</p>
<p>Example:</p>
<div c... | <p>use a regex with <code>^</code> which checks for a pattern at the start of a string.</p>
<pre><code>df.loc[df['Agreement'].str.contains('^Agreement'),'Alias'] = [['Agree','Agreement']]
Agreement Alias
0 SampleAgreement None
1 Agreement1 [Agree, Agreement]
2 Agreeme... | python|pandas|dataframe|startswith | 0 |
17,010 | 66,506,636 | create 1-D numpy.ndarray instead of 2 dimensional | <p>I am trying to do a classification using Python.
I have some input columns (let k variables) and one output column.</p>
<pre><code>Let inputfeatures
= array([[ 0, 0, 0, ..., 0, 0, 0],
[ 1, 0, 0, ..., 0, 0, 0],
[ 1, 0, 0, ..., 0, 0, 0],
...,
[ 0, 0, 0, ..., ... | <p>You can't simply transform an <code>n</code>-dimensional label (or "target output") into a 1-dimensional one. In some cases where the output distribution is an <code>m</code>-dimensional manifold embedded into an <code>n</code>-dimensional space, you may try to do a projection first (including, if necessa... | python|arrays|numpy|classification | 1 |
17,011 | 57,319,192 | parsing tsv file starting with quotation mark | <p>I tried to parse a TSV file which contains two columns, some lines only contain quotation mark. Is there a way to parse them as separate lines using python without adding '\' before the quotation mark?</p>
<pre><code>presents O
it O
in O
" O
classical O
" O
principles O
on O
which O
' O
the O
o... | <p>You can tell <code>csv.reader</code> to ignore quote characters by adding <code>quoting = csv.QUOTE_NONE</code> when you create the instance:</p>
<pre><code>import csv
with open("sample.tsv") as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter="\t", quoting=csv.QUOTE_NONE)
for line in tsvreader:
p... | python|pandas|csv | 2 |
17,012 | 24,228,905 | Sample data from combination of two probability distributions | <p>I want to make a mock catalogue. I have access to two sets of real data and I want to use their properties to generate the mock catalogue:
The <strong>first</strong> one contains the information from <strong>magnitude</strong> and <strong>redshift</strong> (<code>z</code>).
The <strong>second</strong> set has inf... | <p>Let R = red shift, M = magnitude, W = weight. If I understand correctly, you are trying to sample from P(W, R).</p>
<p>Given the data at hand, you do not have enough information for a complete solution: note that P(W, R) = P(W | R) P(R) where P(W | R) = \int P(W, M | R) dM = \int P(W | M, R) P(M | R) dM. You can der... | numpy|statistics|scipy|probability-theory | 2 |
17,013 | 43,502,319 | barplot x axis construction from data pandas seaborn python | <p>So i'm trying to create a barplot using seaborn. My data is in the form</p>
<pre><code>Packet number,Flavour,Contents
1,orange,4
2,orange,3
3,orange,2
4,orange,4
...
36, orange,3
1, coffee,5
2, coffee,3
...
1, raisin,4
etc.
</code></pre>
<p>My code is currently:</p>
<pre><code>revels_data = pd.read_csv("testtt.tx... | <p>You want to use <code>hue</code> for that. As well, currently you are displaying the mean of each category. To calculate different function you can use <code>estimator</code>.</p>
<p>Thus, your code should be:</p>
<pre><code>ax = sns.barplot(x="Packet number", y="Contents", hue="Flavour", data=rd)
</code></pre>
<... | python|pandas|bar-chart|seaborn | 2 |
17,014 | 43,552,993 | How to number a columns name pandas | <p>I want to name columns in a pandas dataframe from 1 to length of the data. </p>
<p>I have</p>
<pre><code>foo = pd.DataFrame(n, columns=('protein', 1...n ))
</code></pre> | <p>The default column names in pandas is 0 to range(len(data))-1. So if you don't pass the columns = parameter in pd.DataFrame and then rename first column, you will get desired result</p>
<p>Eg:
n = np.ones(10).reshape(2,5)
df = pd.DataFrame(n) </p>
<pre><code> 0 1 2 3 4
0 1.0 1.0 1.0 1.0 1.0
... | python|list|pandas|dataframe | 1 |
17,015 | 73,064,783 | How to round values in a column of sets within a pandas dataframe? | <p>A confidence interval calculation returns two numbers inside a set of brackets, which I put into a dataframe. From this point, I need to round down the values, and put the output into an excel file.</p>
<p>In the below sample code, how can I round down the values in Col1, to 2 decimals.</p>
<pre><code>import pandas ... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>panda.apply</code></a> on column <code>Col1</code> and <code>round(num, 2)</code> for rounding nums to 2 decimals.</p>
<pre><code>df['Col1'] = df['Col1'].apply(lambda x : tuple([round(x[0], ... | python|pandas|list|xlwings | 2 |
17,016 | 72,850,621 | Weights and Bias dimensions in TensorFlow for LSTM | <p>I am confused about the dimensions of the hidden weight array for an LSTM. I understand the input weight and bias dimension just fine. Now I just recently started learning about RNNs and LSTMs so maybe I do not fully understand their operation. Here is my understanding. A LSTM layer has a number of cells which hold ... | <p>Here are the relevant equations from the Wiki on <a href="https://en.wikipedia.org/wiki/Long_short-term_memory" rel="nofollow noreferrer">LSTM</a></p>
<p><a href="https://i.stack.imgur.com/L6W94.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L6W94.png" alt="" /></a></p>
<p>Notice, that as you sai... | python|tensorflow|keras|lstm|recurrent-neural-network | 2 |
17,017 | 73,082,256 | How to create a list of tokenized words from dataframe column using spaCy? | <p>I'm trying to apply <code>spaCy</code>s tokenizer on dataframe column to get a new column containing list of tokens.
Assume we have the following dataframe:</p>
<pre><code>import pandas as pd
details = {
'Text_id' : [23, 21, 22, 21],
'Text' : ['All roads lead to Rome',
'All work and no play ma... | <p>Try this</p>
<pre><code>example_df["tokens"] = example_df["Text"].apply(lambda x : [token.text for token in nlp.tokenizer(x)])
</code></pre>
<p>which gives us</p>
<p><a href="https://i.stack.imgur.com/juZxN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/juZxN.png" alt="enter i... | python|pandas|nlp|spacy|tokenize | 1 |
17,018 | 73,072,257 | Resolve warning "A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy"? | <p>When I import SciPy or a library dependent on it, I receive the following warning message:</p>
<pre><code>UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1
</code></pre>
<p>It's true that I am running NumPy version 1.23.1, however this message is a... | <p>I have the same issue.</p>
<p>The <a href="https://docs.scipy.org/doc/scipy/dev/toolchain.html#numpy" rel="noreferrer">scipy 1.7.3 docs</a> specifies
<code>1.16.5 <= numpy <1.24.0</code> while in scipy 1.7.3 code <a href="https://github.com/scipy/scipy/blob/59e6539cf80dc04b16b0f0ab52343381f0a7a2fa/setup.py#L55... | python|numpy|scipy|conda | 5 |
17,019 | 72,924,655 | Python How to replace values in specific columns (defined by an array) with zero | <p>I'm trying to replace values in specific columns with zero with python, and the column numbers are specified in another array.</p>
<p>Given the following 2 numpy arrays</p>
<pre><code>a = np.array([[ 1, 2, 3, 4],
[ 1, 2, 1, 2],
[ 0, 3, 2, 2]])
</code></pre>
<p>and</p>... | <p>Your question is:</p>
<blockquote>
<p>I'm trying to replace values in specific columns with zero with python, and the column numbers are specified in another array.</p>
</blockquote>
<p>This can be done like this:</p>
<pre class="lang-py prettyprint-override"><code>a[:,b] = 0
</code></pre>
<p>Output:</p>
<pre><code>... | python|arrays|numpy | 2 |
17,020 | 70,655,623 | Multiply 1 Dataframe by a row in another one selected based on its index value | <p>I am pulling my hair on this one.</p>
<p>I have 2 Dataframes:</p>
<p>df1 holds data for Players with their position (zone) (Forward, Midfield or Defender) and some of their</p>
<p>game stats.</p>
<pre><code>df1 = pd.DataFrame({'Zone': ['DEF', 'MID', 'FWD'], 'Tackles': [5, 10, 5], 'Goals': [0, 1, 1], 'Shots': [10, 5,... | <p>Append temporary <code>Zone</code> as index of <code>df1</code>:</p>
<pre><code>df1['Index'] = df1.set_index('Zone', append=True).mul(df2, level=1).sum(axis=1).values
print(df1)
# Output
Zone Tackles Goals Shots Index
Player A DEF 5 0 10 30
Player B MID 10 1 5 ... | python|pandas|dataframe|indexing|.loc | 0 |
17,021 | 70,632,285 | Is it possible to apply some transformation ( augmentation) of Text data Dynamically during training in Tensorflow? | <p>Let us suppose I have this very simple pipeline <strong>which already works</strong>:</p>
<pre><code>X = [['she let the balloon float up into the air with her hopes and dreams'],
['the old rusted farm equipment surrounded the house predicting its demise'],
['he was so preoccupied with whether or not ... | <p>When I train my models I use the map function in the input pipeline of my dataset. Here is a guide: <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map</a></p>
<p>You need to define a function with the trans... | tensorflow|keras|deep-learning|nlp|tensorflow2.0 | 0 |
17,022 | 70,698,487 | How to get a Pytorch data loader per class? | <p>I want to train my model on 1 MNIST class at a time.</p>
<p>I can load the data with a general loader:</p>
<pre><code>import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.autograd import Variable
trans = transf... | <p>A rather simple solution would involve grouping the dataset by truth value, and creating a unique dataloader per group:</p>
<pre class="lang-py prettyprint-override"><code>...
from torch.utils.data import Subset, DataLoader
subsets = {target: Subset(train_set, [i for i, (x, y) in enumerate(train_set) if y == target... | python|pytorch|pytorch-dataloader | 1 |
17,023 | 42,883,415 | How to replace a value within a tensor by indices? | <p>The below code add something to a specific location within a tensor by indices (thanks to @mrry's answer <a href="https://stackoverflow.com/questions/34685947/adjust-single-value-within-tensor-tensorflow">here</a>). </p>
<pre><code>indices = [[1, 1]] # A list of coordinates to update.
values = [1.0] # A list of v... | <p>A simple option to updating a Tensor based on its own values or indices is using <code>tf.where</code> and <code>tf.tensor_scatter_nd_update</code>:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
x = tf.constant([[4.0, 43.0, 45.0],
[2.0, 22.0, 6664.0],
... | python|tensorflow|tensor | 3 |
17,024 | 42,770,605 | choosing certain columns of a dataframe from a file | <p>I have a dataframe df</p>
<pre><code>Fruit Apple Orange Banana Pear
basket1 0 1 10 15
basket2 1 5 7 10
basket3 10 15 0 0
</code></pre>
<p>I have another dataframe select</p>
<pre><code>type1 type2 type3
Apple Apple Orange
Orange Pear ... | <p>You can create a list of values from your dataframe select:</p>
<pre><code>type1 = list(select['type1'].dropna())
type2 = list(select['type2'].dropna())
type3 = list(select['type3'].dropna())
</code></pre>
<p>The use these lists to select the slice of the df</p>
<pre><code> df_type1 = df[type1]
df_type2 = df[typ... | python|pandas | 1 |
17,025 | 42,871,395 | add rows in pandas dataframe based on date and value | <p>I have a pandas dataframe like the following:</p>
<pre><code>id, date, add_days
1, 2017-01-01, 3
2, 2017-03-05, 5
3, 2017-02-27, 3
.
.
.
</code></pre>
<p>I want to repeat the ids and increase date by given add_days:</p>
<pre><code>id, date, add_days
1, 2017-01-01, 3
1, 2017-01-02, 3
1, 2017-01-03, 3
2, 2017-03-05... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> with <code>groupby</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a>... | python|pandas | 3 |
17,026 | 42,588,416 | Using for loop to build DataFrame | <p>I am using the following code to make a DataFrame which contains closing prices of two symbols with column heading as their symbol name respectively.</p>
<pre><code>symbols=['KEL','PAEL']
start_date = '2016-05-01'
end_date = '2017-03-02'
allocation = 50000
def data(symbol):
dates=pd.date_range(start_date,end_... | <p>your problem is very similar to this one : <a href="https://stackoverflow.com/a/42591863/3027854">https://stackoverflow.com/a/42591863/3027854</a></p>
<p>The mistake you are making as pointed out by @A-Za-z is <code>df=data(symbol)</code> you are overwriting your dataframe so you loose the data for <code>KEL</code>... | python-3.x|pandas | 0 |
17,027 | 42,798,804 | Merce csv files (from a folder) into one, adding columns with different names using Python | <p>I need to merge several CSV files that are located in a folder into a single one.</p>
<p>My original data is like this</p>
<p><strong>y_1980.csv:</strong></p>
<pre><code> country y_1980
0 afg 196
1 ago 125
2 alb 23
3 . .
. . .
</code></pre>
<p><str... | <p>Pandas makes this quite easy. With a loop and merge you can simply do:</p>
<p><strong>Code:</strong></p>
<pre><code>import pandas as pd
files = ['file1', 'file2']
dfs = None
for filename in files:
df = pd.read_csv(filename, sep='\s+')
if dfs is None:
dfs = df
else:
dfs = dfs.merge(df,... | python|csv|pandas|merge | 1 |
17,028 | 26,944,918 | Python: looking for duplicates in list | <p>I have a list of floats, and I want to know how many duplicates are in it.</p>
<p>I have tried with this:</p>
<pre><code>p = t_gw.p(sma, m1, m2) #p is a 1d numpy array
p_list = list(p)
dup = set([x for x in p_list if p_list.count(x) > 1])
print dup
</code></pre>
<p>I have also tried to use collections.co... | <p>Your numpy-array is two-dimensional. So <code>list(p)</code> does not do, what you expect. Use <code>list(p.flat)</code> instead.</p>
<p>Or (mis)use numpy's histogram function:</p>
<pre><code>cnt, bins = numpy.histogram(p, bins=sorted(set(p.flat))+[float('inf')])
dup = bins[cnt>1]
</code></pre> | python|numpy|count|hashable | 2 |
17,029 | 25,247,315 | Scipy output of Kolmogorov–Smirnov test | <p>I have made a call for the KS-test function on python to compare two features: size and duration, and I am kind of lost in explaining the output. Here is my code:</p>
<pre><code>from scipy.stats import ks_2samp
import csv
ds1=getColumn("TraceBG.csv",5)
ds2=getColumn("TraceFG.csv",5)
ds11=getColu... | <p>The KS test is associated with a null hypothesis: The groups being compared are sampled from the same population.</p>
<p>If the null hypothesis is true, the p value is the probability of observing the particular deviation between the sampled groups.</p>
<p>For size, the observed level of deviation is to be expecte... | python|numpy | 1 |
17,030 | 30,387,887 | Repeat pandas dataframe over time | <pre><code>import pandas as pd
import pdb, random
dates = pd.date_range('1950-01-01', '1950-12-31', freq='D')
data = [int(1000*random.random()) for i in xrange(len(dates))]
cum_data = pd.Series(data, index=dates)
</code></pre>
<p>How do I repeat this dataframe over the next 10 years?</p> | <p>This should work.</p>
<p>For each year in the list of years you provide, I extend the data by the same initial dataset unless it is a leap year.</p>
<p>On a leap year, I insert the entry defined by <code>fill_leap</code> at the 60th day (31 days in January + 29 days in February on a leap year)</p>
<pre><code>impo... | python|pandas | 2 |
17,031 | 26,832,866 | Finding what elements are in a 2-D array | <p>I'm trying to find what elements are in a 2-D array, such as something along the lines below:</p>
<pre><code>import numpy as np
a = np.array([[1,0,0],[1,3,0],[2,7,4]])
print find_element(a)
[0,1,2,3,4,7]
</code></pre>
<p>Is there a function that would do this for me?</p> | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a>:</p>
<pre><code>>>> a = np.array([[1,0,0],[1,3,0],[2,7,4]])
>>> np.unique(a)
array([0, 1, 2, 3, 4, 7])
</code></pre> | python|numpy | 4 |
17,032 | 39,392,572 | numpy vectorization of interdependent arrays | <p>I need to populate two interdependent arrays simultaneously, based on their previous element, like so:</p>
<pre><code>import numpy as np
a = np.zeros(100)
b = np.zeros(100)
c = np.random.random(100)
for num in range(1, len(a)):
a[num] = b[num-1] + c[num]
b[num] = b[num-1] + a[num]
</code></pre>
<p>Is ther... | <p>As mentioned in @Praveen's post, we can write those expressions for few iterations trying to find the closed form and that would be a triangular matrix of course for <code>c</code>. Then, we just need to add in <em>iteratively-scaled</em> <code>b[0]</code> to get full <code>b</code>. To get <code>a</code>, we simply... | numpy|vectorization | 3 |
17,033 | 39,203,714 | List of Structure subclass returns wrong values when casting to numpy array | <p>I've built a simple Structure subclass with two fields, holding a void pointer to an array, and the array length. However, when I try to create a list of these using input lists of the same length, the value of the returned void pointer is the same as the last array used to create the instance:</p>
<pre><code>from ... | <p>The problem is that the numpy array is immediately garbage-collected and the underlying memory freed, resulting in a dangling pointer.</p>
<p>The solution is to keep a reference to the underlying <code>buffer</code> object:</p>
<pre><code>def __init__(self, seq):
array = np.array(seq, dtype=np.float64)
sel... | python|arrays|numpy|ctypes | 2 |
17,034 | 19,522,857 | About NumPy array in Python | <p>What is the difference between:</p>
<pre><code>import numpy as np
A = np.zeros((3,))
</code></pre>
<p>and</p>
<pre><code>import numpy as np
B = np.zeros((1,3))
</code></pre>
<p>Thanks for your answer!</p> | <p>The first one creates a 1D <code>numpy.array</code> of zeros:</p>
<pre><code>>>> import numpy as np
>>> A = np.zeros((3,))
>>> A
array([ 0., 0., 0.])
>>> A[0]
0.0
>>>
</code></pre>
<p>The second creates a 2D <code>numpy.array</code> of 1 row and 3 columns, filled with... | python|arrays|numpy | 2 |
17,035 | 29,057,130 | Python 3.4 Pandas 15.2join function locks pc | <p>I'm loading 6 small csv files with 100krecords, indexed by a 15 alphanumeric text field using a laptop with an i5 and 8Gig of ram. </p>
<p>I load the files into memory, which shows 9% used. Then I execute a join statement. </p>
<pre><code> Df1.join(df2,df3,df4,df5,df6) # join all tables
</code></pre>
<p>Yes, i... | <p>This seems like it might be because of a silly problem. pandas should give you an error message, but your tables are too large for it to realize that they're the wrong types. Here's what I think is going on:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.15.2/generated/pandas.DataFrame.join.html#pan... | python|join|memory|pandas | 0 |
17,036 | 29,337,714 | How to run naive Bayes from NLTK with Python Pandas? | <p>I have a csv file with feature (people's names) and label (people's ethnicities). I am able to set up the data frame using Python Pandas, but when I try to link that with NLTK module to run a naive Bayes, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\file.py",... | <p>This line</p>
<pre><code>featuresets = [(feature, label) for index, (feature, label) in frame.iterrows()]
</code></pre>
<p>is choking nbc.train()</p>
<p>featuresets should be of the form [(featureset, label)] , where the featureset variable is a <i>dict</i> (not a str) and label is the known class label for the f... | python-2.7|pandas|classification|nltk|naivebayes | 1 |
17,037 | 29,237,412 | Transforming DataFrame | <p>here' a question on transforming a DataFrame. After creating a DataFrame from a pivot table and applying .unstack(), I came up with a table like this</p>
<pre>
Amount
Color Red Yellow Blue Green
Date
2006-01 56 41 15 10
2006-01 51 23 26 36
2006-01 36 54 ... | <p>You can get rid of your top-level columns by just selecting the one top-level column value:</p>
<pre><code>df = df["Amount"]
</code></pre>
<p><code>Color</code> isn't the name of a column - it's the name of the row of column names. If you don't want your column levels to have names, you can set them to <code>None... | python|pandas|dataframe | 3 |
17,038 | 33,899,369 | Ranking order per group in Pandas | <p>Consider a dataframe with three columns: <code>group_ID</code>, <code>item_ID</code> and <code>value</code>. Say we have 10 <code>itemIDs</code> total.</p>
<p>I need to rank each <code>item_ID</code> (1 to 10) <strong>within</strong> each <code>group_ID</code> based on <code>value</code>, and then see the mean rank... | <p>There are lots of different arguments you can pass to <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.rank.html" rel="noreferrer"><code>rank</code></a>; it looks like you can use <code>rank("dense", ascending=False)</code> to get the results you want, after doing a <code>groupby<... | python|pandas | 86 |
17,039 | 23,520,952 | Python: Change format of np.array or allow tolerance in in1d function | <p>I have two numpy arrays (data files loaded with <code>np.loadtxt</code>). They do not have the same length (or number of rows if you will).</p>
<p>I want to create a mask, where I find the values in the smaller array in the larger array. For that I can use <code>np.in1d</code>. However, the precision on the larger ... | <p>You could do it as shown below. If <code>a</code> and <code>b</code> get large, this is going to need lots of memory (on the order of the product of the sizes of a and b). Maybe you could loop over into small-enough chunks of b if that's a problem.</p>
<pre><code>import numpy as np
def in1d_tol(a,b,tol):
d=n... | python|arrays|numpy|intersection | 2 |
17,040 | 22,906,167 | How to set xlim for a plot in python? | <p>why doesn't "xlim" work in the following script:</p>
<pre><code>from pylab import *
from numpy import *
x = linspace (0, 2*pi, 100)
y = sin (x)
clf ()
plot (x, y, 'b-', label = "sin (x)")
xlim (0, 2*pi)
axis ('equal')
grid ()
legend ()
show ()
</code></pre> | <p>If you leave out the use of <code>axis('equal')</code> aspect ratio, the limitation of the x-values works for me. Possibly this is different for different Matplotlib backends. I am using Mac Os X default backend.</p> | python|python-2.7|numpy|matplotlib | 0 |
17,041 | 15,436,716 | Best way to represent a training set to split with | <p>A training set is made off a set of samples and a set of labels one for each sample. In my case a sample is a vector while a label is a scalar. To deal with this I use Numpy. Consider this example:</p>
<pre><code>samples = np.array([[1,0],[0.2,0.5], [0.3,0.8]])
labels = np.array([1,0,0])
</code></pre>
<p>Now I hav... | <p>The mixing of indices with float datatypes makes me uneasy. When you say split the training set, is this completely random? If so I would go with the random permutation vector - I don't think your solution is any faster (even without my data type reservations) because you're still allocating memory when creating you... | python|arrays|numpy|artificial-intelligence | 1 |
17,042 | 29,507,928 | Replace slice of a numpy array with values from another array | <p>Say I've got two numpy arrays which were created this way:</p>
<pre><code>zeros = np.zeros((270,270))
ones = np.ones((150,150))
</code></pre>
<p>How can I insert <code>ones</code> in <code>zeros</code> at position <code>[60,60]</code>?
I want an array that looks like a "square in the square".</p>
<p>I've tried th... | <p>This is one way you can replace values in zeros with ones. </p>
<pre><code>zeros[60:210,60:210] = ones
</code></pre> | python|arrays|numpy|insert | 7 |
17,043 | 62,258,704 | What does 'INFO:tensorflow:Oracle triggered exit' mean with keras tuner? | <p>When I run Keras Tuner search, the code runs for some epochs and then says:
'INFO:tensorflow:Oracle triggered exit'.</p>
<p>What does this mean? I am still able to extract best hyperparameters. Is it due to early stopping? I have tried both randomsearch and hyperband.</p> | <p>You can solve this with:</p>
<pre><code>tuner = RandomSearch(
tune_rnn_model,
objective='val_accuracy',
seed=SEED,
overwrite=True,
max_trials=MAX_TRIALS,
directory='project')
</code></pre>
<p>To begin a new search and ignore any prior results, we set <code>overwrite=True</code>. Alternativel... | python|tensorflow|keras|neural-network|keras-tuner | 3 |
17,044 | 62,446,668 | pandas substraction by column value | <p>I have one time series on a pandas dataframe that has a row with the month. I've called df1. Then I get the monthly mean by group_by, I've called df2 the resulting dataframe. Now I would like to subtract the monthly mean of each column without using a loop. This is, the row "month==1" in df2, needs to be subtracted ... | <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> for new <code>DataFrame</code> filled by aggregate values, so possible subtract by <a href="http://pandas.pydata.org/pandas-docs/stable/refer... | python|pandas|dataframe|array-broadcasting | 1 |
17,045 | 62,419,264 | Update multiple rows in MySQL with Pandas dataframe | <p>I have worked on a dataframe (previously extracted from a table with SQLAlchemy), and now I want to retrieve the changes updating that table.</p>
<p>I have done it in this very unefficient way:</p>
<pre><code>engine = sql.create_engine(connect_string)
connection = engine.connect()
metadata = sql.MetaData()
pbp = ... | <p>Consider using proper placeholders instead of manually formatting strings:</p>
<pre><code>query_update = sql.text("""
UPDATE playbyplay
SET Player_1_Visitor = :Player_1_Visitor_y
, Player_2_Visitor = :Player_2_Visitor_y
, Player_3_Visitor = :Player_3_Visitor_y
, Player_4_Visitor = :Player_... | python|mysql|pandas|sqlalchemy | 2 |
17,046 | 62,250,027 | Historic Stock Prices in Pandas DataFrame | <p>This code is able to get the history of stock prices and the dates are set as the index of the DataFrame.</p>
<p>How can I pass the dates (index) to a column and add the ticker out of iteration to another column?</p>
<pre><code>import yfinance as yf
import pandas as pd
tickers = ["GOOG","AMZN"]
df2 = pd.DataFram... | <p>You can just do this:</p>
<pre><code>for ticker in tickers:
tkr = yf.Ticker(ticker)
hist = tkr.history(period="1y")
df2 = df2.append(hist)
df2['Ticker'] = ticker
print(df2.reset_index())
Date Open High Low Close Volume Dividends Stock Splits Ticker
0 2019-06-06 ... | python|pandas | 1 |
17,047 | 62,364,429 | Android semantic segmentation post-processing is too slow | <p>I'd really appreciate it if anyone can advise with a task I've been working without success for the last week.
I have semantic segmentation model (MobileNetV3 + Lightweight ASPP).Short info: input - 1024x1024, output - same size and 2 classes (bg and vehicle), so my output shape is (1, 1048576, 2). I'm not the mobil... | <p>New Update. Thanks to <a href="https://stackoverflow.com/users/7118084/farmaker">Farmaker</a>, I used a piece of code found in his repo from comment above and now pipeline looks like:</p>
<pre class="lang-java prettyprint-override"><code> int channels = 3;
int n_classes = 2;
int float_byte_size = 4;
... | java|android|tensorflow-lite|opencv4android|semantic-segmentation | 1 |
17,048 | 62,360,340 | mode.save() create only one file | <p>i read the documentation of model.save(). it says that it creates the folder but when i save it it just create a single file. when i use this file to change the code from keras to tensorflow-lite it gives this error:</p>
<pre><code>OSError: SavedModel file does not exist at: C:\Users\Munib\New folder\3_layer_model_... | <p>I think the model you saved is a <code>keras model</code> and not 'SavedModel<code>. So, you need to use</code>from_keras_model` as shown below. </p>
<p>I tried to simulate the issue by using simple model and was successfully reproduced your issue. check below fro the code.</p>
<pre><code>!pip install tf-nightly
i... | python|tensorflow|keras|model | 2 |
17,049 | 51,387,753 | how to filter string with regular expression in pandas dataframes | <pre><code>import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13] ['Adam', 14]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
3 Adam 14
</code></pre>
<p>I want to get only Names starting with A . I tried following code
mask = d... | <p>Use this:</p>
<pre><code>mask = df['Name'].str.startswith("A")
</code></pre>
<p>For example:</p>
<pre><code>In [52]: df
Out[52]:
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
3 Adam 14
In [53]: mask = df['Name'].str.startswith("A")
In [54]: df[mask]
Out[54]:
Name Age
0 Alex 10
3 Ada... | python|pandas | 4 |
17,050 | 51,186,374 | Import System Modules in a Conda Environment | <p>I have installed caffe and pytorch0.3 in my system path(environment), and there is a project which only works under caffe and history version of pytorch0.2. To solve that I install pytorch0.2 in a Conda environment and I wonder if there is any way can save me from installing a caffe again in this conda environment. ... | <p>Activate your environment and try the following</p>
<pre><code>conda install package-name --offline
</code></pre>
<p>Also, in case you wish to clone the root or some other environment to a conda environment, you can use -- clone. For instance, when you wish to clone the root - </p>
<pre><code>conda create -n pyto... | anaconda|conda|pytorch | 1 |
17,051 | 51,529,840 | Pandas combine duplicate columns that contain strings | <p>I'm having problems (sort of) with combining duplicate columns. It seems to work on older versions of Pandas/Python (not sure what the culprit is here), but not on the latest version. </p>
<p>I basically have a dataframe of mixed values with duplicate column names after a concat. The values are either going to be a... | <p>I think you need <code>transpose</code> the dataframe firstly, <code>reset the index</code>, and then <code>rename</code> the duplicate <code>index</code> column values, and lastly use <code>groupby</code>.</p>
<pre><code>df_t = df.T.reset_index()
df_t["index"] = df_t["index"].str.split(".").str[0]
result = df_t.gr... | python|pandas|pandas-groupby | 1 |
17,052 | 51,171,560 | compare two columns having list of strings in pandas | <p>I have a data frame in pandas having two columns where each row is a list of strings, how would it be possible to check if there is word match(es) in these two columns on a unique row(flag column is the desired output)</p>
<pre><code>A B flag
hello,hi,bye bye, also 1
but, as wel... | <p>You can convert each value to separately words by split and <code>set</code>s and check intersection by <code>&</code>, then convert values to boolean - empty sets are converted to <code>False</code>s and last convert it to <code>int</code>s - <code>Falses</code> are <code>0</code>s and <code>True</code>s are <c... | python|pandas | 3 |
17,053 | 48,067,854 | Trouble understanding tensorflow shuffle_batch enqueue_many=False | <p>I am reading the Tensorflow documentation and the code for the Cifar10 example. This bit is currently racking my brain:</p>
<pre><code># Creates batches of 32 images and 32 labels.
image_batch, label_batch = tf.train.shuffle_batch(
[single_image, single_label],
batch_size=32,
num_threads=4,
capacity=50000,... | <p>The <code>single_image</code> or <code>single_label</code> tensor would usually refer to an operation that retrieves the next value from a queue. To create a batch, it would then for example retrieve the batch size (e.g. 32) of values from those tensors if it wasn't shuffled. In the case where it is shuffled it will... | python|tensorflow | 1 |
17,054 | 48,591,713 | Pearson correlation and nan values | <p>I have two CSV_files with hundreds of columns and I want to calculate Pearson correlation coefficient and p value for every same columns of two CSV_files. The problem is that when there is a missing data "NaN" in one column, it gives me an error. When ".dropna" removes nan value from columns, sometimes the shapes of... | <p>Here is one solution. First calculate the "bad" indices for your 2 numpy arrays. Then mask to ignore those bad indices.</p>
<pre><code>x = np.array([5, 1, 6, 9, 10, np.nan, 1, 1, np.nan])
y = np.array([4, 4, 5, np.nan, 6, 2, 1, 8, 1])
bad = ~np.logical_or(np.isnan(x), np.isnan(y))
np.compress(bad, x) # array([ ... | python|arrays|numpy|nan|pearson-correlation | 12 |
17,055 | 48,777,345 | Vectorized random walk in Python with boundaries | <p>I'm trying to simulate a 2-D random walk in python with boundaries (the particle/object will can't cross the boundaries and must return back). However my version is not vectorised and is very slow. How do I implement it without(or minimising) the use of loops.</p>
<p>Here is my approach</p>
<pre><code>def bound_wa... | <p>Here is one approach that is fast, but not 100% equivalent to your implementation. The difference is that in my implementation, at the boundary the chance of going in one of the directions parallel to the boundary is half that of the directions retreating from the boundary. That is arguably the better model if you t... | python|python-2.7|numpy|scipy | 1 |
17,056 | 48,653,893 | merging two dataframes with same rows and indexes in pandas | <p>I'm trying to merge two pandas dataframes that have common row indexes and common columns 0,1,2 but different column 3, so the resulting dataframe has columns from both:</p>
<p>First dataframe:</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 817 entries, 0 to 816
Data columns (total 3 column... | <p>I would try:</p>
<pre><code>pd.merge(df, df2, on=['0', '1'])
</code></pre>
<p>maybe</p>
<pre><code>pd.merge(df, df2, on=[0,1]
</code></pre> | python|pandas|dataframe|merge | 3 |
17,057 | 48,455,129 | Pip is correctly installing libraries to the proper directory, but I cannot import those packages properly in program | <p>I installed (with pip) MatPlotLib and Pandas, and they are both not working properly in programs. Here is the strange thing...
When I type the following into the interactive environment of IDLE
import pandas as pd</p>
<p>pd.Series([1, 2, 3, 4, 5])</p>
<p>I get this as output: (indicating that it works properly)</... | <p>SOLVED. So when I did:</p>
<p>import sys</p>
<p>sys.path.append(path to pandas library) </p>
<p>it worked! so now I can fully use pandas. I guess I will just have to do this anytime I download a new library and it doesn't work. Thank you for all the help</p> | python|python-3.x|pandas|python-import | 0 |
17,058 | 70,744,865 | Make a Column Based on Pandas Timeseries Minutes OHLCV Dataframe Where New Column Fills with Corresponding Day's First Value from a Specific Column | <p>My initial <strong>Pandas Dataframe</strong> is:</p>
<pre><code> Open High Low Close Volume
2021-11-19 09:30:00-05:00 16549.50 16559.25 16516.25 16530.25 20198.0
2021-11-19 09:35:00-05:00 16530.50 16562.00 16525.50 16556.50 11274.0
..... | <p>Here is my <strong>solution</strong>. May be there are better solutions than this solution.</p>
<pre><code>#Here df is our initial ohlcv dataframe
#Groupby date and timestamp
df1 = pd.DataFrame(df.groupby([df.index.date, df.index], axis=0)['Open'].first())
#Make Timestamp as column
df1.reset_index(level=1, inplace... | python|pandas|dataframe|numpy|time-series | 0 |
17,059 | 70,764,910 | convert dataframe in python to json or dictionary type object | <p>I have data frame like</p>
<pre><code>data = pd.DataFrame({'col1' :['A','A','A','B','B','C','C','C'], 'col2': ['13','15','17','11','15','12','21','23'], 'col3' : [3,5,8,7,2,5,1,3]},columns= ['col1', 'col2', 'col3'])
print(data)
col1 col2 col3
0 A 13 3
1 A 15 5
2 A 17 8
3 B 11 ... | <p>You'll have to bite the bullet and use a lambda with a groupby statement.</p>
<p>Note lambda's aren't very efficient and this doesn't really seem like a logical / proper json structure.</p>
<p>but to answer your question.</p>
<pre><code>data.groupby('col1')\
.apply(lambda x : {'col2' : dict(zip(x['col2'],x[... | python|pandas | 0 |
17,060 | 70,884,452 | Formatting column in pandas to decimal places using table.style based on value | <p>I am trying to format a column in a dataframe using style.
So far I successfully used the styling for a fixed number of decimals:</p>
<p>mytable.style.format('{:,.2f}', pd.IndexSlice[:, ['Price']])</p>
<p>but I need to expand this to formatting based on value as this:</p>
<ul>
<li>if value is >=1000, then format ... | <p>Building upon @Code_beginner's answer – the callable should return formatted string as output:</p>
<pre><code>def my_format(val):
if val >= 1000:
return f"{val:,.0f}"
if val >= 1:
return f"{val:,.2f}"
return f"{val:,.5f}"
mytable.style.format({'Price':... | pandas|dataframe | 2 |
17,061 | 70,755,256 | How to add elements of an array to a numpy array to represent coordinates? | <p>Hey people of Stackoverflow,
I want to achieve the following procedure.
I have these 2 arrays:</p>
<pre><code>a = np.array([175, 370])
b = [array([175, 176, 176, 176]), array([371, 369, 370, 371])]
</code></pre>
<p>the elements of b array should represent coordinates of some points</p>
<pre><code>b = [array[x1, x2, ... | <p>You can try the <a href="https://docs.python.org/3.9/library/functions.html#zip" rel="nofollow noreferrer">zip</a> function to pair two arrays in <code>b</code> and append it to <code>a</code></p>
<pre><code>import numpy as np
a = [175, 370]
b = [np.array([175, 176, 176, 176]), np.array([371, 369, 370, 371])]
a = ... | python|arrays|numpy | 0 |
17,062 | 70,839,909 | Merge pandas dataframes and transform in SQL | <p>I have few dataframes:</p>
<p><strong>DF_1</strong></p>
<pre><code>| | TYPE | SYMBOL | DESCRIPTION | OPOL | FIRST_INTEREST_DATE |
|----|------|--------|-------------|------|---------------------|
| 0 | BOND | 1 | FIRST | 10 | 20220531 |
| 1 | BOND | 2 | SECOND | 20 | ... | <p>you need to upload code or show a sample of your data.</p>
<p>Anyways here's a solution based on a limited information that you've provided:</p>
<p><code>df_3 = pd.concat([df_1, df_2], axis=0)</code></p>
<p>then you can use</p>
<pre class="lang-py prettyprint-override"><code>from sqlalchemy import create_engine
engi... | python|sql|pandas|dataframe | 1 |
17,063 | 70,973,508 | Calculate amount of rows satisfy condition in multiple columns | <pre><code>import pandas as pd
# initialize list of lists
data = [['tom', 'Y','Y','N'], ['nick', 'N','N','N'], ['juli', 'N','Y','N'],
['Luc', 'Y','Y','N'], ['Adg', 'Y','N','N'], ['Flav', 'N','Y','N'],
['Alf', 'Y','Y','N'], ['Jut', 'Y','N','N'], ['Uan', 'Y','Y','Y']]
# Create the pandas DataFrame
df = ... | <p>just group by them:</p>
<pre><code>df = df.groupby(['Tipo_1', 'Tipo_2','Tipo_3']).count().reset_index()
print(df)
</code></pre>
<p>output:</p>
<pre><code>>>>
Tipo_1 Tipo_2 Tipo_3 Name
0 N N N 1
1 N Y N 2
2 Y N N 2
3 Y Y N 3
4 ... | python|pandas|plot | 4 |
17,064 | 51,596,059 | python cx_oracle hang when storing as DataFrame? | <p>I'm trying to store the results of an Oracle SQL query into a dataframe and the execution hangs infinitely. But, when I print the query it comes out instantly. What is causing the error when saving this as a DataFrame?</p>
<pre><code>import cx_Oracle
import pandas as pd
dsn_tns = cx_Oracle.makedsn('HOST', 'PORT', s... | <p>Pandas's <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow noreferrer"><code>read_sql</code></a> requires a connection object for its <em>con</em> argument not the result of a cursor's <code>execute</code>. Also, consider using <a href="http://docs.sqlalchemy.org/en/... | python|oracle|pandas | 0 |
17,065 | 51,618,724 | Reshaping dataframe from vertical to horizontal in python | <p>I have data samples from a database which I want to reshape from vertical to horizontal in python for further data analysis.
The dataframe looks like this:</p>
<pre><code>ID measured_at weight
aa 2017-11-04 78.1
bb 2018-04-08 74.2
bb 2018-04-16 73.2
bb 2018-04-28 72.1
cc 2018-03-02 90.2
cc 2018-0... | <p>You can use <code>GroupBy</code> with <code>list</code> a couple of times, followed by <code>pd.concat</code>.</p>
<p>I leave renaming columns and elevating index to column as an exercise.</p>
<pre><code>g = df.groupby('ID')
df_dates = pd.DataFrame(g['measured_at'].apply(list).values.tolist(), index=g.groups)
df_w... | python|pandas|dataframe|data-analysis | 0 |
17,066 | 51,831,526 | pandas merge multiple dataframes | <p>For example: I have multiple dataframes. Each data frame has columns: variable_code, variable_description, year. </p>
<p>df1:</p>
<pre><code>variable_code, variable_description
N1, Number of returns
N2, Number of Exemptions
</code></pre>
<p>df2:</p>
<pre><code>variable_code, variable_description
N1, ... | <p>First, concatenate df1, df2, by using </p>
<pre><code> final_df = pd.concat([df1,df2]).
</code></pre>
<p>Then we can convert columns variable_code, variable_name into dictionary. variable_code as keys, variable_name as values by using </p>
<pre><code> d = dict(zip(final_df['variable_code'], final_df['variable_na... | pandas|dataframe | 0 |
17,067 | 41,719,812 | Error while calling eval() on Tensor variable in keras | <p>I am using keras and using a layer output for some modifications. Before, using the output ( a tensor variable ) I am converting it to numpy array and thus calling eval() on it, as below:</p>
<pre><code>def convert_output(orig_output):
conv_output = invoke_modifications(orig_output.eval(), 8)
</code></pre>
<p>... | <p>You don't need to call eval() at all, your conversion_method should be done using symbolic functions (the ones from keras.backend) and should be differentiable.</p>
<p>It won't work otherwise, the network won't be able to be trained with Keras/Theano.</p> | python|numpy|theano|keras|keras-layer | 1 |
17,068 | 47,916,065 | Summing edges in pandas | <p>Have a dataframe that represents a network with directed edges between nodes A, B and C. I want to sum the flows between nodes to measure the strength of connections between nodes. Below is the df I have..</p>
<pre><code>To From Flow
A A 1
A B 4
A C 2
B A 5
B B 2
B C 6
C A 3
C B 5
C... | <p>Here is one way to solve this.</p>
<pre><code>df["Node 1"] = df[["To","From"]].min(axis=1)
df["Node 2"] = df[["To","From"]].max(axis=1)
result = df.groupby(["Node 1","Node 2"], as_index=False)["Flow"].sum()
</code></pre>
<p>The first two lines just create a consistent order for the groups. The third line just adds... | python|pandas | 1 |
17,069 | 48,967,207 | Convert Time with AM/PM and +UCT (Python) | <p>I'm trying to convert
<code>'11/09/2011 11:33:00 PM +0000'</code> (object) into a datetime variable using Pandas' <code>pd.to_datetime()</code>:</p>
<pre><code>df['Datetime'] = pd.to_datetime(df['Datetime'],format = '%d/%m/%Y %I:%M:%S %p', utc=True)
</code></pre>
<p>however getting a error back:</p>
<blockquote>... | <p>If the <code>+0000</code> is fixed you can add it to the format string like:</p>
<h3>Code:</h3>
<pre><code>pd.to_datetime(df['Datetime'], format='%d/%m/%Y %I:%M:%S %p +0000', utc=True)
</code></pre>
<h3>Test Code:</h3>
<pre><code> df = pd.DataFrame([
'11/09/2011 11:33:00 PM +0000',
'11/09/2011 11:33:00 P... | python|pandas|datetime | 1 |
17,070 | 49,140,589 | Filling Pandas columns with lists of unequal lengths | <p>I am having trouble filling Pandas dataframes with values from lists of unequal lengths.</p>
<p><code>nx_lists_into_df</code> is a list of numpy arrays.</p>
<p>I get the following error: </p>
<blockquote>
<p>ValueError: Length of values does not match length of index</p>
</blockquote>
<p>The code is below:</p>... | <p>We'll leverage <code>pd.Series</code> to attach an appropriate index and will allow us to use the <code>pd.DataFrame</code> constructor without complaining of unequal lengths.</p>
<pre><code>df1, df2 = (
pd.DataFrame(dict(zip(df_cols, map(pd.Series, d))))
for d in nx_lists_into_df
)
</code></pre>
<hr>
<pr... | python|python-3.x|pandas|numpy | 1 |
17,071 | 58,998,132 | Pandas dataframe conditional column based on multiple conditions only working on first condition? | <p>I have a data frame that looks something like this: (there are about 100 more columns irrelevant to my conditional column calculation)</p>
<pre><code>col1 col2 col3
a NaN NaN
b NaN NaN
NaN a NaN
NaN b NaN
NaN NaN a
NaN NaN b
</code></pre>
... | <p>Let us try <code>bfill</code></p>
<pre><code>df['col4']=df.bfill(1).iloc[:,0]
df
Out[107]:
col1 col2 col3 col4
0 a NaN NaN a
1 b NaN NaN b
2 NaN a NaN a
3 NaN b NaN b
4 NaN NaN a a
5 NaN NaN b b
</code></pre> | python|pandas|dataframe | 4 |
17,072 | 58,960,685 | Joint distribution from pandas dataframe? | <p>I have a pandas dataframe that has two columns <code>A</code> and <code>B</code>, both of which contain numbers. I want to create a joint distribution from these columns, ie. I want to bin both columns (where each bin of <code>A</code> contains every bin of <code>B</code>, and so on for a joint distribution) and ass... | <p>You can cut <code>A</code> and <code>B</code> into their own bins, then apply a <code>groupby</code> to count them:</p>
<pre><code># Some sample input data
np.random.seed(42)
df = pd.DataFrame(np.random.randint(1, 1000, (1000, 2)), columns=['A', 'B'])
# Assign values in columns A & B into 5 bins each
# The bin... | pandas | 0 |
17,073 | 58,956,597 | Elegant mapping of GroupBy into dataframe | <p>In order to best decide how to handle missing data of each feature in a weather dataset, I want to get the length of the longest block of NaNs for each feature and each weather station, the latter being denoted by 'id'. Although the following accomplishes this, I am aware of the code's awkwardness. What would be an ... | <p>How about applying your function to the groupby using <code>agg</code>:</p>
<pre><code>result = weather_df.groupby('id').agg({
'temperature': max_repeated_nans,
'wind_speed': max_repeated_nans
})
</code></pre> | python|pandas|dataframe|pandas-groupby|missing-data | 1 |
17,074 | 70,132,755 | Pandas fill NaN in columns based on some conditions | <p>I have a pandas dataframe which consists of weekly values for a given id, looking something like :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>val_week1</th>
<th>val_week2</th>
<th>val_week3</th>
<th>val_week4</th>
<th>val_week5</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>... | <pre class="lang-py prettyprint-override"><code>temp = df.filter(like='val')
temp = temp.mask(temp.cumsum(1).eq(0), np.nan)
df.assign(**temp)
id val_week1 val_week2 val_week3 val_week4 val_week5
0 1 NaN NaN 3.0 2.0 0
1 2 1.0 0.0 0.0 2.0 ... | python|pandas|dataframe | 3 |
17,075 | 70,152,993 | Python: Intersect 2 lists mucisians with excluding the ratings from the list with basic tools | <p>Trying to intersect 2 lists of musicians with their rating in each specific list. Want to find similarities: whose musicians who are in both lists, but to do so I have to exclude the rating.
First I tried to write the code to find the same musicians for lists without ratings, however got empty output [].
May be some... | <p>Modify your intersection function as such</p>
<pre><code>def intersect(list_of_names1, list_of_names2):
list1 = [" ".join(line[:-1]) for line in list_of_names1]
list2 = [" ".join(line[:-1]) for line in list_of_names2]
list3 = list(set(list1) & set(list2))
return list3
p... | python-3.x|numpy|intersect | 1 |
17,076 | 56,296,468 | Get variable scope in tensorflow 2.0 | <p>I am using the new version of tensorflow (2.0.0 alpha) and I dont know why it does not allow me to run:</p>
<pre><code>tf.get_variable_scope().reuse_variables()
</code></pre>
<p>I am getting the following error:</p>
<pre><code>AttributeError: module 'tensorflow' has no attribute 'get_variable_scope'
</code></pre... | <p>From comments</p>
<blockquote>
<p>No, <code>variable_scope</code> and <code>get_variable</code> have been removed from <code>TensorFlow 2.x</code> (although you can still find them under <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1" rel="nofollow noreferrer">tf.compat.v1</a>). In <code>TF 2.x</co... | python|tensorflow|variables|scope | 1 |
17,077 | 55,870,089 | How to create a new column with values after groupby & rollingsum? | <p>I am trying to create a new column in an existing <code>df</code>. The values of the new column are created by a combination of the groupby and rolling sum. How do I do this?</p>
<p>I've tried two approaches both resulting in either NaN values or 'incompatible index of the inserted column with frame index'</p>
<p>... | <p>To ensure alignment on the original (non-duplicated) index:</p>
<pre><code>df.groupby('HomeTeam', as_index=False)['FTHP'].rolling(4).sum().reset_index(0, drop=True)
</code></pre>
<hr>
<p>With a <code>df</code>:</p>
<pre><code> HomeTeam FTHP
A a 0
B b 1
C b 2
D a 3
E ... | python|pandas|group-by|multiple-columns|rolling-sum | 0 |
17,078 | 64,983,913 | How to vectorize pandas operation | <p>I have a dataset of house sales with timestamped Periods(per quarter). I want to adjust the price according to the house pricing index change per region. I have a separate dataframe with 3 columns, the Quarter, the Region and the % change in price. I am currently achieving this by iterating over both dataframes. Is ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with <code>left_on</code> and <code>right_on</code>, then get all 4 column in output:</p>
<pre><code>df = houses_df.merge(HPindex_df,
le... | python|pandas|dataframe | 2 |
17,079 | 64,646,490 | Calculate similarity between rows of a dataframe (count values in common) | <p>I want to calculate similarity between the rows of my dataframe. I have some columns with informations about some people. One row is one person. It looks like that :</p>
<pre><code> print(df)
id name firstname email town age
0 1 martin pierre truc@machin.com Paris... | <p>You can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="noreferrer"><code>scipy.spatial.distance.pdist</code></a> with a custom distance function</p>
<pre><code>from scipy.spatial.distance import pdist, squareform
pd.DataFrame(1 - squareform(pdist(df.set_inde... | python|python-3.x|pandas|dataframe | 6 |
17,080 | 64,718,049 | Multiindex Re-indexing - custom sort | <p>How do you reindex a multiindex? I have 2 indexes, where the first one requires a manual sort, and the 2nd index is by descending order.</p>
<p>In the below, index1 needs to be custom sorted by: Cat-B, Cat-A, Cat-C; index2 by descending order.</p>
<pre><code>Index1 Index2
Cat-A Apple
Orange
Banana
Cat... | <p>You need <code>pd.CategoricalIndex</code> however since this orders in one direction we will manually need to invert the order.</p>
<pre><code>cati = pd.CategoricalIndex(
df.index.get_level_values(0).unique(), ["Cat-C", "Cat-A", "Cat-B"], ordered=True
)
#note 'Cat-C' is first but wi... | python|pandas|dataframe|sorting | 0 |
17,081 | 64,627,576 | Pass weights into CrossEntropyLoss in correct order | <p>I'm trying to use weight in <code>torch.nn.CrossEntropyLoss</code>,</p>
<p>but I'm not sure which order should I put</p>
<p>e.g.</p>
<pre><code> weight = torch.tensor([1.0, 52337/34649, 52337/11066]).to(device)
criterion = nn.CrossEntropyLoss(weight=weight)
</code></pre>
<p>My class0 has 52337 examples ... | <p>after you define your criterion as above you will have to call it like:</p>
<pre><code>loss = criterion (inputs, targets)
</code></pre>
<p>the targets will be encoded 0 .. C-1 where C is number of classes (0,1 or 2 in your case). So your weights order and number should correspond to your targets.</p> | python|pytorch | 0 |
17,082 | 64,789,762 | add rows to pandas dataframe based on days in week | <p>So I'm fairly new to pandas and I run into this problem that I'm not able to fix.</p>
<p>I have the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'Day': ['2018-12-31', '2019-01-07'],
'Product_Finished': [1000, 2000],
'Product_Tested': [50, 10]})
df['Day'] = pd.to_datetime(d... | <p>You can achieve this by first creating a new DataFrame that contains the desired date range using pandas.date_range.</p>
<p>Step 2, use pandas.merge_asof specifying to get the last value.</p> | python|pandas|dataframe | 0 |
17,083 | 40,251,658 | How to fill missing DataFrame value by copying a value from another column | <p>Mick Jagger's last name is missing in a data. Only the fist name and the band's name were specified </p>
<pre><code>import pandas as pd
df = pd.DataFrame({ 'fist': ['John', 'Mick'],
'last':['Lennon', ''],
'band':['Beatles', 'Rolling Stones'] })
</code></pre>
<p>I can easi... | <p>a missing data would normally be a NaN values, not a string. So in the case that you have NaNs instead of '', you can actually pass another <code>column</code> to the <code>fillna()</code> method:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({ 'fist': ['John', 'Mick'],
... | python|pandas|dataframe | 2 |
17,084 | 40,101,130 | how do I calculate a rolling idxmax | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the... | <p>There is no simple way to do that, because the argument that is passed to the rolling-applied function is a plain numpy array, not a pandas Series, so it doesn't know about the index. Moreover, the rolling functions must return a float result, so they can't directly return the index values if they're not floats.</p... | python|pandas|numpy|dataframe|series | 14 |
17,085 | 40,900,034 | Python - Extract matrix a into matrix b | <p>I would like to extract matrix A (4,4) into matrix b (7,4).</p>
<p>Below matrix :</p>
<pre><code>>>> Matrix_A = numpy.array([[[10,1.5,-3.8,8.0],[20,10.2,5.2,6.7],[30,0.5,-6.2,-7.1],[40,-0.7,-0.6,-0.5]]])
>>> Matrix_A
array([[[ 10. , 1.5, -3.8, 8. ],
[ 20. , 10.2, 5.2, 6.7],
... | <p>First off all since your arrays ar 3d arrays you should squeeze the size to convert them to 2d arrays for the ease of computation.</p>
<pre><code>In [27]: Matrix_A = np.squeeze(Matrix_A)
In [28]: Matrix_B = np.squeeze(Matrix_B)
</code></pre>
<p>Then you can use <code>np.in1d</code> to find the indices of the comm... | python|numpy|matrix|compare | 1 |
17,086 | 41,048,270 | Next day or next row index in Pandas Data frame | <p>I am trying to find a way to get the next day (next row in this case) in a Pandas dataframe. I thought this would be easy to find but Im struggling. </p>
<p><strong>Starting Data</strong>:</p>
<pre><code> ts = pd.DataFrame(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.columns = ['Va... | <p>I managed to work this one out so sharing the answer:</p>
<pre><code> ts.loc[tsSig.index + pd.DateOffset(days=1)]
tsSig['Val_Dayplus1'] = ts['Val'].ix[tsSig.index + pd.DateOffset(days=1)].values
tsSig
Val Week Val_Dayplus1
2000-02-15 1.551125 7 -0.102154
2000-02-24 1.525402 8 -... | python|pandas | 2 |
17,087 | 41,023,733 | Use Google Cloud Machine Learning service to predict with a locally retrained Inception model | <p>I have locally retrained the Inception model using the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py" rel="noreferrer">retrain.py</a> file from Google Code Lab TensorFlow for Poets and want to use Google Cloud machine Learning service to make prediction... | <p>This <a href="https://cloud.google.com/blog/big-data/2016/12/how-to-train-and-classify-images-using-google-cloud-machine-learning-and-cloud-dataflow" rel="nofollow noreferrer">posting</a> yesterday by Google's <a href="https://stackoverflow.com/users/6915676/slaven-bilac">Slaven Bilac</a> appears to be the answer.</... | tensorflow|google-cloud-ml | 3 |
17,088 | 53,946,436 | multiple index to columns in pandas | <p>I have a dataframe in pandas:</p>
<pre><code>(index) amount
0.0 0 73.74770979
0.0 1 34.36146516000001
1.0 0 25.759792399999995
1.0 1 117.37044276999995
</code></pre>
<p>I would like to have a DataFrame like this:</p>
<pre><code>index amount_0, amount_1
0.0 73.... 34...
1.0 25.... 117...
</co... | <p>I believe <code>df.unstack(level=-1)</code> should do the trick.</p> | python|python-3.x|pandas|dataframe | 2 |
17,089 | 66,135,132 | Apply dictionary to dataframe column containing strings | <p>I am trying to apply a dictionary to a dataframe column that contains rows of strings, eg:</p>
<p>0 [some, text, etc...</p>
<p>1 [other, text...</p>
<p>And have used the code below that works on a single string but not for a dataframe:</p>
<pre><code>dict = pd.read_csv(r'C:\Users\dictionary.csv', header=... | <p>This error can come out if you have NaN value in your Data Series</p> | pandas|dictionary|normalization | 0 |
17,090 | 66,240,259 | Prediction with ANN are most of the time false | <p>my probleme is that my ANN predicts only about 2 times out of 10 the right digit but when the ANN was fitted it tells me about 98% accuarcy. I'm quit a starter with ANNS and I don't know if I'm missing something abvious or why it is like it is.
For testing I use a tabel with 81 digits (allways in a row from 1 to 9).... | <p>One thing you can do is add validation_data in model.fit like this :</p>
<pre><code> model.fit(x_train, y_train, epochs=50, validation_data=(x_test,y_test))
</code></pre>
<p>You can also add some 2Dconv layers with pooling before the flatten one. Or add more neurones.</p>
<p>Let me know if it helps.</p> | python|tensorflow|keras|mnist|digits | 0 |
17,091 | 66,235,771 | Need a more efficient way of creating a dictionary of dataframes from a single large dataframe | <p>So the issues is that I have a large dataframe (some millions of rows) and I need to split it into separate dfs based on a value of metric (which can have several thousand unique values in the df) and then put all individual dfs into a dictionary.</p>
<p>The data looks like this:</p>
<pre><code>>>> df.sampl... | <pre class="lang-py prettyprint-override"><code>df_grouped = df.groupby('metric')
mhi_dict = {}
for key in df_grouped.groups:
group = df_grouped.get_group(key)
mhi_dict[key] = group
</code></pre> | python|pandas | 1 |
17,092 | 52,852,742 | how to read tensorflow confusion matrix rows and columns | <p>For my 2 classes (<code>1 = [0, 1]</code> and <code>0 = [1, 0]</code>) CNN model I use <code>tf.confusion_matrix</code> to finding a confusion matrix for the model. one of my results is like below for validation set:</p>
<pre><code>[ [1800 17]
[283 600] ]
</code></pre>
<p>after doing some search I see more th... | <p>The truth is behind the code ;)
<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/confusion_matrix.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/confusion_matrix.py</a></p>
<blockquote>
<p>Class labels are expected to s... | python-3.x|tensorflow | 1 |
17,093 | 52,631,632 | Regex: How to capture words with spaces/hyphens excluding numbers? | <p>I have a dataset that looks like this:</p>
<pre><code>Column1
-------
abcd - efghi 1234
aasdas - asdas 54321
asda-asd 2344
aasdas(asd) 5234
</code></pre>
<p>I want to be able to pull everything out that will exclude a number so it will look like this:</p>
<pre><code>Column2
-------
abcd - efghi
aasdas - asdas
asd... | <p>Like using <code>replace</code> </p>
<pre><code>df.Column1.str.replace('\d+','')
Out[775]:
0 abcd-efghi
1 aasdas-asdas
2 asda-asd
3 aasdas(asd)
Name: Column1, dtype: object
#df.Column1=df.Column1.str.replace('\d+','')
</code></pre> | python|regex|string|pandas | 2 |
17,094 | 52,873,451 | Pandas: difference between groups | <p>Hi I have a panda df that looks like the following (not real data)</p>
<pre><code>index datedjourney sequence values
1 1 1 120
2 1 1 100
3 1 2 75
4 1 3 50
5 1 3 30
6 ... | <p>Create a "diff_between_groups" column which is the difference between "values" and "values" shifted one row.</p>
<p>Make a boolean mask to find the rows where "datedjourney" is the same and "sequence" is different from the row above.</p>
<p>Use pandas Series where function to replace "diff_between_groups" values u... | python|pandas | 2 |
17,095 | 46,625,632 | tensorflow reduce_mean vs numpy mean | <p>As far as I understand tensorflow reduce_mean and numpy mean should return identical values, but below example returns different values:</p>
<pre><code>import numpy as np
import tensorflow as tf
t_1 = tf.constant([1,3,4,5])
t_2 = tf.constant([7,8,9,0])
list_t = [t_1, t_2]
reduced_t_list = tf.reduce_mean(list_t)
se... | <p>From <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/constant_op/constant_value_tensors#constant" rel="nofollow noreferrer"><code>tf.constant</code> docs</a>:</p>
<pre><code>If the argument dtype is not specified, then the type is inferred from the type of value.
</code></pre>
<p>The <code>dtype... | numpy|tensorflow|mean | 1 |
17,096 | 68,926,632 | Create Repeating N Rows at Interval N Pandas DF | <p>i have a df1 with shape 15,1 but I need to create a new df2 of shape 270,1 with repeating rows from each row of the rows in df1 at intervals of 18 rows 15 times (18 * 15 = 270). The df1 looks like this:</p>
<pre><code> Sites
0 TULE
1 DRY LAKE I
2 PENASCAL I
3 EL CABO... | <p>I FINALLY found the answer: convert the dataframe to a series and use repeat in the form: my_series.repeat(N) and then convert back the series to a df.</p> | pandas|dataframe|rows|repeat | 0 |
17,097 | 44,571,370 | Filtering a dataframe from information in another dataframe using Pandas | <p>I have a dataframe that is below.</p>
<pre><code>df = pd.DataFrame(columns=['Chromosome', 'Start','End'],
data=[
['chr1', 2000, 3000],
['chr1', 500, 1500],
['chr3', 3000, 4000],
['chr5', 4000, 5000],
['chr17', 9000, 10000],
['chr19', 1500, 2500]... | <p>You can try this:</p>
<pre><code>df.merge(probes, left_on='Chromosome', right_on='Chrom').query('Start < Position < End')
</code></pre>
<p>Output:</p>
<pre><code> Chromosome Start End Probe Chrom Position
0 chr1 2000 3000 CG999 chr1 2500
2 chr19 1500 2500 CG000 chr19 2... | python|pandas|filter | 5 |
17,098 | 60,894,305 | Memory problem using python pandas to join stock DataFrames in loop | <p>I am trying to join a lot of dataframes in order to do the correlation matrix in pandas.
So, it seems that I have to keep on adding columns on the right hand, with the "Date" as the index.
But, when I try to do this function with just 50 dataframes, it ends with the memory error.</p>
<p>Is there anyone knows what i... | <p><code>Pandas</code> is not designed for such dynamic concatenations. You could just append things into a list, and convert that list into a DataFrame. Like so:</p>
<pre><code>join=[]
for key, value in stock_dic.items():
join.append({'Date':value} )
df_join=pd.DataFrame(join)
</code></pre> | python|mysql|pandas | 1 |
17,099 | 60,912,882 | Is there a way to print a pandas data frame as copyable code? | <p>Every now and then I need to debug code and arrive to a point where I find a valid "oracle" or "fixture" for a new test case and then need to print the data frame to the console and turn it into a data frame initialization code. Is there a way to print a data frame into copyable code? I know I could just dump it in ... | <p>If what you seek is representation of the DataFrame that could be use as valid Python code as suggest you use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">to_dict</a>, as follows:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(da... | python|pandas | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.