本文介绍了使用iloc为pandas DataFrame中的特定单元格设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个与和 this .区别在于我必须按位置选择行,因为我不知道索引.
I have a question similar to this and this. The difference is that I have to select row by position, as I do not know the index.
我想做类似df.iloc[0, 'COL_NAME'] = x
的操作,但是iloc不允许这种访问.如果执行df.iloc[0]['COL_NAME] = x
,则会出现有关链接索引的警告.
I want to do something like df.iloc[0, 'COL_NAME'] = x
, but iloc does not allow this kind of access. If I do df.iloc[0]['COL_NAME] = x
the warning about chained indexing appears.
推荐答案
对于混合位置和索引,请使用.ix
.但是您需要确保索引不是整数,否则会引起混乱.
For mixed position and index, use .ix
. BUT you need to make sure that your index is not of integer, otherwise it will cause confusions.
df.ix[0, 'COL_NAME'] = x
更新:
或者,尝试
Update:
Alternatively, try
df.iloc[0, df.columns.get_loc('COL_NAME')] = x
示例:
import pandas as pd
import numpy as np
# your data
# ========================
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 2), columns=['col1', 'col2'], index=np.random.randint(1,100,10)).sort_index()
print(df)
col1 col2
10 1.7641 0.4002
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
# .iloc with get_loc
# ===================================
df.iloc[0, df.columns.get_loc('col2')] = 100
df
col1 col2
10 1.7641 100.0000
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
这篇关于使用iloc为pandas DataFrame中的特定单元格设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!