This question already has answers here:
How to convert index of a pandas dataframe into a column
(9 answers)
Closed 1 year ago.
My df has the columns 'Country' and 'Country Code' as the current index. How can I remove this index and create a new one that just counts the rows? I´ll leave the picture of how it´s looking. All I want to do is add a new index next to Country. Thanks a lot!
If you are using a pandas DataFrame and your DataFrame is called df:
df = df.reset_index(drop=False)
This question already has answers here:
How can I pivot a dataframe?
(5 answers)
How to pivot a dataframe in Pandas? [duplicate]
(2 answers)
Closed 1 year ago.
I have a dataframe like this:
index,col1,value
1,A,1
1,B,2
2,A,3
2,D,4
2,C,5
2,B,6
And I would like to convert this dataframe to this:
index,col1_A,col1_B,col1_C,col1_D
1,1,2,np.Nan,np.nan
2,3,4,5,6
The conversion is based on the index column value and for each unique index column, the column values from col1 is converted to column name and its associated value is set to the corresponding value available in value columns.
Currently my solution contains looping by creating subset of df as temporary df based on each index and then starting looping there. I am wondering if there is already builtin solution available for it in pandas. please feel free to suggest.
This question already has answers here:
How to get the last N rows of a pandas DataFrame?
(3 answers)
Closed 2 years ago.
I have the following panda dataframe:(df)
How can I append only the last row (Date 2021-01-22) to a new dataframe (df_new)?
df_new = df_new.append(df.tail(1))
if df_new is not defined. The following code will do it.
df_new = df.tail(1)
This question already has answers here:
How can I pivot a dataframe?
(5 answers)
Pandas: Adding new column to dataframe which is a copy of the index column
(3 answers)
Closed 2 years ago.
I have a dataframe with 4 columns: Mes (month), Clientes (clients), Mercadorias (Assets) and Quantidade (quantity) and I'm trying to create a new dataframe grouping by the columns month and clients running the following code: data = df.groupby(['Mes','Clientes'])['Quantidade'].sum()
The output values are ok however it is creating a pandas.core.series.Series and wish to create a pandas.core.frame.DataFrame
Could someone please help me?
This question already has answers here:
Get statistics for each group (such as count, mean, etc) using pandas GroupBy?
(9 answers)
Closed 3 years ago.
I want to merge duplicate rows by adding a new column 'count'
Final dataframe that I want
rows can be in any order
You can use:
df["count"] = 1
df = df.groupby(["user_id", "item_id", "total"])["count"].count().reset_index()