我有以下代码,它只有一个函数,它接收输入数据帧并输出一个版本,按label
对它们进行分组并对它们求和。
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时,它似乎与我无关。我没有做chained-indexing
之类的事情,因为警告中提供的链接表示。
2)当我尝试在函数之外重现错误时,我不能出于某种原因:
input_df[['A']]=input_df[['A']].astype(float)
input_df[['A','B']]=input_df[['A','B']].astype(float)
......那些都完美无缺。
有没有其他方法可以重现此警告,是否适用于此处?感谢。
答案 0 :(得分:1)
我认为警告是因为你的行subdf[columns] = subdf[columns].values.astype(float)
。您从groupby获得subdf
,因此subdf
是对原始DataFrame的某些行的引用。在此切片上设置值会导致警告。换句话说,就好像你做了链式索引:
input_df[rows_that_are_part_of_this_group][columns] = ...