gpt4 book ai didi

python - pandas 试图告诉我什么警告?

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:38 25 4
gpt4 key购买 nike

我有以下代码,它只具有一个函数,该函数接受输入数据帧并输出一个按标签对它们进行分组并对它们求和的版本。

import pandas as pd
import random
import numpy as np

random.seed = 10

input_data = np.array(
[
[random.randint(0,9) for x in range(4)]+['g'],
[random.randint(0,9) for x in range(4)]+['g'],
[random.randint(0,9) for x in range(4)]+['a'],
[random.randint(0,9) for x in range(4)]+['b'],
[random.randint(0,9) for x in range(4)]+['b']
]
)

input_df = pd.DataFrame(data=input_data, columns=['A','B', 'C', 'D', 'label'])

def group_and_sum(input_df):
final_df = pd.DataFrame()
for gr,subdf in input_df.groupby('label'):
new_df = pd.DataFrame()

new_df['label'] = [gr]
columns = [x for x in input_df.columns if x!='label']
subdf[columns] = subdf[columns].values.astype(float)
for col in columns:
new_df[col] = [sum(subdf[col].values)]

new_df['sum'] = sum([new_df[x].values for x in columns])
final_df = pd.concat([final_df, new_df])
final_df.index = np.array(range(len(final_df)))
return final_df

final_df = group_and_sum(input_df)

抛出以下警告:

Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.17.0-py2.7-macosx-10.6-intel.egg/pandas/core/frame.py", line 2269
self.ix._setitem_with_indexer((slice(None), indexer), value)
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

有两件事:

1) 当我查看警告 here 时这似乎与我无关。正如警告中提供的链接所示,我没有执行诸如链式索引之类的操作。

2)当我尝试在函数之外重现错误时,由于某种原因我无法重现:

input_df[['A']]=input_df[['A']].astype(float)
input_df[['A','B']]=input_df[['A','B']].astype(float)

...它们都运行得很好。

还有其他方法可以重现此警告吗?它是否适用于此?谢谢。

最佳答案

我相信该警告是由于您的行 subdf[columns] = subdf[columns].values.astype(float) 引起的。您从 groupby 中获得了 subdf,因此 subdf 是对原始 DataFrame 某些行的引用。在此切片上设置值会导致警告。换句话说,就好像您进行了链式索引:

input_df[rows_that_are_part_of_this_group][columns] = ...

关于python - pandas 试图告诉我什么警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com