Skip to content Skip to sidebar Skip to footer

How To Loop Through A Pandas Dataframe

I am trying to loop through a Pandas dataframe. The list L includes values that are used to specify what row X or Y should begin from i.e., (1:, 2:, 3:). list = [1,2,3] for L in

Solution 1:

IIUC you can do something like the following:

l = [1,2,3]
results = []

for idx in l:
    X = data.ix[idx:, 'X':]
    Y = data.ix[idx:, 'Y']     
    regressor = LinearRegression()
    regressor.fit(X, Y)
    results.append(regressor.predict([[Variable]]))

However, I don't know what Variable is here, you could also just do the following:

for df in data.iloc[::1]:
    regressor = LinearRegression()
    regressor.fit(df['X'], df['Y'])
    results.append(regressor.predict([[Variable]]))

Solution 2:

You should try iterrrows,[http://pandas-docs.github.io/pandas-docs-travis/basics.html#iterrows]

>>>df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])>>>row = next(df.iterrows())[1]>>>row
int      1.0
float    1.5
Name: 0, dtype: float64

Solution 3:

You can also convert it to dict or list in before and than use as you know:

list_from_df = df.to_list()
for item in list_from_df:
   print(item)

Or as a dict:

df.to_dict()
for key, value in list_from_df.items():
   print(key) # indexprint(value)

Post a Comment for "How To Loop Through A Pandas Dataframe"