将标量值分配给空的 DataFrame 似乎没有任何作用 [英] Assigning a scalar value to an empty DataFrame doesn't appear to do anything
问题描述
我是熊猫新手,有一个非常基本的问题,拜托!
I'm new to pandas and have a very basic question, please!
通过 spyder 在 Python v3.6 上:
On Python v3.6 through spyder:
x= pd.DataFrame(columns = ['1','2'])
print(x)
x['1'] = '25'
print(x)
从打印语句来看,数据框 x 似乎没有改变.我的问题:x['1'] = '25'
有什么作用?
From the print statements, the dataframe x does not appear to change.
My question: What does x['1'] = '25'
do, if anything?
推荐答案
分配标量和可迭代对象的语义实际上是有区别的(将列表等容器视为类列表对象).
There is actually a difference between the semantics of assigning scalars and iterables (think containers such as lists as list-like objects).
考虑,
df = pd.DataFrame(columns=['1', '2'])
df
Empty DataFrame
Columns: [1, 2]
Index: []
您已经定义了一个 空 数据框,没有任何索引(没有行),但只有列的架构.
You've defined an empty dataframe without any index (no rows), but only a schema for the columns.
当您为列分配标量时,分配将在所有行中广播.在这种情况下,因为没有,所以什么也没有发生:
When you assign a scalar to a column, the assignment is broadcast across all rows. In this case, since there are none, nothing happens:
df['1'] = 123
df
Empty DataFrame
Columns: [1, 2]
Index: []
然而,分配一个类似列表的可迭代对象是另一回事,因为 Pandas 会为其创建新行:
However, assigning a list-like iterable is a different story, as pandas will create new rows for it:
df['1'] = [123]
df
1 2
0 123 NaN
<小时>
现在,要了解标量分配的工作原理,请考虑一个类似的空 DataFrame,但具有已定义的索引:
Now, to understand how scalar assignment works, consider a similar empty DataFrame, but with a defined index:
df = pd.DataFrame(columns=['1', '2'], index=[0, 1])
df
1 2
0 NaN NaN
1 NaN NaN
它仍然是空的"(不是真的),但现在我们可以分配标量并广播分配,
it is still "empty" (not really), but now we can assign scalars and the assignment is broadcast,
df['1'] = 123
df
1 2
0 123 NaN
1 123 NaN
将此行为与之前显示的行为进行对比.
Contrast this behaviour with that previously shown.
这篇关于将标量值分配给空的 DataFrame 似乎没有任何作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!