Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

python - In pandas, what's the difference between df['column'] and df.column?

I'm working my way through Pandas for Data Analysis and learning a ton. However, one thing keeps coming up. The book typically refers to columns of a dataframe as df['column'] however, sometimes without explanation the book uses df.column.

I don't understand the difference between the two. Any help would be appreciated.

Below is come code demonstrating the what I am talking about:

In [5]:

import pandas as pd

data = {'column1': ['a', 'a', 'a', 'b', 'c'], 
        'column2': [1, 4, 2, 5, 3]}
df = pd.DataFrame(data, columns = ['column1', 'column2'])
df

Out[5]:
column1 column2
0    a   1
1    a   4
2    a   2
3    b   5
4    c   3
5 rows × 2 columns

df.column:

In [8]:

df.column1
Out[8]:
0    a
1    a
2    a
3    b
4    c
Name: column1, dtype: object

df['column']:

In [9]:

df['column1']
Out[9]:
0    a
1    a
2    a
3    b
4    c
Name: column1, dtype: object
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

for setting, values, you need to use df['column'] = series.

once this is done however, you can refer to that column in the future with df.column, assuming it's a valid python name. (so df.column works, but df.6column would still have to be accessed with df['6column'])

i think the subtle difference here is that when you set something with df['column'] = ser, pandas goes ahead and adds it to the columns/does some other stuff (i believe by overriding the functionality in __setitem__. if you do df.column = ser, it's just like adding a new field to any existing object which uses __setattr__, and pandas does not seem to override this behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...