我有一个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
>>>