Home > database >  Python - list 2 columns from excel file as list but alternate between values in columns
Python - list 2 columns from excel file as list but alternate between values in columns

Time:02-04

I have an excel file and have 2 columns that I would like to convert to a list. I want to alternate between the columns, so it would be like this:

"F1,O1,F2,O2,F3,O3....."

whats the best way using python? I have read the columns as df, and when i ask for list it just shows the headers.

#read profles excel ss, column O and drop all Nan cells
import pandas
path=r"Profiles.xlsx"
df = pandas.read_excel(path,usecols="F,O").dropna(how="all")
print(list(df))

This just shows "Header F, Header O"

Probably very simple but im new to python and learning :)

CodePudding user response:

To alternate between the two columns in the DataFrame df, you can try the following code:

# Convert columns to lists
col_F = df['F'].tolist()
col_O = df['O'].tolist()

# Combine the two lists alternating elements
result = [col_F[i] if i%2 == 0 else col_O[i//2] for i in range(len(col_F)   len(col_O))]

CodePudding user response:

This can be done with list comprehension, as mentioned in another another A simple for loop can also do the trick that you can understand easily.

Here is a sample on how that can be done:

a = list(range(1, 10, 2))
b = list(range(2,11, 2))
df = pd.DataFrame(columns = ['A','B'])
df['A'] = a
df['B'] = b
df

The sample dataframe created would be something like this:

    A   B
0   1   2
1   3   4
2   5   6
3   7   8
4   9   10

This is the for loop you want to run to get the desired result:

res = []
for i,r in df.iterrows():
    res.append(r['A'])
    res.append(r['B'])
print(res)
  • Related