Extract distinct values from Dataframe and insert them into new Dataframe with same column Name

Viewed 586

Using python 3.7 , pandas 1.1.3 , Anaconda Jupyter Notebook

I am new into python and I have a following dataframe.

DF_1

Name  Date
AAA   2000-09-01
BBB   2001-08-01
CCC   2002-07-01
AAA   2005-05-01

I just want to extract distinct values from 'Name' column and create a new dataframe (df_2) and insert into it with same column name.

Output df_2 should look like this

Name
AAA
BBB
CCC
4 Answers

Try this:

df_2 = DF_1[['Name']].drop_duplicates()

How about:

DF_2 = pd.DataFrame(DF_1.Name.unique(), columns=['Name'])

You can also do it using np.unique which is a little faster compared to pd.Series.unique() and pd.Series.drop_duplicates()

import pandas as pd
import numpy as np
df_2 = pd.DataFrame(np.unique(df_1['Name']),columns=['Name'])

for that u may not need a dataframe series would be a perfect fit

df2=pd.Series(df['name'].unique(),name='name')

in case u want a dataframe here is another way of doing it

df.drop("num",axis=1).drop_duplicates()
Related