id
stringlengths
7
11
source
stringclasses
1 value
category
stringclasses
11 values
title
stringlengths
15
214
text
stringlengths
70
30.5k
url
stringlengths
57
160
tags
stringlengths
3
113
created_at
int64
1.22B
1.79B
se_79790995
stackoverflow
DATA_SCIENCE
Failing to fill empty date values with numpy nan
Failing to fill empty date values with numpy nan I have below code import pandas as pd import numpy as np dat = pd.DataFrame({'A' : [1,2,3,4,5], 'B' : ['2002-01-01', '2003-01-01', '2004-01-01', '2004-01-01', '2005-01-01']}) dat['B'] = pd.to_datetime(dat['B']) dat['A'] = np.where( dat['A'].isin([1...
https://stackoverflow.com/questions/79790995/failing-to-fill-empty-date-values-with-numpy-nan
python, pandas
1,760,520,483
se_79790533
stackoverflow
DATA_SCIENCE
How to write a pandas-compatible, non-elementary expression in narwhals
How to write a pandas-compatible, non-elementary expression in narwhals I'm working with the narwhals package and I'm trying to write an expression that is: applied over groups using .over() Non-elementary/chained (longer than a single operation) Works when the native df is pandas import narwhals as nw import polars...
https://stackoverflow.com/questions/79790533/how-to-write-a-pandas-compatible-non-elementary-expression-in-narwhals
python, pandas, dataframe, python-polars, python-narwhals
1,760,468,856
se_78273394
stackoverflow
DATA_SCIENCE
Add exception handler and continue code execution
Add exception handler and continue code execution I have this Python code used to read files: import pandas as pd metadata_files = [] csv_df = pd.DataFrame() meta_files_list = (pd.read_csv(file, encoding='utf-8', sep=";") for file in metadata_files) meta_files_df = pd.concat(meta_files_list, ignore_index=True) Somet...
https://stackoverflow.com/questions/78273394/add-exception-handler-and-continue-code-execution
python, pandas
1,712,228,560
se_78485326
stackoverflow
DATA_SCIENCE
Pandas Extract Phone Number if it is in Correct Format
Pandas Extract Phone Number if it is in Correct Format I have a column that has phone numbers. They are usually formatted in (555) 123-4567 but sometimes they are in a different format or they are not proper numbers. I am trying to convert this field to have just the numbers, removing any non-numeric characters (if th...
https://stackoverflow.com/questions/78485326/pandas-extract-phone-number-if-it-is-in-correct-format
python, pandas, regex, dataframe, text-extraction
1,715,790,927
se_79790517
stackoverflow
DATA_SCIENCE
Create an incremental suffix for values in a pandas column that have duplicate values in another column
Create an incremental suffix for values in a pandas column that have duplicate values in another column Setup I have a dataframe, df import pandas as pd df = pd.DataFrame( { 'Name':['foo','foo','foo','bar','bar','bar','baz','baz','baz'], 'Color':['red','blue','red','green','green','blue','yellow',...
https://stackoverflow.com/questions/79790517/create-an-incremental-suffix-for-values-in-a-pandas-column-that-have-duplicate-v
python, pandas, dataframe
1,760,467,762
se_12850345
stackoverflow
DATA_SCIENCE
How do I combine two dataframes?
How do I combine two dataframes? I have a initial dataframe D. I extract two data frames from it like this: A = D[D.label == k] B = D[D.label != k] I want to combine A and B into one DataFrame. The order of the data is not important. However, when we sample A and B from D, they retain their indexes from D.
https://stackoverflow.com/questions/12850345/how-do-i-combine-two-dataframes
python, pandas
1,349,999,617
se_52904433
stackoverflow
DATA_SCIENCE
How to add/subtract an array of varying Month timedeltas in Pandas?
How to add/subtract an array of varying Month timedeltas in Pandas? I wish to subtract some number of months from a datetime column. Each row has a different number of months to subtract. For example, df = pd.DataFrame({ 'timestamp': pd.date_range('2017-10-01', '2018-10-01', freq='m'), 'delta_in_months': [1, ...
https://stackoverflow.com/questions/52904433/how-to-add-subtract-an-array-of-varying-month-timedeltas-in-pandas
python, pandas, dataframe, datetime, datetimeoffset
1,540,029,304
se_79789768
stackoverflow
DATA_SCIENCE
Increase the date by number of months in pandas
Increase the date by number of months in pandas I have below pandas data frame import pandas as pd import numpy as np dat = pd.DataFrame({'A' : [1,2,3,4,5], 'B' : ['2002-01-01', '2003-01-01', '2004-01-01', '2004-01-01', '2005-01-01']}) dat['A'] = dat['A'].astype('Int64') Now I want to create another date column from ...
https://stackoverflow.com/questions/79789768/increase-the-date-by-number-of-months-in-pandas
python, pandas, dataframe
1,760,409,862
se_65327510
stackoverflow
DATA_SCIENCE
Creating a scatterplot for a grouped pandas dataframe
Creating a scatterplot for a grouped pandas dataframe I have a Pandas DataFrame where I want to group by a certain column. Afterwards, I want to make a scatterplot of this grouped dataframe. However if I do so I get an error, because the column I group by is nog recognized. # Data loading, processing and for more impo...
https://stackoverflow.com/questions/65327510/creating-a-scatterplot-for-a-grouped-pandas-dataframe
python, pandas, dataframe, matplotlib, scatter-plot
1,608,136,992
se_58260771
stackoverflow
DATA_SCIENCE
How to show first+last N rows of a DataFrame
How to show first+last N rows of a DataFrame I am looking for the best way to quickly preview the first and last N rows of a DataFrame at the same time. I realize I can use df.head(N) and df.tail(N) separately but this returns two DataFrames. Is it best to simply call these 2 separate functions and concatenate the tw...
https://stackoverflow.com/questions/58260771/how-to-show-firstlast-n-rows-of-a-dataframe
python, pandas, dataframe
1,570,391,813
se_30912746
stackoverflow
DATA_SCIENCE
Pandas remove null values when to_json
Pandas remove null values when to_json i have actually a pandas dataframe and i want to save it to json format. From the pandas docs it says: Note NaN‘s, NaT‘s and None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters Then using the orient op...
https://stackoverflow.com/questions/30912746/pandas-remove-null-values-when-to-json
python, json, pandas
1,434,622,978
se_79789223
stackoverflow
DATA_SCIENCE
Why is there a duplicate index when using sort_index() in pandas?
Why is there a duplicate index when using sort_index() in pandas? I am doing target mean mapping based on an external statistical table, where org_ is the external data and merged_data is the set of training data and test data. After processing, the features of merged_data and org_ are exactly the same, and then fed i...
https://stackoverflow.com/questions/79789223/why-is-there-a-duplicate-index-when-using-sort-index-in-pandas
python, pandas, machine-learning
1,760,355,424
se_79788916
stackoverflow
DATA_SCIENCE
Is there a way in Python to make a row of an HTML table multi-lined?
Is there a way in Python to make a row of an HTML table multi-lined? I have a Python script that constructs a pandas DataFrame from API data, which I then convert to a pretty_html_table that will be the body of an email. In one of the rows, I have data containing an address. It is formatted as follows Street Address: ...
https://stackoverflow.com/questions/79788916/is-there-a-way-in-python-to-make-a-row-of-an-html-table-multi-lined
python, pandas, dataframe
1,760,328,704
se_33680666
stackoverflow
DATA_SCIENCE
Creating a new pandas column by using lambda function on two existing columns
Creating a new pandas column by using lambda function on two existing columns I am able to add a new column in Pandas by defining user function and then using apply. However, I want to do this using lambda; is there a way around? For example, df has two columns a and b. I want to create a new column c which is equal t...
https://stackoverflow.com/questions/33680666/creating-a-new-pandas-column-by-using-lambda-function-on-two-existing-columns
python, pandas, dataframe, function, apply
1,447,359,961
se_79783950
stackoverflow
DATA_SCIENCE
How to pivot a Pandas dataframe into the desired format?
How to pivot a Pandas dataframe into the desired format? I have the following data in a dataframe: Product t_Proj CFType1 CFType2 CFType3 0 Product1 0 270 193 130 1 Product1 1 233 197 362 2 Product1 2 130 278 375 3 Product1 3 162 365 225 4 Product1 4 278 138 214 5 Product1 ...
https://stackoverflow.com/questions/79783950/how-to-pivot-a-pandas-dataframe-into-the-desired-format
python, pandas, dataframe, pivot, pivot-table
1,759,773,285
se_64664878
stackoverflow
DATA_SCIENCE
apply relativedelta to a column of dates
apply relativedelta to a column of dates below is my df import pandas as pd df = pd.DataFrame({'Date': ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09']}) I can create a column with another date which is two months prior to the...
https://stackoverflow.com/questions/64664878/apply-relativedelta-to-a-column-of-dates
python, pandas, datetime, vectorization
1,604,414,145
se_60197113
stackoverflow
DATA_SCIENCE
pandas calculate delta time
pandas calculate delta time Here's some code where that will generate some random data, and chart plus lines representing 30th & 90th percentiles. import pandas as pd import numpy as np from numpy.random import randint import matplotlib.pyplot as plt %matplotlib inline np.random.seed(10) # added for reproductibility...
https://stackoverflow.com/questions/60197113/pandas-calculate-delta-time
python, pandas, data-science
1,581,542,785
se_22923775
stackoverflow
DATA_SCIENCE
Calculate Time Difference Between Two Pandas Columns in Hours and Minutes
Calculate Time Difference Between Two Pandas Columns in Hours and Minutes I have two columns, fromdate and todate, in a dataframe. import pandas as pd data = {'todate': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')], 'fromda...
https://stackoverflow.com/questions/22923775/calculate-time-difference-between-two-pandas-columns-in-hours-and-minutes
python, pandas, datetime, python-datetime, timedelta
1,396,907,370
se_67153936
stackoverflow
DATA_SCIENCE
Use Sqlalchemy to Connect SQL Server - Pandas
Use Sqlalchemy to Connect SQL Server - Pandas Try to write the dataframe into DB, but getting the error below. Create Dataframe import pandas as pd d = {'col1': [1, 2], 'col2': ['VIP', 'Eco']} df = pd.DataFrame(data=d) Connect to SQL Server at Azure from sqlalchemy import create_engine engine = create_engine ('mssql...
https://stackoverflow.com/questions/67153936/use-sqlalchemy-to-connect-sql-server-pandas
python, sql-server, pandas, sqlalchemy
1,618,784,328
se_79787585
stackoverflow
DATA_SCIENCE
How to combine multiple rows of Pandas dataframe into one row using a key
How to combine multiple rows of Pandas dataframe into one row using a key I am trying to manipulate a CSV using Pandas and I need to get the data into the format of one row per ID. This is an example of what I am trying to accomplish: From: df = pd.DataFrame({ 'ID': [1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 5, 6, 7], 'Color'...
https://stackoverflow.com/questions/79787585/how-to-combine-multiple-rows-of-pandas-dataframe-into-one-row-using-a-key
python, pandas, dataframe, csv, group-by
1,760,117,183
se_39067831
stackoverflow
DATA_SCIENCE
DataFrame with MultiIndex to nested dictionary
DataFrame with MultiIndex to nested dictionary I have a dataframe with a MultiIndex. 01.01 02.01 03.01 04.01 bar total1 40 52 18 11 total2 36 85 5 92 baz total1 23 39 45 70 total2 50 49 51 65 foo total1 23 97 17 97...
https://stackoverflow.com/questions/39067831/dataframe-with-multiindex-to-nested-dictionary
pandas, dictionary, group-by, nested, multi-index
1,471,806,125
se_79787051
stackoverflow
DATA_SCIENCE
python plotly scatter ols trendline has a kink in it
python plotly scatter ols trendline has a kink in it I am using plotly express to model some data, and wanted to add a trendline = 'ols' to it. when I do, I obtain a kink in the result here is the code used: d={'category': {63: 'test', 128: 'test', 192: 'test', 256: 'test', 320: 'test', 385: 'test', 449: 'test', 513:...
https://stackoverflow.com/questions/79787051/python-plotly-scatter-ols-trendline-has-a-kink-in-it
python, pandas, plotly, trendline
1,760,077,811
se_79786581
stackoverflow
DATA_SCIENCE
Using .loc to change a value in a pd.Dataframe with a variable as column name
Using .loc to change a value in a pd.Dataframe with a variable as column name I need to change a value in a pd dataframe with .loc let show with an example : import pandas as pd df = pd.DataFrame(data={"A":["bla","bla2"],"B":[1,2]}) I would like to do: df.loc[df.A=="bla","B"]=3 This command perform what I want but I...
https://stackoverflow.com/questions/79786581/using-loc-to-change-a-value-in-a-pd-dataframe-with-a-variable-as-column-name
python, pandas
1,760,023,419
se_47152691
stackoverflow
DATA_SCIENCE
How can I pivot a dataframe?
How can I pivot a dataframe? How do I pivot the pandas dataframe below such that the col values become columns, row values become the index, and mean of val0 becomes the values? (In some cases this is called transforming from long-format to wide-format.) Consider a dataframe df with columns 'key', 'row', 'item', 'col'...
https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe
python, pandas, group-by, pivot, pivot-table
1,510,041,628
se_79786055
stackoverflow
DATA_SCIENCE
Why does changing a DataFrame in one Jupyter cell also change another variable?
Why does changing a DataFrame in one Jupyter cell also change another variable? I am working in Jupyter Notebook with pandas, and I noticed something strange. In one cell , I did this: import pandas as pd df1 = pd.DataFrame({"A":[1,2,3]}) df2 = df1 Then in another cell, I changed df2: df2.loc[0,"A"] = 100 But when ...
https://stackoverflow.com/questions/79786055/why-does-changing-a-dataframe-in-one-jupyter-cell-also-change-another-variable
python, pandas, dataframe, jupyter-notebook, copy
1,759,988,089
se_42708193
stackoverflow
DATA_SCIENCE
When pivoting a Pandas dataframe, how do I make the column names the same as in R? (flat, label in column names)
When pivoting a Pandas dataframe, how do I make the column names the same as in R? (flat, label in column names) I have a dataframe (df) that looks like this: +---------+-------+------------+----------+ | subject | pills | date | strength | +---------+-------+------------+----------+ | 1 | 4 | 10/10/20...
https://stackoverflow.com/questions/42708193/when-pivoting-a-pandas-dataframe-how-do-i-make-the-column-names-the-same-as-in
python, pandas, pivot, reshape
1,489,106,887
se_79785896
stackoverflow
DATA_SCIENCE
Reconfigure a Pandas Dataframe
Reconfigure a Pandas Dataframe Our old ERP system generates orphaned HTML reports with the following format which I import into Pandas Work Order Item Type Material Labor 0 552603 Budget 71119 4567 1 552603 Actual 34745 212 2 789101 Budget 580 4522 3 789101 Act...
https://stackoverflow.com/questions/79785896/reconfigure-a-pandas-dataframe
python, pandas, dataframe, data-engineering
1,759,962,394
se_56948444
stackoverflow
DATA_SCIENCE
A vectorized approach to create a new column in pandas dataframe with a value from another column but not same row
A vectorized approach to create a new column in pandas dataframe with a value from another column but not same row I need to create a new column from the existing values of a column, based on on a matching condition with another column. But the value to be filled may or may not from the same row. I have implemented th...
https://stackoverflow.com/questions/56948444/a-vectorized-approach-to-create-a-new-column-in-pandas-dataframe-with-a-value-fr
python, pandas, database, dataframe
1,562,661,155
se_79784978
stackoverflow
DATA_SCIENCE
Importing a table from a webpage as a dataframe in Python
Importing a table from a webpage as a dataframe in Python I am trying to read in a specific table from the US Customs and Border Protection's Dashboard on Southwest Land Border Encounters as a dataframe. The url is: https://www.cbp.gov/newsroom/stats/southwest-land-border-encounters. I am particularly interested in th...
https://stackoverflow.com/questions/79784978/importing-a-table-from-a-webpage-as-a-dataframe-in-python
python, pandas, web-scraping
1,759,877,812
se_79785397
stackoverflow
DATA_SCIENCE
Why does Pandas not recognise my sqlalchemy connection engine?
Why does Pandas not recognise my sqlalchemy connection engine? I'm trying to connect to an IBM DB2 database from Python. I'm using Python 3.12.10, SQLAlchemy 1.4.54, and Pandas 2.3.2. This is what my code looks like: import os import sqlalchemy import pandas as pd from keyring import get_credential if os.name == "nt"...
https://stackoverflow.com/questions/79785397/why-does-pandas-not-recognise-my-sqlalchemy-connection-engine
python, pandas, sqlalchemy, db2
1,759,922,344
se_30718231
stackoverflow
DATA_SCIENCE
Aggregating in pandas groupby using lambda functions
Aggregating in pandas groupby using lambda functions I have an aggregation statement below: data = data.groupby(['type', 'status', 'name']).agg({ 'one' : np.mean, 'two' : lambda value: 100* ((value>32).sum() / reading.mean()), 'test2': lambda value: 100* ((value > 45).sum() / value.mean()) }) I get KeyE...
https://stackoverflow.com/questions/30718231/aggregating-in-pandas-groupby-using-lambda-functions
python, pandas, numpy, lambda, group-by
1,433,794,366
se_77900971
stackoverflow
DATA_SCIENCE
pandas FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version
pandas FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version In order to print dataframes nicely using tabulate, so that NaN and NaT are printed as empty cells, I've been using this successfully: print(tabulate(df.astype(object).fillna(""))) Now, t...
https://stackoverflow.com/questions/77900971/pandas-futurewarning-downcasting-object-dtype-arrays-on-fillna-ffill-bfill
python, pandas, downcast
1,706,543,690
se_77962778
stackoverflow
DATA_SCIENCE
How to delete CELLS and shift to right in Pandas Dataframe
How to delete CELLS and shift to right in Pandas Dataframe So I have a below table P Q R | -------- | --------| -------- | Performan| Dispite | Cammmr | Dispo | camera | battery | Perfumo | Displu | Cammmmt | Disper | camera | battery | Dispite | camera | battery so I want the...
https://stackoverflow.com/questions/77962778/how-to-delete-cells-and-shift-to-right-in-pandas-dataframe
python, pandas, startswith
1,707,405,385
se_79780171
stackoverflow
DATA_SCIENCE
Different Date Formats In Same Column
Different Date Formats In Same Column I've a dataset having a column: Joining_date with different date formats. I want to convert them in a one same date format df['Joining_Date'] 0 2016-10-26 2 16/08/2018 3 2017/06/28 6 2021-05-29 9 01-28-13 12 2021-05-26 13 2018-04-06...
https://stackoverflow.com/questions/79780171/different-date-formats-in-same-column
python, pandas, datetime-format
1,759,328,466
se_69230690
stackoverflow
DATA_SCIENCE
How to increase row height in Pandas?
How to increase row height in Pandas? There are good answers on how to change column width in pandas dataframes, for example here but I couldn't find anything describing how we can change row height? I'm trying to view two long texts side by side to compare them and I'd like to increase the row height to make it easie...
https://stackoverflow.com/questions/69230690/how-to-increase-row-height-in-pandas
python, pandas, nlp
1,631,925,292
se_79784134
stackoverflow
DATA_SCIENCE
How to count pandas DataFrame cells using unique cell values as rows and columns
How to count pandas DataFrame cells using unique cell values as rows and columns Let's say I have a DataFrame df like this: pd.DataFrame({'Planet':['Planet_1','Planet_1','Planet_2','Planet_2','Planet_3','Planet_3'],'FeatureType':['Lake','Lake','Crater','Volcano','Lake','Canyon'],'FeatureName':['Floop','Xoop','Goop','Z...
https://stackoverflow.com/questions/79784134/how-to-count-pandas-dataframe-cells-using-unique-cell-values-as-rows-and-columns
python, pandas, dataframe
1,759,793,796
se_79774466
stackoverflow
DATA_SCIENCE
How to export a Jupyter Notebook with plots and rich formatting to PDF without losing formatting?
How to export a Jupyter Notebook with plots and rich formatting to PDF without losing formatting? I am using Jupyter Notebook inside an Anaconda virtual environment and I have a notebook with multiple plots using matplotlib and pandas DataFrames with styled formatting. When I try to export the notebook to PDF via File...
https://stackoverflow.com/questions/79774466/how-to-export-a-jupyter-notebook-with-plots-and-rich-formatting-to-pdf-without-l
python, pandas, matplotlib, pdf, jupyter-notebook
1,758,783,700
se_79783318
stackoverflow
DATA_SCIENCE
Plotly - add dropdown list or buttons to OHLC / Candlestick graph
Plotly - add dropdown list or buttons to OHLC / Candlestick graph I have the following dataframe: lst = [['10/01/2025 8:30:00', 2.74, 2.87, 2.60, 2.65, 14, 'SPXW251001P06590000', 'P', 6590], ['10/01/2025 8:31:00', 2.80, 2.80, 2.50, 2.53, 61, 'SPXW251001P06590000', 'P', 6590], ['10/01/2025 8:32:00', 2.45,...
https://stackoverflow.com/questions/79783318/plotly-add-dropdown-list-or-buttons-to-ohlc-candlestick-graph
python, pandas, plotly, plotly-dash
1,759,716,961
se_77115274
stackoverflow
DATA_SCIENCE
copy a dataframe to new variable with method chaining
copy a dataframe to new variable with method chaining Is it possible to copy a dataframe in the middle of a method chain to a new variable? Something like: import pandas as pd df = (pd.DataFrame([[2, 4, 6], [8, 10, 12], [14, 16, 18], ]) .assign(somethi...
https://stackoverflow.com/questions/77115274/copy-a-dataframe-to-new-variable-with-method-chaining
python, pandas, method-chaining
1,694,810,787
se_59895729
stackoverflow
DATA_SCIENCE
How to parse xml from requests?
How to parse xml from requests? Here's my code, which you can run without any API key: import requests r = requests.get('http://api.worldbank.org/v2/country/GBR/indicator/NY.GDP.MKTP.KD.ZG') If I print r.text, I get a string that starts with '\ufeff<?xml version="1.0" encoding="utf-8"?>\r\n<wb:data page="1" pages="2...
https://stackoverflow.com/questions/59895729/how-to-parse-xml-from-requests
python, xml, pandas, python-requests
1,579,866,009
se_53840372
stackoverflow
DATA_SCIENCE
Error while trying to read a csv using pandas.
Error while trying to read a csv using pandas. My xor.csv is: x1,x2,x3,x4,y 0,0,0,0,0 0,0,0,1,1 0,0,1,0,1 0,0,1,1,0 0,1,0,0,1 0,1,0,1,0 0,1,1,0,0 0,1,1,1,1 Code to fetch this file using pandas is: import numpy as np import pandas as pd import matplotlib.pyplot as plt testing_data = pd.read_csv('..\Data_Set\xo...
https://stackoverflow.com/questions/53840372/error-while-trying-to-read-a-csv-using-pandas
python, pandas
1,545,164,005
se_63904201
stackoverflow
DATA_SCIENCE
Cleaning a dataset and removing special characters in Python
Cleaning a dataset and removing special characters in Python I am fairly new to all of this so apologies in advance. I've got a dataset (.csv). One column contains strings with whole sentences. These sentences contain misinterpreted utf-8 characters like ’ and emojis like 🥳. So the dataframe (df) looks kind of li...
https://stackoverflow.com/questions/63904201/cleaning-a-dataset-and-removing-special-characters-in-python
python, pandas, data-cleaning
1,600,180,704
se_79780994
stackoverflow
DATA_SCIENCE
How to efficiently handle lookups between resampled and original DataFrames in Pandas?
How to efficiently handle lookups between resampled and original DataFrames in Pandas? I am building a backtesting project in Python using Pandas. I have: A large tick / 1-minute level DataFrame (df) with full market data. A 15-minute interval DataFrame (df_15) created from it using resampling. In my strategy, I ca...
https://stackoverflow.com/questions/79780994/how-to-efficiently-handle-lookups-between-resampled-and-original-dataframes-in-p
python, pandas, dataframe
1,759,414,077
se_67414868
stackoverflow
DATA_SCIENCE
setting index value to np.uint64 in a panda dataframe changes its type to int64
setting index value to np.uint64 in a panda dataframe changes its type to int64 I am trying to set the dtype on the index of a panda dataframe import pandas as pd import numpy as np a = pd.DataFrame(columns=['value']) a.loc[np.uint64(3)] = [3] # Here I would expect to get UINT64 but it's INT64 a.index.dtype > dtype('...
https://stackoverflow.com/questions/67414868/setting-index-value-to-np-uint64-in-a-panda-dataframe-changes-its-type-to-int64
pandas, dataframe, uint64, dtype
1,620,291,270
se_21546739
stackoverflow
DATA_SCIENCE
Load data from txt with pandas
Load data from txt with pandas I am loading a txt file containig a mix of float and string data. I want to store them in an array where I can access each element. Now I am just doing import pandas as pd data = pd.read_csv('output_list.txt', header = None) print data Each line in the input file looks like the followi...
https://stackoverflow.com/questions/21546739/load-data-from-txt-with-pandas
python, pandas, file-io
1,391,500,138
se_70371193
stackoverflow
DATA_SCIENCE
Map float ranges in pandas.series to strings in dictionary and save to dataframe
Map float ranges in pandas.series to strings in dictionary and save to dataframe I would like a simple method for mapping float ranges to strings and saving back to a dataframe. I understand you can not use range() with floats. setup df import pandas as pd d = [1.1, 5.6, 7.9, 6.2] df = pd.DataFrame(data=d) Mapping di...
https://stackoverflow.com/questions/70371193/map-float-ranges-in-pandas-series-to-strings-in-dictionary-and-save-to-dataframe
python, pandas, dataframe
1,639,608,057
se_61609286
stackoverflow
DATA_SCIENCE
How to convert rows into columns but only for part of a table in python?
How to convert rows into columns but only for part of a table in python? I have a table which has the same structure as the below simplified example: I would like to convert Columns 1 and 2 into column headers with values in the columns being found in C1 value and C2 value. The rest of the table needs to remain un...
https://stackoverflow.com/questions/61609286/how-to-convert-rows-into-columns-but-only-for-part-of-a-table-in-python
python, pandas, pivot-table, transpose
1,588,668,713
se_76009318
stackoverflow
DATA_SCIENCE
Python Vectorization Split String
Python Vectorization Split String I want to use vectorization to create a column in a pandas data frame that retrieve the second/last part of a string, from each row in a column, that is split on '_'. I tried this code: df = pd.DataFrame() df['Var1'] = ["test1_test2","test3_test4"] df['Var2'] = [[df['Var1'].str.split...
https://stackoverflow.com/questions/76009318/python-vectorization-split-string
python, pandas, string, split, vectorization
1,681,415,372
se_79780371
stackoverflow
DATA_SCIENCE
Pandas dataFrame standard deviation issue
Pandas dataFrame standard deviation issue I have this details. import pandas as pd import numpy as np # Sample dataset data = { "date": pd.date_range("2025-10-01", periods=7), "sales": [200, 220, 250, np.nan, 300, 310, 305], "region": ["East", "West", "East", "West", "East", "West", "East"] } df = pd.Data...
https://stackoverflow.com/questions/79780371/pandas-dataframe-standard-deviation-issue
python, pandas, dataframe
1,759,343,972
se_62274461
stackoverflow
DATA_SCIENCE
Converting all columns of dtype &#39;object&#39; to &#39;float&#39; in Python/Pandas
Converting all columns of dtype &#39;object&#39; to &#39;float&#39; in Python/Pandas I wanted to convert all the 'object' type columns to another data type (float) in a dataframe without hard coding the column names. I was able to piece together some code from other answers that seems to work, but I feel like there's ...
https://stackoverflow.com/questions/62274461/converting-all-columns-of-dtype-object-to-float-in-python-pandas
python, pandas, type-conversion
1,591,672,839
se_79777562
stackoverflow
DATA_SCIENCE
Use-case for interpolation (pandas) and linear space (numpy)
Use-case for interpolation (pandas) and linear space (numpy) What is the difference between using an interpolation in the pandas package and the linear space of the numpy package? For instance in the following: import numpy as np import pandas as pd In [12]: np.linspace(1, 4, 7) Out[12]: array([1. , 1.5, 2. , 2.5, 3...
https://stackoverflow.com/questions/79777562/use-case-for-interpolation-pandas-and-linear-space-numpy
python, pandas, numpy
1,759,088,897
se_79778330
stackoverflow
DATA_SCIENCE
Efficient way to extract substrings (like date and strike price) from filenames in Pandas
Efficient way to extract substrings (like date and strike price) from filenames in Pandas I’m working on a project where I process a large dataset of CSV files. Each file has a name like this: NATURALGAS21FEB25270CE.MCX and here i want to extract the following things -: 21FEB25 -DATE 270-Price CE-type Although there ...
https://stackoverflow.com/questions/79778330/efficient-way-to-extract-substrings-like-date-and-strike-price-from-filenames
python, pandas
1,759,161,550
se_76170153
stackoverflow
DATA_SCIENCE
Plotly: how to change z-order of traces
Plotly: how to change z-order of traces I am having an issue with the order in which my Plotly.express and Plotly.graph_objects plots are showing up. My scatter plot is plotting in front of my grey shaded continuous errors. I have tried manually changing the order of the traces via updating each traces position in th...
https://stackoverflow.com/questions/76170153/plotly-how-to-change-z-order-of-traces
python, pandas, plotly, plotly-express
1,683,181,587
se_79778443
stackoverflow
DATA_SCIENCE
How to transfer Python variables from one Flask view to another?
How to transfer Python variables from one Flask view to another? I am working on a Flask app constructed as follows: The starting HTML template, controlled by a view, displays a text box, where the user can enter a SQL request to request a SQLite database connected to the app. In a second view, the request is execute...
https://stackoverflow.com/questions/79778443/how-to-transfer-python-variables-from-one-flask-view-to-another
python, pandas, flask
1,759,171,304
se_79777919
stackoverflow
DATA_SCIENCE
Is there a way to complement / supplement a stubs package with additional type information in a stubs file?
Is there a way to complement / supplement a stubs package with additional type information in a stubs file? I am using pyright in strict mode and I would like to avoid littering my code with exceptions telling pyright to ignore some line. I have been using my own stub file to great success in the case of dependencies ...
https://stackoverflow.com/questions/79777919/is-there-a-way-to-complement-supplement-a-stubs-package-with-additional-type-i
python, pandas, pyright
1,759,136,227
se_79777484
stackoverflow
DATA_SCIENCE
I can not get the storms to appear on graph and it is not plotting right
I can not get the storms to appear on graph and it is not plotting right This is what I have to do The police department has requested the creation of a Storm and Crime Data Report (SCDR) using historical data from the city of Miami for the calendar year 2024. Miami police have made a connection linking an increase in...
https://stackoverflow.com/questions/79777484/i-can-not-get-the-storms-to-appear-on-graph-and-it-is-not-plotting-right
python, pandas, matplotlib
1,759,080,940
se_79777410
stackoverflow
DATA_SCIENCE
When should I use .copy() after filtering a DataFrame in pandas?
When should I use .copy() after filtering a DataFrame in pandas? I am working on a project where I frequently filter my DataFrame and then return it for further processing. For example, in one file I have this code: df = df[df['Ticker'].str.startswith("NATURALGAS", na=False)].copy() I am a bit confused about the foll...
https://stackoverflow.com/questions/79777410/when-should-i-use-copy-after-filtering-a-dataframe-in-pandas
python, pandas, copy, startswith
1,759,072,887
se_79776615
stackoverflow
DATA_SCIENCE
Find percentage of grouped variable in a Dataframe in pandas
Find percentage of grouped variable in a Dataframe in pandas I have a dataframe where column 1 has values like 'A', 'B' etc (categorical variable) and column 2 (also a nominal categorical variable) has values like 'city 1', 'city 2' etc. I want to group by column 1 and find out percentage of 'city 1' in each category ...
https://stackoverflow.com/questions/79776615/find-percentage-of-grouped-variable-in-a-dataframe-in-pandas
python, pandas, dataframe
1,758,961,285
se_50985481
stackoverflow
DATA_SCIENCE
pandas how to add details to csv before writing a data frame
pandas how to add details to csv before writing a data frame I need to write to a csv file that has 3-5 lines(rows) of details about the file, followed by 3 rows of blank lines before I can append a data frame. Here is how the file should look like. (Note: lines having '#' are comments for demonstration) some details ...
https://stackoverflow.com/questions/50985481/pandas-how-to-add-details-to-csv-before-writing-a-data-frame
python, pandas, export-to-csv
1,529,661,583
se_79776565
stackoverflow
DATA_SCIENCE
How can I calculate XIRR from irregular cash flows in Python and validate results against Excel’s XIRR function?
How can I calculate XIRR from irregular cash flows in Python and validate results against Excel’s XIRR function? I am working on calculating the Extended Internal Rate of Return (XIRR) for a series of irregular cash flows using Python. The cash flows occur on uneven dates, and I want the result to match Excel’s XIRR f...
https://stackoverflow.com/questions/79776565/how-can-i-calculate-xirr-from-irregular-cash-flows-in-python-and-validate-result
python, pandas, finance, xirr
1,758,955,450
se_57681978
stackoverflow
DATA_SCIENCE
Python 3.x fill missing NaN values with the mode
Python 3.x fill missing NaN values with the mode I have programmed the following dataframe in Python: import pandas as pd import numpy as np def main(): x=pd.DataFrame(np.array([10,"worker","France", 20,"eng","Italy", 30,"doctor","Spain", ...
https://stackoverflow.com/questions/57681978/python-3-x-fill-missing-nan-values-with-the-mode
python, pandas
1,566,938,462
se_44533880
stackoverflow
DATA_SCIENCE
Custom pandas Datetime offset / frequency for trading times: 9:30AM-4:00PM business days except US holidays
Custom pandas Datetime offset / frequency for trading times: 9:30AM-4:00PM business days except US holidays Trading data is recorded on non-holiday business days starting at 9:30AM, and data is recorded periodically (5 seconds, 5 minutes, 30 minutes, etc) until 4:00PM. For instance, [9:30AM, 9:35AM,...,3:50PM, 3:55PM...
https://stackoverflow.com/questions/44533880/custom-pandas-datetime-offset-frequency-for-trading-times-930am-400pm-busin
pandas, datetime, time-series, algorithmic-trading, datetimeindex
1,497,403,031
se_53218931
stackoverflow
DATA_SCIENCE
How to unnest (explode) a column in a pandas DataFrame, into multiple rows
How to unnest (explode) a column in a pandas DataFrame, into multiple rows I have the following DataFrame where one of the columns is an object (list type cell): df = pd.DataFrame({'A': [1, 2], 'B': [[1, 2], [1, 2]]}) Output: A B 0 1 [1, 2] 1 2 [1, 2] My expected output is: A B 0 1 1 1 1 2 3 2 ...
https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe-into-multiple-rows
python, pandas, dataframe, pandas-explode
1,541,729,962
se_12680754
stackoverflow
DATA_SCIENCE
Split (explode) pandas dataframe string entry to separate rows
Split (explode) pandas dataframe string entry to separate rows I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, a should become b: In [7]: ...
https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows
python, pandas, numpy, dataframe
1,349,124,136
se_79775605
stackoverflow
DATA_SCIENCE
What is the best way in pandas (or Python) to “explode” the list of cities into separate rows?
What is the best way in pandas (or Python) to “explode” the list of cities into separate rows? I am learning data science and working with JSON data. Suppose I have a JSON file with provinces and their populations, but each province also has a list of cities. For example: When I load this into pandas: import pandas as...
https://stackoverflow.com/questions/79775605/what-is-the-best-way-in-pandas-or-python-to-explode-the-list-of-cities-into
python, pandas
1,758,873,523
se_71253017
stackoverflow
DATA_SCIENCE
Using ILIKE with parameters in Python with pd.read_sql and psycopg2
Using ILIKE with parameters in Python with pd.read_sql and psycopg2 This query runs without problem in SQL (PostgreSQL database): SELECT number_column FROM number_table WHERE number_column ILIKE ANY (array[ '%57244048699%', '%150310003808%', ...
https://stackoverflow.com/questions/71253017/using-ilike-with-parameters-in-python-with-pd-read-sql-and-psycopg2
python, pandas, postgresql, psycopg2
1,645,710,632
se_19384532
stackoverflow
DATA_SCIENCE
Get statistics for each group (such as count, mean, etc) using pandas GroupBy?
Get statistics for each group (such as count, mean, etc) using pandas GroupBy? I have a dataframe df and I use several columns from it to groupby: df[['col1','col2','col3','col4']].groupby(['col1','col2']).mean() In the above way, I almost get the table (dataframe) that I need. What is missing is an additional column...
https://stackoverflow.com/questions/19384532/get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby
python, pandas, dataframe, group-by, statistics
1,381,849,212
se_79774320
stackoverflow
DATA_SCIENCE
Databricks Cleanroom: Does Invited Collaborator have capability to adjust Timeout Error Timer?
Databricks Cleanroom: Does Invited Collaborator have capability to adjust Timeout Error Timer? I am running tests on a notebook from within Databricks' "Cleanroom" environment (therefore it is run on serverless compute managed by Databricks). Im running into the following timeout error when running some test job runs ...
https://stackoverflow.com/questions/79774320/databricks-cleanroom-does-invited-collaborator-have-capability-to-adjust-timeou
python, pandas, pyspark, databricks, azure-databricks
1,758,766,733
se_72577475
stackoverflow
DATA_SCIENCE
How to randomly select a single value in Pandas data frame
How to randomly select a single value in Pandas data frame I was searching forever to find an answer to this and no one seemed to have asked, so I am asking and providing my answer here. How do you randomly select a single cell value in pandas data frame? It is really simple. I was struggling finding the syntax for th...
https://stackoverflow.com/questions/72577475/how-to-randomly-select-a-single-value-in-pandas-data-frame
python, pandas
1,654,879,328
se_79773594
stackoverflow
DATA_SCIENCE
Overwrite Excel/CSV with pandas while file is open
Overwrite Excel/CSV with pandas while file is open Is it possible to overwrite and save a DataFrame to an Excel or CSV file if that file is already open? I tried using df.to_excel("file.xlsx", index=False) to overwrite an existing Excel file that I had open. I expected pandas to save the df and replace the file conten...
https://stackoverflow.com/questions/79773594/overwrite-excel-csv-with-pandas-while-file-is-open
python, pandas, dataframe, export-to-csv, export-to-excel
1,758,709,621
se_79765484
stackoverflow
DATA_SCIENCE
Why does Pandera print failing rows with pa.check() and a lambda function but not on a column check?
Why does Pandera print failing rows with pa.check() and a lambda function but not on a column check? New to using Pandera. I want it to print the record(s) that fail the check. This is the simple check I want, fail when the system capacity is over 500: import pandera.pandas as pa import pandas as pd schema = pa.DataFr...
https://stackoverflow.com/questions/79765484/why-does-pandera-print-failing-rows-with-pa-check-and-a-lambda-function-but-no
python, pandas, pandera
1,757,960,643
se_62435533
stackoverflow
DATA_SCIENCE
Converting series element to int
Converting series element to int I have a pandas series- 3959 2019 Name: DATE, dtype: int64 which has only one element. I wanted to convert that element to integer. I did- for i in last_row_year.to_numpy(): last_year=i to get last_year as 2019 (int type) Is there a more pythonic way to do this?
https://stackoverflow.com/questions/62435533/converting-series-element-to-int
python, pandas
1,592,416,954
se_61854550
stackoverflow
DATA_SCIENCE
Pandas Compare two data frames and look for duplicate elements
Pandas Compare two data frames and look for duplicate elements I want to compare df and df_equal. df contains several individual data frames import pandas as pd df1 = pd.DataFrame([[ 'b', 'b', 'b' ]], columns=['a', 'b', 'c']) Output: a b c 0 b b b df2 = pd.DataFrame([[ 'x', 'x', ...
https://stackoverflow.com/questions/61854550/pandas-compare-two-data-frames-and-look-for-duplicate-elements
python, pandas, data-science, equality
1,589,730,474
se_79772749
stackoverflow
DATA_SCIENCE
How to set background seaborn style in a multi-plot figure with subplot()
How to set background seaborn style in a multi-plot figure with subplot() I have a multi-plot bar plot figure produced with matplotlib/ seaborn and I'd like to control the tick lines and background style. When I try to use sns.set_style("whitegrid"), the background is grey/ not whitegrid. Example data, similar structu...
https://stackoverflow.com/questions/79772749/how-to-set-background-seaborn-style-in-a-multi-plot-figure-with-subplot
python, pandas, matplotlib, seaborn
1,758,638,765
se_61195623
stackoverflow
DATA_SCIENCE
Python: How to save a JSON file without brackets?
Python: How to save a JSON file without brackets? I'm trying to generate a JSON file, however it's generating with brackets which is not intended. How can I overcome this? Code: import pandas as pd df = pd.DataFrame({"A": [10], "B": [20], "C": [30]}) df.to_json('file.json', or...
https://stackoverflow.com/questions/61195623/python-how-to-save-a-json-file-without-brackets
python, json, python-3.x, pandas
1,586,807,496
se_51711750
stackoverflow
DATA_SCIENCE
Read Relative Lines in a text document and convert to Pandas DF
Read Relative Lines in a text document and convert to Pandas DF Working on a Python 3.6 read of a text file to extract relative lines to convert into a pandas dataframe. What works: Searching for a phrase in a text document and converting the line into a pandas df. import pandas as pd df = pd.DataFrame() list1 = []...
https://stackoverflow.com/questions/51711750/read-relative-lines-in-a-text-document-and-convert-to-pandas-df
python, pandas, search, python-3.6
1,533,571,913
se_71678938
stackoverflow
DATA_SCIENCE
Python packages blocked by group policy
Python packages blocked by group policy I'm trying to set up Python on my work computer. I'm able to install packages via pip after getting it unblocked. That was easy since it's just a .exe file for them to unblock. I'm trying to use pandas/numpy and I get the error saying it was blocked by group policy. In the same ...
https://stackoverflow.com/questions/71678938/python-packages-blocked-by-group-policy
python, pandas, numpy, group-policy, applocker
1,648,649,859
se_53045122
stackoverflow
DATA_SCIENCE
Filter data based on two columns from another dataframe
Filter data based on two columns from another dataframe I have the following two dataframes: df = pd.DataFrame({ 'id': ['1', '1', '2', '3', '3', '8','4', '1', '2', '4'], 'start': ['2017-01-01', '2017-02-01', '2017-03-01', '2017-02-01', '2017-03-01', '2017-04-01', '2017-01-01', '2017-04-01', '2017-05-01', '201...
https://stackoverflow.com/questions/53045122/filter-data-based-on-two-columns-from-another-dataframe
python, pandas, dataframe, python-3.5
1,540,814,619
se_51751961
stackoverflow
DATA_SCIENCE
Pandas - adding a column based on multiple conditions
Pandas - adding a column based on multiple conditions trying to add a boolean column to a df based on two mutually exclusive conditions: df['Type'] == 'CMBX' df['SubType'].isin(['EM','NAHY']) they work separately df['Px Quoted'] = np.where(df['Type'] =='CMBX', True, False) df[df['Type']=='CMBX'].head(5) Out[72]: ...
https://stackoverflow.com/questions/51751961/pandas-adding-a-column-based-on-multiple-conditions
python, pandas
1,533,747,521
se_54652103
stackoverflow
DATA_SCIENCE
Updating a pandas column with a dictionary lookup
Updating a pandas column with a dictionary lookup Have a dataframe, df: import pandas as pd import numpy as np i = ['dog', 'cat', 'rabbit', 'elephant'] * 3 df = pd.DataFrame(np.random.randn(12, 2), index=i, columns=list('AB')) ...and a lookup dict for column B: b_dict = {'elephant': 2.0, 'dog': 5.0} How can col...
https://stackoverflow.com/questions/54652103/updating-a-pandas-column-with-a-dictionary-lookup
python, pandas
1,549,981,118
se_54651361
stackoverflow
DATA_SCIENCE
Find count of a column in pandas dataframe based on condition
Find count of a column in pandas dataframe based on condition I am using below method to find count of a pandas dataframe having 55k rows. This is included in a for loop of site list (4000 sites). It is taking many minutes to complete the loop of 4000 sites when below line is included. for i in g_sitelist: x = le...
https://stackoverflow.com/questions/54651361/find-count-of-a-column-in-pandas-dataframe-based-on-condition
python, python-3.x, pandas, dataframe
1,549,978,645
se_55570596
stackoverflow
DATA_SCIENCE
get count of entries less or equal in Series
get count of entries less or equal in Series I want to get the count of all elements less or equal to each entry in a pandas.Series eg: if __name__ == '__main__': import pandas as pd a = pd.Series(data=[4,7,3,5,2,1,1,6]) le = pd.Series(data=[a[a <= i].count() for i in a]) print(le) Result: 0 5 1...
https://stackoverflow.com/questions/55570596/get-count-of-entries-less-or-equal-in-series
python, pandas
1,554,716,846
se_41624241
stackoverflow
DATA_SCIENCE
Pandas Split Dataframe into two Dataframes at a specific column
Pandas Split Dataframe into two Dataframes at a specific column I have pandas DataFrame which I have composed from concat. One row consists of 96 values, I would like to split the DataFrame from the value 72. So that the first 72 values of a row are stored in Dataframe1, and the next 24 values of a row in Dataframe2....
https://stackoverflow.com/questions/41624241/pandas-split-dataframe-into-two-dataframes-at-a-specific-column
python, pandas, numpy, dataframe
1,484,260,423
se_24685012
stackoverflow
DATA_SCIENCE
Renaming multiple identically named columns in Pandas DataFrame
Renaming multiple identically named columns in Pandas DataFrame I have several columns named the same in a df. I need to rename them but the problem is that the df.rename method renames them all the same way. How I can rename the below blah(s) to blah1, blah4, blah5? df = pd.DataFrame(np.arange(2*5).reshape(2,5)) df.c...
https://stackoverflow.com/questions/24685012/renaming-multiple-identically-named-columns-in-pandas-dataframe
python, pandas
1,405,021,573
se_53054694
stackoverflow
DATA_SCIENCE
Python Dataframe that calculate percentage change by lambda
Python Dataframe that calculate percentage change by lambda How could I calculate the percentage change in python dataframe using lambda? The dataframe: and I would like to calculate the percentage change of volume of each row. The result should be like: I tried that: df.Volume.map(lambda x: ((df.Volumne.iloc[i+1])-...
https://stackoverflow.com/questions/53054694/python-dataframe-that-calculate-percentage-change-by-lambda
python, pandas, lambda
1,540,851,432
se_79770363
stackoverflow
DATA_SCIENCE
Tiingo Python Pandas Datetime
Tiingo Python Pandas Datetime I am grabbing OHLC stock price data from tiingo using the following code: df = get_tiingo_data(ticker, start_date="1990-01-01", end_date="2025-12-31") Which calls this function: def get_tiingo_data(ticker, start_date, end_date): url = f"https://api.tiingo.com/tiingo/daily/{ticker}/pri...
https://stackoverflow.com/questions/79770363/tiingo-python-pandas-datetime
python, pandas, tiingo
1,758,379,248
se_58521976
stackoverflow
DATA_SCIENCE
psycopg2 error : literal carriage return found in data
psycopg2 error : literal carriage return found in data I am trying to push data from a python dataframe to Postgres database using psycopg2 and sqlalchemy. This is the script - from sqlalchemy import create_engine import psycopg2 as pg import io address = 'postgresql://username:password@dbname.endpoint.rds.amazonaws...
https://stackoverflow.com/questions/58521976/psycopg2-error-literal-carriage-return-found-in-data
python, pandas, postgresql, csv, psycopg2
1,571,830,542
se_79769815
stackoverflow
DATA_SCIENCE
Some pieces are missing in my Python First Fit Decreasing bar cutting algorithm
Some pieces are missing in my Python First Fit Decreasing bar cutting algorithm I'm implementing a bar cutting optimization in Python using the First Fit Decreasing (FFD) algorithm. I have a list of orders, each with a quantity and length. The code should allocate all pieces into bars of fixed length (6000mm) and gene...
https://stackoverflow.com/questions/79769815/some-pieces-are-missing-in-my-python-first-fit-decreasing-bar-cutting-algorithm
python, pandas
1,758,304,415
se_79769512
stackoverflow
DATA_SCIENCE
Tring to get data from yfinance for timeframe for 2 days, but getting an error when aggreagating the data
Tring to get data from yfinance for timeframe for 2 days, but getting an error when aggreagating the data I'm trying to get some data with yfinance, but I'm trying to get the timeframe for 2 days, which doesn't exist by default for yfinance. So, I tried to agreggate 1 day + 1 day. But I'm getting an error in trying to...
https://stackoverflow.com/questions/79769512/tring-to-get-data-from-yfinance-for-timeframe-for-2-days-but-getting-an-error-w
python, pandas, dataframe, yfinance
1,758,285,666
se_56669718
stackoverflow
DATA_SCIENCE
How to get the source code for property in python
How to get the source code for property in python I want to programmatically get the source code for a given class property (e.g., pandas.DataFrame.iloc). I tried using inspect.findsource(), which works fine for classes and functions. However, it doesn't work for properties. import pandas import inspect type(pandas....
https://stackoverflow.com/questions/56669718/how-to-get-the-source-code-for-property-in-python
python, pandas, python-inspect
1,560,953,343
se_79754742
stackoverflow
DATA_SCIENCE
How to read LZO compressed pandas HDF5 files?
How to read LZO compressed pandas HDF5 files? Here is the situation: I have data saved into pandas HDF5 files. Some data is compressed using lzo and some using blosc:zstd. Under RHEL-7, I was able to read both types of files. Then, I was forcefully upgraded to RHEL-8 by our IT. Since then, I can only read blosc:zstd c...
https://stackoverflow.com/questions/79754742/how-to-read-lzo-compressed-pandas-hdf5-files
pandas, hdf5, pytables, lzo, blosc
1,756,910,199
se_79769175
stackoverflow
DATA_SCIENCE
Convert dataframe of boolean values to list of ranges where value is True. (eg. output: &quot;column-header, 24-79&quot;)
Convert dataframe of boolean values to list of ranges where value is True. (eg. output: &quot;column-header, 24-79&quot;) My goal is to compare the contents of two 2-d arrays (~15k rows, 8 columns) and get a list of the rows/columns where the comparison (greater-than) is true. I need that output in a readable format, ...
https://stackoverflow.com/questions/79769175/convert-dataframe-of-boolean-values-to-list-of-ranges-where-value-is-true-eg
python, pandas, tuples
1,758,262,129
se_77899043
stackoverflow
DATA_SCIENCE
How to catch DateParseError in pandas?
How to catch DateParseError in pandas? I am running a script that uses pd.to_datetime() on inputs that are sometime not able to be parsed. For example if I try to run pd.to_datetime('yesterday') it results to an error DateParseError: Unknown datetime string format, unable to parse: yesterday, at position 0 I 'd like t...
https://stackoverflow.com/questions/77899043/how-to-catch-dateparseerror-in-pandas
python, pandas, python-datetime
1,706,524,314
se_79768568
stackoverflow
DATA_SCIENCE
Conditionally updating values in the same dataframe, getting ValueError: Can only compare identically-labeled Series objects
Conditionally updating values in the same dataframe, getting ValueError: Can only compare identically-labeled Series objects I'm trying to update a DataFrame value in place and unable to do so. I've tried several different methods, none of which have worked. Looking up information online only gets me examples of compa...
https://stackoverflow.com/questions/79768568/conditionally-updating-values-in-the-same-dataframe-getting-valueerror-can-onl
python, pandas, dataframe
1,758,205,349
se_79768990
stackoverflow
DATA_SCIENCE
Saving a figure with the name of passed dataframe
Saving a figure with the name of passed dataframe I have a function that receives a pandas dataframe as an argument, plot it, and save the generated figure with the name of passed dataframe. . For instance this is the function: def plot_function(df): plt.figure(figsize=(8, 5)) plt.bar(df["x"], df["y"]) plt...
https://stackoverflow.com/questions/79768990/saving-a-figure-with-the-name-of-passed-dataframe
python, pandas, matplotlib
1,758,236,745
se_79768902
stackoverflow
DATA_SCIENCE
Sort each row of a pandas column consisting of delimited strings
Sort each row of a pandas column consisting of delimited strings CONTEXT Let's say I have df, which consists of a column of delimited strings that I would like to sort. import pandas as pd df = pd.DataFrame({'sort_me':['foo; bar','foo; bar','bar; foo']}) df sort_me 0 foo; bar 1 foo; bar 2 bar; foo DESIR...
https://stackoverflow.com/questions/79768902/sort-each-row-of-a-pandas-column-consisting-of-delimited-strings
python, pandas, dataframe, list, sorting
1,758,228,442
se_79768855
stackoverflow
DATA_SCIENCE
Adding subtotals to a pandas dataframe
Adding subtotals to a pandas dataframe I was looking to add subtotals to a pandas dataframe - a question which I found to be asked here often. The answers making use of the deprecated pd.append aren't relevant anymore so I figured a more up-to-date version could be useful, not only for me, but for others as well. The ...
https://stackoverflow.com/questions/79768855/adding-subtotals-to-a-pandas-dataframe
python, pandas, dataframe, subtotal
1,758,223,838
se_53893554
stackoverflow
DATA_SCIENCE
Transfer and write Parquet with python and pandas got timestamp error
Transfer and write Parquet with python and pandas got timestamp error I tried to concat() two parquet file with pandas in python . It can work , but when I try to write and save the Data frame to a parquet file ,it display the error : ArrowInvalid: Casting from timestamp[ns] to timestamp[ms] would lose data: I c...
https://stackoverflow.com/questions/53893554/transfer-and-write-parquet-with-python-and-pandas-got-timestamp-error
python, pandas, parquet
1,545,460,258
se_79767967
stackoverflow
DATA_SCIENCE
Making matplotlib boxplot include columns with NaN values
Making matplotlib boxplot include columns with NaN values I've been trying to plot a data frame as a box plot using matplotlib. My data frame looks something like this: 9-1 9-2 9-3 9-4 9-5 0 23 16.0 18.0 18.0 26 1 27 18.0 20.0 17.0 33 2 10 9.0 15.0 8.0 30 3 23 30.0 19.0 5.0 15 ...
https://stackoverflow.com/questions/79767967/making-matplotlib-boxplot-include-columns-with-nan-values
pandas, dataframe, matplotlib, nan, boxplot
1,758,167,573
se_59840150
stackoverflow
DATA_SCIENCE
Google Analytics Data to Pandas Dataframe
Google Analytics Data to Pandas Dataframe I'm trying to send google analytics data to a pandas dataframe using the google analytics api. I've followed along the code examples that are available in the official documentation and I now have code that manages to print out the data that I need. I need help figuring out ho...
https://stackoverflow.com/questions/59840150/google-analytics-data-to-pandas-dataframe
python, python-3.x, pandas, dataframe, google-analytics-api
1,579,606,051