简体   繁体   中英

set column of pandas.DataFrame object

Ideally, I want to be able something like:

cols = ['A', 'B', 'C']
df = pandas.DataFrame(index=range(5), columns=cols)
df.get_column(cols[0]) = [1, 2, 3, 4, 5]

What is the pythonic/pandonic way to do this?

Edit: I know that I can access the column 'A' by df.A , but in general I do not know what the column names are.

好的,这特别简单。

df[cols[0]] = [1, 2, 3, 4, 5] 

You do not need to store what columns a DataFrame has separately.

You can find out what columns exist in a pandas DataFrame by accessing the DataFrame.columns variable.

To access the Series attached to a particular column, you can use the getitem method of the DataFrame []

Tiny example:

col = df.columns[0]
df[col] = [1, 2, 3, 4, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM