Home > Blockchain >  Create array from dataframe columns in python - error when iterating
Create array from dataframe columns in python - error when iterating

Time:10-01

I have created this dataframe

d = {'col1': [1], 'col2': [3]}
df = pd.DataFrame(data=d)
print(df)

enter image description here

I have then created a field called "columnA" which is supposed to be an array made of the two elements contained in col1 and col2:

filter_col = [col for col in df if col.startswith('col')]
df["columnA"] = df[filter_col].values.tolist()
print(df)

enter image description here

Now, I was expecting the columnA to be a list (or an array), but when I check the length of that field I get 1 (not 2, as I expected):

print("Lenght: ",str(len(df['columnA'])))

Length: 1

What do I need to do to get a value of 2 and therefore be able to iterate through that array?

For example, I would be able to do this iteration:

for i in range(len(df['columnA'])):
    print(i)

Result: 0 1

Can anyone help me, please?

CodePudding user response:

You are on right track, instead of direct using len() on dataframe, you have to take values and then apply

print("Lenght: ",len(df['columnA'].values[0]))

CodePudding user response:

for item in df["columnA"]:
    for num in item:
        print(num)

This will iterate directly over the column

  • Related