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 |
|---|---|---|---|---|---|---|
368,700 | 73,377,750 | Constructing Correlation Matrix With Only certain Columns | <p>I have a 60 column dataset.</p>
<p>I want to create a correlation matrix for only 10 of the columns, compared with the other 50 columns.</p>
<p>I dont want to have a 60x60 correlation matrix.
I need a 10*50 correlation matrix.</p>
<p>Any help?</p> | <p>Make your correlation matrix as you normally would, then limit the index and columns to the values you want.</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random(size=(100, 60)))
correlation = df.corr()
first_10 = correlation.columns[:10]
exclude_10 = correlation.columns.drop(f... | python|pandas|dataframe|correlation | 1 |
368,701 | 73,470,692 | Blocking issue with pandas_datareader in Anaconda - "conda install -c anaconda pandas-datareader" not fixing it | <p>I have a blocking issue with pandas_datareader (Windows) installed with Anaconda/Jupyter. The solutions proposed in other StackOverflow posts are not working as following described.</p>
<p>This is a simple code for testing the datareader package</p>
<pre><code>import pandas as pd
import numpy as np
from pandas_datar... | <p>I found a post explaining how to install conda packages in a Jupyter notebook and it seems it has fixed the problem:</p>
<pre><code>import sys
!conda install --yes --prefix {sys.prefix} pandas-datareader
</code></pre>
<p>but I don't know why, so if anybody knows what happened and why this fixed the problem, an expla... | python|anaconda|jupyter|pandas-datareader | 0 |
368,702 | 73,257,430 | Concatenate Two DataFrames Based On DateTime Column | <p>I have two dataframes.</p>
<p>First one:</p>
<pre><code>Date B
2021-12-31 NaN
2022-01-31 500
2022-02-28 540
</code></pre>
<p>Second one:</p>
<pre><code>Date A
2021-12-28 520
2021-12-31 530
2022-01-20 515
2022-01-31 529
2022-02-15 544
2022-02-25 522
</code></pre>
<p>I want to concatenate both... | <p>You need a left merge on the month period:</p>
<pre><code>df2.merge(df1,
left_on=pd.to_datetime(df2['Date']).dt.to_period('M'),
right_on=pd.to_datetime(df1['Date']).dt.to_period('M'),
suffixes=(None, '_'),
how='left'
)
</code></pre>
<p>Then <code>drop(columns=['key_0... | python-3.x|pandas|dataframe|datetime|concatenation | 1 |
368,703 | 73,422,622 | Matplotlib: how to plot with filled and unfilled marker alternate one by one? | <p>I am plotting with a set of data and every m points are a subset. I would like to use filled marker and hollow marker alternatively for each subset, i.e. if <code>i</code> equals even numbers the marker is filled, and if <code>i</code> equals odd numbers the marker is unfilled. I could accomplish this by nesting <co... | <p>This code can do that.</p>
<pre><code>...
colorlist = ['red', 'blue', 'black', 'green']
mfclist = colorlist
mfclist = [x if i % 2 == 0 else "None" for i,x in enumerate(mfclist)]
...
for i in range(0, n):
ax.plot(x[i*m:(i+1)*m], y[i*m:(i+1)*m], markerfacecolor=mfclist[i],linestyle='none', marker='o', ... | python|numpy|matplotlib | 1 |
368,704 | 73,490,286 | pandas df of api query | <p>I have API data that looks like this below in JSON of one <code>ip</code> address. Typical query contains 50 <code>ip</code> devices.</p>
<pre><code>[{'ip': '11.22.33.44',
'services': [{'port': 80,
'service_name': 'HTTP',
'transport_protocol': 'TCP'},
{'port': 1911, 'service_name': 'FOX', 'transport_pro... | <p>try this:</p>
<pre><code>df = pd.DataFrame(data)
data["coordinates"]=data["location"].apply(lambda x:x["coordinates"])
</code></pre>
<p>if you mean by using only <code>pandas</code> to create a dataframe with the <code>coordinates</code> columns from start It is not the solution</p> | python|pandas | 1 |
368,705 | 73,424,597 | generate matrix with independent columns | <p>I am trying to generate matrices with independent columns. At the moment I am using <code>assume</code> which works, but requires a lot of computation:</p>
<pre><code>import sys
import hypothesis.strategies as st
import numpy as np
from hypothesis import assume
from hypothesis.extra.numpy import arrays
@st.composit... | <p>Here's a partial solution that, instead of doing essentially rejection sampling, uses the <a href="https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process" rel="nofollow noreferrer">Gram-Schmidt process</a> to generate your columns. It's partial, because it actually seems to be a bit slower than the rejection sam... | python|numpy|python-hypothesis | 2 |
368,706 | 73,476,955 | Pandas to_excel deletes everything that is already on the excel file | <pre><code>df = pd.DataFrame(df)
df.to_excel("Lista FATF.xlsx", index=False, startrow=1)
</code></pre>
<p>When the code runs everything that already is on the excel file vanishes, i don't want it to happen. I want to just add things to the excel file, not delete the ones that already are there.</p> | <p>To do that you need to explicitly create an <a href="https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer">ExcelWriter</a> in append mode :</p>
<pre><code>with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
df.to... | python|excel|pandas|dataframe | 1 |
368,707 | 73,278,051 | fill each row of a dataframe with zero starting from the column in which the values decreases with respect to the value in the previous column | <p>I would like to fill each row of a dataframe with zero starting from the column in which the value decreases with respect to the value in the previous column</p>
<p>I have the following Dataframe:</p>
<pre><code>ActualDf = pd.DataFrame(np.array([[2, 3, 2, 3, 4, 5, 0, 0, 0, 0, 0], [1, 1, 1, 2, 2, 3, 1, 1, 0, 0, 0], [... | <p>Here is an approach similar using a <code>mask</code>:</p>
<pre><code>DesiredDf =ActualDf.mask(ActualDf.diff(axis=1).lt(0).cummax(axis=1), 0)
</code></pre>
<p>output:</p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 10
0 2 3 0 0 0 0 0 0 0 0 0
1 1 1 1 2 2 3 0 0 0 0 0
2 2 2 2 3 3 5 0 0 ... | python|pandas|dataframe|row|fill | 2 |
368,708 | 73,478,965 | H3 polyfill for country-scale polygons | <p>I am trying to generate a grid for a given (multi) polygon. I understand a grid as a collection of h3 indices within a (multi)polygon boundary.</p>
<p>Here is the code that I implemented so far:</p>
<pre class="lang-py prettyprint-override"><code> def generate_grid(region_bounds: gpd.GeoDataFrame) -> pd.DataFrame... | <p>Yes, <code>polyfill</code> (<code>polygonToCells</code> in v4) can be CPU/memory intensive for large regions at fine resolutions of H3. Res 10 is roughly a city block, so a large country will likely have millions of cells.</p>
<p>The best option at the moment is to split up the input into contiguous polygons. The re... | geopandas|geo|h3 | 0 |
368,709 | 73,482,600 | Pandas Print Empty Data Frame with headers | <p>This is probably pretty basic question, but I am stuck here. I would like to print a empty pandas dataframe on console with headers. I will try to explain it here.</p>
<p>I create a dataframe with a dictionary and print it, it prints the data with headers.</p>
<pre><code>>>> details = {'EmpId' : [1, 2],'Emp... | <pre><code>DF_01=pd.DataFrame(columns=['Emp Id', 'Emp Name'])
DF_02=details = pd.DataFrame({'EmpId' : [1, 2],'EmpName' : ["A", "B"]})
def PrintDF(Dataframe):
if len(Dataframe.index)==0:
Strs=''
for i in Dataframe.columns:
Strs+=str(i)+' '
print(Strs[:-1])
else:
pr... | python|pandas | 1 |
368,710 | 73,278,757 | Pandas pivot columns based on column name prefix | <p>I have a dataframe</p>
<pre><code>df = AG_Speed AG_wolt AB_Speed AB_wolt C1 C2 C3
1 2 3 4 6 7 8
1 9 2 6 4 1 8
</code></pre>
<p>And I want to pivot it based on prefix to get:</p>
<pre><code>df = Speed Wolt C1 C2 C3 Category
1 2 6 7 8 ... | <p>We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>pd.wide_to_long</code></a> for this. But since it expects the column names to start with the stubnames, we have to reverse the column format:</p>
<pre><code>df.columns = ["_".join(col.... | pandas|dataframe|pivot-table|pandas-melt | 2 |
368,711 | 73,371,787 | Input 0 of layer "conv2d_24" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 1) | <p>I am currently attempting to make my first deep learning model which is meant to detect fire and smoke in images.</p>
<p>The code works up until I attempt to fit the model where it throws the error</p>
<pre><code>ValueError: Exception encountered when calling layer "sequential_8" (type Sequential).
Inpu... | <p>You probably have an issue with your <code>x_train</code> data. What is the result of this print if you execute it right before calling <code>fit()</code>?</p>
<pre><code>print(train.shape, test.shape)
</code></pre>
<p>In your first layer you set the input shape of <code>(196, 196, 3)</code> + the batch size -> f... | tensorflow|keras|deep-learning | 1 |
368,712 | 73,358,914 | How can I web scrape a government website with python? I cannot properly do it, the table just cannot show | <p>I am trying to web scrape the data from this government website: <a href="https://www.itf.gov.hk/en/project-search/search-result/index.html?isAdvSearch=1&Programmes=TVP" rel="nofollow noreferrer">https://www.itf.gov.hk/en/project-search/search-result/index.html?isAdvSearch=1&Programmes=TVP</a>
However, after... | <p>The table is rendered through javascript, and the data returned through an api. You need to get the data from the source.</p>
<p>Once you have the <code>"Reference"</code>, you then can feed those into the api again to get the "linked" data. And finally merge them together.</p>
<p><strong>Code:</... | python|pandas|web-scraping | 1 |
368,713 | 73,389,083 | Why do I get errors when importing tfjs-node? | <pre><code>import * as tfn from '@tensorflow/tfjs-node
</code></pre>
<p>throws me followed warnings:</p>
<pre><code>WARNING Compiled with 4 warnings 15:06:46 ... | <p>Based on your error, it's likely that you are using Python 3. According to <a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-node" rel="nofollow noreferrer">the documentation</a>, "Windows & OSX build support for node-gyp requires Python 2.7". In the event that you are using the correct vers... | vuejs2|tensorflow.js | 1 |
368,714 | 73,214,828 | python pandas sum value based on date&string | <p>Given the 2 dataframes</p>
<pre><code>df1
Year Month Day Name value
2022 2 11 ADP1 5,3
2022 2 15 ADP2 300,2
2022 3 21 ADP1 7000,3
2022 3 25 ADP2 13,2
2022 8 15 ADP1 444,1
2022 8 5 ADP2 3333,2
</code></pre>
<pre><code>df2
Name1 Name2 Date1 Date2
xx APD1 2022-02-23 2022-04-3... | <p>You have one date in df2 2022-02-23, and in the expected result it is 2022-02-03. I fixed it. Also, in your df1, the value column has a fractional part in the form of a comma, which I replaced with a dot, as is the case in most cases, and converted the column type to float. Based on this, I assume that all your data... | python|pandas|dataframe|date|lambda | 0 |
368,715 | 73,359,534 | Pytorch precision and recall error: The `target` has to be an integer tensor | <p>I have this pytorch code (full code is the 'graph level tasks: graph classification' from <a href="https://colab.research.google.com/github/phlippe/uvadlc_notebooks/blob/master/docs/tutorial_notebooks/tutorial7/GNN_overview.ipynb#scrollTo=W1-amTnr90uF" rel="nofollow noreferrer">here</a>:</p>
<pre><code>class GraphLe... | <p>Before passing it to the precision_recall function, you can just change the datatype of your target values. They appear to be float but the required type is integer. That makes sense as labels are categorical.</p>
<p>Assuming data.y is a numpy array, you can do:</p>
<pre><code>precision_and_recall = precision_recall... | python|pytorch|pytorch-lightning|pytorch-geometric | 0 |
368,716 | 73,454,725 | Replace nan values in one column of a dataframe with another column value of second dataframe | <p>I have a dataframe df1 which has customer id and a min_date, the second dataframe has a column open_dt where there are some nan values which I want to replace with min_date value where the customerid matches</p>
<p>df1</p>
<pre><code> CUSTOMERID OPEN_DT
0 BATCH7MRN1 2019-03-26
1 BATCH7MRN10 2016-09-02
2 B... | <p>IIUC, first merge <code>df1</code> and <code>df2</code> on the column <code>CUSTOMERID</code>. Then, replace the nan values by the merged column from <code>df1</code>.</p>
<pre><code>df2 = df2.merge(df1, on='CUSTOMERID', suffixes=['2', '1'])
df2.loc[df2['OPEN_DT_2'].isnull(), 'OPEN_DT_2'] = df2['OPEN_DT_1']
df2 = df... | python|pandas | 0 |
368,717 | 73,396,992 | How can I convert one row of values with panda | <p>How can I convert one row of values with panda</p>
<pre><code>df = pd.read_csv('blackred.csv')
words = []
for i in df:
words.append(i)
num = []
</code></pre>
<p>I want to grab the index 0 column and convert it into a list of numbers and set it to num</p>
<p>How can I do that</p>
<p>This is my csv file I just w... | <p>Use <code>.to_list()</code>.</p>
<p>You will get a list: <code>[7, 21, 19, 9, 2]</code>.</p>
<pre><code>import pandas as pd
# Create a DataFrame
df = pd.DataFrame(columns=['black','red','even','odd', 'NONE'], index = [0])
df.loc[0] = [7, 21, 19, 9, 2]
# Grab data in a row into a list
df.loc[0].to_list()
</code></p... | python|pandas|list|csv|plot | 0 |
368,718 | 73,482,806 | min/max value of a column based on values of another column, grouped by and transformed in pandas | <p>I'd like to know if I can do all this in one line, rather than multiple lines.</p>
<p>my dataframe:</p>
<pre><code> import pandas as pd
df = pd.DataFrame({'ID' : [1,1,1,1,1,1,2,2,2,2,2,2]
,'A': [1, 2, 3, 10, np.nan, 5 , 20, 6, 7, np.nan, np.nan, np.nan]
, 'B': [0,1,1,0,1,1,1,1,1,0,1,0]
, 'desired_outp... | <p>Here is a way to do it:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'ID' : [1,1,1,1,1,1,2,2,2,2,2,2],
'A': [1, 2, 3, 10, np.nan, 5 , 20, 6, 7, np.nan, np.nan, np.nan],
'B': [0,1,1,0,1,1,1,1,1,0,1,0],
'desired_output... | python|pandas|group-by|max|transform | 1 |
368,719 | 73,264,724 | pandas listing same indexes | <p>if a table has the same index 3 times in a row, I want it to fetch me this dataframe.</p>
<p>example</p>
<pre><code>index var1
1 a
2 b
2 c
2 d
3 e
2 f
5 g
2 f
</code></pre>
<p>After the code</p>
<p>expected output</p>
<pre><code>index var1
2 b
... | <p>One option is to split data frame on the diff index, check size of each chunk and filter out chunks with sizes smaller then threshold and then recombine them:</p>
<pre><code>import pandas as pd
import numpy as np
diff_indices = np.flatnonzero(df['index'].diff().ne(0))
diff_indices
# array([0, 1, 4, 5, 6, 7], dtype=... | python-3.x|pandas|dataframe | 2 |
368,720 | 73,400,694 | Maximum value for different days | <p>I've got a datadrame with the following columns : Date / High price / Low price. About 300 trading days and the timeframe is hours. It's only for a single security.</p>
<p>I would like to find the code for the maximum high price for each different days.
Maximum high price for day 1, Maximum high price for day 2...</... | <p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.idxmax</code></a> for indices by maximal <code>High price</code> per dates:</p>
<pre><code>df1 = df.loc[df.groupby(df['Date'].dt.date)['High p... | pandas|dataframe | 0 |
368,721 | 73,395,080 | Make a new column in a dataframe for every new instance based off another column | <p>I am trying to make new columns in a dataframe based on how many times a new value gets paired with another column.</p>
<p>original dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Primary Address</th>
<th>Alternative Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>J... | <p>First, create a column that contains a <strong>list of all "alternative addresses"</strong> for each person:</p>
<pre class="lang-py prettyprint-override"><code>f = lambda g: pd.Series([g['Primary'].dropna().iloc[0],
list(g['Alternative'].dropna())],
index=... | python|pandas|dataframe | 1 |
368,722 | 73,510,139 | Unable to run Tensorflow 2 with matplotlib | <p>I have installed matplotlib in the tensorflow environment (Jupyter notebook) using conda install command. There is no error in the compilation. But while running, I am encountering a message " Dead Kernel" and the program terminates. The other programs without matplotlib are executed smoothly. Not able to ... | <p>Try installing the "Conda" or the "Jupyter Notebook" again :)</p> | python|tensorflow|matplotlib | 1 |
368,723 | 73,472,400 | Best way to handle element of dict that has multiple key/value pairs inside it | <pre><code>[{'id': 2, 'Registered Address': 'Line 1: 1 Any Street Line 2: Any locale City: Any City Region / State: Any Region Postcode / Zip code: BA2 2SA Country: GB Jurisdiction: Any Jurisdiction'}]
</code></pre>
<p>I have the above read into a dataframe and that is the output so far. The issue is I need to break ou... | <p>Tried to write a code that generalizes your question, but there were some limitations, regarding your data format. Anyway I would do this:</p>
<pre><code>def address_spliter(my_data, my_keys):
address_data = my_data[0]['Registered Address']
key_address = {}
for i,k in enumerate(keys):
print(k)
... | python-3.x|pandas|dataframe|parsing | 2 |
368,724 | 73,408,591 | Why are my janitor functions not working in Tkinter? | <p>I have functions that work perfectly fine in a standard python script but when I put them in Tkinter they error out. I can't seem to find the issue. I've tried to write this out as simple as I can code. The data that will be pasted into the input will come in this same format.</p>
<pre><code># Standard Python Code t... | <p>The problem starts here:</p>
<pre><code>data = data_input.get(1.0, tk.END)
</code></pre>
<p>When you enter your raw data here, it will actually <em>add</em> a line break at the end. So, what you are inputting here would be the equivalent of ending your <code>raw_data</code> multiline string as follows:</p>
<pre><cod... | python|pandas|user-interface|tkinter|error-handling | 3 |
368,725 | 73,503,340 | Export multiple dataframes in one excel tab | <p>I need to Export or save pandas multiple Dataframe in one excel tab. Let's suppose my df's are below and need to export it the same way in the excel all together in one tab.</p>
<pre><code> df1:
Id Name Rank
1 Scott 4
2 Jennie 8
3 Murphy 1
df2:
Id Name Rank
1 John 14
2 Brown 18
3 Clai... | <p>You can loop through a list of your dfs and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer"><strong><code>pandas.ExcelWriter</code></strong></a> :</p>
<pre><code>import pandas as pd
list_df = [df1, df2, df3, df4]
df1.name = 'df1'
df2.name = 'df2'
df3.name... | python|pandas|dataframe | 0 |
368,726 | 73,319,581 | Calculate mean of certain rows for each group after group by Pandas | <p>I have a dataframe which records 2 parameters and time for many IDs. There are malfunction situations that all parameters are 0.0, but date exists, like row 5.</p>
<pre><code> 0 id Param1 Param2 date
1 1 1.45 6.47 2014-09-01
2 1 2.84 66.7 2014-09-03
3 2 -0.21 30 2014-11-1... | <p>Check below code, if it provides desired output.
Note that I have used rolling window of 3 row considering smaller set of data.</p>
<p><strong>Data frame :</strong></p>
<pre><code>import pandas as pd
import numpy as np
Idata= {'id':[1,1,2,2,2,2,3,3,3],'param1':[1.45,2.84,-0.21,9970,0,8.26,0,90.1,9.01],'param2':[6.47... | python|pandas|group-by | 1 |
368,727 | 73,431,543 | Want to confirm if this is a problem with model or I am doing something wrong tflite | <p>Someone contacted me because they want fron end of a <strong>tflite</strong> model! When I actually created a front end it is predicting everything as Positive with an accuracy of 99.9%! Just wanted to know if it's my fault or the model is not correct!</p>
<p>Here is the code I am using for prediction:</p>
<pre><cod... | <p>Finally I was able to solve the problem. Actually while training the model the data wasn't preprocessed but while making prediction I was preprocessing the data!
So I just removed the following line from the <strong>predict</strong> function:</p>
<pre><code> img /= 255
</code></pre> | tensorflow|keras|tensorflow-lite|testflight | 0 |
368,728 | 73,350,133 | How to calculate mean and standard deviation of a set of images | <p>I would like to know I to calculate the <code>mean</code> and the <code>std</code> of a given dataset of <code>RGB</code> images.<br>
For example, with <em>imagenet</em> we have <code>imagenet_stats: ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]</code>.<br>
I tried:</p>
<pre><code>rgb_values = [np.mean(Image.open(im... | <h1>Two solutions:</h1>
<ul>
<li><p>The first solution iterates over the images. It is <strong>MUCH slower</strong> than the second solution, and it uses <strong>the same amount of memory</strong> because it first loads and then stores <em>all the images</em> in a list. So it is strictly worse than the second solution,... | python|image|numpy|machine-learning | 0 |
368,729 | 73,293,491 | pandas dataframe plot barh color based on values not column | <p>I have this dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(
data={
"Time": ['07/10/2022 08:22:44','07/10/2022 08:27:22','07/10/2022 08:27:44','07/10/2022 08:29:55','07/10/2022 08:33:14','07/10/2022 08:48:44'],
"Sum":[50,5,10,20,5,30]
} ... | <p>You can try <code>Series.plot</code> with <code>color</code> argument</p>
<pre class="lang-py prettyprint-override"><code>colors=[]
for val in df['Sum']:
if val <= 10:
colors.append('green')
elif 10 < val <=20:
colors.append('orange')
else:
colors.append('red')
# or
colo... | pandas|numpy|matplotlib|plot|colors | 2 |
368,730 | 73,463,366 | Extract columns from 3 CSVs in to 1 CSV (Python) | <p>I'm looking for a way to combine 3 CSVs that contain information in the columns D and E like this with the first row called X Days:</p>
<pre><code> D E F G
1 3 Days 4 Days
2 $100 $200
3 $111 $222
4 ... ...
5 ... ...
</code></pre>
<p>I want to combin... | <p>read all three csvs in to dataframes and then use <code>pd.concat(...,axis=1)</code> to concat them as new columns.</p>
<pre class="lang-py prettyprint-override"><code>df1 = pd.read_csv(file1)
df2 = pd.read_csv(file2)
df3 = pd.read_csv(file3)
df1['F'] = '' #making those blank columns
df2['I'] = ''
df_final = pd.con... | python|pandas|dataframe | 0 |
368,731 | 73,229,255 | how to merge data from a dictionary to a pandas dataframe with certain conditions | <p>I have this dictionary which contains cities and their coordinates:</p>
<pre class="lang-none prettyprint-override"><code>{'Rosario': [-60.63932, -32.946819],
'Concordia': [-74.448212, 40.31094],
'Avellaneda': [-58.367439, -34.660179],
'Corrientes': [-58.834099, -27.4806],
'Caballito': [-58.44104, -34.622639],
'Buen... | <p>1st step will be to make your dictionary into a dataframe:</p>
<pre><code>cities_dict = {'Rosario': [-60.63932, -32.946819], 'Concordia': [-74.448212, 40.31094], 'Avellaneda': [-58.367439, -34.660179], 'Corrientes': [-58.834099, -27.4806], 'Caballito': [-58.44104, -34.622639], 'Buenos Aires': [-78.497498, -9.12417],... | python|pandas|join|merge | 2 |
368,732 | 73,281,821 | How do I measure the difference between two values within each row of my dataframe if they are separated by amino acids? | <p>I have a large dataframe which features mutations in the format: "R68S, M90V, Y227A, F327A", etc. where the letters represent single letter abbreviations for amino acids, and the numbers represent the location of these mutations within the genome.</p>
<p>Minimal, reproducible example:</p>
<pre><code>import... | <p>Let us first find all the locations of mutation from each genome then <code>map</code> a lambda function which calculates the distance between consecutive locations</p>
<pre><code>s = df['MUTATION'].str.findall(r'\b[A-Z](\d+)[A-Z]\b')
df["DISTANCE"] = s.map(lambda l: [int(a) - int(b) for a, b in zip(l[1:],... | python|pandas|dataframe | 2 |
368,733 | 73,336,835 | Nested loop over list of dataframes | <p>I've got a list of dataframes that I want filtered depending on the values in one column that all three of them have. I want to split all three dataframes into three each; one sub-dataframe for each value in that one column. So I want to make 9 dataframes out of 3.
I've tried:</p>
<pre><code>df_list=[df_a,df_b,df_c]... | <p>This should give you a list with dictionaries: One dictionary for each of the original dataframes, each one containing one dataframe referenced with the unique name from 'COLUMN'.</p>
<pre><code>tables = [{'df_' + name: df[df['COLUMN'] == name].copy() for name in df['COLUMN'].unique()} for df in df_list]
</code></pr... | python|pandas|dataframe|loops | 0 |
368,734 | 73,460,184 | How to convert a list to an 1D array in Python? | <p>Trying to convert a list to 1D array and that list contain arrays like this</p>
<p>from</p>
<pre><code>[array([1145, 330, 1205, 364], dtype=int64),
array([1213, 330, 1247, 364], dtype=int64),
array([ 883, 377, 1025, 412], dtype=int64),
array([1038, 377, 1071, 404], dtype=int64),
array([1085, 377, 1195, ... | <p>use <code>.reshape(-1)</code> on the individual arrays inside that list.</p> | python|arrays|python-3.x|numpy | 1 |
368,735 | 73,429,235 | pandas dataframe calculate rolling mean using cutomized window size | <p>I'm trying to calculate the rolling mean/std for a column in dataframe. The pandas or numpy_ext rolling methods seem to need a fixed window size. The dataframe has a column "dates", I want to decide the window size based on the "dates", for example, when calculating mean/std, for rows at day 10, ... | <p>You can perform your operation with a <code>rolling</code>, you however have to pre- and post-process the DataFrame a bit to generate the shift:</p>
<pre><code>A = 3
B = 8
s = (df
# de-duplicate by getting the sum/count per identical date
.groupby('dates')['quantity']
.agg(['sum', 'count'])
# reindex to fill m... | python|pandas|dataframe|numpy|rolling-computation | 2 |
368,736 | 73,489,412 | Converting pandas df from long to wide with duplicated rows and categorical variables as values | <p>I have a simple dataframe</p>
<pre><code>{'ID': {0: 101, 1: 101, 2: 101, 3: 102, 4: 102, 5: 102, 6: 102, 7: 102, 8: 103, 9: 103}, 'Category': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'A', 5: 'A', 6: 'B', 7: 'B', 8: 'A', 9: 'B'}}
</code></pre>
<p>You can see that ID has duplicates and gives me a reshaping error.</p>
<p>I ... | <p>You can assign an enumeration within each ID and query that before pivoting:</p>
<pre><code>N = 5
(df.assign(role_enum=df.groupby('ID').cumcount()+1)
.query('role_enum<=@N')
.pivot(index='ID', columns='role_enum', values='Category')
.add_prefix('Role').reset_index() # book-keeping
)
</code></pre>
<p>O... | python|pandas|pivot|reshape | 1 |
368,737 | 73,450,750 | Stack dataframes in Pandas vertically and horizontally with overlapping years | <p>Related to <a href="https://stackoverflow.com/questions/73127093/stack-dataframes-in-pandas-vertically-and-horizontally">Stack dataframes in Pandas vertically and horizontally</a></p>
<p>I have the following 3 dataframes:</p>
<pre><code>data1 = {
'country': {0: 'USA', 1: 'USA', 2: 'USA', 3: 'USA', 4: 'USA'},
... | <p>What you want is <code>combine_first</code>. When you call <code>df1.combine_first(df2)</code>, it fills NA cells in <code>df1</code> with matching cells in <code>df2</code>. The two data frames are matched on their indexes.</p>
<pre class="lang-py prettyprint-override"><code>cols = ["year", "country&... | python|pandas|dataframe | 2 |
368,738 | 73,359,071 | count list values that appears in dataFrame using python | <p>I want to count list value that is exists in dataframe:</p>
<p>I want to use a loop to go through list values and dataframe df and if list[0] exist in df count++.</p>
<p>my code:
df = pd.read_excel('C:\Users\ma\Desktop\filee')
df looks like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<... | <p>Firstly, welcome to StackOverflow. Check the guidelines for how to properly ask a question (there is no question in your post). I think I understand what you want though.</p>
<p>In general, you don't want to use loops with pandas. Its not the way the API was intended to be used. You would probably want to use pandas... | python|pandas|list|dataframe | 0 |
368,739 | 73,260,866 | Why Numpy array operation can not be done with Numba? | <p>I am writing a simple code to use numpy array inside numba jit as following,</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import random
import time
import math
import numba
from numba import jit,prange
nx=100
p1=np.zeros([nx],dtype=float)
@jit(nopython=True)
def f(r):
... | <p>The type of <code>p1</code> is <code>readonly array(float64, 1d, C)</code> which means you cannot modify it. This is why setting an items does not work: Numba cannot find a function so to set the value of a <code>readonly</code> array. The array is marked as readonly because it is a global variable and this is what ... | python|arrays|numpy|numba | 2 |
368,740 | 73,295,340 | In the code below, I get an error as "first argument must be an iterable of pandas objects". How can I fix this? | <p>I'm trying to understand how iteration in Python works. Isn't the first method the same as the second method? How can we write the first method with the traditional method?</p>
<p>I get an error in second way:
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFra... | <p>In the second case the line <code>df_from_each_file = (pd.read_csv(f))</code> just assigns a dataframe obtained from the latest file to your variable. You pass as an argument a single object (data from the last file), so <code>pd.concat</code> has nothing to concatenate. That's why it says <code>TypeError: first arg... | python|pandas|iteration | 2 |
368,741 | 73,236,721 | Pandas groupby/pivot dataframe of customer orders | <p>Right now I have a DataFrame that looks something like this:</p>
<p><strong>SAMPLE INPUT</strong></p>
<pre><code> name email product qty_ordered
0 jane jane@email.com Red Shirt 2
1 john john@email.com Green Shirt 2
2 john john@email.com Red Shirt 1
3 jim jim@email.com ... | <pre><code>df.groupby(['name', 'email', 'product']).agg({'qty_ordered' : 'sum'})
</code></pre> | python|pandas|dataframe|group-by | 1 |
368,742 | 73,298,820 | Tensorflow gradient tape returns None for all variables | <p>I'm trying to adapt the tensorflow text generation tutorial (<a href="https://www.tensorflow.org/text/tutorials/text_generation" rel="nofollow noreferrer">https://www.tensorflow.org/text/tutorials/text_generation</a>) to using a simple gan akin to (<a href="https://www.tensorflow.org/tutorials/generative/dcgan" rel=... | <p>As reported by <a href="https://stackoverflow.com/users/8990644/bui">@bui</a>, the problem is this line right here:</p>
<pre><code>sampled_indices = tf.random.categorical(generated[i], num_samples=1)
</code></pre>
<p>However, you might be missing something IMO... in particular, the last layer of your generator is th... | tensorflow|keras|tensorflow2.0|recurrent-neural-network|generative-adversarial-network | 0 |
368,743 | 73,266,731 | Group dataframe using start and end column value | <p>I have thousands of recordings. I want to group the dataframe by setting starting column value(1st column) being 'B' till ending value being 'B' but ending 'B' not included.
I want to work on data which is between 'B' and till 'B'. How can I do that using pandas?</p>
<pre><code>B,0,15000.000000,716.881652,-0.065916 ... | <pre><code>import pandas as pd
from io import StringIO
data = """
B,0,15000.000000,716.881652,-0.065916
K,0,-33,1,4030
K,1,-16,2,4028
K,2,-18,12,4036
K,3,-14,-3,4054
P,0,-452,4089,329
P,1,-428,4082,427
P,2,-382,4078,518
P,3,-363,4052,545
P,4,-347,4064,508
K,4,-2,17,4048
K,5,-18,12,4048
P,5,-373,4068,409... | python|pandas | 0 |
368,744 | 73,180,343 | How to create a list of N items with a budget constraint and multiple conditions on Python | <p>I have the following df of Premier League players (ROI_top_players):</p>
<pre><code> player team position cost_2223 total_points ROI
0 Mohamed Salah Liverpool FWD 13.0 259 29.77
1 Trent Alexander Liverpool DEF 8.4 ... | <p>As OP did not provide the data, I went and scraped the first 'Fantasy Football players list' I could find. There is no ROI in that data, however there are 'Points', which we will try to maximize, so I guess OP can apply this to maximize the ROI in his data.</p>
<pre><code>from selenium import webdriver
from selenium... | python|pandas|dataframe|loops|iterator | 1 |
368,745 | 73,220,588 | How can I add a stacked growth column to my time series data in pandas? | <p>I have a table like below, using this dummy data:</p>
<pre><code>data = [['Jane', 10,10.5,11,13,45,41,66,21,88,99,77,84,66,8,77,22,11,44,69,85,36,4,
87,74,56,88,23,6,9,8,55,12,4,58,36,44,89,81,7,98,52,11,45,87,96,32,58,76],
['John',11,22,55,23,6,9,8,41,12,4,58,66,99,36,44,89,81,7,98,52,33,11,45,87,
... | <p>Based on the formula example you have given :</p>
<pre><code>3Y Jan 21 = ((1+Jan 2021 rate) * (1+Jan 2020 rate) * (1+Jan 2019 rate)-1
2Y Jan 21 = ((1+Jan 2021 rate) * (1+Jan 2020 rate))-1
</code></pre>
<h4>Transposing and filtering values of interest from dataframe</h4>
<pre><code>NDF = df.T
NDF, NDF.columns = NDF[1... | python|pandas|datetime | 1 |
368,746 | 73,410,193 | Pandas Similar rows Search | <p>How would I filter data on multiple criteria through the spreadsheet using python(pandas)?</p>
<p>I am trying to filter transactions with all <strong>Curr1=USD</strong>, where <strong>Trade Time within 1 minute</strong>, Have <strong>the same Notional 1</strong> and have <strong>the Price</strong> within .5% spread ... | <pre><code>from openpyxl import load_workbook
import pandas as pd
path = 'Import.xlsx'
sheet_name = 'DifferentSheet'
currency = 'USD'
max_spread = 0.005
def filter_transactions(transactions, currency, max_spread):
df = transactions.copy()
df['Trade Time'] = df['Trade Time'].dt.round(freq='min')
df = df[df... | python|excel|pandas|vba|dataframe | 0 |
368,747 | 34,877,314 | Unexpected behaviour when indexing a 2D np.array with two boolean arrays | <pre><code>two_d = np.array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
first = np.array((True, True, False, False, False))
second = np.array((False, False, False, True, True))
</... | <p>When given multiple boolean arrays to index with, NumPy pairs up the indices of the True values. The first true value in <code>first</code> in paired with the first true value in <code>second</code>, and so on. NumPy then fetches the elements at each of these (x, y) indices.</p>
<p>This means that <code>two_d[first... | python|arrays|numpy|indexing|slice | 12 |
368,748 | 34,936,754 | Intersection of two numpy arrays of different dimensions by column | <p>I have two different numpy arrays given. First one is two-dimensional array which looks like (first ten points):</p>
<pre><code>[[ 0. 0. ]
[ 12.54901961 18.03921569]
[ 13.7254902 17.64705882]
[ 14.11764706 17.25490196]
[ 14.90196078 17.25490196]
[ 14.50980392 17.64705882]
[ 14.11764706... | <p>You can use <code>np.in1d(array1, array2)</code> to search in <code>array1</code> each value of <code>array2</code>. In your case you just have to take the first column of the first array:</p>
<pre><code>mask = np.in1d(a[:, 0], b)
#array([False, False, False, False, False, False, False, False, True, True], dtype=... | python|arrays|numpy|axis|intersection | 5 |
368,749 | 35,314,887 | set a pandas datetime64 pandas dataframe column as a datetimeindex without the time component | <p>After importing data from a HDF5 file the index for my stock data has disappeared. </p>
<p>One of the columns in my dataframe "Date" is a Datetime64. How do I convert this date column to a <code>datetimeindex</code> column but without the time parts at the end.</p>
<p>So that slicing the dataframe like this <code>... | <p>IIUC, starting from a sample dataframe as:</p>
<pre><code> Date x
0 2016-01-01 20:01 1
1 2016-01-02 20:02 2
</code></pre>
<p>you can do:</p>
<pre><code>df = df.set_index(pd.DatetimeIndex(df['Date']).date)
</code></pre>
<p>which returns your <code>DatetimeIndex</code> only with the <code>date</... | python|pandas|indexing | 0 |
368,750 | 35,155,655 | Loss function for class imbalanced binary classifier in Tensor flow | <p>I am trying to apply deep learning for a binary classification problem with high class imbalance between target classes (500k, 31K). I want to write a custom loss function which should be like:
minimize(100-((predicted_smallerclass)/(total_smallerclass))*100)</p>
<p>Appreciate any pointers on how I can build this ... | <p>You can add class weights to the loss function, by multiplying logits.
Regular cross entropy loss is this:</p>
<pre><code>loss(x, class) = -log(exp(x[class]) / (\sum_j exp(x[j])))
= -x[class] + log(\sum_j exp(x[j]))
</code></pre>
<p>in weighted case:</p>
<pre><code>loss(x, class) = weights[class] ... | classification|tensorflow | 49 |
368,751 | 35,213,787 | TensorFlow Batch Outer Product | <p>I have the following two tensors:</p>
<pre><code>x, with shape [U, N]
y, with shape [N, V]
</code></pre>
<p>I want to perform a batch outer product: I'd like to multiply each element in the first column of <code>x</code> by each element in the first row of <code>y</code> to get a tensor of shape <code>[U, V]</code... | <p>Would the following work, using <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/math_ops.html#batch_matmul" rel="noreferrer"><code>tf.batch_matmul()</code></a>?</p>
<pre><code>print x.get_shape() # ==> [U, N]
print y.get_shape() # ==> [N, V]
x_transposed = tf.transpose(x)
print x_transpo... | tensorflow | 6 |
368,752 | 35,208,961 | Filter query by linked object key in SQLAlchemy | <p>Judging by the title <a href="https://stackoverflow.com/questions/2010454/sqlalchemy-filter-query-by-related-object">this</a> would be the exact same question, but I can't see how any of the answers are applicable to my use case:</p>
<p>I have two classes and a relationship between them:</p>
<pre><code>treatment_a... | <p>First, there are two issues with table definitions:</p>
<p>1) In the <code>treatment_association</code> you have <code>Integer</code> column pointing to <code>chronic_treatments.code</code> while the <code>code</code> is <code>String</code> column.</p>
<p>I think it's just better to have an integer <code>id</code>... | python|sqlite|pandas|sqlalchemy | 1 |
368,753 | 34,956,828 | TypeError: Scalar value for argument 'color' is not numeric in openCV | <p>Here is my code</p>
<pre><code>im = cv2.imread('luffy.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,0)
contours,h = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
moment = cv2.moments(cnt)
c_y = moment['m10']/(moment['m00']+0.... | <blockquote>
<p>centroid_color = tuple ([int(x) for x in centroid_color])</p>
</blockquote> | python|opencv|numpy | 8 |
368,754 | 34,964,240 | python pandas and matplotlib installation conflict | <p>I am using a Mac OSX Yosemite 10.10.5 and I am trying to practice data science with python on my laptop. I am using python 3.5.1 on a virtualenv however when I install pandas and matplotlib seems like both of them are having a conflict when trying to be imported. Both has same error and the output is:</p>
<pre><cod... | <p>Just run:</p>
<pre><code>export LC_ALL=C
</code></pre>
<p>before accessing python through terminal.</p> | python|pandas|matplotlib|python-3.5|data-science | 2 |
368,755 | 35,270,450 | TensorFlow on Mobile Devices (Android, iOS, Windows Phone) | <p>I am currently looking on different deep learning frameworks out there, specifically to train and deploy convolutional neural networks. The requirements are, that it can be trained on a normal PC with a GPU, but then the trained model has to be deployed on the three main mobile operating systems, namely Android, iOS... | <p>TensorFlow currently doesn't support iOS or Windows. Here are the open github issues tracking them :</p>
<ul>
<li><a href="https://github.com/tensorflow/tensorflow/issues/16" rel="nofollow">iOS support</a></li>
<li><a href="https://github.com/tensorflow/tensorflow/issues/17" rel="nofollow">Windows support</a></li>
... | android|ios|mobile|windows-phone-8.1|tensorflow | 1 |
368,756 | 35,051,673 | statsmodels: printing summary of more than one regression models together | <p>In the Python library <code>Statsmodels</code>, you can print out the regression results with <code>print(results.summary())</code>, how can I print out the summary of more than one regressions in one table, for better comparison? </p>
<p>A linear regression, code taken from <code>statsmodels</code> documentation:<... | <p>There is <code>summary_col</code>, which AFAIR is still missing from the documentation.</p>
<p>I have not really tried it out much, but I found a related example from an issue to remove some of the "nuisance" parameters.</p>
<pre><code>"""
mailing list, and issue https://github.com/statsmodels/statsmodels/pull/163... | python|pandas|statsmodels | 8 |
368,757 | 35,208,874 | Skipping char-string values while comparing to a column values of mixed type to int or float in pandas Dataframe | <p>I have a dataframe in which one column have mixed type values in it:</p>
<pre><code>df
name ref
a 100
b 103.78
c own
d 108
e abc@yahoo.com
f 110.45
</code></pre>
<p>So the <code>ref</code> col has mixed type. Now I have to query on it like:</p>
<pre><code> d = df[df['ref'] > 105... | <p>This returns a boolean series that can be used as a mask, obtaining all df rows in which ref can be converted to numeric.</p>
<pre><code>pd.to_numeric(df.ref,'coerce').notnull()
</code></pre>
<p>This is not enough as the column dtype is still str.</p>
<pre><code>df[pd.to_numeric(df.ref,'coerce').notnull()].ref &g... | python|pandas | 1 |
368,758 | 34,906,443 | Pandas data-frame creation as permutations of 2 series? | <p>I have data set with two columns </p>
<pre><code>ColA ColB
1 1
2 2
3 3
</code></pre>
<p>I want to create resultant frame of </p>
<pre><code>ColA ColB
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
</code></pre> | <p>You could use <code>itertools</code> for this</p>
<pre><code>import pandas as pd
import itertools
</code></pre>
<p>Create the original dataframe</p>
<pre><code>df = pd.DataFrame([[1,2,3]]*2, index=['ColA', 'ColB']).T
</code></pre>
<p>Permute the two columns of the dataframe you are interested in:</p>
<pre><code... | python|pandas|sequences | 5 |
368,759 | 35,164,333 | Efficient way of creating a permutated 2D array with a range of integers | <p>I'm trying to find an efficient way to generate a set of x-y coordinates that identifies every position in a square lattice, such that, if the lattice is made up of <code>NxN</code> grids, where</p>
<pre><code>N = 100; x = range(N)
</code></pre>
<p>I want to compute a set of arrays such as <code>array([[0,0], [0,1... | <p>Try <code>N = 100; result = [[x, y] for x in range(N) for y in range(N)]</code></p> | python|arrays|numpy|permutation | 3 |
368,760 | 34,952,651 | only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices | <p>I am implementing fft as part of my homework. My problem lies in the implemention of shuffling data elements using bit reversal. I get the following warning:</p>
<blockquote>
<p>DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future.</p>
<p>data[x], data[y] = data[... | <p>I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.</p> | python|python-3.x|numpy|fft|dft | 56 |
368,761 | 35,106,283 | to split an array into subarray in python | <p>Hi I am new to programming and python programming.
I have a tab delimited txt file that I have imported using <code>numpy.getfromtxt</code> and it looks like</p>
<pre><code>[['chr' 'start' 'end' 'name' 'score' 'strand']
['chr1' '822979' '822980' 'CLL6.08_1_snv' '88.2' '+']
...,
['chrX' '153986959' '153986960' 'CL... | <p>You cannot make association in a list [] you have to use a dictionary {}</p>
<pre><code>>>> subarray=({'Chr1':'bla'=='blu'})
>>> print subarray
{'Chr1': False}
</code></pre> | python|numpy | 0 |
368,762 | 35,181,265 | Calculate percent change on a Pandas DataFrame | <p>I have the following DataFrame:</p>
<pre><code> Value 1lag
Date
2005-04-01 258.682029 214.382786
2005-05-01 173.253998 258.682029
2005-06-01 244.432029 173.253998
2005-07-01 213.706019 244.432029
2005-08-01 213.67... | <p>You can just use <code>pct_change()</code> on the dataframe.</p>
<pre><code>>>> df.pct_change()
Value 1lag
Date
2005-04-01 NaN NaN
2005-05-01 -0.330243 0.206636
2005-06-01 0.410831 -0.330243
2005-07-01 -0.125704 0.410831
2005-08-01 -0.000165 -0.1... | python|pandas|dataframe | 15 |
368,763 | 35,147,630 | How can I stop RNN after generating a special output word in Tensorflow? | <p>I want to implement an encoder-decoder model for sequence to sequence learning.</p>
<p>Encoder reads the input sequence word by word and update its hidden state.</p>
<p>Decoder uses the hidden state of encoder to initializing its hidden state. and then generating output with respect to last generated output (y(t-1... | <p>I suppose you want something like the <code>sequence_length</code> of <code>tf.nn.rnn</code>. I want it too, but it seems TensorFlow doesn't have it. </p>
<p>What I've being doing so far and found a good way around this limitation is to pad the decoder labels at train time with the EOS symbol. Usually, you would ne... | tensorflow|recurrent-neural-network | 1 |
368,764 | 35,160,119 | Pandas Dataframe: Fill Missing Months | <p>I've seen this done with the Panda Timeseries, but was hoping to get some help with Dataframes. I have a file of monthly values from 1966-2009. I do not have data for the year 1985 and would like to add data for 2010/2011 as well. These additions would simply have NaNs attached to them. </p>
<p>With the code below,... | <p>I think better is use <code>periodindex</code> by converting <code>datetimeindex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_period.html" rel="nofollow"><code>to_period</code></a>.</p>
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand... | python|datetime|pandas|time-series | 1 |
368,765 | 35,184,894 | Limiting the number of GB to read in read_csv in Pandas | <p>I often work with <code>csv</code> files that are 100s of GB in size. Is there any way to tell <code>read_csv</code> to only read a fixed number of <code>MB</code> from a <code>csv</code> file?</p>
<h3>Update:</h3>
<p>It looks like <code>chunks</code> and <code>chunksize</code> can be used for this, but the documen... | <p>You can pass <code>nrows=number_of_rows_to_read</code> to your read_csv function to limit the lines that are read.</p> | python-3.x|pandas | 1 |
368,766 | 35,208,443 | Pylint complains "no value for argument 'cls'" | <p>I have defined the following class-method to define my object from a pandas.DataFrame instead of from a list like so:</p>
<pre><code>class Container(object):
@classmethod
def from_df(cls, df):
rows = [i for _, i in df.iterrows()]
return cls(rows)
</code></pre>
<p>and <code>pylint</code> com... | <p>Typically this error is related to non-complaint function signatures.</p>
<p>Given your code:</p>
<pre><code>class Container(object):
def __init__(self, iterable, cls):
self.content = [cls(item) for item in iterable]
@classmethod
def from_df(cls, df):
rows = [i for _, i in df.iterrows()]... | python|pandas|pylint | 7 |
368,767 | 35,252,460 | Inconsistent results when concatenating parsed csv files | <p>I am puzzled with the following problem. I have a set of csv files, which I parse iterativly. Before collecting the dataframes in a list, I apply some function (as simple as <code>tmp_df*2</code>) to each of the <code>tmp_df</code>. It all worked perfectly fine at first glance, until I've realized I have inconsisten... | <p>Updating numexpr to 2.4.6 (or later), as numexpr 2.4.4 had some bugs on windows. After running the update it works for me.</p> | python|pandas | 0 |
368,768 | 35,174,274 | how to plot a regression line | <p>I cannot make a proper regression line. My a1 value is supposed to be positive, but it is negative. If I skip the mask part then my a1, b1, c1 values become NaN.</p>
<pre><code>kwargs = dict(delimiter = '\t',\
skip_header = 0,\
missing_values = 'NaN',\
converters = {0:matplotlib.dates.str... | <p>After going through your code a second time I noticed that the arguments for polyfit are in the wrong order. The signature of polyfit is <code>numpy.polyfit(x, y, deg)</code>.</p>
<p>Try using</p>
<pre><code>a1,b1,c1 = polyfit(stage_ratM, dis_ratM, 2)
</code></pre>
<p>(Note the swapped order of <code>stage_ratM</... | python|numpy|matplotlib|regression | 1 |
368,769 | 30,960,408 | Capping values after a trigger level in a different variable | <p>I wish to have the values of 'Original_Level' cap to the level where another column 'NS' hits a trigger (in this case abs(NS) >= 4 ). This new column, 'Desired_Level', created while leaving the 'Original_Level' column unchanged. The below df shows a cap of 13.122 and 50.887 when abs(NS) >= 4</p>
<pre><code>In [36... | <p>You want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.clip.html#pandas.Series.clip" rel="nofollow"><code>clip</code></a> for this, firstly find the indices of your upper and lower clip values using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idx... | pandas|triggers | 1 |
368,770 | 31,082,291 | Wrapping a numpy array element to integer | <p>I have a list of subgraphs that I am attempting to access within a loop:</p>
<pre><code> index=[5,3,4,1,1,3,4,2,3,4,2,2,3,3,2,4]
subgraph=[[subgraph1],[subgraph2],[subgraph3],[subgraph4],[subgraph5]]
for i in range(len(index)):
for j in range(i+1,len(index)):
if index[j]==index[i]
co... | <p>You can convert <code>numpy.float64</code> to float by doing this: <code>var.item()</code>. Then convert it into an integer so you can use it as your index: <code>int(var.item())</code></p> | python|arrays|numpy|indexing|casting | 3 |
368,771 | 30,773,073 | Save pandas DataFrame using h5py for interoperabilty with other hdf5 readers | <p>Here is a sample data frame:</p>
<pre><code>import pandas as pd
NaN = float('nan')
ID = [1, 2, 3, 4, 5, 6, 7]
A = [NaN, NaN, NaN, 0.1, 0.1, 0.1, 0.1]
B = [0.2, NaN, 0.2, 0.2, 0.2, NaN, NaN]
C = [NaN, 0.5, 0.5, NaN, 0.5, 0.5, NaN]
columns = {'A':A, 'B':B, 'C':C}
df = pd.DataFrame(columns, index=ID)
df.index.name = ... | <p>Here is my approach to solving this problem. I am hoping either someone else has a better solution or my approach is helpful to others.</p>
<p>First, define function to make a numpy structure array (not a record array) from a pandas DataFrame.</p>
<pre><code>import numpy as np
def df_to_sarray(df):
""&... | matlab|numpy|pandas|h5py | 12 |
368,772 | 30,944,577 | Check if string is in a pandas dataframe | <p>I would like to see if a particular string exists in a particular column within my dataframe.</p>
<p>I'm getting the error</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().</p>
</blockquote>
<pre><code>import pandas as pd
BabyDataSet = [('... | <p><code>a['Names'].str.contains('Mel')</code> will return an indicator vector of boolean values of size <code>len(BabyDataSet)</code></p>
<p>Therefore, you can use</p>
<pre><code>mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
print ("There are {m} Mels".format(m=mel_count))
</code></pre>
<p>O... | python|pandas | 162 |
368,773 | 30,989,884 | How to set first column to a constant value of an empty np.zeros numPy matrix? | <p>I'm working on setting some boundary conditions for a water table model, and I am able to set the entire first row to a constant value, but not the entire first column. I am using <code>np.zeros((11, 1001))</code> to make an empty matrix. Does anyone know why I am successful at defining the first row, but not the fi... | <p>All you have to do is to change </p>
<pre><code>head[0][0:]
</code></pre>
<p>to</p>
<pre><code>head[:, 0] = 16
</code></pre>
<p>If you want to change the first row you can just do:</p>
<pre><code>head[0, :] = 16
</code></pre>
<p>EDIT:</p>
<p>Just in case you also wonder how you can change an arbitrary amount ... | python|numpy|matrix|modeling | 4 |
368,774 | 30,984,920 | Selecting Data from Last Week in Python | <p>I have a large database and I am looking to read only the last week for my python code. </p>
<p>My first problem is that the column with the received date and time is not in the format for datetime in pandas. My input (Column 15) looks like this:</p>
<pre><code>recvd_dttm
1/1/2015 5:18:32 AM
1/1/2015 6:48:23 AM
1/... | <pre><code>import datetime as dt
# convert strings to datetimes
df['recvd_dttm'] = pd.to_datetime(df['recvd_dttm'])
# get first and last datetime for final week of data
range_max = df['recvd_dttm'].max()
range_min = range_max - dt.timedelta(days=7)
# take slice with final week of data
sliced_df = df[(df['recvd_dttm'... | python|datetime|pandas|format|dataframe | 3 |
368,775 | 30,851,195 | pandas converting column names to variables efficiently | <p>I do have following dataframe:</p>
<pre><code>{'2003-12-02LVDT0023': {0: 2.3407617000000001e-06,
1: 2.3402380999999998e-06,
2: 2.3410341000000001e-06,
3: 2.3417209999999999e-06,
4: 2.3419282000000002e-06,
5: 2.3420178e-06,
6: 2.3424012999999999e-06},
'2003-12-02LVDT0024': {0: 2.3612594999999998e-06,
... | <p>This should get you at least close to the dataframe you want:</p>
<ol>
<li><p>Replace the column index with a hierarchical one:</p>
<pre><code>ind = [(t[0:10], t[10:-4], t[-2:]) for t in df.columns]
newcol = pd.MultiIndex.from_tuples(ind, names = ['date', 'factor', 'id'])
df.columns = newcol
</code></pre></li>
<li... | python|pandas | 0 |
368,776 | 31,054,904 | Pandas: Conditionally generate descriptions from column content | <p>I am trying to iron out some issues with a function that uses <code>pandas regex</code> via <code>str.extract</code> to get each row in column <code>"name"</code> to generate column <code>"description"</code>. I am using <code>regex</code> and not <code>split</code> since the code must be able to manage a variety of... | <p>I spent some time writing this function:</p>
<pre><code>description_map = {"AXP":"American Express", "BIDU":"Baidu"}
sign_map = {"LONG": "", "SHORT": "-"}
stock_match = re.compile(r"\s(\S+)\s")
leverage_match = re.compile("[0-9]x|x[0-9]|X[0-9]|[0-9]X")
def f(value):
f1 = lambda x: description_map[stock_match... | python|pandas | 2 |
368,777 | 30,766,512 | Obtaining Legendre polynomial form once Legendre coefficients are determined | <p>I have obtained the coefficients for the Legendre polynomial that best fits my data. Now I am needing to determine the value of that polynomial at each time-step of my data. I need to do this so that I can subtract the fit from my data. I have looked at the documentation for the Legendre module, and I'm not sure ... | <p>To simplify Ahmed's example</p>
<pre><code>In [1]: from numpy.polynomial import Polynomial, Legendre
In [2]: p = Polynomial([0.5, 0.3, 0.1])
In [3]: x = np.random.rand(10) * 10
In [4]: y = p(x)
In [5]: pfit = Legendre.fit(x, y, 2)
In [6]: plot(*pfit.linspace())
Out[6]: [<matplotlib.lines.Line2D at 0x7f81536... | python|numpy | 2 |
368,778 | 31,053,022 | Pandas read_csv - rows with variable number of columns | <p>I have a CSV file that has rows with a variable number of columns (and no column headers). E.g. the file could begin with some rows with 23 columns and then some rows with 83 columns etc. Now when read_csv() starts reading the file it guesses the number of columns after the first few rows are read (I think) so if th... | <pre><code># coding: utf-8
# In[16]:
def params(text):
pairs = text.split("|")
print pairs
out = {i.split("=")[0]:i.split("=")[1] for i in pairs}
return pd.Series(out)
params("asd=2|qwe=5")
# In[27]:
import pandas as pd
aa = pd.DataFrame({'id':[1,2],'text':["asd=2|qwe=5","asd=20|qwe=5|qzxc=5"]})... | python|csv|pandas | -2 |
368,779 | 31,080,383 | Counting categorical data pandas group by dataframe | <p>I have a data frame that looks like this:</p>
<pre><code>+---+-----------+----------------+-------+
| | uid | msg | count |
+---+-----------+----------------+-------+
| 0 | 121437681 | eis | 1 |
| 1 | 14403832 | eis | 1 |
| 2 | 190442364 | eis | 1 |
|... | <p>Group by uid and apply <code>value_counts</code> to the msg column:</p>
<pre><code>>>> d.groupby('uid').msg.value_counts()
uid
14403832 eis 1
121437681 eis 1
144969454 eis 1
190102625 eis 1
190104837 eis 1
190... | python|pandas | 19 |
368,780 | 30,880,770 | Python and conflicting module names | <p>It seems that if a file is called <code>io.py</code> and it imports <code>scipy.ndimage</code>, the latter somehow ends up failing to find its own submodule, also called <code>io</code>:</p>
<pre><code>$ echo "import scipy.ndimage" > io.py
$ python io.py
Traceback (most recent call last):
File "io.py", line 1... | <p>The simple fix is to avoid naming your module <code>io</code>, because it's conflicting with a core library module name. </p>
<p>It's not really a bug in numpy, but user error: just as we shouldn't use <code>list</code> as a variable name because it's shadowing the builtin <code>list</code> name, we shouldn't use ... | python|numpy|scipy | 5 |
368,781 | 31,188,979 | Is numpy.linalg.inv() giving the correct matrix inverse? EDIT: Why does inv() gives numerical errors? | <p>I have a matrix shaped (4000, 4000) and I would like to take the inverse. (My intuition of the inverting matrices breaks down with such large matrices.)</p>
<p>The beginning matrix has values of the magnitude <code>e-10</code>, with the following values: <code>print matrix</code> gives an output</p>
<pre><code>[[ ... | <p>Your matrix is ill-conditionned, since </p>
<pre><code>np.linalg.cond(matrix) > np.finfo(matrix.dtype).eps
</code></pre>
<p>According to <a href="https://stackoverflow.com/a/13264934/1791279">this answer</a> you could consider using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.linal... | python|numpy|matrix|matrix-inverse | 6 |
368,782 | 67,320,280 | How to combine heatmap with contour plot? | <p>I have two similar three-dimensional, but separate datasets (in different CSV files), where α and δ are the independent variables, and ϕ (first dataset) or a percentage value (second dataset) are the dependent variables. The datasets resemble Pivot tables.</p>
<p>I've already managed to plot a heatmap of the first d... | <p>Try with <code>contour</code>:</p>
<pre><code>x,y = np.meshgrid(np.arange(df2.shape[0])+0.5,
np.arange(df2.shape[1])+0.5,
indexing='ij'
)
ax=sns.heatmap(df1)
ax.contour(x,y, df2, levels=[40,80,100])
</code></pre> | python|pandas|matplotlib|seaborn | 0 |
368,783 | 67,580,181 | Adding values of a 1D array to a 2D array based on a 1D array of indexes | <p>I'm working with numpy and I hit a roadblock, I think it's an easy question and can be done using indexing, but I still haven't figure it out. So I have 2D array and from each row I get the index of the minimum value, what I want is to use this index to add values to the 2D array, here is an example</p>
<pre><code>a... | <p>You were close. Try this:</p>
<pre><code>newarray = a.copy()
newarray[np.arange(len(a)), minimum] += values
</code></pre> | python|numpy | 1 |
368,784 | 67,223,165 | Negative dimension size caused by subtracting 5 from 1 for 'conv3d_1/convolution' (op: 'Conv3D') with input shapes | <p>I m trying to train a data on a 3dcnn I used the code bellow :</p>
<pre><code># image specification
img_rows,img_cols,img_depth=16,16,15
# CNN Training parameters
batch_size = 2
nb_classes = 6
nb_epoch =50
# number of convolutional filters to use at each layer
nb_filters = [32, 32]
# level of pooling to perform a... | <p>There is problems in the structure of the model. Please add the code marked by blue and think about problems in code marked by red: <a href="https://i.stack.imgur.com/o3kWO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o3kWO.png" alt="enter image description here" /></a></p>
<p>...the full code ... | tensorflow|keras|deep-learning|conv-neural-network | 0 |
368,785 | 67,457,523 | python script works interactively but fails with pandas write permission problems as a cron job | <p>I have Anaconda with python 3.8 on macOS Big Sur. The python script works just fine within PyCharm or interactively inside a shell script :</p>
<p><em>/Users/nicholaskalita/opt/anaconda3/bin/python3.8 /Users/nicholaskalita/PycharmProjects/CrpytoScrape/CMCScrape.py</em></p>
<p>The shell script need to be launched reg... | <p>After clearing out the following directories this problem vanished</p>
<pre><code>~/Library/LaunchAgents
/Library/LaunchAgents
/Library/LaunchDaemons
/Library/StartupItems
</code></pre> | pandas|permissions | 0 |
368,786 | 67,353,743 | How to increase FPS for my face mask detection project using OpenCV? | <p>I'm building a face mask detector on my Raspberry Pi but the problem is the video is super laggy. Is there any way I can get the video output to be more than 1 FPS? I'm new to Python and am using this code I found online to test if it works or not. When I use the Pi camera normally I get a good amount of FPS, but wh... | <p>Deeplearning Machine Models are known to be commonly slow while parsing an image. Have you tried making an Opencv haarcascade? Maybe try compressing the resolution of the frames, Tutorial over here <a href="https://www.geeksforgeeks.org/how-to-compress-images-using-python-and-pil/" rel="nofollow noreferrer">https://... | python|tensorflow|opencv|keras|raspberry-pi | 0 |
368,787 | 67,432,140 | yearly spaced dates on the exact same date | <p>I would like to have the exact same date every year from an end date to next one from today. For example if my end is "20251220", I would like to get the following list of dates
"20211220","20221220","20231220","20241220". However, if it was "20250220" I on... | <p>One idea with list comprehension:</p>
<pre><code>import datetime as dt
end = dt.date(2025, 12,20)
today = dt.datetime.today()
l = [end.replace(year=i)
for i in range(today.year, end.year)
if end.replace(year=i) > today.date()]
print (l)
[datetime.date(2021, 12, 20),
datetime.date(2022, 12, 20),
da... | python|pandas|datetime | 1 |
368,788 | 67,267,305 | How should Exponential Moving Average be used in custom TF2.4 training loop | <p>I have a custom training loop that can be simplified as follow</p>
<pre><code>inputs = tf.keras.Input(dtype=tf.float32, shape=(None, None, 3))
model = tf.keras.Model({"inputs": inputs}, {"loss": f(inputs)})
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9, nesterov=True)
for i... | <p>Create the EMA object before the training loop:</p>
<pre><code>ema = tf.train.ExponentialMovingAverage(decay=0.9999)
</code></pre>
<p>And then just apply the EMA after your optimization step. The ema object will keep shadow variables of your model's variables. (You don't need the call to <code>tf.control_dependencie... | tensorflow|tensorflow2.0 | 5 |
368,789 | 67,461,890 | How to smoothen the data into stepped curve? | <p>I have a saved data frame for which I got local maxima and local minima calculated. refer attached picture- <a href="https://i.stack.imgur.com/xWJ9n.png" rel="nofollow noreferrer">data frame plot with local minima and maxima</a>.
In this pic, I combined the local minima and maxima column into single and then filled ... | <p><strong>zero</strong> is not correct value for <code>fillna()</code>. It's better as the local minimum or maximum</p>
<ul>
<li>generated a curve off <em>sine</em> curve and randomised it to give it a few features</li>
<li>calculated local min/max as per method you have used</li>
<li><code>fillna(method="bfill&... | python|pandas | 1 |
368,790 | 67,567,477 | indexing multiple minimum values from a numpy ndarray | <p>I have a set of coordinates in the below data structure.
How do I find the indices for the K minimal X value points?
e.g. for the below data with <code>k=3</code>, the output should be something like <code>[5,4,3]</code></p>
<pre><code>array([[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]... | <p>Since your data is not in <code>nx2</code> shape, reshape it first and use <code>argsort</code> to get the sorted indices and index first <code>k</code></p>
<pre><code>x = np.array(
[[[463, 445]],
[[461, 447]],
[[461, 448]],
[[ 42, 2]],
[[ 41, 1]],
[[ 40, 100]]])
k = 3
print (np.arg... | python|numpy|multidimensional-array|numpy-ndarray | 1 |
368,791 | 67,356,366 | Split a data frame into six equal parts based on number of rows without knowing the number of rows - pandas | <p>I have a df as shown below.</p>
<p>df:</p>
<pre><code>ID Job Salary
1 A 100
2 B 200
3 B 20
4 C 150
5 A 500
6 A 600
7 A 200
8 B 150
9 C 110
10 B 200
11 B 220
12 A 150
13 C 20
14 B 50
</code></pre>
<p>I would like to split... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.array_split.html" rel="nofollow noreferrer"><strong><code>np.array_split()</code></strong></a>:</p>
<pre class="lang-py prettyprint-override"><code>dfs = np.array_split(df, 6)
for index, df in enumerate(dfs):
df.to_csv(f'df{index+1}.csv... | python|pandas|dataframe | 7 |
368,792 | 67,349,208 | Extract info from each row of a dataframe without a loop | <p>I have a large dataframe (~500,000 rows). Processing each row gives me a Counter object (a dictionary with objects counts). The output I want is a new dataframe which column headers are the objects that are being counted (the keys in the dictionary). I am looping over the rows, however it takes very long.I know that... | <p>I think must use a vecotrized solution maybe: "<em>Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided (using) a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing.</... | pandas|dataframe|loops|append|nltk | 0 |
368,793 | 67,417,141 | Syntax error in INSERT INTO command while using pyodbc | <p>This is the code where syntax error occurs</p>
<pre><code>import pyodbc
import pandas as pd
from datetime import date
Today = date.today()
Today = Today.strftime('%d-%m-%y')
NSE_Deli = pd.read_csv("C:/Users/PC/Desktop/Daily Data/NSE_Deliverables.csv")
def append_NSE_Deliverables():
for row in NSE_Del... | <p>The column name <code>Deli%</code> needs to be quoted. Access ODBC will accept backquotes, but square brackets are more commonly used in Microsoft's dialects of SQL</p>
<pre class="lang-py prettyprint-override"><code>cursor.execute("INSERT INTO tbl1A_Deliverable_NSE ([Symbol],[Series],[Volume],[DeliVolume],[Del... | pandas|ms-access|pyodbc | 0 |
368,794 | 67,251,758 | Stuck at this error "RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu" | <p>I am running the following code. If I try to run it on CPU only it runs fine but it takes too much time to train. So I thought to change the runtime to GPU and made appropriate changes. Now it is stuck.</p>
<pre><code>import torch
from models.bert_attention_model import AttentionModel
from models.bert_cnn_model impo... | <p>The problem is exactly as the error says, Pytorch expects all operations to be done in the same device but the two tensors you are adding are in different places.</p>
<p>You need to add <code>.to(device)</code> to these variables</p>
<pre><code> count0,count1,count2 = torch.zeros(1),torch.zeros(1),torch.zeros(1)
... | python|pytorch | 3 |
368,795 | 67,382,437 | Parsing non-zero padded 12-hour datetime format in Python | <p>I am trying to parse a date-time string in python. It is a non-zero padded 12-hour format (<code>%I</code>) with a trailing string denoting <code>[AM, PM]</code> (<code>%p</code>)</p>
<p>I cannot interpret the following error messages. How is the string incorrectly formatted?</p>
<h2>With Datetime <code>.strptime()<... | <p>You have day and month the wrong way round.</p>
<p>This should work.</p>
<pre><code>from datetime import datetime
datetime.strptime("3/31/21 1:50PM", '%m/%d/%y %I:%M%p')
</code></pre> | python|pandas|datetime | 2 |
368,796 | 67,466,829 | Outer merge in pandas with more than two data frames | <p>I have a 3 dfs as shown below</p>
<p>df1:</p>
<pre><code>ID March_Number March_Amount
A 10 200
B 4 300
C 2 100
</code></pre>
<p>df2:</p>
<pre><code>ID Feb_Number Feb_Amount
A 1 100
B 8 5... | <p>We can create a list of <code>dfs</code> in this case <code>dfl</code> which we want to merge and then we can merge them together.</p>
<p>We can add as many dfs as we want in <code>dfl=[df1, df2, df3,..., dfn]</code></p>
<pre><code>from functools import reduce
dfl=[df1, df2, df3]
df_merged = reduce(lambda left,righ... | python-3.x|pandas|dataframe|merge | 1 |
368,797 | 67,583,855 | input_shape error in first dense layer of tensoflow | <p>I am trying to create a model which takes a python list of 4 elements and returns two values as a prediction. Here is my code:</p>
<pre><code>class DQNagent:
def create_model(self):
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(16, activation ='relu',input_shape =(4,1)))
... | <p><code>.predict(X)</code> expects batch to be the first dimension of <code>X</code>. In your case it interprets your 4x1 array like you provided a batch of 4 examples of size 1. Add a new dimension to state for it to become 1x4 so it's a batch of 1, that contains 4 features.</p>
<pre><code>class DQNagent:
def cr... | python-3.x|tensorflow|machine-learning|keras|keras-layer | 0 |
368,798 | 67,190,810 | NumPy array with largest value on diagonal and other values shuffled | <p>I am trying to create a square NumPy (or PyTorch, since PyTorch code can be turned into NumPy with minimal effort) matrix which has the following property: given a set of values, the diagonal elements in each row have the largest value and the other values are randomly shuffled for the other positions.</p>
<p>For ex... | <p>First you can generate a randomized array on the first axis with <code>np.random.shuffle()</code>, then I've used a (not so easy to understand) mathematical tricks to shift each rows:</p>
<pre><code>import numpy as np
from numpy.fft import fft, ifft
# First create your randomized array with np.random.shuffle()
x = ... | python|arrays|numpy|pytorch | 0 |
368,799 | 67,349,942 | How do I display correlation coefficients of each individual variable in Python? | <p>I ran a linear regression model and have my coefficients. How do I print my variables next to my coefficients?</p>
<pre><code>df = pd.read_csv('data', sep=";")
reg = linear_model.LinearRegression()
reg.fit(df[["age", "area", "bedrooms"]],df.price)
print(reg.coef_)
Output
[ ... | <p>My preferred approach is <code>pd.Series(reg.coef_,index=df.columns)</code>, then printing comes for free. Also it is easier to work with <code>pd.Series</code> for other calculations, comparisons of models via <code>pd.concat</code> etc.</p> | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.