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_72749009 | stackoverflow | DATA_SCIENCE | Pandas read_xml - AttributeError: module 'pandas' has no attribute 'read_xml' | Pandas read_xml - AttributeError: module 'pandas' has no attribute 'read_xml'
I ran into the error:
AttributeError: module 'pandas' has no attribute 'read_xml'
This would be a huge lifesaver if I could ingest the XML with one function into a pandas df without trying to iterate through etc.
I am runni... | https://stackoverflow.com/questions/72749009/pandas-read-xml-attributeerror-module-pandas-has-no-attribute-read-xml | python, pandas, xml, readxml | 1,656,101,858 |
se_46534653 | stackoverflow | DATA_SCIENCE | Error 'AttributeError: 'DataFrameGroupBy' object has no attribute' while groupby functionality on dataframe | Error 'AttributeError: 'DataFrameGroupBy' object has no attribute' while groupby functionality on dataframe
I have a dataframe news_count. Here are its column names, from the output of news_count.columns.values:
[('date', '') ('EBIX UW Equity', 'NEWS_SENTIMENT_DAILY_AVG') ('Date', '')
('day', '') (... | https://stackoverflow.com/questions/46534653/error-attributeerror-dataframegroupby-object-has-no-attribute-while-groupby | python, pandas, dataframe, group-by, pandas-groupby | 1,506,983,509 |
se_70575998 | stackoverflow | DATA_SCIENCE | Getting data from World Bank API using pandas | Getting data from World Bank API using pandas
I'm trying to obtain a table of data obtaining just the country, year and value from this World Bank API but I can't seem to filter for just the data I want. I've seen that these types of questions have already been asked but all the answers didn't seem to work.
Would real... | https://stackoverflow.com/questions/70575998/getting-data-from-world-bank-api-using-pandas | python, pandas, dataframe | 1,641,285,267 |
se_62615608 | stackoverflow | DATA_SCIENCE | Sum of null and empty values in pandas dataframe | Sum of null and empty values in pandas dataframe
I have a dataframe that contains both NULL values and empty strings.
As follows (with code for repro)
data = {'vals1': [None, '100', '', '200'],
'vals2': ['100', '100', '', ''],
'vals3': ['100', None, '100', None],
'vals4': ['', '', '', '']}
df ... | https://stackoverflow.com/questions/62615608/sum-of-null-and-empty-values-in-pandas-dataframe | python, pandas, string | 1,593,292,216 |
se_55168294 | stackoverflow | DATA_SCIENCE | Python Crosstabs Multiple Variables or Rows; Demographic Table | Python Crosstabs Multiple Variables or Rows; Demographic Table
I have a similar question to: Crosstab with multiple items but am not trying to do it in R, I am trying to do it in Python Pandas with Crosstab.
I have been trying to use Python Pandas crosstab function to make a demographic table, but have only been able ... | https://stackoverflow.com/questions/55168294/python-crosstabs-multiple-variables-or-rows-demographic-table | python, pandas | 1,552,583,015 |
se_54466196 | stackoverflow | DATA_SCIENCE | Descriptive statistics in Python /with Pandas with std in parentheses | Descriptive statistics in Python /with Pandas with std in parentheses
This question concerns the best-practice to do descriptive statistics in Python with a formatted output that correspond to tables found in academic publications: means with their respective standard deviations in parenthesis below. Final goal is to ... | https://stackoverflow.com/questions/54466196/descriptive-statistics-in-python-with-pandas-with-std-in-parentheses | python, pandas, statistics, statsmodels, standard-deviation | 1,548,955,897 |
se_22235245 | stackoverflow | DATA_SCIENCE | Calculate summary statistics of columns in dataframe | Calculate summary statistics of columns in dataframe
I have a dataframe of the following form (for example)
shopper_num,is_martian,number_of_items,count_pineapples,birth_country,tranpsortation_method
1,FALSE,0,0,MX,
2,FALSE,1,0,MX,
3,FALSE,0,0,MX,
4,FALSE,22,0,MX,
5,FALSE,0,0,MX,
6,FALSE,0,0,MX,
7,FALSE,5,0,MX,
8,FAL... | https://stackoverflow.com/questions/22235245/calculate-summary-statistics-of-columns-in-dataframe | python, pandas, csv, dataframe, profiling | 1,394,137,736 |
se_79927467 | stackoverflow | DATA_SCIENCE | After upgrading pandas from 0.25.1 to 2.1.4, group by user and ffill by month is way slower | After upgrading pandas from 0.25.1 to 2.1.4, group by user and ffill by month is way slower
I have monthly data in .csv format totaling around 10 million rows. I am creating a requisite dataframe from it and I noticed that the runtime to create that df increased from some 20 min to 8 hours with the upgrade of pandas ... | https://stackoverflow.com/questions/79927467/after-upgrading-pandas-from-0-25-1-to-2-1-4-group-by-user-and-ffill-by-month-is | python, pandas, dataframe | 1,776,437,766 |
se_60077438 | stackoverflow | DATA_SCIENCE | Color only header with pandas | Color only header with pandas
Is there a way to give a colour to the header of a dataframe column with pandas?
What I have now is:
def funct(x):
c1 = 'background-color: #add8e6'
df1 = pd.DataFrame('', index=x.index, columns = x.columns)
df1['Sales in pieces last 6 weeks'] = c1
return df1
sales_report.style.apply... | https://stackoverflow.com/questions/60077438/color-only-header-with-pandas | python, excel, pandas, header, styles | 1,580,911,053 |
se_73831165 | stackoverflow | DATA_SCIENCE | Python Sqlalchemy insert data into AWS Redshift | Python Sqlalchemy insert data into AWS Redshift
I want to load a large excel table data into AWS Redshift, using Python psycopg2 take a long time to load, so I try to use Sqlalchemy. but the redshift-sqlalchemy documentation is confusing. So I want to use the regular Sqlalchemy library. Below code can pull data from A... | https://stackoverflow.com/questions/73831165/python-sqlalchemy-insert-data-into-aws-redshift | python-3.x, pandas, amazon-web-services, sqlalchemy, amazon-redshift | 1,663,954,277 |
se_76485954 | stackoverflow | DATA_SCIENCE | Using Pandas,loading data from excel to redshift using python, able to load data. but when excel has 20000+ rows taking 7+ hours. way to optimize | Using Pandas,loading data from excel to redshift using python, able to load data. but when excel has 20000+ rows taking 7+ hours. way to optimize
I am experiencing slow performance when using Pandas to load data from an Excel file into an existing Redshift table. The Excel file has 10+ columns and 20000+ rows, and the... | https://stackoverflow.com/questions/76485954/using-pandas-loading-data-from-excel-to-redshift-using-python-able-to-load-data | python, pandas, amazon-redshift, psycopg2 | 1,686,869,324 |
se_74880220 | stackoverflow | DATA_SCIENCE | Groupby aggregate multiple columns with same function | Groupby aggregate multiple columns with same function
I am trying to do groupbyof this table. I have multiple value columns some of them I want to sum & some I want to count.
df_p = pd.DataFrame({'H1':['A1','A1','C1','B1','A1','C1'],
'H2':['X1','Y1','Z1','X1','Y1','Z1'],
'V1':... | https://stackoverflow.com/questions/74880220/groupby-aggregate-multiple-columns-with-same-function | python, pandas, group-by, aggregate | 1,671,646,529 |
se_79931483 | stackoverflow | DATA_SCIENCE | Fastest rolling window method for datetime | Fastest rolling window method for datetime
I'm currently trying to apply a bit of a convoluted function to a rolling window of 30 minutes on time data within a loop, and I'm finding that it's taking too long to be reasonable.
I've included a minimal example below that's currently coming in at 94 ms, which with the act... | https://stackoverflow.com/questions/79931483/fastest-rolling-window-method-for-datetime | python, pandas, datetime, optimization | 1,777,052,817 |
se_22591174 | stackoverflow | DATA_SCIENCE | pandas: multiple conditions while indexing data frame - unexpected behavior | pandas: multiple conditions while indexing data frame - unexpected behavior
I am filtering rows in a dataframe by values in two columns.
For some reason the OR operator behaves like I would expect AND operator to behave and vice versa.
My test code:
df = pd.DataFrame({'a': range(5), 'b': range(5) })
# let's insert so... | https://stackoverflow.com/questions/22591174/pandas-multiple-conditions-while-indexing-data-frame-unexpected-behavior | python, pandas, dataframe, indexing, conditional-statements | 1,395,579,179 |
se_79930922 | stackoverflow | DATA_SCIENCE | Pandas Multi-index behavior changes with number of indexes? | Pandas Multi-index behavior changes with number of indexes?
I had a multi-indexed pandas series with more than two levels in the row multi-index.
arrays = [
["bar", "baz", "foo", "qux"],
["one", "two",],
["a", "b","c" ]
]
index = pd.MultiIndex.from_product(arrays, names=["first", "second","third"])
s ... | https://stackoverflow.com/questions/79930922/pandas-multi-index-behavior-changes-with-number-of-indexes | python, pandas, multi-index | 1,776,972,107 |
se_79929586 | stackoverflow | DATA_SCIENCE | Incorrect time index in mdf file created in asammdf (python) | Incorrect time index in mdf file created in asammdf (python)
I am creating an mdf file from a pandas dataframe in python. Data is sampled at .015s rate. Issue I'm having is that the created mdf file shows the time index as being around 11 hrs total file time whereas the actual time length in the dataframe is around 9 ... | https://stackoverflow.com/questions/79929586/incorrect-time-index-in-mdf-file-created-in-asammdf-python | python, pandas, asammdf | 1,776,788,352 |
se_79929818 | stackoverflow | DATA_SCIENCE | Python 3.13.0 on Mac OS, jupyter notebook can't find pandas installed | Python 3.13.0 on Mac OS, jupyter notebook can't find pandas installed
I have installed pandas using
pip3 install pandas
In my terminal it works fine with no error
import pandas as pd
But I can't do so in Jupyter Notebook, this is the error:
------------------------------------------------------------------------... | https://stackoverflow.com/questions/79929818/python-3-13-0-on-mac-os-jupyter-notebook-cant-find-pandas-installed | python, pandas, macos-tahoe | 1,776,829,196 |
se_62601489 | stackoverflow | DATA_SCIENCE | Create a new column with frequency-based categories in pandas | Create a new column with frequency-based categories in pandas
I would need to create a new column as follows:
if the frequency of an item is greater or equal than 5 then set 'best seller';
if the frequency of an item is between 2 (inclusive) and 5 then set 'ok';
if the frequency of an item is lower than 2 then set '... | https://stackoverflow.com/questions/62601489/create-a-new-column-with-frequency-based-categories-in-pandas | python, pandas, dataframe | 1,593,199,108 |
se_79925592 | stackoverflow | DATA_SCIENCE | How to minimize mdf file size, created in python using asammdf | How to minimize mdf file size, created in python using asammdf
Hello I'm looking for advice/best practice how to minimize the size of an mdf file created using python/ asammdf.
I have an MDF file created by a data logger and file size is 2.4MB. It contains time series data (100+ channels sampled at different rates). W... | https://stackoverflow.com/questions/79925592/how-to-minimize-mdf-file-size-created-in-python-using-asammdf | python, pandas, asammdf | 1,776,193,083 |
se_79916764 | stackoverflow | DATA_SCIENCE | Group DataFrame unique line counts by first entry | Group DataFrame unique line counts by first entry
I'm doing some data analysis on a Ranked Choice Voting election, and I'm bumping up against some hierarchical sorting.
I have a jagged dataframe like
Ranked 1 | Ranked 2 | Ranked 3 | [...] | Ranked N
A | B
A
B
A | B | C
abstain
A | B ... | https://stackoverflow.com/questions/79916764/group-dataframe-unique-line-counts-by-first-entry | python, pandas | 1,774,819,661 |
se_79929046 | stackoverflow | DATA_SCIENCE | Is there a simple way to take bitwise-and of a pandas series? | Is there a simple way to take bitwise-and of a pandas series?
I have a pandas series of a bunch of 32 bit integers, and I'd like to roll through with series.rolling and get the bitwise-and of all the values in the window, basically trying to do this except that obviously bitwise_and is not a real pandas function one c... | https://stackoverflow.com/questions/79929046/is-there-a-simple-way-to-take-bitwise-and-of-a-pandas-series | python, pandas, numpy | 1,776,717,633 |
se_75903371 | stackoverflow | DATA_SCIENCE | HoW count sequences in Python | HoW count sequences in Python
I have a series like below. The series is a dataframe. I convert to a series just to show here.
Responses = {N, N, N, N, N, S, N, N, N, N, N, N, S, N, N, N, N, N, N, N, N, N, N, N, N, N, S, S, S, S, S, S, N, N, S, N, N, N, S, S, S, S, N, S, N, N, N, N, N, N, N, S, S, N, N, N, S, S, S, N, ... | https://stackoverflow.com/questions/75903371/how-count-sequences-in-python | python, pandas, numpy | 1,680,304,095 |
se_79925508 | stackoverflow | DATA_SCIENCE | How to calculate percentage change in pandas data frame for multiple rows at once? | How to calculate percentage change in pandas data frame for multiple rows at once?
by default pct_change on data frame will calculate pct change for immediate above (or the row number given via periods). I am looking to calculate pct_change w.r.t say current row and all N rows above it. i.e. I want current rows to hav... | https://stackoverflow.com/questions/79925508/how-to-calculate-percentage-change-in-pandas-data-frame-for-multiple-rows-at-onc | python, pandas, dataframe | 1,776,184,305 |
se_42077190 | stackoverflow | DATA_SCIENCE | Trailing Three Years Pandas Dataframe | Trailing Three Years Pandas Dataframe
I am looking to take the trailing three years (last three years) of my data set. I have merged the year, month and quarter columns into one column named 'date' which is a datetime function. I would like to use his 'date' column in order to get the last 3 years depending on when I ... | https://stackoverflow.com/questions/42077190/trailing-three-years-pandas-dataframe | python, pandas, datetime | 1,486,414,896 |
se_76055072 | stackoverflow | DATA_SCIENCE | How do you sort a dataframe with the integer in a column with strings and integers on every row? | How do you sort a dataframe with the integer in a column with strings and integers on every row?
How would you sort the following dataframe:
df = pd.DataFrame({'a':['abc_1.2.6','abc_1.2.60','abc_1.2.7','abc_1.2.9','abc_1.3.0','abc_1.3.10','abc_1.3.100','abc_1.3.11'], 'b':[1,2,3,4,5,6,7,8]})
>>>
a b
0 ... | https://stackoverflow.com/questions/76055072/how-do-you-sort-a-dataframe-with-the-integer-in-a-column-with-strings-and-intege | python, pandas, dataframe, sorting, natural-sort | 1,681,910,667 |
se_71860388 | stackoverflow | DATA_SCIENCE | pandas: checking if all given values are in index | pandas: checking if all given values are in index
I have several pandas data frames with different indexes. Lets say for this example I have indexes from 50 to 200, how can I check if all three given numbers for example [10, 51, 99] are within that index? (I need this for validation purposes to return errors if an i... | https://stackoverflow.com/questions/71860388/pandas-checking-if-all-given-values-are-in-index | python, python-3.x, pandas, dataframe, isin | 1,649,865,073 |
se_71834027 | stackoverflow | DATA_SCIENCE | Python pivot column with comma and bracket separated | Python pivot column with comma and bracket separated
I am working with a large dataframe that currently looks like this:
ID
Region
Noun
1
North America
[('Everything', 'NP'), ('the product','NP'), ('it','NP')]
2
North America
[('beautiful product','NP')]
The third column contains noun phrase(s) and each ... | https://stackoverflow.com/questions/71834027/python-pivot-column-with-comma-and-bracket-separated | python, pandas, dataframe, pivot | 1,649,709,523 |
se_51678110 | stackoverflow | DATA_SCIENCE | IndexError: At least one sheet must be visible reading from a CSV file | IndexError: At least one sheet must be visible reading from a CSV file
I have a CSV file that looks like this:
first-name,last-name,email-address
Yes,Beth,bethfat@gmail.com
Iran,Dajango,django@me.com
Paul,Walker,info@walker.com
Ray,Johnson,JJRay@gmail.com
I'm trying to convert this CSV file into a Excel file for fu... | https://stackoverflow.com/questions/51678110/indexerror-at-least-one-sheet-must-be-visible-reading-from-a-csv-file | python, excel, pandas, csv | 1,533,320,324 |
se_62839546 | stackoverflow | DATA_SCIENCE | Python dataframe drop rows which occur less frequently | Python dataframe drop rows which occur less frequently
I have a data frame with repeatedly occurring rows with different names. I want to delete less occurring rows. My data frame is very big. I am giving only a small size here.
dataframe:
df =
name value
0 A 10
1 B 20
2 ... | https://stackoverflow.com/questions/62839546/python-dataframe-drop-rows-which-occur-less-frequently | python, pandas, dataframe, pandas-groupby | 1,594,402,514 |
se_73711327 | stackoverflow | DATA_SCIENCE | Get column groups that have a change in value in other column pandas | Get column groups that have a change in value in other column pandas
I have a large dataset, have a column with usernames and other column for their status.
username status
John TRUE
John TRUE
John FALSE
Mike FALSE
... ...
I want to see if a user's status changes and who that user i... | https://stackoverflow.com/questions/73711327/get-column-groups-that-have-a-change-in-value-in-other-column-pandas | python, pandas, dataframe | 1,663,127,564 |
se_74636203 | stackoverflow | DATA_SCIENCE | Get nearest low and high values across multiple dataframe columns | Get nearest low and high values across multiple dataframe columns
I have a dataframe similar to this:
import pandas as pd
id = [1001, 1002, 1003]
a = [156, 224, 67]
b = [131, 203, 61]
c = [97, 165, 54]
d = [68, 122, 50]
value = [71, 180, 66]
df = pd.DataFrame({'id':id, 'a':a, 'b':b, 'c... | https://stackoverflow.com/questions/74636203/get-nearest-low-and-high-values-across-multiple-dataframe-columns | python, pandas, dataframe | 1,669,860,322 |
se_53838548 | stackoverflow | DATA_SCIENCE | Python Compare dataframe contents and replace if match? | Python Compare dataframe contents and replace if match?
I am working on a small program as practice in python and need some help trying to compare two columns in a data frame and replace the contents of one with another. I can see my results as I have converted the data frame to excel.
Anyway, I want to compare two c... | https://stackoverflow.com/questions/53838548/python-compare-dataframe-contents-and-replace-if-match | python, pandas, dataframe | 1,545,155,471 |
se_79927393 | stackoverflow | DATA_SCIENCE | Calculate how many days passed since the last played match for each team | Calculate how many days passed since the last played match for each team
I am trying to create two columns in my dataframe, with the days passed since the last match played from both the home team and the away team.
This is what my dataframe looks like:
Date team_home team_away
2026-05-10 Tottenham ... | https://stackoverflow.com/questions/79927393/calculate-how-many-days-passed-since-the-last-played-match-for-each-team | python, pandas, date, date-difference | 1,776,430,049 |
se_20180324 | stackoverflow | DATA_SCIENCE | Bin pandas dataframe by every X rows | Bin pandas dataframe by every X rows
I have a simple dataframe which I would like to bin for every 3 rows.
It looks like this:
col1
0 2
1 1
2 3
3 1
4 0
and I would like to turn it into this:
col1
0 2
1 0.5
I have already posted a similar question here but I have no Idea ... | https://stackoverflow.com/questions/20180324/bin-pandas-dataframe-by-every-x-rows | python, pandas, dataframe, binning | 1,385,323,616 |
se_79927637 | stackoverflow | DATA_SCIENCE | Modin + Dask distributed: AttributeError: type object 'ABCMeta' has no attribute 'deploy_axis_func' | Modin + Dask distributed: AttributeError: type object 'ABCMeta' has no attribute 'deploy_axis_func'
I'm trying to use Modin with a Dask LocalCluster to parallelize pandas DataFrame operations in a Django application (Python 3.13). Even with processes=False (thread-based workers, same process), the Dask... | https://stackoverflow.com/questions/79927637/modin-dask-distributed-attributeerror-type-object-abcmeta-has-no-attribute | python, pandas, dask, dask-distributed, modin | 1,776,457,694 |
se_79906667 | stackoverflow | DATA_SCIENCE | LossySetItemError when converting column type of 'int64' to 'float64' with astype() | LossySetItemError when converting column type of 'int64' to 'float64' with astype()
I've been trying to normalize some data in Python/Pandas, but I've encountered a bit of a conundrum. Normalizing data requires me to divide each column value by the maximum value of said column, thus yielding a range of... | https://stackoverflow.com/questions/79906667/lossysetitemerror-when-converting-column-type-of-int64-to-float64-with-astyp | python, pandas, dataframe | 1,773,380,625 |
se_59494111 | stackoverflow | DATA_SCIENCE | Pandas Python - value_counts() or idxmax() returns different value each time | Pandas Python - value_counts() or idxmax() returns different value each time
I have a Series which consists of a list of some random products. This is what it looks like if I print the describe:
<bound method NDFrame.describe of 176 reversible jacket
231 the n... | https://stackoverflow.com/questions/59494111/pandas-python-value-counts-or-idxmax-returns-different-value-each-time | python, python-3.x, pandas | 1,577,399,511 |
se_34853828 | stackoverflow | DATA_SCIENCE | unable to import module named pandas | unable to import module named pandas
I have python 2.7 and python 3 installed.
I also have pip2.7 and pip3 installed.
I use IPython Notebook in the Jupyter console. Using the console I can use every module I want but I'm trying to use the terminal :
python script.py arg1 arg2
I have installed pandas 0.17.1 in both ve... | https://stackoverflow.com/questions/34853828/unable-to-import-module-named-pandas | python, pandas, import, module | 1,453,117,106 |
se_63918555 | stackoverflow | DATA_SCIENCE | How to sort a heatmap to show highest correlations together? | How to sort a heatmap to show highest correlations together?
I'm trying to create a heatmap to show relationships between how many times Customers use reports, using the Count column as the values within the Heatmap Customers can use several templates as many times as they want. My dataframe looks something like this ... | https://stackoverflow.com/questions/63918555/how-to-sort-a-heatmap-to-show-highest-correlations-together | python, pandas, seaborn, jupyter, heatmap | 1,600,253,836 |
se_44645433 | stackoverflow | DATA_SCIENCE | ModuleNotFoundError: No module named 'pandas' | ModuleNotFoundError: No module named 'pandas'
I'm following a practical machine learning tutorial and I am already stuck on the second video. https://www.youtube.com/watch?v=JcI5Vnw0b2c&t=195s
import pandas as pd
import Quandl
df = Quandl.get('WIKI/GOOGL')
print(df.head())
When I run the same code as th... | https://stackoverflow.com/questions/44645433/modulenotfounderror-no-module-named-pandas | python, pandas | 1,497,940,239 |
se_68170884 | stackoverflow | DATA_SCIENCE | How to apply Target Encoding in test dataset? | How to apply Target Encoding in test dataset?
I am working on a project, where I had to apply target encoding for 3 categorical variables:
merged_data['SpeciesEncoded'] = merged_data.groupby('Species')['WnvPresent'].transform(np.mean)
merged_data['BlockEncoded'] = merged_data.groupby('Block')['WnvPresent'].transform(n... | https://stackoverflow.com/questions/68170884/how-to-apply-target-encoding-in-test-dataset | python, pandas | 1,624,921,602 |
se_38749305 | stackoverflow | DATA_SCIENCE | LabelEncoder order of fit for a Pandas df | LabelEncoder order of fit for a Pandas df
I am fitting a scikit-learn LabelEncoder on a column in a pandas df.
How is the order, in which the encountered strings are mapped to the integers, determined? Is it deterministic?
More importantly, can I specify this order?
import pandas as pd
from sklearn import preproce... | https://stackoverflow.com/questions/38749305/labelencoder-order-of-fit-for-a-pandas-df | python, pandas, scikit-learn | 1,470,242,481 |
se_49188960 | stackoverflow | DATA_SCIENCE | How to show all columns' names on a large pandas dataframe? | How to show all columns' names on a large pandas dataframe?
I have a dataframe that consist of hundreds of columns, and I need to see all column names.
What I did:
In[37]:
data_all2.columns
The output is:
Out[37]:
Index(['customer_id', 'incoming', 'outgoing', 'awan', 'bank', 'family', 'food',
'governme... | https://stackoverflow.com/questions/49188960/how-to-show-all-columns-names-on-a-large-pandas-dataframe | python, pandas, dataframe | 1,520,581,744 |
se_79924609 | stackoverflow | DATA_SCIENCE | What is the best way to modify values in a slice of a column with .iloc in Pandas | What is the best way to modify values in a slice of a column with .iloc in Pandas
With ChainedAssignmentErrors being enforced in Pandas 3.0 I was wondering what the best way to modify values in a slice of a column where the slicing is done with .iloc[] is.
For example this causes a ChainedAssignmentEror:
df = pd.DataF... | https://stackoverflow.com/questions/79924609/what-is-the-best-way-to-modify-values-in-a-slice-of-a-column-with-iloc-in-panda | python, pandas | 1,776,061,049 |
se_79924374 | stackoverflow | DATA_SCIENCE | Why does asyncio.gather with pandas DataFrame rows not run concurrently? | Why does asyncio.gather with pandas DataFrame rows not run concurrently?
I'm processing a large pandas DataFrame (500k rows) where each row requires an HTTP request. I switched from requests to aiohttp + asyncio expecting a significant speedup, but the async version runs just as slowly as the synchronous loop. I can't... | https://stackoverflow.com/questions/79924374/why-does-asyncio-gather-with-pandas-dataframe-rows-not-run-concurrently | python, pandas, python-asyncio, aiohttp | 1,776,006,641 |
se_79788168 | stackoverflow | DATA_SCIENCE | How to efficiently denormalize a SQL DB to produce Parquet files | How to efficiently denormalize a SQL DB to produce Parquet files
I'm trying to create a parquet file from a heavily normalized SQL database with a snowflake schema. Some of the dimensions have very long text attributes so that a simply running a big set of joins to denormalize the data that's fed to PyArrow takes a wh... | https://stackoverflow.com/questions/79788168/how-to-efficiently-denormalize-a-sql-db-to-produce-parquet-files | python, pandas, parquet, pyarrow | 1,760,206,784 |
se_77855706 | stackoverflow | DATA_SCIENCE | How can I merge two dataframes based on range of dates? | How can I merge two dataframes based on range of dates?
I have two DataFrames: df1 and df2
import pandas as pd
df1 = pd.DataFrame({
'a': ['2024-01-01 04:00:00', '2023-02-02 20:00:00'],
'id': ['a_1', 'a_2']})
df1['a'] = pd.to_datetime(df1.a)
df2 = pd.DataFrame({
'a': [
'2024-01-01 4:00:00', '2024-... | https://stackoverflow.com/questions/77855706/how-can-i-merge-two-dataframes-based-on-range-of-dates | python, pandas, dataframe | 1,705,855,052 |
se_77098113 | stackoverflow | DATA_SCIENCE | Solving incompatible dtype warning for pandas DataFrame when setting new column iteratively | Solving incompatible dtype warning for pandas DataFrame when setting new column iteratively
Setting the value of a new dataframe column:
df.loc[df["Measure"] == metric.label, "source_data_url"] = metric.source_data_url
now (as of Pandas version 2.1.0) gives a warning,
FutureWarning:
Setting an item of incompatible dt... | https://stackoverflow.com/questions/77098113/solving-incompatible-dtype-warning-for-pandas-dataframe-when-setting-new-column | python, pandas, dataframe, warnings, variable-assignment | 1,694,615,918 |
se_55962676 | stackoverflow | DATA_SCIENCE | Comparing two different sized pandas Dataframes and to find the row index with equal values | Comparing two different sized pandas Dataframes and to find the row index with equal values
I need some help with comparing two pandas dataframe.
I have two dataframes.
The first dataframe is:
df1 =
a b c d
0 1 1 1 1
1 0 1 0 1
2 0 0 0 1
3 1 1 1 1
4 1 0 1 0
5 1 1 1 0
6... | https://stackoverflow.com/questions/55962676/comparing-two-different-sized-pandas-dataframes-and-to-find-the-row-index-with-e | python-3.x, pandas, dataframe, compare, equality | 1,556,851,701 |
se_79923563 | stackoverflow | DATA_SCIENCE | How to add string signal to mdf file asammdf python | How to add string signal to mdf file asammdf python
I am creating a an mdf file from a pandas dataframe with time series data. I have string channels that I am not sure how to add, I get an error using the code below.
data = {
"GLOBAL_TIME": [1, 2, 3, 4, 5],
"INT_SIGNAL": [10, 20, 30, 40, 50],
"FLOAT_SIGNA... | https://stackoverflow.com/questions/79923563/how-to-add-string-signal-to-mdf-file-asammdf-python | python, pandas, asammdf | 1,775,832,299 |
se_79922267 | stackoverflow | DATA_SCIENCE | Why does pandas apply return NaN when function lacks return statement, instead of keeping original value? | Why does pandas apply return NaN when function lacks return statement, instead of keeping original value?
I am trying to transform a column in a pandas DataFrame using the 'apply' method, but I get 'NaN' (or 'None') for some elements, even though I expected the original values to remain unchanged.
Here is a simplified... | https://stackoverflow.com/questions/79922267/why-does-pandas-apply-return-nan-when-function-lacks-return-statement-instead-o | python, pandas, nan | 1,775,658,325 |
se_79922604 | stackoverflow | DATA_SCIENCE | Pandas isn't showing all the rows I have set with max_rows | Pandas isn't showing all the rows I have set with max_rows
Pandas isn't showing all the rows I have specified with display.max_rows
I have specified 100 rows for pandas to show using:
pd.set_option('display.max_rows', 100)
But when I display the DataFrame, it only shows 10 rows.
I tried using display.height but i... | https://stackoverflow.com/questions/79922604/pandas-isnt-showing-all-the-rows-i-have-set-with-max-rows | python, pandas, dataframe, display | 1,775,719,920 |
se_79120327 | stackoverflow | DATA_SCIENCE | Why does "SettingWithCopyWarning" get raised (seemingly) inconsistently? | Why does "SettingWithCopyWarning" get raised (seemingly) inconsistently?
Setup
We first import pandas and numpy and then create a 5000 rows x 10 columns pd.DataFrame called df
import pandas as pd
import numpy as np
# Generate non-trivial df
data = np.random.rand(5000, 10)
column_names = [f'col_{i}' for i in... | https://stackoverflow.com/questions/79120327/why-does-settingwithcopywarning-get-raised-seemingly-inconsistently | python, pandas, dataframe, pandas-settingwithcopy-warning | 1,729,742,960 |
se_79920675 | stackoverflow | DATA_SCIENCE | Water sewage demand | Water sewage demand
Any suggestions on what approach to use when trying to normalize a set of 75 CSV files that contain an average of 300.000 rows with "water flow"?
The problem is the frequency of the meter (some of them measure each minute, other each 5 other 15 min) etc, and also the unit it uses (some of them Cubi... | https://stackoverflow.com/questions/79920675/water-sewage-demand | python, pandas, dataframe, statistics | 1,775,429,390 |
se_34682828 | stackoverflow | DATA_SCIENCE | Extracting specific selected columns to new DataFrame as a copy | Extracting specific selected columns to new DataFrame as a copy
I have a pandas DataFrame with 4 columns and I want to create a new DataFrame that only has three of the columns. This question is similar to: Extracting specific columns from a data frame but for pandas not R. The following code does not work, raises an... | https://stackoverflow.com/questions/34682828/extracting-specific-selected-columns-to-new-dataframe-as-a-copy | python, pandas, dataframe, chained-assignment | 1,452,274,485 |
se_75722640 | stackoverflow | DATA_SCIENCE | Python - XlsxWriter: Referring to columns by column name, not column letter (Hardcode vs. dynamic variable) | Python - XlsxWriter: Referring to columns by column name, not column letter (Hardcode vs. dynamic variable)
I'm wondering if there's a way to refer to columns when using XlsxWriter by their name, and not the column letter or index, in the event that the column index changes but I still want the formatting to apply to ... | https://stackoverflow.com/questions/75722640/python-xlsxwriter-referring-to-columns-by-column-name-not-column-letter-har | python, excel, pandas, dataframe, xlsxwriter | 1,678,714,664 |
se_58227308 | stackoverflow | DATA_SCIENCE | transpose datetime with label | transpose datetime with label
I wish to transpose this datetime into a column with a label (name) associated with the times in range. Then ultimately add them to a sqlite table
I have searched and tried some of the suggestions here but I could nnot get what I'm looking for
2019-10-2 Bob
2019-10-3 Bob
2019-10-4 ... | https://stackoverflow.com/questions/58227308/transpose-datetime-with-label | python, pandas, datetime | 1,570,139,241 |
se_76592108 | stackoverflow | DATA_SCIENCE | How can a Pandas DatetimeArray be sorted? | How can a Pandas DatetimeArray be sorted?
I have a DataFrame which contains a date column.
I need to get the unique values of that column and then sort them out. I started with:
unique_dates = data['date'].unique()
Which works well. Next, I need to sort this unique list of dates.
However, I am having issues because u... | https://stackoverflow.com/questions/76592108/how-can-a-pandas-datetimearray-be-sorted | python, python-3.x, pandas, dataframe | 1,688,157,686 |
se_46476962 | stackoverflow | DATA_SCIENCE | Pandas: DataFrame row into variables | Pandas: DataFrame row into variables
I have the following DataFrame:
x = DataFrame({
"x" : [1,2,3],
"y" : [4,5,6],
"z" : [7,8,9]
})
I want to retrieve the row where x equals 1, and store the y and z values there in variables with the same name.
I'm able to do this, but I had to resort t... | https://stackoverflow.com/questions/46476962/pandas-dataframe-row-into-variables | python, pandas, dataframe | 1,506,627,211 |
se_79909353 | stackoverflow | DATA_SCIENCE | UnicodeEncodeError: 'charmap' codec can't encode characters when writing to HTML | UnicodeEncodeError: 'charmap' codec can't encode characters when writing to HTML
I have a pandas DataFrame that I wish to paste into an HTML document. The DataFrame contains Dingbat characters used as symbols to highlight values as good (checkmark), nearly bad (triangle), or bad (exclamation point). Here a... | https://stackoverflow.com/questions/79909353/unicodeencodeerror-charmap-codec-cant-encode-characters-when-writing-to-html | python, html, python-3.x, pandas, unicode | 1,773,759,136 |
se_41190852 | stackoverflow | DATA_SCIENCE | Most efficient way to forward-fill NaN values in numpy array | Most efficient way to forward-fill NaN values in numpy array
Example Problem
As a simple example, consider the numpy array arr as defined below:
import numpy as np
arr = np.array([[5, np.nan, np.nan, 7, 2],
[3, np.nan, 1, 8, np.nan],
[4, 9, 6, np.nan, np.nan]])
where arr looks like ... | https://stackoverflow.com/questions/41190852/most-efficient-way-to-forward-fill-nan-values-in-numpy-array | python, arrays, performance, pandas, numpy | 1,481,914,938 |
se_79920255 | stackoverflow | DATA_SCIENCE | Querying pandas with SQL, not returning new dataframe | Querying pandas with SQL, not returning new dataframe
I'm trying to make a small application that loads CSV and parquet files into a pandas dataframe, and allows me to query them with SQL and create graphs using matplot. However whenever I query it, it doesn't return a new dataframe. And if I remove the if data is non... | https://stackoverflow.com/questions/79920255/querying-pandas-with-sql-not-returning-new-dataframe | python, pandas, dataframe | 1,775,334,906 |
se_33094297 | stackoverflow | DATA_SCIENCE | Create trading holiday calendar with Pandas | Create trading holiday calendar with Pandas
I'm trying to create a Trading calendar using Pandas. I'm able to create a cal instance based on the USFederalHolidayCalendar. The USFederalHolidayCalendar is not consistent with the Trading calendar in that the Trading calendar doesn't include Columbus Day and Veteran's Day... | https://stackoverflow.com/questions/33094297/create-trading-holiday-calendar-with-pandas | python, pandas, calendar | 1,444,711,489 |
se_71047810 | stackoverflow | DATA_SCIENCE | Pandas - groupby result as table | Pandas - groupby result as table
I'm new to Pandas and Plotly and currently working on a small analysis project looking at my Netflix data.
I'm trying to display a table of my top 10 films (by max. duration watched). I have:
top10 = df.groupby(['Film Title'])['Duration'].sum().nlargest(10)
and
table = go.Figure(data=... | https://stackoverflow.com/questions/71047810/pandas-groupby-result-as-table | python, pandas, group-by, plotly | 1,644,402,140 |
se_76908885 | stackoverflow | DATA_SCIENCE | Translating an add column operation from a dataframe to SQL | Translating an add column operation from a dataframe to SQL
I will use Pandas here for this example but it should be applicable for any dataframe library. Pandas makes it quite pleasant to add on additional columns to an existing data frame. Here is the first example:
>>> import pandas as pd
>>> df=pd.DataFrame(data={... | https://stackoverflow.com/questions/76908885/translating-an-add-column-operation-from-a-dataframe-to-sql | sql, r, pandas, dataframe | 1,692,130,526 |
se_79919173 | stackoverflow | DATA_SCIENCE | Pandas IndexError: DataFrame indexer is not allowed for .iloc | Pandas IndexError: DataFrame indexer is not allowed for .iloc
I'm trying to plot actual vs predicted values using matplotlib.
Here is my code:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
path = '/content/dri... | https://stackoverflow.com/questions/79919173/pandas-indexerror-dataframe-indexer-is-not-allowed-for-iloc | python, pandas, dataframe, matplotlib, google-colaboratory | 1,775,146,989 |
se_77046709 | stackoverflow | DATA_SCIENCE | Pandas Remove Blank Row in Column Multi Index | Pandas Remove Blank Row in Column Multi Index
I have a MultiIndex dataframe in pandas. I can't seem to get rid of the blank row under the column headers in the resulting Excel file while maintaining the multi-indices.
Here is what I have:
3 Month Total
3 Month Total
3 Month Total
August
August
August
July
July... | https://stackoverflow.com/questions/77046709/pandas-remove-blank-row-in-column-multi-index | python, pandas, excel, dataframe, multi-index | 1,693,936,020 |
se_79918462 | stackoverflow | DATA_SCIENCE | Pandas aggregate() creates weird DataFrame | Pandas aggregate() creates weird DataFrame
I've been scratching my head over this way too long now, but can't find any answers online, and I hope someone can shed some light on this.
I'm working with Pandas and a csv file, from which I need to aggregate the values of two columns, and plot them (with matplotlib). I hav... | https://stackoverflow.com/questions/79918462/pandas-aggregate-creates-weird-dataframe | python, pandas, matplotlib | 1,775,055,328 |
se_68478097 | stackoverflow | DATA_SCIENCE | Excel file format cannot be determined, you must specify an engine manually | Excel file format cannot be determined, you must specify an engine manually
I am not sure why I am getting this error although sometimes my code works fine!
Excel file format cannot be determined, you must specify an engine manually.
Here below is my code with steps:
1- list of columns of customers Id:
customer_id = [... | https://stackoverflow.com/questions/68478097/excel-file-format-cannot-be-determined-you-must-specify-an-engine-manually | python, python-3.x, pandas, dataframe, valueerror | 1,626,916,920 |
se_79884813 | stackoverflow | DATA_SCIENCE | Fetching large datasets from SAP HANA using hdbcli in Python is very slow | Fetching large datasets from SAP HANA using hdbcli in Python is very slow
I am trying to fetch data from an SAP HANA database using Python. I am using the hdbcli library to connect to HANA and pandas to read the data. The main requirement of my use case is to efficiently fetch large datasets from SAP HANA using batch ... | https://stackoverflow.com/questions/79884813/fetching-large-datasets-from-sap-hana-using-hdbcli-in-python-is-very-slow | python, pandas, etl, hana | 1,770,459,341 |
se_79907381 | stackoverflow | DATA_SCIENCE | Fitting linear regression and computing metrics in python | Fitting linear regression and computing metrics in python
I have two data series of model prediction and observations. I am able to make line plots of these series. I would like to add a linear regression fit of the two data series. i would also like to add metrics as annotations to the plot. i need assistance how to ... | https://stackoverflow.com/questions/79907381/fitting-linear-regression-and-computing-metrics-in-python | python, pandas, scikit-learn, linear-regression | 1,773,477,002 |
se_75848538 | stackoverflow | DATA_SCIENCE | Real time Pandas dataframe visualisation in Jupyter lab | Real time Pandas dataframe visualisation in Jupyter lab
I'm looking for a tool that allows to visualize in real time the pandas dataframes with an excel look (filter and sort).
Does anyone know an extension of this type? Knowing of VS code proposes this tool, I am looking for the same thing on Jupyter Lab
When I say r... | https://stackoverflow.com/questions/75848538/real-time-pandas-dataframe-visualisation-in-jupyter-lab | python, pandas, dataframe, jupyter-lab, viewer | 1,679,843,173 |
se_71054457 | stackoverflow | DATA_SCIENCE | KeyError: 0 in if clause? | KeyError: 0 in if clause?
I try to plot the following dataframe:
x
y
end_x
end_y
outcome
94.8
34.4
91.2
4.0
Successful
10.5
20.4
52.3
55.8
Unsuccessful
13.2
29.8
58.9
1.0
Successful
I cannot figure out what I do wrong here:
for x in range(len(df['x'])):
if df['outcome'][x] == 'Successful':
pl... | https://stackoverflow.com/questions/71054457/keyerror-0-in-if-clause | python, pandas, error-handling | 1,644,429,408 |
se_79915504 | stackoverflow | DATA_SCIENCE | Generic sklearn template | Generic sklearn template
I am creating a reusable scikit-learn pipeline for tabular data with numeric and categorical columns.
I want to:
Impute missing numeric values with the median
Scale numeric columns
Impute categorical values with the most frequent value
One-hot encode categorical columns
Here is my curren... | https://stackoverflow.com/questions/79915504/generic-sklearn-template | python, pandas, machine-learning, scikit-learn | 1,774,592,450 |
se_79873837 | stackoverflow | DATA_SCIENCE | Numpy axis rules | Numpy axis rules
I am a Python developer, but I don't understand one thing: what are the numpy axis? Sometimes, when I use Sklearn, I have errors about axis. And I need explanations about values and reshape functions. | https://stackoverflow.com/questions/79873837/numpy-axis-rules | python, pandas, dataframe, numpy, scikit-learn | 1,769,092,188 |
se_79915481 | stackoverflow | DATA_SCIENCE | Is this modular scikit-learn pipeline design correct for a binary classification task? | Is this modular scikit-learn pipeline design correct for a binary classification task?
I'm building a modular machine learning pipeline for a binary classification problem using scikit-learn.
I structured the code into separate functions for preprocessing, scaling, and model training.
I would like to verify whether th... | https://stackoverflow.com/questions/79915481/is-this-modular-scikit-learn-pipeline-design-correct-for-a-binary-classification | python, pandas, dataframe, machine-learning, scikit-learn | 1,774,589,221 |
se_78553082 | stackoverflow | DATA_SCIENCE | Using .assign in a dataframe with a custom function | Using .assign in a dataframe with a custom function
I am trying to create a column in a dataframe and passing a custom function that will assign the suffix to the day i.e. 1st, 2nd etc. I have managed to do this with .apply, however I would like to do this with .assign and I am getting the error ValueError: The truth ... | https://stackoverflow.com/questions/78553082/using-assign-in-a-dataframe-with-a-custom-function | python, pandas, dataframe, apply, assign | 1,717,048,143 |
se_79915852 | stackoverflow | DATA_SCIENCE | How to use a list object to select columns in Pandas? | How to use a list object to select columns in Pandas?
I have a Pandas data frame. Here is the head of the data frame.
import pandas as pd
>>> print(data.head().to_dict())
{'sev_wp': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, 'treatm': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}, 'coastal_blue': {0: 1.58052248041715, 1: 1.26409021294804, 2:... | https://stackoverflow.com/questions/79915852/how-to-use-a-list-object-to-select-columns-in-pandas | python, pandas, keyerror | 1,774,627,368 |
se_79915485 | stackoverflow | DATA_SCIENCE | XGBoost Pipeline with ColumnTransformer: Handling categorical + numerical data and improving accuracy | XGBoost Pipeline with ColumnTransformer: Handling categorical + numerical data and improving accuracy
I am building a classification model using XGBoost with a Scikit-learn Pipeline that includes preprocessing for both numerical and categorical features.
import pandas as pd
import numpy as np
from xgboost import XGBCl... | https://stackoverflow.com/questions/79915485/xgboost-pipeline-with-columntransformer-handling-categorical-numerical-data-a | python, pandas, machine-learning, scikit-learn | 1,774,589,704 |
se_71108669 | stackoverflow | DATA_SCIENCE | How do I assemble bunch of Excel files into one or more using Python | How do I assemble bunch of Excel files into one or more using Python
I have around 10k .csv files named as data0,data1 like that in sequence. I want to combine them and want to have a master sheet in one file or at least couple of sheets using Python because I think there is limitation of around 1070000 rows in one Ex... | https://stackoverflow.com/questions/71108669/how-do-i-assemble-bunch-of-excel-files-into-one-or-more-using-python | python, excel, pandas, dataframe | 1,644,825,627 |
se_76723145 | stackoverflow | DATA_SCIENCE | Plotting a table with text-wrapping words | Plotting a table with text-wrapping words
I have to graph a dataframe containing text and the last column contains very long text.
To graph it correctly I need the text once it has passed the vertical grid of the table to be text and new line.
Here is the code that reproduces the problem I want to solve
import pandas ... | https://stackoverflow.com/questions/76723145/plotting-a-table-with-text-wrapping-words | python, pandas, matplotlib | 1,689,782,039 |
se_51549448 | stackoverflow | DATA_SCIENCE | Space delimiter in CSV import to Python | Space delimiter in CSV import to Python
I know there are more than a few questions regarding space delimiters in CSV files.
I have a CSV file that appears to be separated by a space. When importing to Python, I have tried every code out there to identify space as a delimiter. However, I keep getting error messages. F... | https://stackoverflow.com/questions/51549448/space-delimiter-in-csv-import-to-python | python, pandas, csv, delimiter, separator | 1,532,653,856 |
se_74781669 | stackoverflow | DATA_SCIENCE | Python Function to get data from excel which has 1000 Column | Python Function to get data from excel which has 1000 Column
I have a very large excel file and it gets crashed every time whenever I try to find some data so now I'm planning to store the file in Azure Blob Storage/other database and trying to write an Azure function in python so that I can fetch the data from Azure ... | https://stackoverflow.com/questions/74781669/python-function-to-get-data-from-excel-which-has-1000-column | python-3.x, pandas, numpy, pyspark, azure-functions | 1,670,918,590 |
se_79733457 | stackoverflow | DATA_SCIENCE | Can't parse a valid ISO 8601 datetime string pulled from CSV | Can't parse a valid ISO 8601 datetime string pulled from CSV
I have a set of data that I am pulling from an Excel CSV. The column I am using has the timestamps in ISO 8601 format with fractional seconds (YYYY-MM-DDTHH:MM:SS.SSZ)
I have tried using dateutil, isodate, and datetime to parse these values so I can crea... | https://stackoverflow.com/questions/79733457/cant-parse-a-valid-iso-8601-datetime-string-pulled-from-csv | python, pandas, dataframe, python-dateutil, isodate | 1,755,017,774 |
se_50305112 | stackoverflow | DATA_SCIENCE | Pip Install Timeout Issue | Pip Install Timeout Issue
I am trying to install pandas in my company computer.
I tried to do
pip install pandas
but operation retries and then timesout.
then I downloaded the package:
pandas-0.22.0-cp27-cp27m-win_amd64.whl
and install:
pip install pandas-0.22.0-cp27-cp27m-win_amd64
But I get the following error:
R... | https://stackoverflow.com/questions/50305112/pip-install-timeout-issue | python, pandas, pip | 1,526,120,022 |
se_79911487 | stackoverflow | DATA_SCIENCE | How to ffill with a maximum time limit (GAP) across 120M+ rows? | How to ffill with a maximum time limit (GAP) across 120M+ rows?
The Problem:
I'm struggling with a performance bottleneck on a 120M+ row dataset.
I need to forward-fill NaN values in sensor data, but only if the time gap since the last valid reading is less than 5 minutes.
If the gap is larger, it must remain NaN.
A s... | https://stackoverflow.com/questions/79911487/how-to-ffill-with-a-maximum-time-limit-gap-across-120m-rows | python, pandas, dataframe, numpy | 1,774,024,219 |
se_79911872 | stackoverflow | DATA_SCIENCE | Why is there no `orient=table` option for `pandas.DataFrame.to_dict`? | Why is there no `orient=table` option for `pandas.DataFrame.to_dict`?
I'm trying to save a pandas.DataFrame object to disk, as a JSON. The slight complication is that I need to store some additional data alongside it. So my intended JSON would be
{
"additionalData": ...,
"table": {
"schema": ...,
"data": .... | https://stackoverflow.com/questions/79911872/why-is-there-no-orient-table-option-for-pandas-dataframe-to-dict | python, json, pandas, dataframe | 1,774,097,617 |
se_36510146 | stackoverflow | DATA_SCIENCE | How to get value by multi-index with python pandas? | How to get value by multi-index with python pandas?
How can I get the value from a dataframe by its multi-index?
For example, I have a dataframe mm:
>>> np.random.seed(1)
>>> mm = pd.DataFrame(np.random.randn(5,2))
>>> mm['A'] = np.arange(5)
>>> mm['B'] = np.arange(5,10)
>>> mm.set_index(['A','B'], inplace=True)
>>> p... | https://stackoverflow.com/questions/36510146/how-to-get-value-by-multi-index-with-python-pandas | python, pandas, dataframe | 1,460,153,521 |
se_79741738 | stackoverflow | DATA_SCIENCE | broken x axis and broken dual y-axes - draw replot across subplots | broken x axis and broken dual y-axes - draw replot across subplots
My post relates to this one here:
Formatting a broken y axis in python matplotlib
I have borrowed code from this post and adapted it to what I am doing.
I am attempting to create a graph whereby I am maximizing the space where the majority of the data ... | https://stackoverflow.com/questions/79741738/broken-x-axis-and-broken-dual-y-axes-draw-replot-across-subplots | python, pandas, seaborn | 1,755,738,984 |
se_46586419 | stackoverflow | DATA_SCIENCE | AttributeError: 'NoneType' object has no attribute 'fileno' | AttributeError: 'NoneType' object has no attribute 'fileno'
as I am trying to print financial data:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import numpy as np
style.use('ggplot')
start = dt.datetime(200... | https://stackoverflow.com/questions/46586419/attributeerror-nonetype-object-has-no-attribute-fileno | python, pandas, attributeerror, datareader | 1,507,208,822 |
se_79911397 | stackoverflow | DATA_SCIENCE | Python json normalization - nested structure | Python json normalization - nested structure
I am learning to process what i consider a complex json structure and am trying to load this into a dataframe. I want a single record for each outcome id. Here is the sample json structure
{
"_id": 12345,
"reports": [
{
"body": "\n***\nGeneral ... | https://stackoverflow.com/questions/79911397/python-json-normalization-nested-structure | python, json, pandas, dataframe | 1,774,016,203 |
se_79597131 | stackoverflow | DATA_SCIENCE | dtypes for pandas read_parquet | dtypes for pandas read_parquet
Using the pandas.read_parquet() method to read a file, pandas interprets a column with mixed values as type Object. I want instead for pandas to interpret the column types as they are specified in the file.
A parquet file has meta information that states what the type of each column is ... | https://stackoverflow.com/questions/79597131/dtypes-for-pandas-read-parquet | python, pandas, dataframe, parquet, pyarrow | 1,745,866,537 |
se_43175382 | stackoverflow | DATA_SCIENCE | Create a single column dataframe from a list | Create a single column dataframe from a list
I am using the following code to create a data frame from a list:
test_list = ['a','b','c','d']
df_test = pd.DataFrame.from_records(test_list, columns=['my_letters'])
df_test
The above code works fine. Then I tried the same approach for another list:
import pandas as pd
q_... | https://stackoverflow.com/questions/43175382/create-a-single-column-dataframe-from-a-list | python, pandas, dataframe, list | 1,491,183,534 |
se_42603772 | stackoverflow | DATA_SCIENCE | Create a dataframe from cross-validation scores | Create a dataframe from cross-validation scores
I have a dataset stored in a variable, file, and I try to apply 10 fold cross-validation with logistic regression. What I am looking for is the way to list the average of clf.coef_.
print(file.head())
Result Interest Limit Service Convenience Trust Speed
0 ... | https://stackoverflow.com/questions/42603772/create-a-dataframe-from-cross-validation-scores | python, pandas, scikit-learn, cross-validation | 1,488,680,706 |
se_79910407 | stackoverflow | DATA_SCIENCE | Ploty Graph Breaks with multiple sources | Ploty Graph Breaks with multiple sources
I'm working on a dashboard to interactively display ride wait times in a theme park. I've got a script running that polls a web API for wait times every 5 minutes. From that script, I have a series of csv files, sorted by date and ride, each containing the time the sample was t... | https://stackoverflow.com/questions/79910407/ploty-graph-breaks-with-multiple-sources | python, pandas, plotly | 1,773,894,046 |
se_79756149 | stackoverflow | DATA_SCIENCE | Pandas does not fail, warn, or skip when rows have more columns than the header | Pandas does not fail, warn, or skip when rows have more columns than the header
I'm new to Python and to Pandas, and I am desperately trying to understand how or why this is happening.
I have a CSV file with some data, which has some rows which have extra commas , which are not escaped. So there are 4 column headers, ... | https://stackoverflow.com/questions/79756149/pandas-does-not-fail-warn-or-skip-when-rows-have-more-columns-than-the-header | python, pandas, dataframe, csv | 1,757,013,911 |
se_17156084 | stackoverflow | DATA_SCIENCE | unpacking a sql select into a pandas dataframe | unpacking a sql select into a pandas dataframe
Suppose I have a select roughly like this:
select instrument, price, date from my_prices;
How can I unpack the prices returned into a single dataframe with a series for each instrument and indexed on date?
To be clear: I'm looking for:
<class 'pandas.core.frame.DataF... | https://stackoverflow.com/questions/17156084/unpacking-a-sql-select-into-a-pandas-dataframe | python, sql, pandas, dataframe | 1,371,500,267 |
se_12047193 | stackoverflow | DATA_SCIENCE | How to convert SQL Query result to Pandas DataFrame? | How to convert SQL Query result to Pandas DataFrame?
Any help on this problem will be greatly appreciated.
So basically I want to run a query to my SQL database and store the returned data as a Pandas DataFrame.
I have attached code for query.
I am reading the documentation on Pandas, but I have problem to identify th... | https://stackoverflow.com/questions/12047193/how-to-convert-sql-query-result-to-pandas-dataframe | python, mysql, pandas, dataframe, data-structures | 1,345,510,922 |
se_40232520 | stackoverflow | DATA_SCIENCE | How do I incrementally add rows in Pandas Dataframe? | How do I incrementally add rows in Pandas Dataframe?
I am calculating the open-high-low-close (OHLC) of data for a duration of each 15 mins from 9:15 to 15:30 and want to store the OHLC values in a dataframe in each new row.
ohlc = pd.DataFrame(columns=('Open','High','Low','Close'))
for row in ohlc:
ohlc.loc[10] ... | https://stackoverflow.com/questions/40232520/how-do-i-incrementally-add-rows-in-pandas-dataframe | python, pandas, dataframe, append | 1,477,375,687 |
se_75768251 | stackoverflow | DATA_SCIENCE | Duplicated rows while Merging in Python | Duplicated rows while Merging in Python
I have two datasets :
df2
Claim
ABC
ABC
ABC
AAC
AAC
AAC
AAC
ADC
ADC
ADC
df1
Claim
Flag
ABC
1
AAC
0
ADC
1
While merging I am expecting that only first instance gets the flag value, but instead all the duplicates are getting the flag value... | https://stackoverflow.com/questions/75768251/duplicated-rows-while-merging-in-python | python, pandas, dataframe, merge | 1,679,060,225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.