我有一个数据框 df,它有'TPrice'、'THigh'、'TLow'、'TOpen'、'TClose'和'TPCLOSE'列,现在我想将'TPrice'、'THigh'、'TLow'、'TOpen'、'TClose'列的值设置为与'TPCLOSE'列相同的值,对于那些'TPrice'列值为零的行。
展示一些'TPrice'为0的行:
>>> df[df['TPrice']==0][['TPrice','THigh','TLow','TOpen','TClose','TPCLOSE']][0:5]
TPrice THigh TLow TOpen TClose TPCLOSE
13 0 0 0 0 0 4.19
19 0 0 0 0 0 7.74
32 0 0 0 0 0 3.27
43 0 0 0 0 0 12.98
60 0 0 0 0 0 7.48
然后是任务分配:
>>> df[df['TPrice']==0][['TPrice','THigh','TLow','TOpen','TClose']] = df['TPCLOSE']
但是Pandas实际上并没有改变df,因为以下代码仍然可以找到一些行:
>>> df[df['TPrice']==0][['TPrice','THigh','TLow','TOpen','TClose','TPCLOSE']][0:5]
TPrice THigh TLow TOpen TClose TPCLOSE
13 0 0 0 0 0 4.19
19 0 0 0 0 0 7.74
32 0 0 0 0 0 3.27
43 0 0 0 0 0 12.98
60 0 0 0 0 0 7.48
所以怎么做呢?更新Jeff的解决方案:
>>> quote_df = get_quote()
>>> quote_df[quote_df['TPrice']==0][['TPrice','THigh','TLow','TOpen','TClose','TPCLOSE','RT','TVol']][0:5]
TPrice THigh TLow TOpen TClose TPCLOSE RT TVol
13 0 0 0 0 0 4.19 -100 0
32 0 0 0 0 0 3.27 -100 0
43 0 0 0 0 0 12.98 -100 0
45 0 0 0 0 0 26.74 -100 0
60 0 0 0 0 0 7.48 -100 0
>>> row_selection = quote_df['TPrice']==0
>>> col_selection = ['THigh','TLow','TOpen','TClose']
>>> for col in col_selection:
... quote_df.loc[row_selection, col] = quote_df['TPCLOSE']
...
>>> quote_df[quote_df['TPrice']==0][['TPrice','THigh','TLow','TOpen','TClose','TPCLOSE','RT','TVol']][0:5]
TPrice THigh TLow TOpen TClose TPCLOSE RT TVol
13 0 4.19 4.19 4.19 4.19 4.19 -100 0
32 0 4.19 4.19 4.19 4.19 3.27 -100 0
43 0 4.19 4.19 4.19 4.19 12.98 -100 0
45 0 4.19 4.19 4.19 4.19 26.74 -100 0
60 0 4.19 4.19 4.19 4.19 7.48 -100 0
>>>
df.loc[rows_selector,columns_selector] = ...
。 - Jeff