I'm trying to print first name, last name and birthday, so how i could do it?
Here's my code:
import pandas as pd
import numpy as np
from datetime import datetime, date
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("legislators-current.csv")
df.shape
oldest = df['birthday'].min()
print(oldest)
Output should be like this:
last_name | first_name | birthday |
---|---|---|
Cawthorn | David | 1995-08-01 |
CodePudding user response:
First add parse_dates
to read_csv
for datetimes:
df = pd.read_csv("legislators-current.csv", parse_dates=['birthday'])
Then if need filter by minimal birthday
and columns in list use DataFrame.loc
:
df.loc[df['birthday'].eq(df['birthday'].min()), ['last_name','first_name','birthday']]
For all columns use boolean indexing
:
df[df['birthday'].eq(df['birthday'].min())]
CodePudding user response:
You should output the dataframe, you can try to order it by birthday
and then print the first row with .head(1)
. This is an alternative to jezrael's useful answer:
df.sort_values('birthday').head(1)
CodePudding user response:
This is my code. There are many like it, but this one is mine :)
It is not a bad idea to set "birthday" Dtype as "datetime" so python can compare the values. The code will work without that, but sometimes we could get unwanted results.
df = pd.DataFrame({
"last_name":["Cawthron","Doe"],
"first_name":["David","John"],
"birthday":["1995-08-01","1994-07-13"]
})
df['birthday'] = pd.to_datetime(df['birthday'],format='%Y/%m/%d')
df
last_name | first_name | birthday | |
---|---|---|---|
0 | Cawthron | David | 1995-08-01 |
1 | Doe | John | 1994-07-13 |
Below we select the row of DataFrame for which birthday minimum is true.
oldest = df[df["birthday"] == df['birthday'].min()]
oldest
last_name | first_name | birthday | |
---|---|---|---|
1 | Doe | John | 1994-07-13 |
Hope this helped.