use*_*696 3 python dataframe pandas
我有这样的数据帧:
match_id inn1 bat bowl runs1 inn2 runs2 is_score_chased
1 1 KKR RCB 222 2 82 1
2 1 CSK KXIP 240 2 207 1
8 1 CSK MI 208 2 202 1
9 1 DC RR 214 2 217 1
33 1 KKR DC 204 2 181 1
Run Code Online (Sandbox Code Playgroud)
现在我想通过比较runs1和runs2中的值来更改is_score_chased列中的值.如果runs1> runs2,则行中的相应值应为"yes",否则应为no.我尝试了以下代码:
for i in (high_scores1):
if(high_scores1['runs1']>=high_scores1['runs2']):
high_scores1['is_score_chased']='yes'
else:
high_scores1['is_score_chased']='no'
Run Code Online (Sandbox Code Playgroud)
但它没有用.如何更改列中的值?
你可以更轻松地使用np.where.
high_scores1['is_score_chased'] = np.where(high_scores1['runs1']>=high_scores1['runs2'],
'yes', 'no')
Run Code Online (Sandbox Code Playgroud)
通常情况下,如果您发现自己尝试在设置列时进行显式迭代,则会有一个类似的抽象apply或where更快更简洁的抽象.
这是使用apply的好例子。
这里有一个在两列上使用 apply 的例子。
您可以通过以下方式使其适应您的问题:
def f(x):
return 'yes' if x['run1'] > x['run2'] else 'no'
df['is_score_chased'] = df.apply(f, axis=1)
Run Code Online (Sandbox Code Playgroud)
但是,我建议用布尔值填充您的列,以便您可以使其更简单
def f(x):
return x['run1'] > x['run2']
Run Code Online (Sandbox Code Playgroud)
并且还使用 lambdas 这样你就可以在一行中完成
df['is_score_chased'] = df.apply(lambda x: x['run1'] > x['run2'], axis=1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13716 次 |
| 最近记录: |