pandas dataframe 新增单列和多列

喜欢ヅ旅行 2023-02-28 05:37 88阅读 0赞

dataframe 新增单列

assign方法

dataframe assign方法,返回一个新对象(副本),不影响旧dataframe对象

  1. import pandas as pd
  2. df = pd.DataFrame({
  3. 'col_1': [0, 1, 2, 3],
  4. 'col_2': [4, 5, 6, 7]
  5. })
  6. sLength = len(df['col_1'])
  7. df2 = df.assign(col_3=pd.Series([8, 9, 10, 11]).values)
  8. print(df)
  9. print(df2)

结果展示:

  1. col_1 col_2
  2. 0 0 4
  3. 1 1 5
  4. 2 2 6
  5. 3 3 7
  6. col_1 col_2 col_3
  7. 0 0 4 8
  8. 1 1 5 9
  9. 2 2 6 10
  10. 3 3 7 11

简单的方法和insert方法

简单的方法df[‘col_3’] = pd.Series([8, 9, 10, 11])
insert方法 df.insert(loc=len(df.columns), column=“col_4”, value=[8, 9, 10, 11])
这种方式会对旧的dataframe新增列

  1. import pandas as pd
  2. df = pd.DataFrame({
  3. 'col_1': [0, 1, 2, 3],
  4. 'col_2': [4, 5, 6, 7]
  5. })
  6. df['col_3'] = pd.Series([8, 9, 10, 11])
  7. print(df)
  8. df.insert(loc=len(df.columns), column="col_4", value=[8, 9, 10, 11])
  9. print(df)

dataframe 新增多列

list unpacking

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame({
  4. 'col_1': [0, 1, 2, 3],
  5. 'col_2': [4, 5, 6, 7]
  6. })
  7. df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
  8. print(df)

结果展示:

  1. col_1 col_2 column_new_1 column_new_2 column_new_3
  2. 0 0 4 NaN dogs 3
  3. 1 1 5 NaN dogs 3
  4. 2 2 6 NaN dogs 3
  5. 3 3 7 NaN dogs 3

DataFrame也可以一行匹配

  1. df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

concat方法

  1. df = pd.concat(
  2. [
  3. df,
  4. pd.DataFrame(
  5. [[np.nan, 'dogs', 3]],
  6. index=df.index,
  7. columns=['column_new_1', 'column_new_2', 'column_new_3']
  8. )
  9. ], axis=1
  10. )

join方法

  1. df = df.join(pd.DataFrame(
  2. [[np.nan, 'dogs', 3]],
  3. index=df.index,
  4. columns=['column_new_1', 'column_new_2', 'column_new_3']
  5. ))

join + 字典

  1. df = df.join(pd.DataFrame(
  2. {
  3. 'column_new_1': np.nan,
  4. 'column_new_2': 'dogs',
  5. 'column_new_3': 3
  6. }, index=df.index
  7. ))

assign方法

  1. df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)

土方法

  1. df['column_new_1'] = np.nan
  2. df['column_new_2'] = 'dogs'
  3. df['column_new_3'] = 3

发表评论

表情:
评论列表 (有 0 条评论,88人围观)

还没有评论,来说两句吧...

相关阅读