【发布时间】:2022-01-23 02:03:18
【问题描述】:
使用pd.Index 与df.loc 有什么区别?它实际上是同一件事吗?
idx = pd.Index(('a', 'b'))
df = pd.DataFrame({'a': [0, 1], 'b': [2, 3], 'c': [0, 5]})
print(df.loc[:, ('a', 'b')],)
print(df[idx])
| a | b | |
|---|---|---|
| 0 | 0 | 2 |
| 1 | 1 | 3 |
【问题讨论】:
使用pd.Index 与df.loc 有什么区别?它实际上是同一件事吗?
idx = pd.Index(('a', 'b'))
df = pd.DataFrame({'a': [0, 1], 'b': [2, 3], 'c': [0, 5]})
print(df.loc[:, ('a', 'b')],)
print(df[idx])
| a | b | |
|---|---|---|
| 0 | 0 | 2 |
| 1 | 1 | 3 |
【问题讨论】:
loc 如何成为首选方法是described in the documentation。使用多个切片可能会导致SettingWithCopyWarning:
idx = ['a', 'b']
d = df[idx]
d.iloc[0,0] = 9
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
相比之下,使用loc 不会触发SettingWithCopyWarning:
idx = ['a', 'b']
d = df.loc[:,idx]
d.iloc[0,0] = 9
值得注意的是,loc 还允许您将特定轴作为参数传递:
df.loc(axis=1)[idx]
【讨论】:
当你做 loc 时,你可以做索引切片和列切片或组合,但是 pd.index 只能做列切片
df.loc[[0]]
a b c
0 0 2 0
df.loc[[0],['a','b']]
a b
0 0 2
IMO,loc 使用起来更灵活,我会选择loc,从长远来看会更清晰或检查后台。
【讨论】: