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 |
|---|---|---|---|---|---|---|
352,300 | 70,121,476 | how to pysimplegui manage dataframe in excel? | <p>i want to delete dataframe unnamed in red arrow , and the i want to add some text when i click submit i have index from 1 not in 0 like this</p>
<p><a href="https://i.stack.imgur.com/jyEpg.png" rel="nofollow noreferrer">Data_entry.xlsx</a></p>
<p>can you give me solution about this problem ?</p>
<p>in above my code ... | <p>There's are some issues here.</p>
<ul>
<li>Create a blank excel file to store your data.</li>
<li>Open excel file as a dataframe, option <code>index_col</code> set the index column or you may get <code>Unnamed: 0</code> column as index in your dataframe.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>df ... | python|pandas|openpyxl|pysimplegui | 1 |
352,301 | 70,142,870 | Pulling specific word from dataframe string column and storing in new column in Python | <p>I have a Python dataframe column <code>Name</code> who's elements always contain a first name, last name, and the word "over" or "under"</p>
<p>For example: <code>Name</code> = <code>[Michael Johnson Over, Michael Johnson Under, John Smith Over, John Smith Under]</code></p>
<p>I'm trying to creat... | <p><code>.str</code> is a property on <code>pd.Series</code> that exposes string-parsing functionality such as <code>.contains</code>. You can set a new column with boolean indexing where the condition is whether or not the row in <code>"Name"</code> contains the keywords <code>"Over"</code> or <cod... | python|pandas|string|dataframe|split | 1 |
352,302 | 70,047,528 | How do you extract faces from a numpy-stl mesh? | <p>I've read the documentation and searched the internet, however, couldn't reach any useful information.<br />
I'm loading a mesh from file into python using:</p>
<pre><code>import numpy
from stl import mesh
tank = mesh.Mesh.from_file('tank.stl')
</code></pre>
<p>Now I need to extract faces of this tank model, any hel... | <p>With the package trimesh:</p>
<pre><code># Package
import trimesh
myobj = trimesh.load_mesh("tank.stl", enable_post_processing=True, solid=True) # Import Objects
myobj.show()
print(myobj.faces)
</code></pre> | python|mesh|numpy-stl | 1 |
352,303 | 70,310,155 | Pandas split and append | <p>I'm new to working with pandas, I don't know how to solve the following problem.</p>
<p>I have the following dataframe:</p>
<pre><code> 0 1 2 3 4 5
0 a 1 d 4 g 7
1 b 2 e 5 h 8
2 c 3 f 6 i 9
</code></pre>
<p>and I have to turn into the following:</p>
<pre><code>a 1
b... | <p>Try this:</p>
<pre><code>data = {
0: pd.concat(df[c] for c in df.columns[0::2]).reset_index(drop=True),
1: pd.concat(df[c] for c in df.columns[1::2]).reset_index(drop=True),
}
df = pd.DataFrame(data)
</code></pre>
<p>Output:</p>
<pre><code>>>> df
0 1
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f ... | python|pandas | 4 |
352,304 | 70,348,464 | Ray - Tensorflow - parallel processing issue | <p>By following the article
<a href="https://towardsdatascience.com/modern-parallel-and-distributed-python-a-quick-tutorial-on-ray-99f8d70369b8" rel="nofollow noreferrer">https://towardsdatascience.com/modern-parallel-and-distributed-python-a-quick-tutorial-on-ray-99f8d70369b8</a>
I'm trying to use Ray module for paral... | <p>I believe the issue is that you are creating some TF objects (e.g., <code>variable</code>, <code>initialize</code>, and <code>assign</code>) in your main script and then using them inside of the actor. This causes Ray to try to serialize the TF objects when it serializes the <code>Simulator</code> class definition (... | python|tensorflow|ray | 0 |
352,305 | 70,198,804 | Pandas reading csv from url, read first row and set header as second | <p>I have a csv where the first row contains the version number and the 2nd row contains the headers.</p>
<p>Is it possible to read the first row (save the version number to a variable), then create the data frame using the following row as the header?</p>
<p><code>data = pd.read_csv(url, header=1, encoding='windows-12... | <p>Use <code>nrows</code> parameter for read only first row and select columns and then for <code>DataFrame</code> excluded this data use <code>skiprows=1</code> parameter:</p>
<pre><code>c = pd.read_csv(url, nrows=0, encoding='windows-1252').columns
last = c[0]
date = c[1]
data = pd.read_csv(url, skiprows=1, encoding... | python|pandas | 0 |
352,306 | 70,323,908 | trying to get rid of string in column | <pre><code>bank['aon'].apply(lambda x : x == np.nan if bank[bank['aon'].str.contains('UA')] else x)
</code></pre>
<p>ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> | <p>Use a vectorial operation with <code>mask</code>:</p>
<pre><code>bank['aon'] = bank['aon'].mask(bank['aon'].str.contains('UA'))
</code></pre> | pandas | 0 |
352,307 | 70,191,519 | Error Using Apply Function to Create a New Column Based on Multiple Values | <p>I'm trying to write an if, elif function to determine a student's college selectivity based on their GPA and SAT score. My dataframe has the students' names as the index, their GPA, and their SAT score. I want to create a new column that states their selectivity. I thought at first I was messing up my and vs &, ... | <p>In Python, <code>&</code> refers to "bitwise and" - which means that each bit between its arguments are "anded". Example would be</p>
<pre><code> 0b01 & 0b11 == 0b01
</code></pre>
<p>You want to use a "logical and" there, which in python is simply the word <code>and</code>. So ... | python|pandas|dataframe | 0 |
352,308 | 70,262,345 | Pandas dataframe from list of array and multiple array | <p>Currently, I create separate <code>df</code> and finally concat these <code>df</code> to create a single <code>dataframe</code>.</p>
<pre><code>import numpy as np
import pandas as pd
blist_l=['a','b','c','d','e']
nlabel_l=['dis_label']
rt_l=['re','rq']
N=100
nlist=[np.random.rand(5) for _ in range(N)]
nlabel=np.ra... | <p>You can do as follows but it is not exactly really what I would call clean code:</p>
<pre><code>N=100
nlist=[np.random.rand(5) for _ in range(N)]
pd.DataFrame(
{'dis_label' : np.random.randint(3,size=N)} |
dict(zip(['re','rq'], np.random.rand(N,2).T)) |
dict(zip(['a','b','c','d','e'], np.array(nlist).... | python|pandas | 0 |
352,309 | 70,194,210 | How to create a 2D numpy array of pixel values? | <p>I want to create a 2d numpy array of all the pixel locations for a 512 x 512 image. Meaning there would be 512<sup>2</sup> or 262,144 values. It may be slightly more if the x and y zeroes are considered, but you get the idea.</p>
<p>To do it manually would be like this <code>pixels = np.array([[0, 1], [0, 2], [0,3],... | <p>Try this:</p>
<pre><code>pixels = np.array([[x, y] for y in range(512) for x in range(512)])
</code></pre>
<p>Note that you can modify it for different x or y values.</p> | python|arrays|numpy | 3 |
352,310 | 70,118,644 | How do I calculate the transaction amount which is divisible by 10 in pandas | <p>I want to create a new column and assign 0 or 1 based on the condition i.e. if transaction_amount is divisible 10. Transaction_amount is one of the columns from df.</p>
<p>Tried the below code but it is not working.</p>
<pre><code>df = df.assign(whole_amt = lambda x: 1 if (x.transaction_amount%10==0) else 0,axis=1)
... | <pre><code>df['div10'] = df['transaction_amount'].apply(lambda x: 1 if x % 10 == 0 else 0)
</code></pre> | python|pandas|dataframe | 1 |
352,311 | 70,156,785 | How to iterate list in numpy and avoid TypeError: Only integer scalar arrays can be converted to a scalar index | <p>I am using numpy:
I have a list:<code>[array([2, 5, 0, 6, 6, 0, 2, 0]), array([3, 2, 5, 4, 4, 5, 6, 0]), array([1, 1, 5, 1, 4, 6, 0, 0]), array([1, 3, 5, 4, 2, 2, 5, 3]), array([5, 0, 6, 3, 1, 0, 5, 3]), array([1, 5, 1, 6, 0, 3, 5, 5]), array([4, 6, 1, 1, 3, 5, 2, 6]), array([5, 5, 1, 2, 6, 0, 5, 0])] <class 'lis... | <p>To iterate over list of arrays, try this:</p>
<pre><code>fit=[]
for state in collection: #Iterate over each element in the collection
test = Review(state)
fit.append(test.function())
print(fit)
</code></pre>
<p>Or</p>
<pre><code>fit=[]
for i in collection:
state = i
test = Review(state)
fit.appe... | python|arrays|list|numpy|iteration | 1 |
352,312 | 70,205,764 | Indexing a 4D NumPy Array with two 2D arrays | <p>I have a 4D target NumPy array which I want to fill with values from a 2D source array, using two additional 2D arrays which specify the position in the second and third axis of the target array where the value from the source array should be placed. The code below with some sample values can do this using a for-loo... | <pre><code>for t in range(T):
for d in range(D):
n = index_dim_1[t, d]
m = index_dim_2[t, d]
target[t, n, m, d] = source[t, d]
</code></pre>
<p>Since you provide code, but no example, I'll skip that step myself, and 'eyeball' an answer - without testing.</p>
<pre><code> target[np.arange(T)[:... | python|arrays|numpy|multidimensional-array|matrix-indexing | 0 |
352,313 | 70,169,097 | Pandas: transforming dataframe to nested dictionary | <p>I have this dataframe:</p>
<pre><code>Month_Year City_Name Chain_Name Product_Name Product_Price
11-2021 London Aldi Pasta 2.33
11-2021 Bristol Spar Bananas 1.45
10-2021 London Tesco Olives 4.12
10-2021 Cardiff Spar Pasta 2.25
</cod... | <p>You can group your dataframe by all columns except price, then create your dictionaries in a loop:</p>
<pre><code># if more than one price for one product in a chain, then calculate mean:
grouped_df = df.groupby(['Month_Year', 'City_Name', 'Chain_Name', 'Product_Name']).agg('mean')
result = dict()
nested_dict = dic... | python|pandas|dictionary|data-structures|tree | 1 |
352,314 | 70,266,143 | sorting multiple pandas columns and calculating value percent greater than zero | <p>I have a pandas dataframe I melted together with each row being a different single-cell gene expression. I want to sort by metadata columns ('patient ID', 'Cluster ID', 'Gene ID') and count how many cells have a value greater than zero in the 'value' column.</p>
<p>Next I want to divide that by the total value of ce... | <p>Okay I found a way to get what I want:</p>
<p>total counts:</p>
<pre><code>CRC_Merge_GD_total_TEST = CRC_GD_Melt_1.groupby(['HTO_secondID', 'new_clusters_3', 'variable'])['value'].agg(pos=lambda ts: (ts.ge(0)).sum())
CRC_Merge_GD_total_TEST = CRC_Merge_GD_total_TEST.rename(columns={"pos": "Sum of to... | pandas|dataframe|sorting|counting | 0 |
352,315 | 70,090,225 | Given a number, how to get the previous and next value inside a list? | <p>I have the following dataframe:</p>
<pre><code>VALUE_TO_FIND UNORDERED_LIST
5 [0,10]
3 [1,0,10,8,4,2]
2 [9,10,0]
5 [4,8,0,1,2,10]
4 [0,10,4]
</code></pre>
<p>Given the value from column <code>VALUE_TO_FIND</code>, how can I get the previous and next v... | <p>There might be a more efficient solution, but I have tried <code>zip</code>ping the two relevant columns:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'VALUE_TO_FIND': [5, 3, 2, 5, 4,],
'UNORDERED_LIST': [[0,10], [1,0,10,8,4,2], [9,10,0], [4,8,0,1,2,10], [0,10,4],]})... | python|pandas|dataframe | 1 |
352,316 | 70,230,698 | Pandas rsplit with if contains | <blockquote>
<p>Using python with if contains(r'/' and r'\') and rsplit(str,1) I can
separate the values. But using Pandas is not working.
How can I get this result using pandas?</p>
</blockquote>
<pre><code>"PATH_IN","PATH_OUT"
"C:\USER\ARON\TESTE.TXT","C:\OUT\TESTE.TXT"
"S... | <p>Try this:</p>
<pre><code>df['NAME_IN'] = df['PATH_IN'].str.split(r'[/\\]').str[-1]
df['NAME_OUT'] = df['PATH_OUT'].str.split(r'[/\\]').str[-1]
</code></pre>
<p>Output:</p>
<pre><code>>>> df
PATH_IN PATH_OUT NAME_IN NAME_OUT
0 C:\USER\ARON\TESTE.TXT C:\OUT\TESTE.TXT TESTE.T... | pandas|string|contains | 0 |
352,317 | 70,136,050 | Drop rows in a dataframe based on type of the entry | <p>Suppose I have a dataframe <code>x</code> that has a column <code>terms</code>. Terms are supposed to be of type string, but some contain numbers and for this reason I want to delete the rows in the dataframe where the corresponding <code>terms</code> values are integers/floats. I tried the following but received a ... | <p>Say you have a dataframe like this:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a':[1,'sd','sf',2,5,'13','s','143f','d234f','z24']})
# notice 13 is a string here ^^^^
a
0 1
1 sd
2 sf
3 2
4 5
5 13
6 s
7 143f
8 d234f
9 z24
</code></pr... | python|python-3.x|pandas|dataframe | 1 |
352,318 | 70,375,263 | Python: Remove strings from list that doesn't contain specific string but not exact match | <p>I have a list of strings</p>
<p><strong>e.g:</strong></p>
<pre><code>kw_list =
['facebook',
'google',
'bank',
'bank cd rates',
'forever 21',
'bank rates',
'bank of america mortgage rates',
'bank exchange rates']
</code></pre>
<p>and I have a string</p... | <p>I tried something like this, by splitting and checking each word in list:</p>
<pre><code>def check_keyword(kw_string, kw_split):
word_list = kw_string.split(' ')
for word in kw_split:
if word not in word_list:
return False
return True
kw_list = ['facebook',
'google',
... | python|pandas | 1 |
352,319 | 70,320,248 | using entry.get in a list count in python | <p>I try to use the ID entry from the GUI to count the similar IDs in the Excel column.</p>
<p>I always get a <code>0</code> in the if-loop and red color shows.
But there are similar IDs in the column.</p>
<h3>My code</h3>
<pre class="lang-py prettyprint-override"><code>l1 = tk.Label(tab2, text="Status Check"... | <p>I totally agree with <a href="https://stackoverflow.com/questions/70320248/using-entry-get-in-a-list-count-in-python#comment124311906_70320248">furas comment</a>. Thank him, he solved it.</p>
<h3>Issue</h3>
<p>Currently the code is reading the input from your text-field before button is pressed. Place a <code>print(... | python|excel|pandas|tkinter | 0 |
352,320 | 70,073,982 | Way to populate .csv with scraped data in Python with pandas that's closest to 'print' | <p>I managed to scrape multiple pages and I can print my results correctly with:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.marketresearch.com/search/results.asp?qtype=2&datepub=3&publisher=Technavio&categoryid=0&sortby=r'
def scrape_it(url):
... | <h3>What happens?</h3>
<p>Actually you are not storing or returning any information and your indentation of printing is outside the loop.</p>
<h3>How to fix?</h3>
<p>Store the information from iteration in a list of dicts and return it to create a data frame from it:</p>
<pre><code>data = []
for report in reports:... | python|pandas|web-scraping|beautifulsoup | 0 |
352,321 | 70,366,271 | How build two graphs in one figure, module Matplotlib | <p>How to build two graphs in one figure from the equations below</p>
<ol>
<li>y = (x+2)^2</li>
<li>y = sin(x/2)^2</li>
</ol>
<p>There is my code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from math import sin
y = lambda x: sin(x / 2) ** 2
y1 = lambda x: (x + 2) ** 2
fig = plt.subplots()
x = ... | <p>Use <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer"><code>supplots</code></a> to make 2 Axes in your Figure:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, (ax1,ax2) = plt.subplots(nrows=2)
x = np.linspace(-3, 3, 100)
ax1.plot(x... | python|python-3.x|numpy | 0 |
352,322 | 70,163,072 | Python Extracting rows not in another numpy array | <p>Given two numpy matrices 'a' and 'b', I am trying to extract rows in 'a' that are not in 'b'. The problem is the dimension of 'b' is not fixed. If I use <code>.tolist()</code>, then it does not work when 'b' has dimension = 1, since it considers each row with individual elements of 'b' instead of the entire 'b' arra... | <p><code>np.isin</code> actually works and the correct way to do is like this:</p>
<pre><code>>>> a = np.arange(1, 10).reshape(3,3)
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> b
array([[1, 2, 3],
[4, 5, 6]])
>>> c = np.arange(1, 4).reshape(1, 3)
>>&g... | python|numpy | 0 |
352,323 | 70,330,604 | Can I install pytorch cpu + any specified version of cudatoolkit? | <p>My remote has <code>cuda==11.0</code> and I want to install <code>pytorch</code> on it.</p>
<p>I use the command <code>conda install pytorch cudatoolkit=11.0 -c pytorch -c conda-forge</code> but in the installation list:</p>
<pre><code>cudatoolkit conda-forge/linux-64::cudatoolkit-11.0.3-h15472ef_8
pytorch ... | <p>It all depends on whether the <strong>pytorch</strong> channel has built a version against the particular <code>cudatoolkit</code> version. I don't know a specific way to search this, but one can <a href="https://anaconda.org/pytorch/pytorch/files" rel="nofollow noreferrer">browse what builds are available</a> on th... | pytorch|conda | 2 |
352,324 | 70,056,112 | Can't draw circle with right proportions Matplotlib Python | <p>I want to draw Circle on my plot. For this purpose I decided to use patch.Circle class from matplotlib. Cirlce object uses <strong>radius</strong> argument to set a radius of a circle, but if the axes ratio is not 1 (see my plot), how to draw circle with right proportions?
My code for drawing circle is:</p>
<pre><co... | <p>You could use <a href="https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html" rel="nofollow noreferrer"><code>ax.transData</code></a> to transform <code>1,1</code> vs <code>0,0</code> and obtain the deformation in x vs y direction. That ratio can be used to know the horizontal versus the vertical... | python|pandas|matplotlib | 2 |
352,325 | 70,127,250 | Table formatting with pandas Dataframe.to_latex() | <p>Is there any way to instruct pandas <code>Dataframe.to_latex()</code> to append <code>\footnotesize</code> (or other global options) for the output table in LateX? (Of course, other than manually append it, which is not efficient, as I'm generating lots of tables.)</p>
<p>So, right now my code produces the following... | <p>You can tell latex to make these changes for all your tables:</p>
<pre><code>\documentclass{article}
\usepackage{float}
\usepackage{booktabs}
\usepackage{multirow}
% change fontsize
\AtBeginEnvironment{tabular}{\footnotesize}
% switch off centering in tables
\AtBeginEnvironment{table}{\let\centering\relax}
\beg... | python|pandas|latex | 1 |
352,326 | 70,278,189 | How to generate weights with constraint \sum{x_i} = 1 for more than two assets in a meshgrid fashion? | <p>I would like to generate asset weights for more than two assets in a meshgrid fashion so that the sum is one. For example, I can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.linspace.html" rel="nofollow noreferrer">numpy's linespace</a> with two assets, but not sure how to go about it with mor... | <p>Here is a solution that fits your examples.</p>
<p>Using integer partitioning!</p>
<pre class="lang-py prettyprint-override"><code>from sympy.utilities.iterables import partitions
from more_itertools import distinct_permutations
# if you don't want to install more_itertools:
# set(itertools.permutations( ... ))
... | python|algorithm|numpy | 1 |
352,327 | 56,156,032 | Why do I get RuntimeError: CUDA error: invalid argument in pytorch? | <p>Recently I've frequently been getting <code>RuntimeError: CUDA error: invalid argument</code> when calling functions like <code>torch.cholesky</code> e.g.:</p>
<pre class="lang-py prettyprint-override"><code>import torch
a = torch.randn(3, 3, device="cuda:0")
a = torch.mm(a, a.t()) # make symmetric positive-definit... | <p>I discovered that this error was because the machine I'm running things on has CUDA 10 installed now, but I just installed pytorch as <code>pip install torch</code>. From their <a href="https://pytorch.org/" rel="nofollow noreferrer">website</a>, the proper way to install with <code>pip</code> and CUDA 10 is <code>p... | python|cuda|pytorch | 4 |
352,328 | 56,089,337 | How to use the values returned by value_counts() to do further calculations? | <p>I have a column named <code>y_ocsvm</code> that is filled with 1 and -1 in a df named <code>step1</code>. </p>
<p>I used: <code>step1['y_ocsvm'].value_counts()</code> to get the counts of 1's and -1's and the output was:</p>
<pre><code>step1['y_ocsvm'].value_counts()
Out[11]:
1 1622
-1 426
Name: y_ocsvm, ... | <p>Here <code>Series</code> constructor is not necessary, because <code>step1['y_ocsvm'] == -1</code> is <code>Series</code> filled by boolean values:</p>
<pre><code>out = (step1['y_ocsvm'] == -1).value_counts()
</code></pre>
<p>For ratio is possible use:</p>
<pre><code>print (out[True] / out[False])
</code></pre> | python|python-3.x|pandas|dataframe | 3 |
352,329 | 56,331,568 | Insert a row into a dataframe at index i | <p>I need your help on a pandas problem :</p>
<p>I am currently extracting data via APIs that contain gaps in their ranks. </p>
<p>However I need to take into account these on the dataset by replacing them with an average value.</p>
<p>Then I need to insert a row in my dataframe to fill the dataframe. </p>
<p>Illus... | <p>You can use reindex to add missing ranks and fillna to fill missing values.</p>
<pre><code>df = df.set_index('rank').reindex(np.arange(df['rank'].min(), df['rank'].max()+1)).reset_index()
df['value'] = df['value'].fillna(df['value'].mean()).round()
rank timestamp value
0 1 21:50 3450
1 2 ... | python|pandas|dataframe|indexing|insert | 2 |
352,330 | 56,421,236 | Select rows based on columns which doesn't have a specific value and make use of dictionary - Python & Excel - Big Data | <p>I have more than million records and 700 columns stored in a csv like format. Each record represents each person and all the values in each of the columns represent his responses to survey questions. </p>
<p>So, I have given a piece of code of sample input data with two cols</p>
<pre><code>df = pd.DataFrame({'Pers... | <p>To drop the rows for which ALL the columns contain NaNs do this:</p>
<pre><code>df = df.dropna(how='all', axis=0)
</code></pre> | python|python-3.x|pandas|dataframe | 1 |
352,331 | 56,215,878 | Batch calculation of dataframe cells based on values from two other dataframes | <p>Based on a first dataframe </p>
<pre><code>import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(1), freq='D')
symbols = ['A','B']
np.random.seed(seed=1111)
dataA = np.random.randint(1, high=100, size=len(d... | <p>Try using:</p>
<pre><code>df3 = df1 * df2.sum(axis=1)
</code></pre>
<p>And now:</p>
<pre><code>print(df3)
</code></pre>
<p>Is:</p>
<pre><code> A B
2019-05-20 06:58:52.753879 87 410
2019-05-21 06:58:52.753879 168 65
</code></pre> | python|pandas | 0 |
352,332 | 56,187,195 | Iterate through rows in a dataframe and change value of a column based on other column | <p>Assuming I have a dataframe called <em>df</em> which looks like the one shown below:</p>
<pre><code>Id Place
1 NY
2 Berlin
3 Paris
4 Paris
5 Berlin
</code></pre>
<p>And a dictionary, which has IDs as keys and places as values as ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="noreferrer"><code>Series.map</code></a> for replace matched values, then replace <code>NaN</code>s by original column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" re... | python|pandas|dataframe | 5 |
352,333 | 56,022,375 | Tensorflow feed_dict ValueError: setting an array element with a sequence | <p>I'm new to tensorflow and trying to run a CNN on Twitter embedding matrices (each embedding matrix is 574x300 - word x embedding length) in batches of 100 tweets at a time. I keep getting the error <code>ValueError: setting an array element with a sequence.</code> at the following line at the bottom: <code>sess.run(... | <ol>
<li>The input to the <code>conv2d</code> must have <code>rank=4</code>, but you have <code>rank=3</code>. </li>
<li><code>embedding_size</code>, which determines the second dimension of your filter, must be <em>less than or equal</em> to the third dimension of your input tensor. You have third dimension equal to <... | python|tensorflow | 1 |
352,334 | 56,355,410 | Generating Input for LSTM from universal sentence encoder output | <p>I am working on a multi-class classification problem using LSTM and embeddings obtained from Universal sentence encoder. </p>
<p>Previously I was using Glove embeddings, and I get the required input shape for LSTM (batch_size, timesteps, input_dim). I am planning to use the Universal sentence encoder found that the... | <p>Sentence Encoder is different from word2vec or Glove, it's not word-level embeddings:</p>
<blockquote>
<p>The model is trained and optimized for greater-than-word length text,
such as sentences, phrases or short paragraphs. It is trained on a
variety of data sources and a variety of tasks with the aim of
dy... | tensorflow|keras|deep-learning|lstm|embedding | 2 |
352,335 | 56,308,103 | valueerror array is too big arr.size when merge and sum based on title more than 2 data frame | <p>I can't sum fee based on country, currency and product id from dfJANUARY and dfFEBRUARY.
python said 'array is too big'</p>
<p>my file.txt as dfJANUARY has 35,6 mb</p>
<p>my file.txt as dfFEBRUARY has 36,3 mb</p>
<pre><code>In[1]: dfJANUARY
Out[1]
Country PRODUCT ID currency fee
0 Arab Emirate ... | <p>In your case, you want to <code>pd.concat</code> the dataframes (putting the second "below" the first). I'm surprised that <code>pd.merge</code> failed, but it is harder to <code>merge</code> (because it is a more general function). <br>
Try</p>
<pre><code>df = pd.concat([df1,df2])
df.pivot_table(index = ["PRODUCT ... | python|pandas | 0 |
352,336 | 56,395,419 | why using Myarray.size() returns error : " int object is not callable " but Myarray.size is Ok? | <p>I have a wierd Problem which is when i use .size() i get error but using .size is ok.
look at below :</p>
<pre class="lang-py prettyprint-override"><code>a = np.zeros([5,5])
a.size # returns 25
a.size() # returns error : "int obj is not callable "
a.shape # returns (5,5)
</code></pre>
<p>The problem is that i mus... | <p><code>ndarray.size</code> is an <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.html" rel="nofollow noreferrer">attribute</a>, not a function. You can't call it because it is actually just a number:</p>
<blockquote>
<p><code>ndarray.size</code></p>
<p>Number of elements in the array.... | python|function|numpy|size | 1 |
352,337 | 56,340,103 | Does image file type matter in terms of accuracy or speed when training/evaluating in machine learning? | <p>I would like to know if the image file type matters at all in image classification using Keras, Tensorflow, or any other machine learning library. For example:</p>
<p>If I were to train using only JPG files, will the accuracy be significantly affected if I were to evaluate the model using only PNG files?</p>
<p>If... | <p>The file type does not matter.</p>
<p>During training (and inference for that matter) images are converted into a tensors (you can think of this just as a multi dimensional array) where each pixel is represented by a small group of numbers (or a single number for black and white images).</p>
<p>Machine learning is... | image|tensorflow|image-processing|machine-learning|keras | 2 |
352,338 | 56,244,037 | Plot data from Excel in Python | <p>The code I have to read and plot data from my excel file is this:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
excel_file = 'file1.xlsx'
file1 = pd.read_excel(excel_file)
file1.head()
plt.plot(x,y1,y2)
plt.xlabel('wavelenghts')
plt.ylabel('reflectivity')
plt.legend(loc='upper left')
plt.sho... | <pre><code>f, ax = figure()
plt.plot(file1.x,file1.y1,label='')
plt.plot(file1.x,file1.y2)
plt.plot(file1.x,file1.y3)
.....
plt.xlabel('wavelenghts')
plt.ylabel('reflectivity')
plt.legend(loc='upper left')
plt.show
</code></pre> | excel|pandas|matplotlib | 1 |
352,339 | 56,428,549 | How to encrypt a column in Pandas/Spark dataframe using AWS KMS | <p>I want to encrypt values in one column of my Pandas (or PySpark) dataframe, e.g. to take the the column <code>mobno</code> in the following dataframe, encrypt it and put the result in the <code>encrypted_value</code> column:</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*43GsNRunmSCBsdKsUWdiwg.png" alt=... | <p>Since <strong>Spark 3.3</strong> you can do AES encryption (and decryption) without UDF.</p>
<blockquote>
<p><a href="https://spark.apache.org/docs/latest/api/sql/index.html#aes_encrypt" rel="nofollow noreferrer"><strong><code>aes_encrypt</code></strong></a><code>(expr, key[, mode[, padding]])</code> - Returns an en... | pandas|dataframe|encryption|pyspark|amazon-kms | 0 |
352,340 | 56,060,648 | If/else statement within loop over dataframe | <p>I have a dataframe with three columns:
Depth, Shale Volume and Density.</p>
<p>What I need to do is to calculate porosity based on the shale volume and density. So, where the shale volume is >0.7 I apply certain parameters for the porosity calculation and where i have the volume < 0.2 I have other parameters.</p... | <p>Here <code>iterrows</code> is bad choice, because slow and exist vectorized solution, check <a href="https://stackoverflow.com/a/24871316/2901002">Does pandas iterrows have performance issues?</a></p>
<p>So use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer... | python|pandas|numpy|dataframe | 2 |
352,341 | 56,075,288 | How to import tfrecord files in a pandas dataframe? | <p>I have a tfrecord file and would like to import it in a pandas dataframe or numpy array.</p>
<p>I found tools to read tfrecords but they only work inside a tensorflow session, which is not the use case I have...</p>
<p>Thanks for any help I could get !</p> | <p>In Colab you can type (or on your cmd without !)</p>
<pre><code>!pip install pandas-tfrecords
</code></pre>
<p>After installation you can use:</p>
<pre><code>import pandas as pd
import pandas_tfrecords as pdtfr
pdtfr.tfrecords_to_pandas(file_paths=r'/folder/file.tfrecords')
</code></pre>
<p>Good luck!</p> | python-3.x|pandas|tfrecord | 4 |
352,342 | 56,260,348 | Selecting single value in a pandas dataframe | <p>I have the following data frame:</p>
<pre class="lang-none prettyprint-override"><code>Exp Variable Score all best rsmin
ctr Qle MBE -3.061518 0.082860 -3.921793
ctr Qh MBE 12.275757 0.464946 12.288968
ctr NEE ... | <p>you can try:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[(df['Exp'] == 'ctr') & (df['Variable'] == 'Qle') & (df['Score'] == 'MBE'), 'best'].values
</code></pre> | python|pandas|dataframe | 2 |
352,343 | 56,382,601 | Can we freeze selected neurons in a fully connected layer in keras? | <p>So , I need to freeze only a neuron or two in the fully connected dense layer in keras, so that its weight doesn't change during the course of training. Is there a way to do this in keras ?</p> | <p>You might want define a mask and set the elements of the mask corresponding to the neuron you want to freeze to 0. This way gradient won't propagate and the neuron won't be trained.</p>
<p>Something similar to:
<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/model_pruning" rel="nofo... | tensorflow|keras|deep-learning | 0 |
352,344 | 56,192,962 | How to fill pandas dataframes in a loop? | <p>I am trying to build a subset of dataframes from a larger dataframe by searching for a string in the column headings.</p>
<pre class="lang-py prettyprint-override"><code>df=pd.read_csv('data.csv')
cdf = df.drop(['DateTime'], axis=1)
wells = ['N1','N2','N3','N4','N5','N6','N7','N8','N9']
for well in wells:
well... | <p>IIUC this should be enough:</p>
<pre><code>df=pd.read_csv('data.csv')
cdf = df.drop(['DateTime'], axis=1)
wells = ['N1','N2','N3','N4','N5','N6','N7','N8','N9']
well_dict={}
for well in wells:
well_cols = [col for col in cdf.columns if well in col]
well_dict[well] = cdf[well_cols]
</code></pre>
<p>Dictio... | python|pandas|loops|dataframe | 2 |
352,345 | 56,191,072 | Removing Decimal from a column extracted from a dataframe using pandas | <p>I have a dataset in an excel. I read the data into a dataframe "df" using read_excel. </p>
<p>During this process, I observed that col1 from df is providing decimals, when it should only have numbers with only 4 digits. </p>
<p>So, I have two questions here:</p>
<ol>
<li><p>Why is it returning a decimal when th... | <p>Since df_A is a dataframe, you can fillna and then convert the column to int. </p>
<pre><code>df_A['col1'] = df_A['col1'].fillna(0).astype(int)
</code></pre>
<p>Since you are getting the error <code>invalid literal for int() with base 10:</code> with the above code, it means that there are some non-numeric values... | python|pandas | 2 |
352,346 | 56,063,147 | Understand "return data_mine['one'] = 1" in a function | <p>I found the following function in a book I currently read. I understand the function but not why we do <code>data_mine['one'] = 1</code> and why we return <code>data_resampled.one</code>. Can you explain to me the reason why the author is doing that? Here you can find <a href="https://github.com/amueller/introductio... | <p><code>data_mine['one'] = 1</code> makes all values of the column - 'one' (if it exists already) to 1. If it does not exist already, you just appended a new column <code>['one']</code> with all values 1 in <code>data_mine</code>.</p>
<p>Hope this makes you understand the function better.</p> | python|pandas|machine-learning | 0 |
352,347 | 56,333,333 | Module Tensorflow has no attribute KMeans | <p>I'm using Tensorflow for calculating DELF features.
I'm using next example from tensorflow models:
<a href="https://github.com/tensorflow/models/blob/master/research/delf/delf/python/detect_to_retrieve/cluster_delf_features.py" rel="nofollow noreferrer">github</a>. </p>
<p>So there is a line here:</p>
<pre><code>k... | <p>The correct syntax to use KMeans from tensorflow is </p>
<pre><code>tf.contrib.factorization.KMeansClustering()
</code></pre>
<p>For parameters and more information, read <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/KMeans" rel="nofollow noreferrer">this</a>.</p> | python|tensorflow|k-means | 2 |
352,348 | 56,170,858 | How to change column names by even/odd columns in Python | <p>I have a relatively large dataframe with more than one hundred columns. Currently, only the first column was assigned a name, and the dataframe looks like:</p>
<pre><code>Event 0 1 2 3 4 5 6 7 8 9 10 11 ...
</code></pre>
<p>I would like to rename the columns so that they look like</p>
<pre><code>Event Name1 Job1 ... | <p>Here is another example:</p>
<pre><code>import pandas as pd
a = {}
a["Event"] = [1,2,3]
a[0] = [1,2,3]
a[1] = [1,2,3]
a[2] = [1,2,3]
a[3] = [1,2,3]
a[4] = [1,2,3]
df = pd.DataFrame(a)
name = 1
job = 1
for i in df.keys()[1:]:
if i%2==0:
df = df.rename(columns={i: "Name"+str(name)})
name+=1
... | python|python-3.x|pandas | 1 |
352,349 | 56,033,653 | How to determine state in a column based on two other Boolean columns for a timeseries Pandas dataframe? | <p>Given the first dataframe is there a way with pandas<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html#pandas-dataframe-shift" rel="nofollow noreferrer">.shift()</a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html#pandas-dat... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> with forward filling missing values and last replace first <code>None</code>s by <code>False</code> if exist:</p>
<pre><code>import numpy as np
df['D'] = np.select([df['B'], ... | python|pandas|dataframe|boolean | 3 |
352,350 | 56,188,119 | Need help dynamically adding to a dataframe using a variable number of columns | <p>Im doing some text analysis and trying to loop through a dataframe consisting of a list of words in one column and some numeric values in other columns. I want to split out all words in the list column on to different rows and also bring with them the values that were on the same row. I want the code to be usable by... | <p>Thanks for the link @HS-nebula it led me to the answer I needed.
In the end I used a loop afterwards to clean the aggregated tokens but to un-nest them I used the following:</p>
<pre><code>TokensTable = metricsByToken2.apply(lambda x: pd.Series(x['Token']),axis=1).stack().reset_index(level=1, drop=True)
TokensTabl... | python|pandas|dataframe | 0 |
352,351 | 56,190,281 | How to find the indeces of the elements == 0 in a matrix? Each row and column should appear only once | <p>I have a 4x4 matrix and want to find the indexes of the <code>elements == 0</code>. Using <code>tf.where(tf.equal(matrix,0))</code> I get something like: </p>
<pre><code>array([[0, 0],[0, 1], [1, 3],[2, 1],[3, 2]])
</code></pre>
<p>How can I remove <code>[0,1]</code> from the list as I only want exactly one elemen... | <p>This would fall under a "post processing" kind of approach and just uses a loop with conditionals but it seems to give the answer you need. You could put it in a function and use it on your outputs. This approach prioritizes <em>row</em> duplicates and ignores column duplicates.</p>
<pre><code>clean_list_zero = []
... | python|tensorflow | 0 |
352,352 | 56,190,405 | Keras Kernel Initialization with numpy array unable to use load_model | <p>I am trying to use a numpy array from a pretrained model, to initialize a kernel in my keras model. Therefore I am writing my own Initializer function. The function is embedded in a callable class to avoid issues when using load_model. It seems that passing an array as a parameter to the initializer does not work in... | <p>you have to use model.layers.set_weights([kernels,bias_vector])</p>
<p>compile the model with random weights, then set the weights afterward.</p>
<p>you can't set specific weights, you have to craft the entire weight vector and set the layer as a whole.</p> | python|tensorflow|keras | 1 |
352,353 | 56,252,830 | Selecting points above/under lines | <p>I have the following dataset:</p>
<pre><code>df = pd.DataFrame(np.random.rand(50,2), columns=list('AB'))
</code></pre>
<p>plot data</p>
<pre><code>plt.scatter(x=df.A, y=df.B)
x = plt.axhline(y=0.4,c='k')
y = plt.axvline(x=0.4,c='k')
plt.plot([0.2, 0.3], [0, 0.4], c='k')
</code></pre>
<p>I want to select the poi... | <p>I suggest you can use functools:</p>
<pre><code>import numpy as np
import functools
cr1 = functools.reduce(np.logical_and, [df.B < 0.4, df.A < 0.2])
cr2 = functools.reduce(np.logical_and, [df.B < 0.4, df.A > 0.2, df.B > (df.A-0.2)*4])
df_filtered = df[functools.reduce(np.logical_or, [cr1,cr2])]
</co... | python|pandas | 2 |
352,354 | 56,276,877 | Find largest value from multiple colums in each group of row index in Python, arrange those values diagonally in matrix, and find determinant | <p>I am new to Python. I want to find the largest values from all the columns for repetitive row indexes (i.e. 5 to 130), and also show its row and column index label in output.The largest values should be absolute. (Irrespective of + or - sign). There should not be duplicates for row indexes in different groups.
After... | <p>I am not sure about @piRSquared output from what I understood from your question. There might be some errors in there, for instance, in group 2, max(abs(values)) = 52 (underline in red in picture) but 41 is displayed on left...</p>
<p>Here is a less elegant way of doing it but maybe easier for you to understand :</... | python|pandas|numpy|matrix|determinants | 1 |
352,355 | 56,322,862 | why does this if statement give my a ValueError? | <p>I'm trying to iterate over a numpy 2d array and check where the values 1,2 and 3 occur in the array, but i receive a value error, because numpy states that it's ambiguous. What is the best way to fix this problem?</p>
<pre class="lang-py prettyprint-override"><code>for x in range(row):
for y in range(row):
... | <p>Try using <code>grid[x][y]</code> instead of grid[x,y]</p> | python|numpy|valueerror | 0 |
352,356 | 56,011,400 | How to map two dataframes keeping the value same for one dataframe | <p>Im trying to write a script for few ETL transformations. I have 34 fixed columns i.e. df1, according to which I have to map the column name of different input files containing different columns i.e. df2. </p>
<p>df1(Standard Columns):</p>
<p><a href="https://i.stack.imgur.com/WM7EF.png" rel="nofollow noreferrer"... | <p>A way to do this would be to have an intermediate step of mapping the columns.
For instance: </p>
<pre><code>df2.rename(columns = {'Department Code':'Field 1 Dept Number','Column2':'2_column', .....})
</code></pre>
<p>And then you can merge the two dataframes on the columns of interest.</p> | python|pandas|etl | 1 |
352,357 | 56,045,435 | Filling missing values with values from most similar row | <p>I have the following table. Some values are NaNs. Let's assume that columns are highly correlated. Taking <code>row 0</code> and <code>row 5</code> I say that value in <code>col2</code> will be <code>4.0</code>. Same situation for <code>row 1</code> and <code>row 4</code>. But in case of <code>row 6</code>, there is... | <p>This is a hard question , involved <code>numpy</code> broadcast , and <code>groupby</code> + <code>transform</code> , I am using <code>first</code> here , since <code>first</code> will pick up the first not <code>NaN</code> value </p>
<pre><code>s=df.values
t=np.all((s==s[:,None])|np.isnan(s),-1)
idx=pd.DataFrame... | python|pandas|data-science | 4 |
352,358 | 56,376,789 | how to get all the multi valued attributes into a csv file | <p>I have a sample data as below .Below attributes are belong to [data] dictionary. In "XXXX" i have value "Naveen" and in "YYYYY" i have "Kumar" and "Rajesh" . i am trying with the below code to get 2 recorded output </p>
<p>Please help with any suggestion</p>
<pre><code> {
"data": [
{
"Empid": "1234"... | <p>An other answer with DataFrame :</p>
<pre><code>df = pd.DataFrame()
for key in json_file['data'][0].keys():
for j in range(len(json_file['data'][0][key])):
df.loc[j,key] = json_file['data'][0][key][j]['relative']['id']
</code></pre>
<p>Result :</p>
<pre><code>
XXXX YYYYY
0 Naveen Kumar
1 NaN R... | python|json|pandas|dataframe|multi-index | 0 |
352,359 | 55,934,047 | Find average of a column when datatype is object | <p>I have a dataframe as shown below</p>
<p>How can I calculate average of values in the 'list' column?</p>
<pre><code>new = pd.DataFrame({
'list' : ['0 Minute 17 Seconds',
'0 Minute 50 Seconds',
'0 Minute 19 Seconds',
... | <p>For average in seconds use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> with casting to <code>string</code>s:</p>
<pre><code>df = new['list'].str.extract('(\d+)\s+Minute\s+(\d+)\s+Seconds')
df.columns... | python|pandas | 3 |
352,360 | 55,825,822 | Why does tf.keras.layers.Conv2DTranspose need no output_shape compared to tf.nn.conv2d_transpose? | <p>I am missing something basic here. But I always used the <code>tf.nn</code> API for transpose convolution, where I have to specify the output shape, because it is ambiguous(<a href="https://stackoverflow.com/questions/43624625/why-do-we-have-to-specify-output-shape-during-deconvolution-in-tensorflow/43624992#4362499... | <p><code>tf.keras.layers.Conv2DTranpose</code> backends to <code>tf.nn.conv2d_transpose</code> via <code>tf.keras.backend.conv2d_transpose</code>.</p>
<p>To compute the <code>output_shape</code> argument for <code>tf.nn.conv2d_transpose</code> it utilizes the function <code>deconv_output_length</code> (defined <a href... | tensorflow|conv-neural-network|transpose|autoencoder|tensorflow2.0 | 2 |
352,361 | 55,909,006 | How can I list components of a list individually within a pivot table? | <p>Within the following pivot table I would like to separate the element within a list/tuple to be displayed vertically and without the [] brackets of a list.</p>
<p><a href="https://i.stack.imgur.com/KI7sf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KI7sf.png" alt="enter image description here"... | <p>You can try this:</p>
<pre><code>df['Items'].stack().apply(lambda x: pd.Series([i for i in x])).unstack().stack(0)
</code></pre>
<p>Output:</p>
<pre><code>Rank 1 2 3 5
Group
A 0 m NaN NaN NaN
B 0 n o u NaN
1 NaN t NaN NaN
C 0 NaN NaN ... | python|pandas|dataframe|pivot-table | 0 |
352,362 | 55,840,486 | What does Keras model.predict returns? | <p>I am building an autoencoder network for finding outliers in a single-column list of text.</p>
<p>I pick up each character, transform it to ASCII, and put them into an array.</p>
<p>Each line of the array is a row of my input, and each element in the array is an integer representation of the ascii code for the cha... | <p>You can convert back your ASCII numbers to text and you can visulize your result. Use <a href="https://docs.python.org/2/library/functions.html#chr" rel="nofollow noreferrer"><code>chr</code></a>, a python built-in function. It requires input as integer value in range of 0 to 255. So, make sure that your model predi... | python|tensorflow|keras|deep-learning | 1 |
352,363 | 55,622,673 | Python PANDAS: Applying a function to a dataframe, with arguments defined within dataframe | <p>I have a dataframe with headers 'Category', 'Factor1', 'Factor2', 'Factor3', 'Factor4', 'UseFactorA', 'UseFactorB'.</p>
<p>The value of 'UseFactorA' and 'UseFactorB' are one of the strings ['Factor1', 'Factor2', 'Factor3', 'Factor4'], keyed based on the value in 'Category'.</p>
<p>I want to generate a column, 'Res... | <p>Probably not the prettiest solution (because of the iterrows), but what comes to mind is to iterate through the sets of factors and set the 'Result' value at each index:</p>
<pre><code>for i, factors in df[['UseFactorA', 'UseFactorB']].iterrows():
df.loc[i, 'Result'] = df[factors['UseFactorA']] / df[factors['Us... | python|pandas | 1 |
352,364 | 55,644,653 | How to add elements of tensor as scalar summaries in Tensorflow? | <p>I have tensor of 10 elements. How can I add each element as scalar summary, preferably displayed on the same graph in Tensorboard?</p> | <p>You can access them as if the tensor were a numpy array: <code>tensor[i,j]</code>, where the i and j are the indiceswhere the element is located (<code>tensor[i]</code> in the case the elemnt is a vector).</p>
<p>Then add them to the summary: </p>
<pre><code>for i in tensor:
tf.summary.scalar("tensor"+ str(i),... | tensorflow|tensorboard | 0 |
352,365 | 55,704,231 | Convert 1 column data into multi hot encoding | <p>As an example to the problem, suppose we have a dataframe:</p>
<pre><code> Name Class
0 Aci FB
1 Dan TWT
2 Ann GRS
3 Aci GRS
4 Dan FB
</code></pre>
<p>The resulted dataframe would be
df</p>
<pre><code> Name FB TWT GRS
0 Aci 1 0 1
0 Dan 1 1 0
0 Ann 0 0 1
</code><... | <p>The other solutions were failing for me due to memory overflows when I have 315 samples and 1908 labels. Here are some more performant methods.</p>
<p>Using pandas pivot:</p>
<pre><code>def multihotencode(data, samples_col, labels_col):
data = data.copy()
data['present'] = 1
multihot = data.pivot(index=s... | python|pandas|dataframe|binary|dummy-variable | 1 |
352,366 | 55,807,687 | how to see the value in a tensor object | <p>I have a variable <code>a</code> it has the output <code>a = Tensor("Mean_32:0"</code>, <code>shape=(), dtype=float64)</code></p>
<p>how can I see the value present in the form of tensor</p>
<pre><code>a = Tensor("Mean_32:0", shape=(), dtype=float64)
</code></pre> | <p>You should use <code>tf.Session()</code> context to evaluate the tensors.</p>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
tensor = tf.constant([1., 2., 3.])
mean = tf.reduce_mean(tensor)
with tf.Session() as sess:
# both are equivalent:
print(mean.eval()) # 2.0
p... | python|python-3.x|tensorflow | 0 |
352,367 | 55,620,196 | Getting HTML table via pandas read_html won't work | <h2>What works</h2>
<p>I managed to get data from a hmtl table via <code>pd.read_html</code> like so:</p>
<pre class="lang-py prettyprint-override"><code>In[1]:
import numpy as np
import pandas as pd
from tabulate import tabulate
URL = "https://coinmarketcap.com/all/views/all/"
df_in_list = pd.read_html(URL, attrs ... | <p>Yes, you have the wrong <code>class</code> for the table.</p>
<p>If you change <code>df_in_list</code> to <code>df_in_list = pd.read_html(URL, attrs = {'class': 'table'})</code> it should work.</p>
<p>You'll have to change the <code>df = df[['#', 'Name', 'Symbol', 'Market Cap', 'Price' ]]</code> part too, since th... | python|pandas|dataframe|beautifulsoup | 1 |
352,368 | 55,883,079 | `TypeError: get_config() missing 1 required positional argument: 'self'` while trying to save the model in Tensorflow | <p>Please help me with the following. I can't seem to save my model. As you can see I do reference the instance of the <code>Sequential()</code> method</p>
<pre class="lang-py prettyprint-override"><code>model = tf.keras.models.Sequential()
model.add(tf.keras.layers.InputLayer(input_shape=[timePortion,1 ]))
model.add(... | <p>The problem is with the kernel initializer that cannot be serialized because you haven't instantiated it. To instantiate it add round brackets <code>()</code>:</p>
<pre class="lang-py prettyprint-override"><code>kernel_initializer=tf.keras.initializers.VarianceScaling()
</code></pre> | python|tensorflow|keras | 4 |
352,369 | 55,700,083 | Tensorflow SavedModel file size increases with each save | <p>I have a Tensorflow R1.13 training code that saves a SavedModel periodically during a long training run (I am following this excellent <a href="https://medium.freecodecamp.org/how-to-deploy-tensorflow-models-to-production-using-tf-serving-4b4b78d41700" rel="nofollow noreferrer">article</a> on the topic). I have not... | <p>@Hephaestus,</p>
<p>If you're constructing a <code>SavedModelBuilder</code> each time, then it'll add new save operations to the graph every time you <code>save</code>. </p>
<p>Instead, you can construct <code>SavedModelBuilder</code> only once and just call <code>builder.save</code> repeatedly. This will not add ... | tensorflow|tensorflow-serving | 1 |
352,370 | 55,726,107 | Count of values grouped per month, year - Pandas | <p>I am trying to <code>groupby</code> counts of dates per month and year in a specific output. I can do it per day but can't get the same output per month/year. </p>
<pre><code>d = ({
'Date' : ['1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],
'Val' : ['A','B','C','D',... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>GroupBy.transform</code></a> for columns with same size like original DataFrame:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], format= '%d/%m/%y')
y = df['Date'].dt.year... | python|pandas|group-by|count|transform | 11 |
352,371 | 55,931,349 | Tensorflow .pb file only in Android is enough | <p>I am working on image classification and I need some advice. am building large image classifier using keras with backend tensorflow because I want to use that model for Android application so I trained it and convert those checkpoints into protobuf (.pb) file . In many examples I saw 2 files when they export to andr... | <p>If you are looking to use the model on Android, you'll need to convert it to TensorFlow Lite first. This <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite" rel="nofollow noreferrer">codelab</a> might help. The model will return indices and probabilities. If you want to convert th... | android|tensorflow|firebase-mlkit | 1 |
352,372 | 55,953,958 | The SelectKBest gives the scores as nan values | <p>I have a data set and I am trying to get the feature importances using <code>SelectKBest</code> and <code>Chi2</code>, but the <code>SelectKBest</code> is giving the scores of the features as <code>nan</code>.</p>
<p>The data file and code file are present at <a href="https://github.com/MokshithSandeep/DataSet" rel... | <p>All the values in your target variable is <code>1</code>. That is the reason for <code>nan</code> values in your <code>scores_</code>. Hence please verify your target variable. </p>
<p>Just for illustration:</p>
<pre class="lang-py prettyprint-override"><code>>>> from sklearn.datasets import load_digits
i... | python-3.x|pandas|machine-learning|jupyter-notebook|data-science | 2 |
352,373 | 55,907,892 | Matplotlib: Secondary axis with values mapped from primary axis | <p>I have a graph showing x4 vs y:
<img src="https://i.stack.imgur.com/uhy14.png" alt="graph"> </p>
<p>y is the log of some other variable, say q (i.e. y = log(q) )
the value of q is what the layperson will understand when reading this graph.</p>
<p>I want to set up a secondary axis on the right side of the graph, wh... | <p>My suggestion here would be to use a twin axes and share it will the original axes to fix the tick positions. You may then use a <code>FuncFormatter</code> to give the ticks the correct labels. The advantage of this is that you do not need to fix the limits of the plot a priori and can freely zoom and pan inside the... | python|python-3.x|pandas|matplotlib | 2 |
352,374 | 55,942,081 | How to filter on the duplicate rows of a dataframe? | <p>I want to add condition to extract the duplicate rows in a dataframe</p>
<p><strong>DF</strong></p>
<pre><code>KEY STAT NUM ID
ab L 3 1678
cd D 4 23221
ab D 8 1678
cd L 0 38754
</code></pre>
<p>For duplicate key I need to check for ID ... | <p>Create a function and use it for each group</p>
<pre><code>def f(d):
if d.ID.nunique() == 1:
return d.assign(KEY=d.KEY.str.cat(d.STAT, sep='+'))
else:
return d.nlargest(1, columns=['NUM'])
pd.concat([f(d) for _, d in df.groupby('KEY')])
KEY STAT NUM ID
0 ab+L L 3 1
2 ab+D ... | python-3.x|pandas|dataframe | 1 |
352,375 | 56,009,504 | How to exclude and filter few columns in pandas? | <p>I know we can select only few columns using pandas dataframe filter, but can we also exclude only some columns?</p>
<p>Here is MWE:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'id': [1,2,3], 'num_1': [10,20,30], 'num_2': [20,30,40]})
df.filter(re... | <p><strong>Using contains</strong></p>
<pre><code>df.loc[:,~df.columns.str.contains('num')]
df.loc[:,~df.columns.str.startswith('num')]
</code></pre>
<p><strong>Using difference</strong></p>
<pre class="lang-py prettyprint-override"><code>df[df.columns.difference(['num_1','num_2'])]
df[df.columns.difference([i for i in... | python|pandas|dataframe | 5 |
352,376 | 56,002,127 | split several columns in a data-frame | <p>I have a dataframe that I want to split string in the 3th column to the last column, each into two columns and the header remains with the first splitted column.
here is the dataframe:</p>
<pre><code>Sample Pop a1 a10 a100
F295 Pesche AC AT AA
F296 Pesche GT CG AC
F297 ... | <p>You can create <code>MultiIndex</code> in columns by split values by converted strings to lists with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> for join together:</p>
<pre><code>df1 = df.set_index(['Sample','Pop'])
comp = ... | python|pandas | 1 |
352,377 | 55,656,252 | Kivy: How To Solve Crashing App When Using Python Functions | <p>I'm trying to combine the GUI features of Kivy with the Python function I wrote. But whenever I call the function onto one of my <code>Screen</code> classes, the whole app crashes and consumes my memory and cpu usage.</p>
<p>Basically, what I'm trying to do is get the <code>global where</code> variable from the com... | <h1>Root Causes</h1>
<ol>
<li>In <code>class LetterAScreen()</code>, you have instantiated <code>class Identifier()</code> twice i.e. 2 or double instances. Once in method <code>identity()</code> and the other one in method <code>verifier()</code></li>
<li>In method verifier(), it called method <code>self.identity()</c... | android|python|python-2.7|numpy|kivy | 0 |
352,378 | 55,824,345 | Generate lists of all columns in pandas dataframe | <p>My dataframe has 40+ columns. I would like to generate lists with each list containing values from one column. Here is how I tried to do it</p>
<pre><code>cols= df.columns
cols = cols.tolist()
for col in cols:
col = df.col.tolist()
</code></pre>
<p>Error:</p>
<blockquote>
<p>'DataFrame' object has no attrib... | <p>Use <code>[]</code> for select by column name:</p>
<pre><code>for col in cols:
col = df[col].tolist()
</code></pre>
<p>If need all values in lists is possible create dictionary by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>D... | python|pandas | 4 |
352,379 | 55,663,672 | How can I use KNN, Random Forest models in Pytorch? | <p>This may seem like a X Y problem, but initially I had huge data and I was not able to train in given resources (RAM problem). So I thought I could use <code>batch</code> feature of <code>Pytorch</code>. But I want to use Methods like KNN, Random Forest, Clustering except Deep Learning. So is it possible or can I use... | <h2>Update</h2>
<p>Currently, there are some <code>sklearn</code> alternatives utilizing GPU, most prominent being <code>cuML</code> (link <a href="https://github.com/rapidsai/cuml" rel="nofollow noreferrer">here</a>) provided by rapidsai.</p>
<h2>Previous answer</h2>
<p>I would <strong>advise against</strong> using <c... | python-3.x|scikit-learn|pytorch | 6 |
352,380 | 55,648,603 | How to fix 'RuntimeError: Coordinator stopped with threads still running: QueueRunnerThread-dummy_queue-sync_token_q_EnqueueMany' | <p>I'm new to TensorFlow and every time I trained my model, it ends with the error :</p>
<pre><code>RuntimeError: Coordinator stopped with threads still running: QueueRunnerThread-dummy_queue-sync_token_q_EnqueueMany
</code></pre>
<p>Does someone have any idea to fix it ?</p>
<p>I'm on Ubuntu 18.04 and using Python3.6 ... | <p>I have the same problem,my tf version is 1.13,then I upgraded to version 1.14,there's also a same error.</p>
<p>Finally, I change <code>ignore_liver_threads=False</code> to <code>ignore_liver_threads=True</code> in both <code>../tensorflow/contrib/slim/python/slim/learning.py</code> and <code>../tensorflow/python/t... | python|tensorflow|deep-learning | 0 |
352,381 | 55,920,552 | TF lite model performs worse when using Androids NNAPI | <p>I'm benchmarking various tensorflow-lite models using TFLite Model Benchmark Tool<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/benchmark" rel="nofollow noreferrer">1</a>, on an Xiaomi MI9. I've noticed that many models perform worse when I enable inference on Androids Neural Net... | <p>The most likely reason are in the thread suggested by Alex, particularly if you're observing this for well tested standard models like Mobilenet. </p> | android|tensorflow|tensorflow-lite | 0 |
352,382 | 55,680,417 | Rolling Average for last 3 years for same week number Python Pandas | <p>I am finding average of the same weeks whenever there is data available for example 201932, using the average of the data from 201632, 201732 and 201832. Example : 2019 is year and 32 is week number</p> | <p>Generalized sample, not tested fully, you can update as per your needs, please pardon the syntax/compile errors</p>
<pre><code># 1 load your data here
myYearlyWeekAvgList = [[Calendar, WkNumber, France, 0, 201538], [....]]
# 2 initialize variables here
totalSum = 0
movingAves = 0 # track total for that yr
myYear ... | python|pandas|time-series|moving-average|rolling-average | 0 |
352,383 | 55,829,078 | How to slice date from a timestamp and convert to string? | <p>My list of timestamps is given below:</p>
<pre><code>time_list =
[Timestamp('2019-01-24 00:00:00'),
Timestamp('2019-01-27 00:00:00'),
Timestamp('2019-01-29 00:00:00'),
Timestamp('2019-02-08 00:00:00'),
Timestamp('2019-02-09 00:00:00'),
Timestamp('2019-02-10 00:00:00')]
</code></pre>
<p>I would like to take o... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.strftime.html" rel="nofollow noreferrer"><code>Timestamp.strftime</code></a> in list comprehension or loop:</p>
<pre><code>date_list = [x.strftime('%Y-%m-%d') for x in time_list]
</code></pre>
<hr>
<pre><code>date_list = []
fo... | python|pandas | 1 |
352,384 | 55,924,331 | How to apply Guided BackProp in Tensorflow 2.0? | <p>I am starting with <code>Tensorflow 2.0</code> and trying to implement Guided BackProp to display Saliency Map. I started by computing the loss between <code>y_pred</code> and <code>y_true</code> of an image, then find gradients of all layers due to this loss. </p>
<pre><code>with tf.GradientTape() as tape:
log... | <p>First of all, you have to change the computation of the gradient through a ReLU, i.e. <a href="https://i.stack.imgur.com/tfu46.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tfu46.png" alt="Guided BackProp Formula"></a></p>
<p>Here a graphic example from the <a href="https://arxiv.org/abs/1412.6... | python|tensorflow|keras|backpropagation|tensorflow2.0 | 6 |
352,385 | 55,934,897 | How to change pandas timestamps to python datetime objects? | <p>I am searching for a way to change pandas timestamps to python datetime objects and I am failing. I used to_pydatetime().</p>
<p>Below is my code with comments:</p>
<pre><code>import pandas
import datetime
import pytz
forced_UTC = pytz.timezone("Europe/London").localize(datetime.datetime(2019, 1, 30, 9, 5)).tzinf... | <p>It works, but you were printing the <code>type</code> without modifying the type.<br>
Here, you are printing indeed a panda date (<code>first_date</code>) and a panda type (<code>type(first_date)</code>). </p>
<pre><code>first_date = my_df["my_column"].iloc[0]
print (first_date, type(first_date)) # 2019-04-01 01:1... | python|pandas|datetime|timestamp|pytz | 0 |
352,386 | 55,685,658 | How to rename a column in pandas dataframe using apply function? | <p>I want to rename one column in pandas dataframe. I want to do that by using apply function. I wrote a code that does that but I do not know how to use apply fucntion to do this . Can anybody help?</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
url = 'https://raw.githubusercontent.com/lukes/I... | <p>I would agree with jezrael, this just makes it unnecessarily complicated. That's how I would do it as a 'quick and dirty' solution in case you really want to use <code>apply</code> (obviously very similar to jezrael's solution):</p>
<p><code>df_github.columns = df_github.columns.to_series().apply(lambda x: 'Country... | python|pandas | 1 |
352,387 | 55,788,304 | How to convert table Yes/No attributes into binary data? | <p>I have the house voting data table. I want to covert the 16 attributes with Y/N in them to binary data. How can I get all data converted, I searched the website, most of time just convert one column. I want to have short code which can covert all attributes at a time.</p>
<p><img src="https://i.stack.imgur.com/HuSu... | <p>Just use <code>replace</code> with a <code>dict</code>:</p>
<pre><code>df = df.replace({'y': 1, 'n': -1, '?': 0})
</code></pre> | python|pandas|binary | 0 |
352,388 | 55,982,422 | Is there any way to debug TensorFlow code? Also how can I see what's in the variables or objects while I interpret the code? | <p>It's really easy to debug and track variable and object values as you run your Python code but in tensorflow, it's really hard to see what's going on behind the scene. I know tensorflow works in graphs and you have to run the session. Is there any simpler way to see the values as you interpret the code? I have atta... | <p>You can try TensorFlow Eager Execution that allows you to run TensorFlow code directly without having to build a graph and run it during a session. It even says in the description that it enables easier debugging.</p>
<p><a href="https://www.tensorflow.org/guide/eager" rel="nofollow noreferrer">https://www.tensorfl... | python|tensorflow|conv-neural-network | 1 |
352,389 | 55,840,473 | Regex text to pandas dataframe | <p>I have a text file that contains multiple lines in the format given below:</p>
<pre><code>real 0m0.020s
user 0m0.000s
sys 0m0.000s
Round 1 completed. with matrix size of 1200 x 1200 with threads 8
real 0m0.022s
user 0m0.000s
sys 0m0.001s
Round 2 completed. with matrix size of 1200 x 1200 with thr... | <p>You can use a regex:</p>
<pre><code>import re
import pandas as pd
regex = re.compile(r'real +(\dm\d\.\d+s)\nuser +(\dm\d\.\d+s)\nsys +(\dm\d\.\d+s)\nRound +(\d+).+of +(\d+ x \d+).+threads (\d+)')
df = pd.DataFrame(regex.findall(data), columns=['real', 'user', 'sys', 'round', 'matrix size', 'threads'])
print(df)
... | python|regex|pandas | 3 |
352,390 | 55,669,004 | Appending Pandas DataFrame column based on another column | <p>I have Pandas DataFrame that looks like this:</p>
<pre><code>| Index | Value |
|-------|--------------|
| 1 | [1, 12, 123] |
| 2 | [12, 123, 1] |
| 3 | [123, 12, 1] |
</code></pre>
<p>and <strong>I want to append third column with list of array elements lengths</strong>:</p>
<pre><code>| Index ... | <p>You can use <code>list comprehension</code> with <code>map</code>:</p>
<pre><code>dataframe["Expected_value"] = dataframe.Value.map(lambda x: [len(str(y)) for y in x])
</code></pre>
<p>Or nested list comprehension:</p>
<pre><code>dataframe["Expected_value"] = [[len(str(y)) for y in x] for x in dataframe.Value]
</... | python|pandas|dataframe | 3 |
352,391 | 55,805,719 | Pandas groupby overlapping list | <p>I have a dataframe like this</p>
<pre><code> data
0 1.5
1 1.3
2 1.3
3 1.8
4 1.3
5 1.8
6 1.5
</code></pre>
<p>And I have a list of lists like this:</p>
<pre><code>indices = [[0, 3, 4], [0, 3], [2, 6, 4], [1, 3, 4, 5]]
</code></pre>
<p>I want to produce sums of each of the groups in my dataframe us... | <p>Use list comprehension:</p>
<pre><code>a = [df.loc[x, 'data'].sum() for x in indices]
print (a)
[4.6, 3.3, 4.1, 6.2]
</code></pre>
<hr>
<pre><code>arr = df['data'].values
a = [arr[x].sum() for x in indices]
print (a)
[4.6, 3.3, 4.1, 6.2]
</code></pre>
<p>Solution with <code>groupby + sum</code> is possible, but ... | python|pandas|data-science | 1 |
352,392 | 55,954,602 | Image Classifier with Tensorflow and Keras | <p>I'm trying to get an Image Classifier to work. So far the model does seem to work but now every time I want to test an image to see if it is being recognized appropriately I have to do the whole training all over. I'm very new to this but I suppose there should be another way to only test the images without the trai... | <p>Since you are a beginner, you may not know that you actually do not need to retrain the model in order to test :D. Your hunch is right, and we will see down below how you can do that.</p>
<p>You can save the weights of your model in a specific file format. In Keras, it is a file with the extension .hdf5.</p>
<pre>... | python|tensorflow|keras|image-recognition | 5 |
352,393 | 55,740,572 | Read multi-level json in python with pandas from url | <p>I try to read multi-level JSON with pandas and store data in the data-frame for next work with it or for print. The main goal for me is to understand how to read data from each level of JSON.</p>
<p>Here you are my first steps, which works:</p>
<pre><code>import pandas as pd
import requests
log = ("user", "passwo... | <p>From answers above I am not more clever as before. </p>
<p>So I try to reduce my question to one question.
How Can I get table with 4 columns:
Data.Code; Data.snapshots.DateFrom; Data.snapshots.Address.Street; Data.snapshots.Address.City</p>
<p>This is my code, but it is necessary to correct it, but I do not how.... | python|json|pandas|dataframe|python-requests | 0 |
352,394 | 55,776,220 | Dot product between scipy sparse matrix and numpy array give ValueError | <p>I'm trying to calculate the dot product between a scipy parse matrix and a numpy array.</p>
<p>First I was using a numpy matrix, which you can see in the following code:</p>
<pre><code>def power_iteration(matrix, n):
b_k = np.random.rand(matrix.shape[1])
for _ in range(n):
b_k = np.dot(matrix, b_k)... | <p>Seems like in order to use <code>np.dot</code> on sparse matrix you'd need to convert it to dense matrix first with <code>matrix.toarray()</code>.
Also see <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html#matrix-vector-product" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/spars... | numpy|vector|scipy|sparse-matrix|valueerror | 0 |
352,395 | 55,684,521 | How to create a new ndarray after performing a calculation on a slice | <p>I have a 4d numpy array, I want to perform a calculation on several slices of it and then create a new array with all the values in. The main problem is I have fixed slices for 3 dimensions but then several ranges for the fourth axis how do I slice by ranges on the 4th axis please</p> | <p>While I think there are several similar questions on here already (38 results for <code>numpy 4d slice</code>), here's my attempt to visually explain this.
First, I downloaded a <code>.gif</code> from Giphy and converted it into an exemplary multidimensional <code>np.array()</code>; it is 200x200px in size, has 3 co... | python|slice|numpy-ndarray|inequalities | 1 |
352,396 | 55,868,427 | how do I feed the inputs of network if it has not fed by model.fit? | <p>I have a simple network in keras and I define a custom layer which does some operations on input tensor and then returns it to the network, but when I want to implement it, it produces the following error and said the input has not been fed while I think when we use fit function it feeds the network. could you pleas... | <p>It's caused by the line <code>slicAndJpeg(K.eval(noised_image_pad))</code> in your <code>JPEGLayer</code> class. Basically, you're trying to evaluate a tensor by calling <code>K.eval()</code> without feeding any data to it. You can't evaluate an empty tensor, right? This can be fixed by removing that <code>noise()</... | python|tensorflow|keras|keras-layer|tensor | 0 |
352,397 | 55,668,238 | Get cumulative sum Pandas conditional on other column | <p>I want to create a column that shows the cumulative count (rolling sum) of previous purchases (per customer) that took place in department 99</p>
<p>My data frame looks like this ; where each row is a separate transaction. </p>
<pre><code> id chain dept category company brand date productsize... | <p>Your code should be simplify:</p>
<pre><code>s = (shopdata6['dept']==99).astype(int)
shopdata6['transaction_99'] = s.groupby(shopdata6['id']).cumsum()
print (shopdata6)
id dept date purchase purchase_count_dept99(desired) transaction_99
0 id1 199 date1 $10 0 ... | python|pandas|pandas-groupby | 0 |
352,398 | 55,659,946 | Python, iterating and modifying DataFrames in a dictionary of df's | <p>Coming from a C# background (years ago) and being very new to Python I'm struggling to optimise my code. Literally just learned that for loops are very slow.</p>
<p>In the code below the loop that adds a calculated column to each DataFrame in the Dict appears to be a huge bottleneck.</p>
<p>I've read up on ways to... | <pre><code>import pandas as pd
import numpy as np
import datetime as date
import itertools
player_list = ['player' + str(x) for x in range(1,71)]
data = pd.DataFrame({'Names': player_list*1000,\
'Ob1' : np.random.rand(70000),\
'Ob2' : np.random.rand(70000) ,\
'... | python|pandas|optimization|vectorization | 2 |
352,399 | 55,857,147 | I am trying to assign a Holiday classifier to a list of dates | <p>I have two dataframes, one with a list of dates and their corresponding holiday (df2), and another one with a list of transactions (df1). I'm trying to use the first one to flag holidays on the second one, but whenever I try to create a function and apply it, it just returns empty values for everything. </p>
<p>The... | <p>For the if statement to do what you're expecting you need to get a list or a numpy array from the Series returned by the <code>df2['DATE']</code> operation. You can either do it by using the <code>.values</code> property or converting the series to a list <code>list(df2['DATE'])</code>:</p>
<pre><code>import pandas... | python|pandas|datetime|data-manipulation | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.