像df.A = sr
这样的简单操作(将pandas.Series
分配给pandas.DataFrame
中的列)似乎无害,但它有许多细微差别。对于我这样刚开始学习pandas
的人来说,它带来了很多便利,同时也带来了困惑。
下面给出一个简单的示例/挑战:
df:
+----+-----+
| | A |
|----+-----|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
+----+-----+
l = [777, 666, 555, 444, 333]
sr:
+----+-----+
| | 0 |
|----+-----|
| 7 | 777 |
| 6 | 666 |
| 5 | 555 |
| 4 | 444 |
| 3 | 333 |
+----+-----+
df.A = sr
之后的 df
是什么样子?
或
df.A = l
之后的 df
是什么样的?
根据我目前的理解,我分解了df.A = sr
中的所有隐含操作,请纠正/确认/扩展:
例如,我不完全确定正确的术语。
# [0] a column in a DataFrame, is a Series, is a dictionary of index and values
# all cell to cell transfers are key-lookup based, individual element in an
# index is called a "label" for a reason.
# [1] if sr didn't have some of the index labels in df.col's index,
# the old values in those cells in df.col gets WIPED!
df.loc[ ~df.index.isin(sr.index)] = np.nan
# [2] values are transferred from sr cells into df cells with common index-labels.
# As expected
df.loc[ df.index.isin(sr.index), 'A'] =
sr.loc[ [idx for idx in sr.index if idx in df.index] ]
# [3] sr's cells, whoes index-lables are not found in df.index, are ignored and
# doesn't get to be assigned in df
sr.loc[ ~sr.index.isin(df.index)] # goes no where.
# [4] with all the wipping and ignore from above steps,
# there is no error message or warnings.
# it can cause your mistakes to slip thru:
"""
df = pd.DataFrame(0, columns=['A'], index=np.arange(5))
df.loc[ df.index.isin( ['A', 'B']), 'A'] = sr
print(df)
df = pd.DataFrame(0, columns=['A'], index=[])
df.A = sr
print(df)
"""
剧透。设置和结果:
df = pd.DataFrame(0, columns=['A'], index=np.arange(5))
l = [777, 666, 555, 444, 333]
sr = pd.Series(l, index=[7, 6, 5, 4, 3])
RESULTS:
df.A = sr
df:
+----+-----+
| | A |
|----+-----|
| 0 | nan |
| 1 | nan |
| 2 | nan |
| 3 | 333 |
| 4 | 444 |
+----+-----+
df.A = l
df:
+----+-----+
| | A |
|----+-----|
| 0 | 777 |
| 1 | 666 |
| 2 | 555 |
| 3 | 444 |
| 4 | 333 |
+----+-----+
最佳答案
所以您看到的结果是由于以下原因:
sr = pd.Series(l, index=[7, 6, 5, 4, 3])
您将 l 的索引值专门分配给 [7, 6, 5, 4, 3]。
当你这样做时:
df.A = sr
该系列保持其指数值。然后当你定义 df 时:
df = pd.DataFrame(0, columns=['A'], index=np.arange(5))
您确保最高索引值为 4 (index=np.arange(5)
)
因此,您的列输出保留了 sr 的索引值,并将这些值放入 A 中,因此仅显示索引 3,4 值。
当你这样做时:
df.A = l
您只需将 l 中的值分配给 A 列。因此所有值都会出现。如果您将 sr = pd.Series(l, index=[7, 6, 5, 4, 3])
更改为 sr = pd.Series(l)
,则设置 df.A = sr 。您最终会得到与 df.A = l
完全相同的结果。
关于python - 简单: df. A = sr中隐藏的地雷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874509/