Assign values to multiple columns in Pandas

一个人想着一个人 提交于 2019-12-01 04:18:26

Looks like solution is simple:

df['col2'], df['col3'] = zip(*[(2,3), (2,3), (2,3)])

There is a convenient solution to joining multiple series to a dataframe via a list of tuples. You can construct a dataframe from your list of tuples before assignment:

df = pd.DataFrame({0: [1, 2, 3]})
df[['col2', 'col3']] = pd.DataFrame([(2,3), (2,3), (2,3)])

print(df)

   0  col2  col3
0  1     2     3
1  2     2     3
2  3     2     3

This is convenient, for example, when you wish to join an arbitrary number of series.

I ran across this issue when trying to apply multiple scalar values to multiple new columns and couldn't find a better way. If I'm missing something blatantly obvious, let me know, but df[['b','c']] = 0 doesn't work. but here's the simplified code:

# Create the "current" dataframe
df = pd.DataFrame({'a':[1,2]})

# List of columns I want to add
col_list = ['b','c']

# Quickly create key : scalar value dictionary
scalar_dict = { c : 0 for c in col_list }

# Create the dataframe for those columns - key here is setting the index = df.index
df[col_list] = pd.DataFrame(scalar_dict, index = df.index)

Or, what appears to be slightly faster is to use .assign():

df = df.assign(**scalar_dict)

alternatively assign can be used

df.assign(col2 = 2, col3= 3)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html

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