# keep in mind `row` is a named tuple and cannot be edited
for line, row in enumerate(df.itertuples(), 1): # you don't need enumerate here, but doesn't hurt.
if row.Qty:
if row.Qty == 1 and row.Price == 10:
df.set_value(row.Index, 'Buy', 1)
选项2
使用iterrows
# keep in mind that `row` is a `pd.Series` and can be edited...
# ... but it is just a copy and won't reflect in `df`
for idx, row in df.iterrows():
if row.Qty:
if row.Qty == 1 and row.Price == 10:
df.set_value(idx, 'Buy', 1)
选项3
使用带get_value的直上循环
for idx in df.index:
q = df.get_value(idx, 'Qty')
if q:
p = df.get_value(idx, 'Price')
if q == 1 and p == 10:
df.set_value(idx, 'Buy', 1)
好的,如果要在
df
中设置值,则需要跟踪index
值。选项1
使用
itertuples
选项2
使用
iterrows
选项3
使用带
get_value
的直上循环从0.21.0pd.DataFrame.set_value起,不推荐使用pandas.DataFrame.set_value方法
使用pandas.Dataframe.at
第一次在pandas中迭代是可能的,但是非常慢,因此使用另一个矢量化的解决方案。
如果需要迭代,可以使用^{} :
但更好的方法是使用矢量化的解决方案-使用
loc
按布尔掩码设置值:或者用^{} 的溶液:
或者如果您需要} :
if...else
使用^{样本。
按条件设置值:
相关问题 更多 >
编程相关推荐