如何在函数中修改熊猫数据框“ cell”的值?

时间:2018-08-03 08:12:04

标签: python python-3.x pandas function dataframe

为什么要在Pyhon 3中使用此功能?

for i in range(0, len(df.index) ):
    df.loc[i,["Processed"]] =  "YES"

为什么不行?

def mylargeprocess(SomeData,Processed):
    Processed = "YES"

for i in range(0, len(df.index) ):
    mylargeprocess(df.loc[i,["SomeData"]],df.loc[i,["Processed"]])

我很确定这与字符串不可变有关,但是我仍然想了解那些代码之间的区别。

谢谢

1 个答案:

答案 0 :(得分:0)

pd.DataFrame.loc用于设置访问值。在第一个示例中,您正在设置值。在第二个示例中,您仅访问数据。首先,您将pd.DataFrame对象传递给函数,然后将字符串“ Yes”分配给变量Processed

您可以使用print调试自己的情况:

import pandas as pd

df = pd.DataFrame([['this', 'is'], ['a', 'test']],
                  columns=['col1', 'col2'])

def process(df_in):
    df_in = 'hello'
    print(df_in)  # you'll see 'hello' printed twice, no assignment happens

for i in range(len(df.index)):
    process(df.loc[i, ['col2']])