我使用以下代码在数据框中创建新列:
# data is a dataframe object
data.loc[:,'test'] = 5
它附带以下警告:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
我已经使用.loc[]
,为什么还有警告?我的代码中是否有任何特殊的缺点?谢谢!
答案 0 :(得分:0)
为什么不这样做,
>>> import pandas as pd
>>> data = pd.DataFrame([[1, 0], [2, 4]], columns=['unit', 'test'])
>>> data
unit test
0 1 0
1 2 4
>>> data['test'] = 5
>>> data
unit test
0 1 5
1 2 5
>>> data['another_test'] = 6
>>> data
unit test another_test
0 1 5 6
1 2 5 6