【问题标题】:How to modify the value of a pandas dataframe "cell" from within a function?如何从函数中修改熊猫数据框“单元格”的值?
【发布时间】:2018-08-03 08:12:04
【问题描述】:

为什么这会在 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"]])

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

谢谢,

【问题讨论】:

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


    【解决方案1】:

    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']])
    

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 2021-08-16
      • 1970-01-01
      • 2022-12-05
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      相关资源
      最近更新 更多