繁体   English   中英

如何遍历熊猫数据框

[英]How to loop through a Pandas dataframe

我正在尝试遍历Pandas数据框。 列表L包含用于指定XY应该从哪个行开始的值,即(1 :, 2 :, 3 :)。

list = [1,2,3]

for L in list:
    X = data.ix[L:, 'X':]
    Y = data.ix[L:, 'Y']     
    regressor = LinearRegression()
    regressor.fit(X, Y)
    prediction = regressor.predict([[Variable]])

尝试上述操作时的错误是:

TypeError: 'type' object is not iterable

IIUC您可以执行以下操作:

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]]))

但是,我不知道这里的Variable是什么,您也可以执行以下操作:

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

您应该尝试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

您还可以将其转换为dict或在之前和之后使用,如您所知:

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

或作为命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM