简体   繁体   中英

How to extract dates from pandas dataframe using Python?

I have the following dataframe that I created using Pandas:

         Name       BirthDay            
0        Alex     1985-01-01
1        John     1977-01-01
2        Rick     1992-01-01

I need to create separate lists with values from each column. So I do the following:

names = []
birthdays = []
while i < len(df.index):
    name = "".join(df['Name'].iloc[i])
    birthDay= "".join(df['BirthDay'].iloc[i])
    names.append(name)
    bithdays.append(birthDay)
    i += 1

The code works fine to populate the first list with names, but it throws this error trying to extract dates:

TypeError: can only join an iterable

How am I doing wrong?

I think you need Series.tolist and for convert datetimes strftime if need convert datetime s to string s:

names = df['Name'].tolist()
print (names)
['Alex', 'John', 'Rick']

birthdays = df['BirthDay'].dt.strftime('%Y-%m-%d').tolist()
print (birthdays)
['1985-01-01', '1977-01-01', '1992-01-01']

Alternative solution is cast to str :

birthdays = df['BirthDay'].astype(str).tolist()
print (birthdays)
['1985-01-01', '1977-01-01', '1992-01-01']

If need Timestamps (pandas datetimes) in list:

birthdays = df['BirthDay'].tolist()
print (birthdays)
[Timestamp('1985-01-01 00:00:00'), Timestamp('1977-01-01 00:00:00'),
 Timestamp('1992-01-01 00:00:00')]

And for python dates and datetimes use date or to_pydatetime :

birthdays = df['BirthDay'].dt.date.tolist()
print (birthdays)
[datetime.date(1985, 1, 1), datetime.date(1977, 1, 1), datetime.date(1992, 1, 1)]

birthdays = df['BirthDay'].dt.to_pydatetime()
print (birthdays)
[datetime.datetime(1985, 1, 1, 0, 0) datetime.datetime(1977, 1, 1, 0, 0)
 datetime.datetime(1992, 1, 1, 0, 0)]

Thanks cᴏʟᴅsᴘᴇᴇᴅ and Scott Boston for comments.

You could also simply use pandas.Series.values :

names = df.Name.values
birthdays = df.BirthDay.astype(str).values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM