简体   繁体   English

Python Pandas-多重分配

[英]Python Pandas - Multiple assignment

Is there an efficient way to make the following assignment without using for loops? 有没有一种有效的方法可以在不使用for循环的情况下进行以下分配?

for i in range(0,len(df3)):
    if df3.loc[i,'field'] == "a":
        df3.loc[i,'field'] = "111"
    elif df3.loc[i, 'field'] == "b":
        df3.loc[i, 'field'] = "222"
    elif df3.loc[i, 'field'] == "c":
        df3.loc[i, 'field'] = "333"
    else:
        df3.loc[i,'field'] = "444"

You can simply do: 您可以简单地执行以下操作:

 df3.loc[df.field == 'a', 'field'] = '111'

and so on... 等等...

You can shorten the code, but you still need a loop to hop through the df3 structure and hit all your "field" fields. 您可以缩短代码,但仍然需要循环才能跳过df3结构并点击所有“字段”字段。

xlate = {'a':'111', 'b':'222', 'c':'333'}
for i in range(len(df3)):
    df3.loc[i, 'field'] = xlate.get(df3.loc[i, 'field'], '444')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM