x.iloc[1]['x'] 和 x['x'].iloc[1] 有什么区别
What's the difference between x.iloc[1]['x'] and x['x'].iloc[1]
我无法使用 x.iloc[1]['x']=16 将 np.nan 的值更改为 16,但我可以使用 x['x' 更改它.iloc[1]=16。为什么?这两个表达式有什么区别?
x = pd.DataFrame({'x': [1, np.nan, 3], 'y': [3, 4, 5]})
x.iloc[1]['x']=16
print(x.iloc[1]['x'])
nan
x['x'].iloc[1]=16
print(x.iloc[1]['x'])
16.0
欢迎使用 Whosebug
评论中提供的答案是明确和充分的。
iloc 是一个很棒的工具,如果您想按自己的方式使用它,我想补充一点,您必须首先将要在其上的列传递给 select 行。在数据帧上循环以更改值的示例:
import pandas as pd
d = {'col1': [1, 2,'np.nan',4,5], 'col2': ['A','B','C','D','E']}
df = pd.DataFrame(data=d)
col1 col2
0 1 A
1 2 B
2 np.nan C
3 4 D
4 5 E
for i in range(len(df)):
if df['col1'].iloc[i] == "np.nan":
df['col1'].iloc[i] = 16
print(df)
col1 col2
0 1 A
1 2 B
2 16 C
3 4 D
4 5 E
避免链式索引
如评论中所述,您的两种选择都不能保证有效。 documentation 解释推理和基本原理。
一个有效而另一个无效的事实不值得研究,因为这些实施细节可能会发生变化。
对于标量,您应该使用iat
设置值按整数位置或at
按标签 .
iat
用于整数位置的标量设置
x.iat[1, x.columns.get_loc('x')] = 16
at
通过标签设置标量
x.at[x.index[1], 'x'] = 16
如果你的数据帧索引是常规的pd.RangeIndex
,最后的赋值可以简化:
x.at[1, 'x'] = 16
我无法使用 x.iloc[1]['x']=16 将 np.nan 的值更改为 16,但我可以使用 x['x' 更改它.iloc[1]=16。为什么?这两个表达式有什么区别?
x = pd.DataFrame({'x': [1, np.nan, 3], 'y': [3, 4, 5]})
x.iloc[1]['x']=16
print(x.iloc[1]['x'])
nan
x['x'].iloc[1]=16
print(x.iloc[1]['x'])
16.0
欢迎使用 Whosebug 评论中提供的答案是明确和充分的。
iloc 是一个很棒的工具,如果您想按自己的方式使用它,我想补充一点,您必须首先将要在其上的列传递给 select 行。在数据帧上循环以更改值的示例:
import pandas as pd
d = {'col1': [1, 2,'np.nan',4,5], 'col2': ['A','B','C','D','E']}
df = pd.DataFrame(data=d)
col1 col2
0 1 A
1 2 B
2 np.nan C
3 4 D
4 5 E
for i in range(len(df)):
if df['col1'].iloc[i] == "np.nan":
df['col1'].iloc[i] = 16
print(df)
col1 col2
0 1 A
1 2 B
2 16 C
3 4 D
4 5 E
避免链式索引
如评论中所述,您的两种选择都不能保证有效。 documentation 解释推理和基本原理。
一个有效而另一个无效的事实不值得研究,因为这些实施细节可能会发生变化。
对于标量,您应该使用iat
设置值按整数位置或at
按标签 .
iat
用于整数位置的标量设置
x.iat[1, x.columns.get_loc('x')] = 16
at
通过标签设置标量
x.at[x.index[1], 'x'] = 16
如果你的数据帧索引是常规的pd.RangeIndex
,最后的赋值可以简化:
x.at[1, 'x'] = 16