Home > Back-end >  Dynamically selecting columns in pandas based on a list of strings
Dynamically selecting columns in pandas based on a list of strings

Time:12-11

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

CodePudding user response:

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]

CodePudding user response:

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']
  • Related