Reputation: 395
i am trying to get certain data in a dataframe using for loop. But when i run the loop all i get is the index of the data not the values presented in the rows
import pandas as pd
import numpy as np
data = {'time' : [1,2,3,4,5,6,7,8,9,10,11,12], 'values'[290,260,288,300,310,303,329,340,316,330,308,310]}
df = pd.DataFrame(data)
for i in df:
print(i)
I only get the index not the values
I also tried:
for index , values in df:
print(values)
It gives me this error: cannot unpack non-iterable int object
I know iterrows give me rows but i want it as a complete dataframe not each rows
Upvotes: 2
Views: 1132
Reputation: 13
Try using this:
for ind in df.index:
print(list(df[col][ind] for col in df.columns))
This piece of code prints the data row-wise
Upvotes: 0
Reputation: 5032
You can also use df.values
to iterate over the DataFrame
import pandas as pd
import numpy as np
data = {'time' : [1,2,3,4,5,6,7,8,9,10,11,12], 'values':[290,260,288,300,310,303,329,340,316,330,308,310]}
df = pd.DataFrame.from_dict(data)
>>> for i in df.values:
... print(i)
...
[ 1 290]
[ 2 260]
[ 3 288]
[ 4 300]
[ 5 310]
[ 6 303]
[ 7 329]
[ 8 340]
[ 9 316]
[ 10 330]
[ 11 308]
[ 12 310]
Further you can filter the required rows based on the indexes
of the columns
Upvotes: 0
Reputation: 5745
try use DataFrame.iterrows()
:
for index,row in df.iterrows():
print(row)
# each row is a pd.Series object so to access any values call row['column_name']
time,value = row['time'],row['value']
print(time,value)
Note: anyway i want to comment that it is not advised to use this type of operations in pandas because it is a nonvectorized solution which lack in performance in comparison to vectorized operations, I suggest you to look for vectorization in the internet... good luck :)
Upvotes: 7