熊猫:无法将值写入单行数据框

时间:2018-11-12 06:02:41

标签: python pandas dataframe

我有一个单行dataframe(df),我只想在其中使用索引号为每一列插入值。 数据帧df的格式如下。

 a b c
1 0 0 0
2 0 0 0
3 0 0 0

df.iloc[[0],[1]] = predictions[:1]

这会给我以下警告,并且不会在该行中写入任何内容:

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

但是,当我尝试使用

pred_row.iloc[0,1] = predictions[:1]

这给了我错误

ValueError: Incompatible indexer with Series

有没有一种方法可以将值写入单行数据帧。 预测是我尝试在df的特定单元格中设置的任何随机值

1 个答案:

答案 0 :(得分:0)

要将Series的一个元素设置为DataFrame,请更改为predictions[0]

print (df)
   a  b  c
1  0  0  0
2  0  0  0
3  0  0  0

predictions = pd.Series([1,2,3])
print (predictions)
0    1
1    2
2    3
dtype: int64

df.iloc[0, 1] = predictions[0]
#more general for set one element of Series by position
#df.iloc[0, 1] = predictions.iat[0]
print (df)
   a  b  c
1  0  1  0
2  0  0  0
3  0  0  0

详细信息

#scalar 
print (predictions[0])
1

#one element Series
print (predictions[:1])
0    1
dtype: int64

还可以将一个元素Series转换为一个元素数组,但是由标量设置更简单:

df.iloc[0, 1] = predictions[:1].values
print (df)
   a  b  c
1  0  1  0
2  0  0  0
3  0  0  0

print (predictions[:1].values)
[1]
相关问题