繁体   English   中英

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

[英]pandas: Unable to write values to single row 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的特定单元格中设置的任何随机值

对于将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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM