【发布时间】:2021-08-01 14:01:03
【问题描述】:
我正在测试 Dask 数据帧的 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 pass_row['enriched1'] = val1 C:\Users\LZavarella\miniconda3\envs\pbi_powerquery_env\lib\site-packages\pandas\core\indexing.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 pass_row['enriched2'] = val2 :19: SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片
请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy pass_row['enriched3'] = val3
我认为传递到 enrich_row() 函数中的行是 Dataframes,所以我尝试使用 Dataframes 的新 assign() 方法替换“原始”分配:
passed_row.assign(enriched1 = val1)
passed_row.assign(enriched2 = val2)
passed_row.assign(enriched3 = val3)
但我收到以下错误:
AttributeError: 'Series' 对象没有属性 'assign'
所以我传递给函数的行是系列。
另外,直接使用带有this code 的 Pandas 数据帧,不会出现这些警告。
在这一点上我有点困惑。有什么提示吗?
【问题讨论】:
标签: python pandas dataframe dask