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 |
|---|---|---|---|---|---|---|
364,500 | 71,338,307 | query() of generator `max_length` being succeeded | <p>Goal: set <code>min_length</code> and <code>max_length</code> in Hugging Face Transformers generator query.</p>
<p>I've passed <code>50, 200</code> as these parameters. Yet, the length of my outputs are much higher...</p>
<p>There's no runtime failure.</p>
<pre class="lang-py prettyprint-override"><code>from transfo... | <h4>Explanation:</h4>
<p>As explained by Narsil on Hugging Face Transformers <a href="https://github.com/huggingface/transformers/issues/15914#issuecomment-1058112592" rel="nofollow noreferrer">Git Issue response</a></p>
<blockquote>
<p>Models, don't ingest the text one character at a time, but one token
at a time. Th... | python-3.x|huggingface-transformers | 1 |
364,501 | 71,365,379 | How to analyze data from one df to every n data? | <p>I'm currently working with a <code>pandas</code> <code>df</code> where I need to perform an analysis for each 96 datas so far I am doing the process manually usind <code>.loc</code> function :</p>
<pre><code>df_partial1 = df.loc[0:95]
df_partial2 = df.loc[96:191]
</code></pre>
<p>And so on . For each <code>df_part... | <p>Use <code>groupby</code> and a custom group:</p>
<pre><code>import numpy as np
group = np.arange(len(df))//96
# group 0 is 0:95, group 1 is 96:191, etc.
a = [bill(d) for _,d in df.groupby(group)]
</code></pre> | python|pandas|function | 2 |
364,502 | 71,113,477 | Apply a string replace to several columns of a pandas dataframe | <p>I have a dataframe with several columns, two of which are strings of URIs with a final fragment such as:</p>
<p><code>http://company.com/information#name</code></p>
<p><code>http://company.com/information#Company</code></p>
<p>where I need to keep only "name" and "Company" URI fragments, and remo... | <p>You're passing in the string 'DF_COLUMN' as a key, rather than the variable DF_COLUMN from your loop. Since there is no column named 'DF_COLUMN', pandas is throwing a KeyError.</p> | python|pandas|dataframe|lambda | 2 |
364,503 | 71,367,400 | Is it possible to loc a column based on a sort from another column | <p>I have the following DataFrame, and I need to obtain only the values from Column 2 that go from 21 to 1, without losing the sorting from Column 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>44508</td>
<td>20... | <p>Change your condition</p>
<pre><code>df = df.loc[~((dfmerged['Column2'] < 21) & (df['Column2'] > 1))]
</code></pre> | python|pandas|dataframe | 1 |
364,504 | 71,294,900 | Iterate over a pandas DataFrame & Check Row Comparisons | <p>I'm trying to iterate over a large DataFrame that has 32 fields, 1 million plus rows.</p>
<p>What i'm trying to do is iterate over each row, and check whether any of the rest of the rows have duplicate information in 30 of the fields, while the other two fields have different information.</p>
<p>I'd then like to sto... | <p>As a general rule, <a href="https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758">you should always always try not to iterate over the rows of a DataFrame</a>.</p>
<p>It seems that what you need is the pandas <a href="https://pandas.pydata.org/docs/referenc... | python|pandas | 0 |
364,505 | 71,184,059 | Colab: Could not find a version that satisfies the requirement pandas==1.4.1 | <p>In Colab notebook, I did:</p>
<pre><code>!pip install pandas==1.4.1
</code></pre>
<p>but returned:</p>
<pre><code>ERROR: Could not find a version that satisfies the requirement pandas==1.4.1 (from versions: 0.1, 0.2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.5.0, 0.6.0, 0.6.1, 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.8.0, 0.8.1, 0.... | <p><code>pandas</code> 1.4+ <a href="https://pypi.org/project/pandas/1.4.0/" rel="nofollow noreferrer">requires</a> Python >= 3.8. From the list of available versions I can guess you use Python 3.7 or lower.</p>
<p>Upgrade Python or use lower version of pandas. Just <code>pip install pandas</code> should find compat... | pandas|pip|google-colaboratory | 3 |
364,506 | 71,330,255 | Highlight column in DataFrame by comparing with other column | <p>I have a excel which I am reading into DataFrame, comparing the columns and highlight one column and writing to excel. Below is the code and it's not working. I am not seeing cell highlighted. Not sure what I am doing wrong as I learning python.</p>
<pre><code>file = Path(path to excel)
frm_df = pd.read_excel(file)
... | <p>Here is one way to do it:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"AMOUNT A": {0: 1400, 1: 3000, 2: 1500, 3: 3500},
"AMOUNT B": {0: 1400, 1: 3000, 2: 2500, 3: 3500},
}
)
def highlight(df, col1, col2... | python|pandas | 0 |
364,507 | 71,208,261 | It is possible to get only the names of the parent components in PyTorch model | <p>All pretrained models in Pytorch contain "parent" submodules with predefines names, for example AlexNet contains 3 "parent" submodules: <code>features</code>, <code>avgpool</code> and <code>classifier</code>:</p>
<pre><code>model = torch.hub.load('pytorch/vision:v0.10.0','resnet101',pretrained=Tr... | <p>You can use this:</p>
<pre><code>import torch
import torchvision.models as models
model = models.alexnet(pretrained=True)
parents = [parent[0] for parent in model.named_children()] # get parents names
print(parents)
</code></pre>
<p>Output:</p>
<pre><code>['features', 'avgpool', 'classifier']
</code></pre> | pytorch | 1 |
364,508 | 71,415,716 | How to Combine Multiple TensorBoard Directories to Get a Single Curve | <p>I am training a CNN on a remote server that crashes randomly and all the time. Luckily I am able to each time use tensorboard to save the last best weight so I could resume training from there.</p>
<p>I am also able to save events on each training run into a separate log folder automatically generated by tensorboard... | <p>I suspect each training run create a new directory with 2 files, train and validation. You can put all those files in one folder and you can see that the graphs become one.</p>
<p><a href="https://i.stack.imgur.com/gRw9I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gRw9I.png" alt="3 training se... | python|tensorflow|tensorboard|custom-training | 0 |
364,509 | 71,393,124 | Replace NaN value of first row in a groupby with value of next row which contains specific value - Python | <p>I have a DataFrame which looks like the following</p>
<pre><code>email month level
jacob.a@abc.com jan EE2
kylie.l@abc.com jan nan
jacob.a@abc.com mar MG1
sumeer.b@abc.com jan nan
boris.k@abc.com jan nan
kylie.l@abc.com jun EE3
cinkil.m@a... | <p>We could use <code>where</code> to replace values other than "MG" or "EE" with NaN; then <code>groupby</code> + <code>bfill</code> + <code>fillna</code> to fill in NaN values in "level" column with the next value that is either "MG" or "EE" for each "email"... | python|pandas|dataframe|group-by|pandas-groupby | 1 |
364,510 | 71,133,586 | Simple tensorflow LSTM network get stucks on apple silicon | <p>I am building a very simple LSTM network using the imdb dataset in Tensorflow, in particular running on a Apple Silicon chip (M1 max).</p>
<p>My code is the following:</p>
<pre><code>import tensorflow as tf
def get_and_pad_imdb_dataset(num_words=10000, maxlen=None, index_from=2):
from tensorflow.keras.datasets i... | <p><a href="https://github.com/tensorflow/tensorflow/issues/44751" rel="nofollow noreferrer">TensorFlow is not supported by M1 silicon.</a></p>
<p>It is possible to get it installed with some features working, but anything that uses any C under the hood won't work. There are some workarounds such as <a href="https://be... | python|tensorflow|metal|apple-m1|apple-silicon | 0 |
364,511 | 71,345,194 | Bar chart with ticks based on multiple dataframe columns | <p>How can I make a bar chart in matplotlib (or pandas) from the bins in my dataframe?</p>
<p>I want something like this, below, where the x-axis labels come from the <code>low</code>, <code>high</code> in my dataframe (so first tick would read <code>[-1.089, 0)</code> and the y value is the <code>percent</code> column... | <p>Create a new column using the the low, high cols.</p>
<p>Covert the int values in the low and high columns to str type and set the new str in the <code>[<low>, <high>)</code> notation that you want.</p>
<p>From there, you can create a bar plot dirrectly from <code>df</code> using <code>df.plot.bar()</cod... | python|pandas|matplotlib|bar-chart | 1 |
364,512 | 71,142,471 | Filter multi index pivot table based on value count | <p>My code for the pivot table is:</p>
<pre><code>games_df.pivot_table(index=['Name', 'Platform'], values='total_sale', aggfunc='sum')
</code></pre>
<p>I get the following pivot table:</p>
<pre><code> total_sale
Name Platfor... | <p>I was able to solve it:</p>
<pre><code>pivot=games_df.pivot_table(index=['Name', 'Platform'], values='total_sale', aggfunc='sum')
pivot.groupby('Name').filter(lambda x: len(x) > 1)
total_sale
Name Platform
frozen: olaf's quest 3DS ... | python|pandas|dataframe|pivot-table | 1 |
364,513 | 71,423,812 | Add new nodes to one of the output layers in a Keras model | <p>I have a custom ResNet model that I define through the Keras Functional API. Also my model has multiple outputs. The last element of the output array is the fully connected dense layer with <code>num_class</code> nodes. I want to be able to increment the number of nodes of this layer. This is the relevant code for t... | <p>This is the solution I've come up with. I assigned the layers that I wanted to keep as output to variables:</p>
<pre><code>from tensorflow.keras import layers, models, Input, regularizers
inputs = Input(shape=(height, width, channels), name='data')
x = MyLayer()(inputs)
# ... other layers
a = MyLayer(name="a&q... | python|tensorflow|keras | 0 |
364,514 | 71,233,016 | Infer multivalent features with tfdv from pandas dataframe | <p>I want to infer a schema with tensorflow data validation (tfdv) based on a pandas dataframe of the training data. The dataframe contains a column with a multivalent feature, where multiple values (or None) of the feature can be present at the same time.</p>
<p>Given the following dataframe:</p>
<pre><code>df = pd.Da... | <p>A <code>String</code> will be interpreted as a <code>String</code>. Regarding your issue with the <code>List</code>, it might be related to this <a href="https://github.com/tensorflow/data-validation/issues/90#issuecomment-541966795" rel="nofollow noreferrer">issue</a>:</p>
<blockquote>
<p>Currently only pandas colu... | python|pandas|tensorflow|machine-learning|tensorflow-data-validation | 2 |
364,515 | 71,308,623 | Reading HTML file with Python Pandas into dataframe returns invalid literal for int() with base 10 | <p>I am trying to read and extract tables from wikipedia it generally works for most pages but for some reason for this link it doesn't work: <a href="https://en.wikipedia.org/wiki/Great_Britain_at_the_Olympics%27" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Great_Britain_at_the_Olympics'</a></p>
<p>My code... | <p>I think I have found the problem in wikipedia HTML file, there is an unexpected character after colspan parameter (shown below in screenshot). By editing the table and deleting ; symbol I was able to read the table using pandas.</p>
<p><a href="https://i.stack.imgur.com/WXEGP.jpg" rel="nofollow noreferrer"><img src=... | python|html|pandas|web-scraping | 0 |
364,516 | 71,276,065 | Unable to understand working of np.isclose() | <p>For the following input:</p>
<pre><code>import numpy as np
a= np.array([[0.0, 0.0, 0.0],
[1.0, 1.0, -2.234],
[0.0, 0.0, 0.0]])
b= np.array([1.0, 1.0, -2.234])
print(np.isclose(np.transpose(a), b))
</code></pre>
<p>Output:</p>
<pre><code>$ python temp.py
--> [[False True False]
[Fal... | <p>What is happening here is that <code>numpy</code> automatically <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">"broadcasts"</a> the lower-dimensional array to match the shape of the higher-dimensional array.</p>
<p>In this concrete instance the <code>b</code>... | python|arrays|numpy | 2 |
364,517 | 71,298,353 | To remove quotes in a dataframe column of strings | <p>need assistance with something i think i pretty minor but cant seem to find a way around.</p>
<pre><code>twitter_df['Split Tweets'] = twitter_df['Tweets'].apply(lambda x:(x.split())).astype(str).str.lower()
</code></pre>
<p>the above returns the desired result but i cant find a way around getting the quotation marks... | <p>You need to specify the separator, if you are separating by comma then you need to specify</p>
<pre><code>twitter_df['Split Tweets'] = twitter_df['Tweets'].apply(lambda x:(x.split(','))).astype(str).str.lower()
</code></pre> | python|pandas|dataframe | 0 |
364,518 | 71,265,480 | JupyterLab TensorFlow 2.3 Build Failed with 524 | <p>I created a new notebook in Google Cloud Vertex-AI that has the following properties:<a href="https://i.stack.imgur.com/Sg1mE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sg1mE.png" alt="enter image description here" /></a></p>
<p>When I open the notebook, I am prompted by the following message... | <p>To answer your question and to be use as a workaround, you should using the following command (as show on <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/pull/231/commits/4ec5b12698b30c8a9e05dc5c07c86de375bf5143" rel="nofollow noreferrer">the error commit about this issue</a>):</p>
<pre><code>sudo ... | tensorflow|google-cloud-platform|jupyter-lab|build-error | 1 |
364,519 | 71,361,363 | PyQt5: Implement removeRows for pandas table model | <p>I use QTableView to display and edit a Pandas DataFrame.
I use this method in the TableModel class to remove rows:</p>
<pre><code> def removeRows(self, position, rows, QModelIndex):
start, end = position, rows
self.beginRemoveRows(QModelIndex, start, end) #
self._data.drop(position,inplace=... | <p>Your example passes the wrong index to <code>removeRows</code>, which also does not calculate the start and end values correctly. It can be fixed like this:</p>
<pre><code>class MainWindow(QtWidgets.QMainWindow):
...
def delete_row(self):
index = self.tableView.currentIndex()
self.model.remov... | python|pandas|pyqt5|index-error|qabstracttablemodel | 2 |
364,520 | 71,132,488 | Loop through a dataframe checking for a string match | <p>first time poster and python beginner so hopefully asking correctly.</p>
<p>I need to loop through all rows in a dataframe, checking for a string match in one column. If there is a match then I want to insert a date into a new column, if not then use a different date.</p>
<p>I need to iterate through the rows as eac... | <p><code>df['date'] = "wooo"</code> sets the entire column to <code>"wooo"</code>, which I'm sure is not your intention. You should just set <em>that row's <code>date</code> column</em></p>
<pre><code>for index in df.index:
if df.loc[index, 'time'] == '00:00':
df.loc[index, 'date'] = &qu... | python|pandas | 1 |
364,521 | 71,304,186 | Python Dataframe column matching | <p>I have 2 columns A & B. A contains text values separated by '_' and B has some description related to A.</p>
<p>Example:</p>
<pre><code>*Col Terms
AB_BCN_PRC About Bitcoin Price
AC_CR_STT Account credit Statement
A6_AT_MD Audi Automatic Model*
</code></pre>
<p>I need to map A and B so in future ... | <p>If you can define a good complete mapping dictionary (each name separated by _ as a key, the text represented by this name as a value), it can be easily implemented, and finally I used pandas to combine into the format in your example, you can also use print directly, the main focus on the function gen_terms, by the... | python|pandas|text|tags | 0 |
364,522 | 71,420,321 | Pandas pivot based on grouping columns as one | <p>I have below data frame:</p>
<pre><code>Name Account Revenue 1 Revenue 2
John A Set-up 100.00 0.00
Peter K Slot 250.00 0.00
Michael S Set-up 0.00 25.00
</code></pre>
<p>I'm trying to use pandas pivot function so I can have <code>Ac... | <p>You can sum <code>Revenue</code>s before pivoting:</p>
<pre><code>df['Revenue'] = df.filter(like='Revenue').sum(axis=1)
df=df.pivot_table(index='Name',
columns='Account',
values='Revenue',
fill_value=0,
aggfunc='sum')
print (df)
Account Se... | python|pandas|pivot | 1 |
364,523 | 71,168,746 | Error while concatenating values from a dataframe in python | <p>I am reading a csv file using python and displaying the record after asking the user to select an index and then I display all the records corresponding to the index number.</p>
<p>Code:</p>
<pre><code>df = pd.read_csv(csv_filepath, usecols=['userID', 'firstName', 'lastName'])
select_index = int(input("Enter th... | <p>The problem is with column types.</p>
<p>Example:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'userID': [1], 'firstName': ['a'], 'lastName':['b']})
data = df.loc[0, :]
userID = data.userID
firstName = data.firstName
lastName = data.lastName
#solution
x = str(userID) + firstName + lastName
</code></pre>
<p... | python|pandas|dataframe | 1 |
364,524 | 71,117,385 | Filter data in pandas | <p>I have a pandas dataframe:</p>
<p><a href="https://i.stack.imgur.com/ZZUw5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZZUw5.png" alt="enter image description here" /></a></p>
<p>It is a large dataframe. How can i filter out all the rows with id "north_south"?</p> | <p>The contains function under the str accessor returns the values that contain a given set of characters.</p>
<p><code>df[df.id.str.contains('north_south')]</code></p> | python|pandas|dataframe|sumo | 0 |
364,525 | 71,242,410 | How to convert pandas date column to numeric | <p>Let say I have following code</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[pd.to_datetime('2019-01-01').to_period('M'), pd.to_datetime('2019-01-01').to_period('M')], [pd.to_datetime('2019-01-01').to_period('M'), pd.to_datetime('2019-01-01').to_period('M')], [pd.to_datetime('2019-01-01').to_period('M'), pd.... | <p>One option is to directly use <code>.n</code> attribute in side a map:</p>
<pre><code>df.dat3.map(lambda t: t.n)
0 0
1 0
2 0
Name: dat3, dtype: int64
</code></pre> | python|python-3.x|pandas | 2 |
364,526 | 71,305,279 | pandas fill NA but not all based on recent past record | <p>I have a dataframe like as shown below</p>
<pre><code>stud_name act_qtr year yr_qty qtr mov_avg_full mov_avg_2qtr_min_period
0 ABC Q2 2014 2014Q2 NaN NaN NaN
1 ABC Q1 2016 2016Q1 Q1 13.0 14.5
2 ABC Q4 2016 2016Q4 NaN NaN NaN
3 ABC Q4 2017 2017Q4 NaN NaN NaN
4 ABC Q4 2020 ... | <p>In this case, you might want to use <code>append</code> instead of <code>merge</code>. In other words, you want to concatenate vertically instead of horizontally. Then after sorting the DataFrame by <code>stud_name</code> and <code>yr_qtr</code>, you can use <code>groupby</code> and <code>fillna</code> methods on it... | python|pandas|dataframe|numpy|pandas-groupby | 1 |
364,527 | 71,246,093 | Scaling this python script for multiple stocks | <p>First off, thank you for taking the time to help me. We are using this python script that pulls data from Yahoo for a given time period.</p>
<pre><code>import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
star... | <p>You don't have to write the intermediate dataframes (for individual stock symbols) to file. Try something like:</p>
<pre><code>tickers = pd.read_csv(r'path_to/symbols.csv')['symbol_column_name'].values
full_df = pd.DataFrame({})
for ticker in tickers:
df = web.DataReader(ticker,'yahoo', start, end)
full_df ... | python|pandas|finance|stock | 0 |
364,528 | 71,278,752 | using index value greater than as a condition for np where | <p>I'm trying to look for true conditions where "this" is greater than "that" starting with row 2 (index is greater than 1).
For instance if the df is 5 rows long and "this" is greater than "that" in rows 1, 4, and 5 then the return would be 0,0,0,1,1.
The index itself is a datet... | <p>You were close. You just need to enclose your conditions in () and flip the last two np.where() arguments.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'this': [5,2,2,5,5],
'that': [3,3,3,3,3]},
index=['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'])
... | python|pandas|numpy | 1 |
364,529 | 71,108,760 | Exporting Pandas dataframe into SQL Server | <p>I am trying to export a Pandas dataframe to SQL Server using the following code:</p>
<pre><code>import pyodbc
import sqlalchemy
from sqlalchemy import engine
DB={'servername':'NAME', 'database':'dbname','driver':'driver={SQL Native Client 11.0}'
}
engine=create_engine('mssql+pyodbc://'+'DB['servername']+'/'+['dat... | <p>Pandas uses SQLAlchemy to connect to databases, which in turn can use PyODBC. Microsoft <a href="https://docs.microsoft.com/en-us/sql/connect/python/python-driver-for-sql-server?view=sql-server-ver15#getting-started" rel="nofollow noreferrer">recommends using PyODBC to connect to SQL Server</a>.</p>
<p>The <a href="... | sql-server|pandas|dataframe | 0 |
364,530 | 71,176,456 | Returning difference between two strings (irrespective of their type) | <p>We have a data frame and need to compare two its columns.</p>
<p><code>Column 1 (Name: PN) = 555, 333, 444</code></p>
<p><code>Column 2 (Name: whatever)= "555A", 333, "444B"</code></p>
<p><strong>We need to get the difference, i.e. "A" and "B"</strong>. Neither of variants fou... | <p>You can implement a diff function with <a href="https://en.wikipedia.org/wiki/Longest_common_substring_problem" rel="nofollow noreferrer">Longest Common Substring</a>.</p>
<p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAwgFgQwHYHNoF4oG8CwAoKQqUSALigCIBBAERoEkAVegeQDkKoAfSmgUQAyfZu048KfBiI4BufESgBLJAB... | python|python-3.x|pandas|string|dataframe | 0 |
364,531 | 71,241,418 | filling NaN value in a df based on the first value in month | <p>I have a df as below (after concat) I want to fill the NaN value with the first value of the corresponding month (e.g. 05/05/74 to be filled with 5 and 01/06/74 to be filled with NaN)
is there a pythonic way manipulating pandas dataframes to achieve so?</p>
<div class="s-table-container">
<table class="s-table">
<th... | <p>First, convert your column <code>Date</code> to <code>datetime64</code> then group monthly and fill values:</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
df['values'] = df['values'].combine_first(df.groupby(df['Date'].dt.to_period('M'))['values'].transform('first'))
print(df)
# Output
... | python|pandas|dataframe|fillna | 0 |
364,532 | 71,120,615 | How to convert List from column to list of DataFrame? | <p>I have a DataFrame which contains categories, and I want to split the DataFrame using categories as <code>df_name</code>:</p>
<pre><code>df_name = df['category'].unique()
print(sites)
</code></pre>
<p>result:</p>
<pre><code>['df1' 'df2']
</code></pre>
<p>after splitting the DataFrame using a loop, I get 2 smaller Da... | <p>why using loop to filter? you can just use <code>df[df['column'] == 'df1']</code> to filter <code>'df1'</code> value from a column</p>
<p>then if you want to remove column, you can use <code>del df['category']</code></p> | python|pandas | 1 |
364,533 | 71,326,409 | How to speed up iterating over pandas DF and pull certain column for each row | <p>I have a pandas dataframe that can vary in length but will have ~100 columns and anywhere from 40,000 to a couple hundred thousand rows.</p>
<p>We are analyzing automotive engine cylinder events, so each row is a cylinder event and the columns are various statistics associated with these events such as kurtosis, std... | <ol>
<li><p>Divide your df into <em>N</em> sub-dfs, keeping only rows and columns relevant to one Cylinder.</p>
</li>
<li><p>Apply your for-loop for each sub-df. In the for-loop, you can get rid of all <code>[col for col in .....]</code> because now only relevant columns exist in the sub-df.</p>
</li>
<li><p>Refer to t... | python|pandas|dataframe | 0 |
364,534 | 71,288,266 | Error when trying to read 4 txt files into 1 dataframe with pandas | <p>I have four .txt files which I want to directly read into 1 dataframe with pandas. I found in another public question the following code:</p>
<pre><code>path = r'C:\Users\xx\map1'
all_files = glob.glob(path + "/*.txt")
li = []
for filename in all_files:
df = pd.read_csv(filename, index_col=None, hea... | <p>If you have same columns in all your csv files then you can try the code below. I have added header=0 so that after reading txt first row can be assigned as the column names.</p>
<pre><code>import pandas as pd
import glob
path = r'C:\DRO\DCL_rawdata_files' # use your path
all_files = glob.glob(path + "/*.txt... | python|pandas|parse-error | 0 |
364,535 | 71,142,612 | Array of values as input in Snakemake workflows | <p>I started to migrate my workflows from <code>Nextflow</code> to <code>Snakemake</code> and already hitting the wall at the start of my pipelines which very often begin with a list of numbers (representing a "run number" from our detector).</p>
<p>What I have for example is a <code>run-list.txt</code> like<... | <p>In Snakemake you'd use this file to generate lists of the values you want to feed into your workflow. You'd parse the detector IDs and run numbers outside the rules. Off the top of my head your run list looks like it could neatly be handled with pandas, if you want to use an external library.</p>
<pre class="lang-py... | python|pandas|snakemake|directed-acyclic-graphs|nextflow | 3 |
364,536 | 71,333,337 | How to calculate custom fiscal year in pandas? | <p>I have a dataframe like as shown below</p>
<pre><code>app_date
20/3/2017
28/8/2017
18/10/2017
15/2/2017
2/5/2017
11/9/2016
df = pd.read_clipboard()
</code></pre>
<p>Our company fiscal year is from <code>October</code> of current year to <code>September</code> of next year</p>
<pre><code>Q1 - Oct to Dec
Q2 - Jan to ... | <p>You can use:</p>
<pre><code># Create 2 DatetimeIndex instead of a Series (avoid using .dt accessor)
start = pd.to_datetime(df['app_date'].values, dayfirst=False)
end = start + pd.DateOffset(months=3)
cols = ['act_month', 'act_year', 'act_qtr', 'comp_fis_year', 'comp_fis_qtr']
df = df.join(pd.DataFrame([start.month,... | python|pandas|dataframe|numpy|datetime | 2 |
364,537 | 52,261,273 | Can't figure out how to use value in tensor | <p>At '?!?' below is where I don't know how to initiate getting into variable 'recursion' a sample from a normal distribution with mean equal to the x axis value of 'seed' and scale '1.'.</p>
<pre><code>tf.enable_eager_execution()
seed=tf.distributions.Normal(loc=0. , scale=1.).sample()
recursion=tf.distributions.Nor... | <p>It just didn't occur to me to simply pass the tensor variable in and find out what happens. Below is code that works fine, no indexing, like for example 'seed[0]' or 'seed[0:0]' instead of simply 'seed', required:</p>
<pre><code>tf.enable_eager_execution()
seed=tf.distributions.Normal(loc=0. , scale=1.).sample()
r... | python|tensorflow | 0 |
364,538 | 52,117,934 | How to map column names from df to another rapidly? | <p>I have a df that looks this:</p>
<pre><code>df
id email adress
1 a@a main st
</code></pre>
<p>I have another df that looks like this: </p>
<pre><code>df1
Id Field
1 id
2 email
3 address
</code></pre>
<p>How do I rename columns in df1 to the Id values... | <p>You have <code>rename</code> </p>
<pre><code>df1.rename(columns=df2.set_index('field name').id)
Out[10]:
1 2 3
0 1 a@a mainst
</code></pre> | python|python-3.x|pandas | 2 |
364,539 | 52,444,204 | Configure Tensorflow for CPU using Java API | <p>I trying to play with the numbers for <strong>intra_op_parallelism_threads</strong> an <strong>inter_op_parallelism_threads</strong>. I use Tensorflow and Proto version 1.8.0 for Java.
I used the following code:</p>
<pre><code> ConfigProto config = ConfigProto.newBuilder()
.setInterO... | <p>I have got the same problem and here is my way out.</p>
<pre><code>SavedModelBundle.loader("model_dir").withTags("tag").withConfigProto(config.toByteArray()).withXX().load();
</code></pre> | java|tensorflow|inference | 0 |
364,540 | 52,266,000 | Avoiding tf.data.Dataset.from_tensor_slices with estimator api | <p>I'm am trying to figure out the recommended way to use the <code>dataset</code> api together with the <code>estimator</code> api. Everything I have seen online is some variation of this:</p>
<pre><code>def train_input_fn():
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
return dataset
</code... | <p>To use either initializable or reinitializable iterators, you must create a class that inherits from tf.train.SessionRunHook, which has access to the session at multiple times during training and evaluation steps.</p>
<p>You can then use this new class to initialize the iterator has you would normally do in a class... | python|tensorflow | 4 |
364,541 | 52,178,922 | Pytorch Validating Model Error: Expected input batch_size (3) to match target batch_size (4) | <p>I'm building a NN in Pytorch that is supposed to classify across 102 classes. </p>
<p><strong>I've got the following validation function:</strong></p>
<pre class="lang-py prettyprint-override"><code>def validation(model, testloader, criterion):
test_loss = 0
accuracy = 0
for inputs, classes in testloa... | <p>In your validation function,</p>
<pre><code>def validation(model, testloader, criterion):
test_loss = 0
accuracy = 0
for inputs, classes in testloader:
inputs = inputs.to('cuda')
output = model.forward(inputs)
test_loss += criterion(output, labels).item()
ps = torch.exp... | python|neural-network|pytorch | 5 |
364,542 | 52,294,171 | Python: transform float into datetime timestamp | <p>How could I transform the following float:</p>
<pre><code>9.3125
</code></pre>
<p>which corresponds to a time, into a proper Pandas timestamp in the likes of:</p>
<pre><code>Timestamp('2017-11-13 10:00:00')
</code></pre>
<p>The float belongs to the same day, month, and year as the example timestamp above. I have... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timedelta.ceil.html" rel="nofollow noreferrer"><code>Timedelta.ceil</code></a>:</p>
<pre><code>num = 9.3125
a = pd.Timestamp('2017-11-13') + pd.to_timedelta(num, unit='H').ceil('H')
print (a)
2017-11-13 10:00:00
</code></pre> | python|pandas|datetime|timestamp | 2 |
364,543 | 52,153,548 | External database lookup in TF serving or part of the TF graph | <p>I have an tensorflow model that I'm planning to deploy using tensorflow serving for model inference. </p>
<p>Just wondering if there is a way to add some custom logic after the service receives the request and before it goes to the tensorflow model. Specifically, I need a lookup step from an external database, that... | <p>I'd say that you could wrap the TF server in something like a flask app, which takes in a REST request, applies the additional logic (the DB lookup), and populates and sends a request to the TF server (either via HTTP or gRPC). I don't think it would be possible to do it as 'part of the TF graph'. </p> | python|tensorflow|tensorflow-serving | 0 |
364,544 | 52,045,325 | Working with Excel using Pandas without changing format and performing operations | <p>I want to read the below excel and have to work on some of the column that is in green bold type color columns(col1,2 and so on). suppose want to replace the text from some column .. How to do that ? Also, I want that color, font structure of excel to be maintained , Is It possible in Pandas ?
Attaching Image and p... | <p>Reading data out of Excel and into a Pandas DataFrame object will not keep the font and color formatting of Excel. You can do many transformations on the data once it is in a dataframe, but then you will need to write it back out to Excel where you can re-apply your formatting and colors within Excel. Based on your ... | python|excel|python-3.x|python-2.7|pandas | 0 |
364,545 | 52,425,996 | Why USE_OPENCV is OFF in PyTorch installation? | <p>In CMakeLists.txt in pytorch folder, use Opencv is ON.</p>
<pre><code>option(USE_OPENCL "Use OpenCL" OFF)
option(USE_OPENCV "Use OpenCV" ON)
option(USE_OPENMP "Use OpenMP for parallel code" OFF)
</code></pre>
<p>In setup.py, variable is set with Opencv as</p>
<pre><code>use_env_vars = ['CUDA', 'CUDNN', 'MIOPEN', ... | <p>You can use something like this:</p>
<p>USE_OPENCV=1 USE_FFMPEG=1 USE_LMDB=1 python setup.py install</p> | opencv|pytorch|caffe2 | 0 |
364,546 | 52,448,144 | Python 3 Cosine Nearest Neighbor Format | <p>I am working on some data mining self-learning from a free online resource I found. Basically I got a csv file with a bunch of names, movie titles, and what each person rated it. I'm trying to get the K-Nearest Neighbor from it using a cosine metric but I can't get the output to look not awful. Heres what I have so ... | <p>I'm unclear what your desired output looks like. However, you should first instantiate the class and then use the <code>fit()</code> method.</p>
<pre><code>from pandas import DataFrame
import pandas as pd
import numpy as np
from sklearn.neighbors import NearestNeighbors as nn
df = pd.read_csv("https://docs.google... | python|python-3.x|pandas|scikit-learn|sklearn-pandas | 0 |
364,547 | 52,392,407 | Tensorflow: Module must be applied in the graph it was instantiated for | <p>I'm trying to serve universal sentence encoder with Django. </p>
<p>The code is initialized in the beginning as a background process (by using programs such as supervisor), then it communicates with Django using TCP sockets and eventually returns encoded sentence.</p>
<pre><code>import socket
from threading import... | <p>Load your model with the graph that you created and use that in your session.</p>
<pre><code>graph = tf.Graph()
with tf.Session(graph = graph) as session:
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2")
</code></pre>
<p>And use the same graph object in initiate_connection function ... | python|django|tensorflow|tensorflow-hub | 3 |
364,548 | 52,039,658 | Assignment of functions before entering a for-loop in Python | <p>In the following example code I want to replace patches of size <code>ps x ps</code> in a lot of images with zeros, ones or random numbers. Here is an example:</p>
<p><a href="https://i.stack.imgur.com/5kVc3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5kVc3.png" alt="enter image description h... | <p><strong>There are pre-defined functions that take tuples:</strong></p>
<p>Read the docs, for <code>np.random.rand</code>:</p>
<blockquote>
<p>This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to <code>np.random.random_sample</code> .</p>
</blockquote>
... | python|numpy | 5 |
364,549 | 52,306,461 | How to sample batch from a specific class? | <p>I'd like to train a classifier on one ImageNet dataset (1000 classes each with around 1300 images). For some reason, I need each batch to contain 64 images from a specific class (provided as <code>int</code> or placeholder). How to do it efficiently with the latest TensorFlow?</p>
<p>This is a follow-up question to... | <p>Conceptually your Dataset is parameterized by a variable (the label to sample). This is totally doable!</p>
<p>Executing eagerly:</p>
<pre><code>import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
data = dict(
x=tf.constant([1., 2., 3., 4.]),
y=tf.constant([1, 2, 1, 2])
)
requested_lab... | python|tensorflow | 4 |
364,550 | 52,136,539 | Time taken to train Resnet on CIFAR-10 | <p>I was writing a neural net to train Resnet on <strong>CIFAR-10</strong> dataset.
The paper <a href="https://arxiv.org/pdf/1512.03385.pdf" rel="nofollow noreferrer">Deep Residual Learning For Image Recognition</a> mentions training for around 60,000 epochs.</p>
<p>I was wondering - what exactly does an epoch refer t... | <p>The paper never mentions 60000 epochs. An <em>epoch</em> is generally taken to mean one pass over the full dataset. 60000 epochs would be insane. They use 64000 <em>iterations</em> on CIFAR-10. An iteration involves processing one minibatch, computing and then applying gradients.</p>
<p>You are correct in that this... | tensorflow|neural-network|deep-learning|resnet | 2 |
364,551 | 52,443,056 | What is the most efficient way to interchange the values of two variables in a Tensorflow graph? | <p>Given a Tensorflow graph with two variables, var1 and var2, I want to assign the value of var1 to var2 and vice versa. One simple way of doing this is (MWE at end of post)</p>
<pre><code>var_tmp = var1.eval(session=sess)
sess.run([tf.assign(var1, var2])
sess.run([tf.assign(var2, var_tmp)])
</code></pre>
<p>However... | <p>The best way is to use resource variables (with <code>tf.enable_resource_variables()</code> after 1.11, <code>tf.get_variable_scope().set_use_resource(True)</code> before then) and a graph like</p>
<pre><code> a_value = a.read_value()
b_value = b.read_value()
with tf.control_dependencies([a_value, b_value]):
o... | tensorflow | 1 |
364,552 | 52,299,774 | How to convert object columns to string and use replace? | <p>I have some columns <code>['subject', 'H.period', 'DD.period.t']</code> etc. Actually all columns are object type.</p>
<p><a href="https://i.stack.imgur.com/oqyfd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oqyfd.jpg" alt="enter image description here"></a></p>
<p><code>dtype printscreen</co... | <p>There is no string <code>dtype</code> in <code>pandas</code>. As noted in the <a href="https://pandas.pydata.org/pandas-docs/stable/basics.html#mixed-dtypes" rel="nofollow noreferrer">docs</a>:</p>
<blockquote>
<p>Note When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to acco... | python|string|pandas | 4 |
364,553 | 52,417,304 | Remove index from MultiIndex dataframe if child index has column value meeting criteria | <p>I had originally asked this question <a href="https://stackoverflow.com/q/52389667/8146556">here</a>, and I believe it was incorrectly marked as a duplicate. I will do my best here to clarify my question and how I believe it is unique.</p>
<p>Given the following example <code>MultiIndex</code> dataframe:</p>
<pre>... | <p>I got the same result as your example solution by doing the following:</p>
<pre><code>df.loc[df.xs('1', level=2)['Val2'] > 5]
</code></pre>
<p>Comparing time performance this is ~15X faster (in my machine your example takes 36ms while this take 2ms). </p> | python|pandas|pandas-groupby|multi-index | 1 |
364,554 | 52,189,285 | Python find.line does not filter date string from text file | <p>I have a large txt file of data trades, where I want to filter data as I read them into a panda dataframe.</p>
<p>I can't seem to get it to filter/obtain the data when the string is the date.</p>
<pre><code>2017-07-28 09:39:04.442 Allocation: BUY 7.0 AZN @ 43.665,
2017-07-28 09:39:07.724 Allocation: BUY 400.0 BT.... | <p>Because each line is just a string, you can use <code>in</code> like this:</p>
<pre><code>for line in content:
if '2017-07-28' in line:
events.append(line.split(' '))
</code></pre>
<p>or using list comprehension</p>
<pre><code>events = [ line.split(' ') for line in content if '2017-07-28' in line ]
<... | python-3.x|pandas | 2 |
364,555 | 52,123,106 | Add subsection suffix values to pandas column values | <p>Let's say that I have a dataframe with multiple columns. One column establish an identification number (ID) for some guys and other column establish some feature of them, let's say the degree of misdeeds that have committed. An example of that:</p>
<pre><code>`df
Out[63]:
Crime ID
0 13 1
1 13 1
... | <p>I can't think of a good way to do this in a vectorized way, but it's relatively easy to do by looping.</p>
<p>First, you need a dict mapping (Crime, ID) pairs to IDs, so that, e.g., you can give row 9 the same ID as row 7.</p>
<p>Next, you need a dict mapping IDs to the highest sub-IDs used so far, so that, e.g., ... | python|pandas|dataframe | 1 |
364,556 | 52,442,934 | i have 2 datasets xy and xi and i want to combine them to make one data set how can i do it | <p>i want to merge them to get one dataset
I have split datasets into two from ms excel and then i want to combine them again because i wanted to exclude one colum<a href="https://i.stack.imgur.com/A3gw9.png" rel="nofollow noreferrer">enter image description here</a>n </p>
<p><div class="snippet" data-lang="js" data-h... | <p>You can use concat function in pandas </p>
<pre><code>df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
part1 = df.iloc[:,0:3]
part2 = df.iloc[:,3:]
pd.concat([part1,part2], axis=1)
</code></pre>
<p>More reference for Join, merge and concat <a href="http://pandas.pydata.org/pandas-docs/stable/mergi... | python|pandas | 0 |
364,557 | 52,346,695 | How to compute mean on each column by condition | <p>I want to compute mean for each column in a dataframe.
suppose I have a dataframe like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,2,3],
'B':[4,4,4],
'C':[7,8,9],
'D':[3,3,3]})
print(df)
A B C D
0 1 4 7 3
1 2 4 8 3
... | <p>That's.. a strange thing to want. :-) I'd advise against calling it a "mean", that will only confuse people.</p>
<p>Probably the simplest thing to do is to compute the real mean, and then just replace the unique columns with your override of 1.</p>
<pre><code>In [226]: df.mean().where(df.nunique() > 1, 1)
Out[... | python|pandas|numpy | 2 |
364,558 | 52,195,927 | Sum of columns from two data frames that contain float values | <p>I have two data frames.
The columns name are the same of those data frames.
I want to sum the float values of the same columns from dataframes
Then I can use </p>
<pre><code>df3 = df1.add(df2)
</code></pre>
<p>However, my dataframes contain two colums of string. These strings are added too.
How can I wrtie the co... | <p>Use the team names as indices instead of integer indices:</p>
<pre><code>In [2]: df1 = pd.DataFrame(dict(Team=['A','B','C','D'],Value=[1,2,3,4])).set_index('Team')
...: df2 = pd.DataFrame(dict(Team=['A','B','C','D'],Value=[3,1,2,4])).set_index('Team')
In [3]: df1 + df2
Out[3]:
Value
Team
A ... | python|pandas|add | 1 |
364,559 | 52,283,533 | Subtotal for each level in Pivot table | <p>I'm trying to create a pivot table that has, besides the general total, a subtotal between each row level.</p>
<p>I created my df.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
np.array([['SOUTH AMERICA', 'BRAZIL', 'SP', 500],
['SOUTH AMERICA', 'BRAZIL', 'RJ', 200],
['SOUTH AM... | <p>With <code>margins=True</code>, and need change little bit of your <code>pivot</code> <code>index</code> and <code>columns</code> . </p>
<pre><code>newdf=pd.pivot_table(df, index=['CONTINENT'],values=['POPULATION'], columns=[ 'COUNTRY', 'LOCATION'], aggfunc=np.sum, dropna=True,margins=True)
newdf.drop('All').stack... | python-3.x|pandas|pivot-table|subtotal | 3 |
364,560 | 52,251,102 | get data series with value in another data series python | <p>i am want to get some data from 1 data series use value from another data series. for example :</p>
<pre><code>dat1 = {'test1':['a','b','c','d','e','f','g','h','i','j','k'],
'test2':[1,2,3,4,5,6,7,8,9,10,11],'test3'
[10,11,12,13,14,15,16,17,18,19,20]}
dat2 = {'param':['q','a','z','b','o']}
df1 = pd.Data... | <h3><code>query</code></h3>
<pre><code>df1.query('test1 in @df2.param')
test1 test2 test3
0 a 1 10
1 b 2 11
</code></pre>
<hr>
<h3><code>isin</code></h3>
<pre><code>df1[df1.test1.isin(df2.param)]
test1 test2 test3
0 a 1 10
1 b 2 11
</code></pre>
<hr>
<... | python|pandas | 3 |
364,561 | 52,171,458 | Replace Cell with value using positional location of cell | <p>I have the following sample dataframe below: </p>
<pre><code>ID Text Value
A yes 1
C no 1
</code></pre>
<p>I want to replace the 1 value associated with ID 'C' in the second row with 0. Traditional ways of replacement that I found online (using .replace) would replace both 1s with 0. </p>
<p>Below... | <p>How about using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer">.loc</a> which is label based indexing:</p>
<pre><code>df.loc["C", "Value"] = 0
</code></pre>
<p>Or use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFra... | python|pandas|replace|position|row | 1 |
364,562 | 52,449,741 | How do I use numpy vectorize to iterate through a two-dimentional vector? | <p>I am trying to use numpy.vectorize to iterate over a (2x5) matrix which contains two vectors representing the x- and y-values of coordinates. The coordinates (x- and y-value) are to be fed to a function returning a (1x1) vector for each iteration. So that in the end, the result should be a (1x5) vector. My problem i... | <p>This is a bit of a guess, but looks like your code can be simplified to</p>
<pre><code>data = np.array([[1, 2], [1, 3], [2, 1], [1, -1], [2, -1]]) # (5,2) array
th_ = np.array([[1, 1]])
th0_ = -2
alist = [signed_dist(x, th_, th0_) for x in data]
arr = np.array(alist) # (5,?,?) array
arr = arr[:,0,0] # (5,) ar... | python|numpy|matrix|vector|coordinates | 0 |
364,563 | 52,039,167 | Unable to filter rows in panda dataframes | <p>I have a dataframe in which the <code>name</code> column has a few values. </p>
<p>Using <code>Counter()</code> from <code>collections</code>: </p>
<pre><code>Counter(df.name)
</code></pre>
<p>gives</p>
<pre><code>Counter({'': 13460,
'alpha': 986,
'beta': 22480,
'gamma': 123})
</code><... | <p>You cannot assign back, because for non matched values get <code>NaN</code>s:</p>
<pre><code>df = pd.DataFrame({'name': ['','d','','d'], 'val': [10, 20,20,30]})
print(df)
name val
0 10
1 d 20
2 20
3 d 30
df['name'] = df.loc[df['name'] != '', 'name']
print(df)
name val
0 NaN 10
1 ... | python|pandas|dataframe | 0 |
364,564 | 52,066,916 | Pandas can't read excel encoding | <p>I'm trying to import an excel file into Pandas. I'm using <code>df=pd.read_excel(file_path)</code> but it keeps getting me this error:</p>
<pre><code>*** No CODEPAGE record, no encoding_override: will use 'ascii'
*** No CODEPAGE record, no encoding_override: will use 'ascii'
Traceback (most recent call last):
Fil... | <pre><code>pd.read_excel('data.csv' encoding='utf-8')
</code></pre> | python|pandas|encoding | 2 |
364,565 | 52,354,096 | pandas dataframe take rows before certain indexes | <p>I have a dataframe and a list of indexes, and I want to get a new dataframe such that for each index (from the given last), I will take the all the preceding rows that matches in the value of the given column at the index.</p>
<pre><code> C1 C2 C3
0 1 2 A
1 3 4 A
2 5 4 A
3 7 5 B
4 ... | <p>you can make conditions to filter data,if you want just preceding rows match to condition.</p>
<pre><code>ind= 2
col ='C3'
# ".loc[np.arange(ind+1)]" creates indexes till preceding row, so rest of matching conditions can be ignored
df.loc[df.loc[ind][col] == df[col]].loc[np.arange(ind+1)].dropna()
</code></pre>
<... | python|pandas|dataframe|data-processing|data-munging | 1 |
364,566 | 52,108,019 | installing scikit-learn Docker image problem | <p>im trying to install scikit-learn with docker image! its failed and here is the error:</p>
<p><code>ImportError: Numerical Python (NumPy) is not installed.
scikit-learn requires NumPy >= 1.8.2.
Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html
Fa... | <p>I know it's a bit late but faced a similar issue with <code>heroku</code> (they also use linux environments). What you have to do is check the version of your local/dev environment and use that specific versions while deploying, even the python version.</p>
<pre><code>import scipy
import sklearn
import numpy
print(... | python|numpy|scikit-learn|dockerfile|docker-image | 0 |
364,567 | 52,070,051 | Python Numpy appending multiple lists from objects | <p>I am calling an object several times that is returning a numpy list:</p>
<pre><code>for x in range(0,100):
d = simulation3()
d = [0, 1, 2, 3]
d = [4, 5, 6, 7]
</code></pre>
<p>..and many more</p>
<p>I want to take each list and append it to a 2D array.</p>
<p><code>final_array = [[0, 1, 2, 3],[4, 5, 6, ... | <p>You can use <code>np.fromiter</code> to create an array from an iterable. Since, by default, this function only works with scalars, you can use <code>itertools.chain</code> to help:</p>
<pre><code>np.random.seed(0)
from itertools import chain
def simulation3():
return np.random.randint(0, 10, 4)
n = 5
d = np... | python|numpy | 1 |
364,568 | 52,352,511 | Applying matrix functions like scipy.linalg.eigh to higher dimensional arrays | <p>I am new to numpy but have been using python for quite a while as an engineer.
I am writing a program that currently stores stress tensors as 3x3 numpy arrays within another NxM array which represents values through time and through the thickness of a wall, so overall it is an NxMx3x3 numpy array. I want to efficie... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html" rel="nofollow noreferrer"><code>numpy.linalg.eigh</code></a>. It accepts an array like your example <code>a</code>.</p>
<p>Here's an example. First, create an array of 3x3 symmetric arrays:</p>
<pre><code>In [96]: a ... | python|arrays|numpy|scipy | 1 |
364,569 | 52,359,157 | Why can I not import tensorflow-gpu on mac? | <p>I am new to posting here, so forgive me if I mess something up. I have been trying for quite some time to install tensorflow with gpu support on Mac OS 10.12.6. I know Tensorflow for mac support was dropped starting in version 1.2. I am installing version 1.1.0. I was able to install this version, however, when I tr... | <p>According to the GitHub URL there looks like there might be a fix <a href="https://github.com/tensorflow/tensorflow/issues/6729" rel="nofollow noreferrer">here</a></p>
<p>According to one of the users, this seems to be a popular answer:</p>
<p><a href="https://i.stack.imgur.com/b0Gbh.png" rel="nofollow noreferrer"... | python|macos|tensorflow|gpu | 0 |
364,570 | 52,057,552 | tensorflow lite model gives very different accuracy value compared to python model | <p>I am using tensorflow 1.10 Python 3.6</p>
<p>My code is based in the premade <a href="https://www.tensorflow.org/guide/premade_estimators" rel="noreferrer">iris classification model</a> provided by TensorFlow. This means, I am using a Tensorflow DNN premade classifier, with the following difference:</p>
<ul>
<li>1... | <p>This question is answered <a href="https://stackoverflow.com/a/58583602/11517841">here</a> might help.</p>
<p>As mentioned in the answer share, doing some </p>
<blockquote>
<p>pre-processing</p>
</blockquote>
<p>on the image before it is fed into "interpreter.invoke()" solves the issue if that was the problem i... | python|python-3.x|tensorflow|tensorflow-lite | 3 |
364,571 | 52,273,118 | Possible to virtualize NVIDIA GeForce GTX 1070 Graphics Card for Distributed Tensorflow? | <p>I am running Windows 10 on Intel Core i7-8700 CPU with 16 GB RAM, 1 TB HDD and dedicated <a href="https://www.geforce.com/hardware/desktop-gpus/geforce-gtx-1070/specifications" rel="nofollow noreferrer">NVIDIA GeForce GTX 1070</a> graphics card.</p>
<p>I plan to launch 3 Ubuntu instances hosted by my Windows 10 PC.... | <p>I would consider @jdehesa's answer as for now there seems no way to virtulize GPU on Windows for Tensorflow. Thanks to @jdehesa</p> | python|tensorflow|windows-10|nvidia|video-card | 1 |
364,572 | 52,043,920 | Specific Columns Operation in Excel using Pandas | <p>I have excel(<code>test.xlsx</code>) sheet having multiple columns,<code>col1,col2,col3,col4</code> and so on.. I want to perform some operation on <code>col2,col3</code> and then the output <code>output.xlsx</code> having all the columns again with the updated <code>col2,col3</code>..</p>
<p>What I was trying..</p... | <p>You can just assign the result of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>pd.DataFrame.applymap</code></a> to <code>df[cols]</code>. This will leave the rest of your dataframe unchanged.</p>
<pre><code>df = pd.read_excel('test.x... | python|excel|python-3.x|pandas | 1 |
364,573 | 52,311,755 | Avoid nested for loops using List Comprehension and/or map | <p>For a couple of days I've been struggling with how to <strong>optimize</strong> (not only make it look nicer) the 3 <em>nested loops</em> containing a <em>conditional</em> and a <em>function call</em> inside. What I have right now is the following:</p>
<pre><code>def build_prolongation_operator(p,qs):
'''
p... | <p>I dunno about bases and prolongation operators, but you should focus on the algorithm itself. This is almost always sound advice where optimisation is concerned.</p>
<p>Here's probably the crux -- and if not, it's something to get you started: The <code>f_map</code> computation does not depend on <code>i</code>, bu... | python|python-3.x|list|numpy|optimization | 3 |
364,574 | 52,225,908 | For loop pandas and numpy: Performance | <p>I have coded the following for loop. The main idea is that in each occurrence of 'D' in the column 'A_D', it looks for all the possible cases where some specific conditions should happen. When all the conditions are verified, a value is added to a list.</p>
<pre><code>a = []
for i in df.index:
if df['A_D'][i] =... | <p>An initial set of improvements: use <code>apply</code> rather than a loop; create a second dataframe at the start of the rows where <code>df["A_D"] == "A"</code>; and vectorise the value <code>x</code>.</p>
<pre><code>arr = df[df["A_D"] == "A"]
# if the next line is slow, apply it only to those rows where x is need... | python|pandas|performance|loops|numpy | 1 |
364,575 | 60,510,599 | Extract mask from 3D RGB image using a 1D Boolean array | <p>I have a 3D image which is a numpy array of shape (1314, 489, 3) and looks as follows:</p>
<p><a href="https://i.stack.imgur.com/2JXMd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2JXMd.jpg" alt="RGB image"></a></p>
<p>Now I want to calculate the mean RGB color value of the mask (the cob with... | <p>If your question is limited to computing the mean, you don't necessarily need to subset the image. You can simply do, e.g.</p>
<pre class="lang-py prettyprint-override"><code>np.sum(colormaskcutted*boolean[:,:,None], axis = (0,1))/np.sum(boolean)
</code></pre>
<p>P.S. I've played around with indexing, you can amen... | python|arrays|numpy|numpy-slicing | 2 |
364,576 | 60,720,894 | pandas groupby - group names instead of numbers | <p>Groupby.</p>
<p>In my gender parameter.
The values are numeric .</p>
<p>1- male
2- female</p>
<p>Can I change (just for the output!) the values to names?</p>
<pre><code>df.groupby('gender')['age'].mean()
</code></pre>
<p>Out[765]:</p>
<p>gender</p>
<p>1 21.166667</p>
<p>2 17.500000</p>
<p>Name: age, dt... | <p>You could use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rename.html" rel="nofollow noreferrer">series.rename</a> method.</p>
<pre><code>df.groupby('gender')['age'].mean().rename(index={1:"male", 2:"female"})
</code></pre> | python|pandas|pandas-groupby | 1 |
364,577 | 60,580,831 | spatial_softmax layer in tensorflow 2.0 | <p>Tensorflow 1.X used to have a layer <code>tensorflow.contrib.layers.spatial_softmax</code>. The layer basically does a softmax over each channel and returns the coordinates of the maximum point. </p>
<p>However, this functionality seems to be missing in TF 2.0. Is this just not ported yet, or do I miss something?
A... | <p>Check out <a href="https://github.com/tensorflow/tensorflow/issues/6271#issuecomment-266893850" rel="nofollow noreferrer">this</a> comment, apparently spatial softmax can be easily implemented.</p> | tensorflow|keras|deep-learning|softmax | 0 |
364,578 | 60,389,936 | Assign a whole row as None: IndexError: tuple index out of range | <p>Create a new dataframe.</p>
<pre><code>df = pd.DataFrame([[1, 2], [4, 6], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield']) df
</code></pre>
<p>Show it's value:</p>
<pre><code>df
max_speed shield
cobra 1 2
viper 4 6
sid... | <p>Possible solution is add <code>:</code> for select all columns:</p>
<pre><code>df.iloc[0:1,:] = None
print (df)
max_speed shield
cobra NaN NaN
viper 4.0 6.0
sidewinder 7.0 8.0
</code></pre>
<p>Or also omit <code>,</code>:</p>
<pre><code>df.iloc[0:1] = None
p... | python-3.x|pandas|dataframe | 1 |
364,579 | 60,712,402 | dask map_partitions returns pandas data frame, not dask | <p>Everything I can find indicates that dask <code>map_partitions</code> should return a dask dataframe object. But the following code snippet and the corresponding output (using <code>logzero</code>) does not. (note -- calc_delta returns a np.array of floats).</p>
<pre><code>352 logger.debug(type(self.dd))
35... | <p>Is it not because you are calling "compute"? </p>
<p>Maybe this: </p>
<pre class="lang-py prettyprint-override"><code>self.dd.map_partitions(
lambda df: df.assign(
duration1=lambda r: calc_delta(r['a'], r['b'])
, duration2=lambda r: calc_delta(r['a'], r['c'])
... | python-3.x|pandas|dataframe|dask | 1 |
364,580 | 60,702,768 | Compare the three columns and replace the unique string with the string in the remaining columns. Python | <p>My dataframe contains multiple columns among them three columns are related to gender.</p>
<p>df =</p>
<pre><code>gen_1 gen_2 gen_3
M M M
F M M
F F F
F F M
F M F
</code></pre>
<p>The data is taken from 3 different periods.</p>... | <p>I believe you need value with most counts, mode per <code>axis=1</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mode.html" rel="nofollow noreferrer"><code>DataFrame.mode</code></a>:</p>
<pre><code>cols = ['gen_1','gen_2','gen_3']
df['Gender'] = df[cols].mode(axis=1)
pr... | python|pandas | 2 |
364,581 | 60,393,131 | Group pandas rows by ID, create new columns for time entries | <p>I have a pandas dataframe, which has duplicate IDs since each row represents a measure of time.</p>
<pre><code> pd.DataFrame([[1, 2], [1, 3], [2, 6], [2,7]], columns=['id', 'colA'])
</code></pre>
<p>I want to transform it in a way that each row represents one ID, and the time series aspect of the data is captured ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for counter, create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.ht... | python|pandas|dataframe|grouping | 2 |
364,582 | 60,417,932 | finding out how many values matched in a particular column for a particular row in a dataframe in Python | <p>I have a DataFrame:</p>
<pre><code>X Y Z
1 ana python,ms-excel,C++,Aws
2 aba Python,MS-EXCEL,C++,AWS
3 ama Python
</code></pre>
<p>I need to know if columns Z has python, ms-excel or not. </p>
<p>So, maybe the outcome can look like:</p>
<pre><code>X Y Z_new
1 ana 2
2 any 2
3 ama 1
</code></pre>
<p>... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.lower.html" rel="nofollow noreferrer"><code>Series.str.lower</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</cod... | python-3.x|pandas | 2 |
364,583 | 60,749,528 | Is there a more Numpy-esque way of interpolating my rasters? | <p>I've written a little function to interpolate time sequences of irregularly sampled raster images so that they are evenly spaced in time (below). It works fine but I just know from looking at it that I'm missing some shortcuts. I'm looking for a Numpy ninja to give me so pro tips on how to punch up my syntax, and ma... | <p>As the y values to be looked up have to be 1d I can't see a way of not looping through the np.arrays. If the rasters and interpRasters arrays are reshaped as how in the function one loop can be used, without explicit indexing. This gave around a 10% speed improvement for my made up test data.</p>
<pre><code>impor... | python|numpy|raster | 1 |
364,584 | 60,708,695 | How can I make "element wise" comparsion inside of the tf.function? | <p>I try to make my own activation function in TensorFlow 2 and the function looks like this:</p>
<pre><code>@tf.function
def f(x):
r = 2
if x>=0:
return (r**2 * x + 1)**(1/r) - 1/r
else:
return K.exp(r*x) - 1/r
</code></pre>
<p>The problem is that it cant take as argument <code>tf.constant([2.0, 3.0... | <p><code>if</code> statements are converted to <code>cond</code>, but that only takes scalar arguments for the predicate (and does no broadcasting). Try <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="nofollow noreferrer"><code>where</code></a> instead: </p>
<pre><code>return tf.where(x >= 0, (r... | python|tensorflow | 0 |
364,585 | 60,467,264 | Pairwise similarity matrix between a set of vectors in PyTorch | <p>Let's suppose that we have a 3D PyTorch tensor, where the first dimension represents the <code>batch_size</code>, as follows:</p>
<pre><code>import torch
import torch.nn as nn
x = torch.randn(32, 100, 25)
</code></pre>
<p>That is, for each <code>i</code>, <code>x[i]</code> is a set of 100 25-dimensional vectors. I... | <p>The documentation implies that the shapes of the inputs to <code>cosine_similarity</code> must be equal but this is not the case. Internally PyTorch broadcasts via <code>torch.mul</code>, inserting a dimension with a slice (or <code>torch.unsqueeze</code>) will give you the desired result. This is not optimal due to... | python|pytorch|similarity|cosine-similarity|pairwise-distance | 8 |
364,586 | 60,466,189 | CNN training loss regular spikes at the end of the epoch | <p>I am training a CNN in PyTorch with Adam and the initial learning rate is 1e-5. I have 5039 samples in my epoch and the batch size is 1. I have observed that I have a regular spike pattern of training loss at the end of an epoch. Here is a plot of the training loss:
<a href="https://i.stack.imgur.com/wkKFF.png" rel=... | <p>Two possibilities that I can think of:</p>
<ol>
<li>Loss logging method that resets every epoch.</li>
<li>Small dataset.</li>
</ol>
<p>One possibility: the way that you are logging the loss. If, for example, you are accumulating loss at each step, logging the average, and resetting loss at the end of an epoch, then ... | machine-learning|deep-learning|pytorch|conv-neural-network|sgd | 0 |
364,587 | 60,674,600 | Implementing The 'Learning To Read With Tensorflow' Talk From TF Summit 2020 - EncoderDecoder Seq2Seq Model In Tensorflow 2.1/2.2 - Custom Train Step | <hr>
<h2>Background Info</h2>
<hr>
<p>I am creating <strong>Google Colabs</strong> for each talk I found interesting from the Tensorflow 2020 Summit. As a note, I am using Tensorflow 2.1.</p>
<hr>
<p><strong><em>I have encountered a problem when attempting to implement the <code>'Learning To Read With Tensorflow'<... | <h3>Update</h3>
<p>It appears as though Tensorflow has released tutorials detailing all of the demos that were conducted at the Summit.</p>
<p>The result is that you can examine the actual code and determine the differences between theirs and yours. I won't post the differences here because they are more significant ... | tensorflow|machine-learning|tf.keras|encoder-decoder|gradienttape | 0 |
364,588 | 60,371,910 | How to manipulate json in plotly and numpy? | <p>I am trying to plot a graph in plotly with this kind of json data. I have opened up the json file and loaded the data into 'data' variable. The code below randomly generates points to the graph. How do I manipulate the data in x-axis so that it shows the timespan on x-axis and the Value in y-axis. </p>
<pre class="... | <p>can you try the follwing:</p>
<pre><code>X, Y = [], []
for item in data['Elements']:
for sub_item in item['TimeSpans']:
X.append(sub_item['TimeSpan'])
Y.append(sub_item['Value'])
</code></pre> | python|numpy|plotly | 0 |
364,589 | 60,696,469 | How to calculate the sum of a subset within a Dataframe based on multiple columns | <p>I'm relatively new to using Pandas, I have a dataframe that looks like the below, my goal is to replicate the "desired_output" column:</p>
<pre><code>+---------+--------+-------------+-------+------------+----------------+
| Main ID | Sub ID | Senior Flag | order | Dollar Amt | desired_output |
+---------+--------+... | <p>Define the following function:</p>
<pre><code>def fn(row, grp):
if row['Senior Flag'] == 'Y':
return grp[grp['Senior Flag'] == 'N']['Dollar Amt'].sum()
else:
return grp[grp.order > row.order]['Dollar Amt'].sum()
</code></pre>
<p>Then apply it:</p>
<pre><code>df['result'] = df.groupby('M... | python|pandas|pandas-groupby | 1 |
364,590 | 60,679,330 | CNN train with weird result: VAL LOSS increases while VAL ACCURACY / PRECISION / RECALL also increase | <p>I am fine tuning a 5 classes with model Resnet50 w/ 10 millions trainable parameters. Data has around 140,000 samples and 20% are used for validation. Batchsize 256 I may add and lr is warming linearly from 1e-5 up to 3e-4 for first 10 epochs then cosine annealing twice from there for another 20 epochs (10 - 30), we... | <p>Fixed. Four (4) things have to be done:</p>
<p>1) Data is a concern, hence clean data a bit more</p>
<p>2) Put more noice into the model</p>
<p>3) Batchnorm after activation at almost last layer</p>
<p>4) Switch to DenseNet201 which learns much deeper</p>
<pre><code>x = base_model.output
x = GlobalMaxPooling2D(... | python|tensorflow|keras|conv-neural-network | 0 |
364,591 | 60,375,537 | Module 'self' has no attribute 'file' error in class format | <p>I am building a python code to validate the email address and the phone number in a given CSV file using pandas and I want to write a separate CSV file with only the validated values. I am totally new to python and I have written a code for the functionality as follows:</p>
<pre><code>from email_validator import va... | <p>You do not import <em>self</em>.
<em>self</em> is the instance you are in at the time of code execution. </p>
<p>Your problem is that you did not understand classes yet. You tried to call a class method within the class which python does but toes not like.</p>
<p>I'd suggest you have a look at <a href="https://doc... | python|pandas|self | 1 |
364,592 | 60,618,672 | How to split CSV dataset into training and testing set by percentage and save the splitted dataset into local folder with pandas? | <p>I have a large size CSV dataset and need to split training and testing set 77 % and 33 % respectively. Then finally I want to access each file in my local machine. </p> | <h1>Importing the required library</h1>
<pre><code>import math
</code></pre>
<h1>The whole dataset</h1>
<pre><code>df = pd.read_csv('CTU.csv')
total_size=len(df)
train_size=math.floor(0.77*total_size)
</code></pre>
<h1>training dataset and test dataset</h1>
<pre><code>train=df.head(train_size)
test=df.tail(len(df)... | python|pandas|scikit-learn|dataset|python-3.8 | 1 |
364,593 | 60,361,242 | Compare two numeric pandas dataframes (x,y) with interpolation before comparison | <p>I would like to compare two numeric dataframes [x1,y1] and [x2,y2] with different x, using ['x1']</p>
<pre><code>import pandas as pd
first = {'x1':[0,3,5],'y1':[0,3,6]}
df1 = pd.DataFrame(first,columns=['x1','y1'])
print (df1)
x1 y1
0 0 0
1 3 3
2 5 6
second = {'x2':[0,2,4,6],'y2':[0,2,4,6]}
df2 ... | <p>Create one column <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.append.html" rel="nofollow noreferrer"><code>Series.append</code></a> with remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.drop_duplicates... | python|pandas|dataframe | 2 |
364,594 | 60,465,504 | How to find 1st Purchase date who made 2nd purchase within 30 days? | <p>I need your quick help.
I want to find a list of customer_id's and first purchase_date for customers who have made their second purchase within 30 days of their first purchase. </p>
<p>i.e. curstomer_id's 1,2,3 have made their 2nd purchase within 30 days.</p>
<p>I need curstomer_id's 1,2,3 and their respective fir... | <p>You can use window functions to get the first purchase and then count the number of purchases in the first 30 days:</p>
<pre><code>select distinct customer_id, first_purchase_date
from (select t.*,
min(purchase_date) over (partition by customer_id) as first_purchase_date
from t
) t
where pur... | python|sql|pandas | 2 |
364,595 | 60,443,074 | Pandas: Delete Row if Sentence Contains Word from Other Column in Same Row | <p>I have pandas data frame <code>df</code> and I want to <code>delete the row</code> if the sentence column <code>not contain</code> value from word column in <code>same row</code>. </p>
<pre><code>df = pd.DataFrame({'sentence': ['I eat chicken', 'I drive car'],
'word': ['eat', 'bus']})
</code></pre>
... | <p>For row wise comparison we have to use <code>DataFrame.apply</code>:</p>
<pre><code>df[df.apply(lambda x: x['word'] in x['sentence'], axis=1)]
</code></pre>
<p>Or with <code>zip</code> and list comprehension:</p>
<pre><code>m = [word in sentence for word, sentence in zip(df['word'], df['sentence'])]
df[m]
</code>... | python|pandas|dataframe | 3 |
364,596 | 60,641,520 | Create a excel from a dataframe if user puts certain input | <p>if the user introduces the letter Y or y I want to create a xlsx file.
What Am i doing wrong?</p>
<pre><code>excel = str(input('Create excel ( Y / N ): '))
if excel = 'Y' or excel = 'y'
df1.to_excel("output.xlsx")
else print('Done')```
</code></pre> | <p>Simple equal is for assignation while double is for comparison and a ":" is missing.</p>
<pre><code>excel = str(input('Create excel ( Y / N ): '))
if excel == 'Y' or excel == 'y':
df1.to_excel("output.xlsx")
else:
print('Done')
</code></pre> | python|pandas|dataframe | 0 |
364,597 | 60,352,568 | Invalid tape state error in Keras due to custom metric function | <p>So, I'm having some troubles trying to implement a SSIM-based metric function in Keras.</p>
<p>My metric function is:</p>
<pre><code>@tf.function
def custom_ssim(y_actual, y_predicted):
y_pred_aux = tf.argmax(y_predicted, axis=-1)
y_pred_aux = tf.expand_dims(y_pred_aux, axis=3)
y_pred_aux = tf.cast(y_... | <p>You get this error when you pass only the training data and missed to pass the labels in <code>model.fit()</code>. I was able to recreate your error using below code. You can download the dataset I am using in the program from <a href="https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes... | python|tensorflow|keras|metrics|ssim | 0 |
364,598 | 60,626,060 | Copying text from one cell to another without deleting original content python | <p>I have 7 columns, with million rows of data for each column.</p>
<p>I need to copy the data from columns 2,3,4,5,6,7 and place it at the end of the content in column 1. This would result in column 1 having its original content (1 million of rows) plus the additional content of the rest of the columns (6 million of ... | <p>Try <code>pd.melt</code></p>
<pre><code>df_new = pd.melt(df).drop("variable", axis=1)
print(df_new)
value
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
</code></pre> | python|excel|pandas | 1 |
364,599 | 60,541,466 | Match or connect two csv files as datasets with python | <p>I have two datasets in csv format. These datasets have different columns (number of columns and even their headers) although I know some of them are common, my issue is finding common column(s). The basic solution is testing one by one or all combinations of columns in two datasets. Is there any solution, model or a... | <p>You can find that with the intersection in pandas. Basically, you read both the csv in two dataframes and then find the intersection of columns, which will give you call the common columns</p>
<pre><code>import pandas as pd
df1 = pd.read_csv("file1.csv")
df2 = pd.read_csv("file2.csv")
common_cols = df1.columns.int... | python|pandas|data-analysis | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.