Hey you guy I got a dataframe like this
empoyees = [('jack', 34, 'Sydney',800) ,
('Riti', 31, 'Delhi',800) ,
('Aadi', 16, 'New York',800) ,
('Mohit', 32,'Delhi',1500) ,
]
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City',Salary], index=['a', 'b', 'c', 'd'])
how I can loop through columns in each row and get the result like this using pandas in python. Maybe add all it into a small list of each row
a Name jack Age 34 City Sydney Salary 800
b Name Riti Age 31 City Delhi Salary 800
c Name Aadi Age 16 City New York Salary 800
d Name Mohit Age 32 City Delhi Salary 1500
CodePudding user response:
You could use DataFrame.to_dict
with orient set to 'index'
The output of dict would be of the form:
{ idx1 : {col1:val1, col2:val2 ... coln:van},
idx2 : {col1:val1, col2:val2 ... coln:valn},
...
}
Loop through the dict and create a list of strings if would like to store them as a list.
[
f'{idx} {" ".join([str(v) for t in vals.items() for v in t])}'
for idx, vals in df.to_dict("index").items()
]
# output
# ['a Name jack Age 34 City Sydney Salary 800',
# 'b Name Riti Age 31 City Delhi Salary 800',
# 'c Name Aadi Age 16 City New York Salary 800',
# 'd Name Mohit Age 32 City Delhi Salary 1500']
If you only want to print them you don't need to build a list of strings. You could do:
for idx, vals in df.to_dict('index').items():
print(idx, *[v for t in vals.items() for v in t], sep=" ")
#output
# a Name jack Age 34 City Sydney Salary 800
# b Name Riti Age 31 City Delhi Salary 800
# c Name Aadi Age 16 City New York Salary 800
# d Name Mohit Age 32 City Delhi Salary 1500
CodePudding user response:
i kept it simple
s=''
for index, row in df.iterrows():
if index in s:
pass
else:
s =str(index)
for key, value in row[:].items():
s =" " key " " str(value)
print(s)
s=''
output
a Name jack Age 34 City Sydney Salary 800
b Name Riti Age 31 City Delhi Salary 800
c Name Aadi Age 16 City New York Salary 800
d Name Mohit Age 32 City Delhi Salary 1500