我的数据框df
有'TPrice','THigh','TLow','TOpen','TClose','TPCLOSE'
列,现在我想将'TPrice','THigh','TLow','TOpen','TClose'
列的值设置为与'TPCLOSE'
列相同的行TPrice
1}}列值为零。
显示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
那怎么办?
杰夫解决方案的更新:
>>> 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
>>>
答案 0 :(得分:3)
此操作不会自动广播,因此您需要执行此类操作
In [17]: df = DataFrame(dict(A = [1,2,0,0,0],B=[0,0,0,10,11],C=[3,4,5,6,7]))
In [18]: df
Out[18]:
A B C
0 1 0 3
1 2 0 4
2 0 0 5
3 0 10 6
4 0 11 7
首先计算要屏蔽的行(否则它们可能会随时更改) 如果你要修改A(就像你在这里一样)
In [19]: mask = df['A'] == 0
In [20]: for col in ['A','B']:
....: df.loc[mask,col] = df['C']
....:
In [21]: df
Out[21]:
A B C
0 1 0 3
1 2 0 4
2 5 5 5
3 6 6 6
4 7 7 7
这需要进行更改以使其更自然(因为您将rhs上的一系列分配给lhs上的数据帧,现在它不会像您认为的那样进行广播) https://github.com/pydata/pandas/issues/5206
答案 1 :(得分:1)
>>> import pandas as pd
>>> test=pd.DataFrame({'A': [0,1,2], 'B': [3,4,5], 'C': [6,7,8]})
>>> test
A B C
0 0 3 6
1 1 4 7
2 2 5 8
>>> test.apply(lambda x: x.where(test.A!=0, test.C), axis=0)
A B C
0 6 6 6
1 1 4 7
2 2 5 8