0

I currently have a dataframe like this:

    Month    Day Birthday
0   Jan      31  Yes
1   Apr      30  No
2   Mar      31  Yes
3   June     30  Yes

How would I select the columns dynamically and append them to another list? For example:

d= [Birthday, Month, Day, ...]
xx=[]
for f in range(len(d)):
    loan = df[f].values.tolist()
    xx.append(loan)

So that xx is the following:

[Yes,No,Yes,Yes,Jan,Apr,Mar,June,...]

Something like this but on a much larger scale.

I keep getting the following error:

KeyError: 0

When I try

for f in range(len(d)):
    loan = df[d[f]].values.tolist()

I get

IndexError: list index out of range

2 Answers 2

1

Try:

out = df[d].T.values.flatten().tolist()

With df[d], you can change the position of the columns according to d, the transpose the dataframe using T, select values as array, flatten the array and convert to list.

Output:

['Yes', 'No', 'Yes', 'Yes', 'Jan', 'Apr', 'Mar', 'June', 31, 30, 31, 30]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

xx = df.T.to_numpy().flatten().tolist()

Output:

>>> xx
['Jan', 'Apr', 'Mar', 'June', 31, 30, 31, 30, 'Yes', 'No', 'Yes', 'Yes']

Or,

xx = df.to_numpy().flatten().tolist()

Output:

>>> xx
['Jan', 31, 'Yes', 'Apr', 30, 'No', 'Mar', 31, 'Yes', 'June', 30, 'Yes']

3 Comments

Hi, i can easily make it all into a multiple dimensional area but i want it into a 1x1 list based on my set inputs or a set of inputs from a list that's the problem atm but thank you
Oh I see, so like ['Jan', 31, 'Yes', 'Apr', 30, 'No' ...] or ['Jan', 'Apr', ..., 31, 20, ..., 'Yes', 'No', ...]? Which one?
maybe do a ravel or flatten before tolist?

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.