I have a pandas dataframe like as below
df1 = pd.DataFrame({'biz': [18, 23], 'seg': [30, 34], 'PID': [40, 52]})
I would like to do the below
a) pass all the values from each column at once to for loop
For ex:
I am trying the below
cols = ['biz','seg','PID']
for col in cols:
for i, j in df1.col.values:
print("D" str(i) ":" "F" str(j))
print("Q" str(i) ":" "S" str(j))
print("AB" str(i) ":" "AD" str(j))
but this doesn;t work and I get an error
TypeError: cannot unpack non-iterable numpy.int64 object
I expect my output to be like as below
D18:F23
Q18:S23
AB18:AD23
D30:F34
Q30:S34
AB30:AD34
D40:F52
Q40:S52
AB40:AD52
CodePudding user response:
The mistake is in the innermost forloop.
You are requesting an iterator over a 1-dimensional array of values, this iterator yields scalar values and hence they can not be unpacked.
If your dataframe only has 2 items per column, then this should suffice
cols = ['biz','seg','PID']
for col in cols:
i, j = getattr(df1, col).values
print("D" str(i) ":" "F" str(j))
print("Q" str(i) ":" "S" str(j))
print("AB" str(i) ":" "AD" str(j))
CodePudding user response:
for i in range(len(df1)):
print('D' str(df1.iloc[i,0]) ':' 'F' str(df1.iloc[i 1,0]))
print('Q' str(df1.iloc[i,0]) ':' 'S' str(df1.iloc[i 1,0]))
print('AB' str(df1.iloc[i,0]) ':' 'AD' str(df1.iloc[i 1,0]))
print('D' str(df1.iloc[i,1]) ':' 'F' str(df1.iloc[i 1,1]))
print('Q' str(df1.iloc[i,1]) ':' 'S' str(df1.iloc[i 1,1]))
print('AB' str(df1.iloc[i,1]) ':' 'AD' str(df1.iloc[i 1,1]))
print('D' str(df1.iloc[i,2]) ':' 'F' str(df1.iloc[i 1,2]))
print('Q' str(df1.iloc[i,2]) ':' 'S' str(df1.iloc[i 1,2]))
print('AB' str(df1.iloc[i,2]) ':' 'AD' str(df1.iloc[i 1,2]))