正在尝试使用DASK在系列对象的DataFrame;切片副本上设置值(&Q)? [英] "A value is trying to be set on a copy of a slice from a DataFrame" for Series objects using Dask?

查看:16
本文介绍了正在尝试使用DASK在系列对象的DataFrame;切片副本上设置值(&Q)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试DaskDataFrames的apply()方法,并且正在运行以下代码:

import pandas as pd
import dask.dataframe as dd
import time


def enrich_str(str):
        
    val1 = f'{str}_1'
    val2 = f'{str}_2'
    val3 = f'{str}_3'
    time.sleep(3)
    
    return val1, val2, val3
    
def enrich_row(passed_row):
    
    col_name = str(passed_row['colName'])
    my_string = str(passed_row[col_name])
    
    val1, val2, val3 = enrich_str(my_string)
    
    passed_row['enriched1'] = val1
    passed_row['enriched2'] = val2
    passed_row['enriched3'] = val3
    
    return passed_row

df = pd.DataFrame({'numbers': [1, 2, 3, 4, 5], 'colors': ['red', 'white', 'blue', 'orange', 'red']}, 
                  columns=['numbers', 'colors'])
ddf = dd.from_pandas(df, npartitions=2)

ddf['colName'] = 'colors'

result = ddf.apply(enrich_row, axis=1,
                   meta={'numbers': 'int64', 'colors': 'string', 'colName': 'string',
                         'enriched1': 'string', 'enriched2': 'string', 'enriched3': 'string'})

tic = time.perf_counter()
enriched_df = result.compute()
toc = time.perf_counter()

print(f"{enriched_df.shape[0]} rows enriched in {toc - tic:0.4f} seconds")

print(enriched_df)

最终结果是正确的,但我收到以下警告:

5行在9.0715秒内丰富:17: SettingWithCopyWarning:正在尝试对 从DataFrame切片

请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy PASSED_ROW[‘enriched1’]=val1 C:UsersLZavarellaminiconda3envspbi_powerquery_envlibsite-packagespandascoreindexing.py:692: SettingWithCopyWarning:正在尝试对 从DataFrame切片

请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy Iloc.setitem_with_indexer(索引器,值,self.name) :18:SettingWithCopyWarning:值为 正在尝试设置来自DataFrame的切片的副本

请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy PASSED_ROW[‘enriched2’]=val2:19: SettingWithCopyWarning:正在尝试对 从DataFrame切片

请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy PASSED_ROW[‘enriched3’]=val3

我假设传入enrich_row()函数的行是Dataframe,所以我尝试使用Dataframes:

的新assign()方法将&raw";赋值替换到其中
passed_row.assign(enriched1 = val1)
passed_row.assign(enriched2 = val2)
passed_row.assign(enriched3 = val3)

但我收到以下错误:

AttributeError:‘Series’对象没有‘Assign’属性

所以我传递给函数的行是Series。

另外,将Pandas数据帧直接与this code一起使用时,不会出现这些警告。

在这一点上我有点困惑。有什么提示吗?

推荐答案

我正在MacOS上运行您的代码,但以下版本无法重现此问题:

- python=3.9.1
- pandas=1.2.4
- dask=2021.4.1

这篇关于正在尝试使用DASK在系列对象的DataFrame;切片副本上设置值(&Q)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆