Assigning a scalar value to an empty DataFrame doesn't appear to do anything

大憨熊 提交于 2021-02-19 03:24:58

问题


I'm new to pandas and have a very basic question, please!

On Python v3.6 through spyder:

x= pd.DataFrame(columns = ['1','2'])
print(x)
x['1'] = '25'
print(x)

From the print statements, the dataframe x does not appear to change. My question: What does x['1'] = '25' do, if anything?


回答1:


There is actually a difference between the semantics of assigning scalars and iterables (think containers such as lists as list-like objects).

Consider,

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: []

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

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.



来源:https://stackoverflow.com/questions/56602703/assigning-a-scalar-value-to-an-empty-dataframe-doesnt-appear-to-do-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!