1

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?

0

2 Answers 2

2

I think you need Series.tolist and for convert datetimes strftime if need convert datetimes to strings:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the error was bithdays instead of birthdays but this certainly works!
0

You could also simply use pandas.Series.values:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.