如何在 pandas 中使用默认值向现有 dataframe 添加新列
我们可以使用 dataframe 对象的 assign()
和 insert()
方法,以默认值向现有 dataframe 添加新列。我们还可以将默认值直接分配给要创建的 dataframe 列。
在以下各节中,我们将使用以下 dataframe
作为示例。
import pandas as pd
dates = ["april-10", "april-11", "april-12", "april-13"]
fruits = ["apple", "papaya", "banana", "mango"]
prices = [3, 1, 2, 4]
df = pd.dataframe({"date": dates, "fruit": fruits, "price": prices})
print(df)
输出:
date fruit price
0 april-10 apple 3
1 april-11 papaya 1
2 april-12 banana 2
3 april-13 mango 4
pandas.dataframe.assign()
在 pandas dataframe 中添加新列
我们可以使用 pandas.dataframe.assign() 方法向现有的 dataframe 添加新列,并为新创建的 dataframe
列分配默认值。
import pandas as pd
dates = ["april-10", "april-11", "april-12", "april-13"]
fruits = ["apple", "papaya", "banana", "mango"]
prices = [3, 1, 2, 4]
df = pd.dataframe({"date": dates, "fruit": fruits, "price": prices})
new_df = df.assign(profit=6)
print(new_df)
输出:
date fruit price profit
0 april-10 apple 3 6
1 april-11 papaya 1 6
2 april-12 banana 2 6
3 april-13 mango 4 6
该代码在 dataframe 中创建一个新列 profit
,并将整个列的值设置为 6
。
访问新列以将其设置为默认值
我们可以使用 dataframe 索引在 dataframe 中创建新列并将其设置为默认值。
语法:
df[col_name] = value
它在 dataframe df
中创建一个新列 col_name
,并将整个列的默认值设置为 value
。
import pandas as pd
dates = ["april-10", "april-11", "april-12", "april-13"]
fruits = ["apple", "papaya", "banana", "mango"]
prices = [3, 1, 2, 4]
df = pd.dataframe({"date": dates, "fruit": fruits, "price": prices})
df["profit"] = 5
print(df)
输出:
date fruit price profit
0 april-10 apple 3 5
1 april-11 papaya 1 5
2 april-12 banana 2 5
3 april-13 mango 4 5
pandas.dataframe.insert()
在 pandas dataframe 中添加新列
pandas.dataframe.insert() 允许我们在 dataframe 中在指定位置插入列。
语法:
dataframe.insert(loc, column, value, allow_duplicates=false)
它在位置 loc
处创建一个名称为 column
的新列,默认值为 value
。allow_duplicates=false
确保 dataframe 中只有一列名为 column
的列。
import pandas as pd
dates = ["april-10", "april-11", "april-12", "april-13"]
fruits = ["apple", "papaya", "banana", "mango"]
prices = [3, 1, 2, 4]
df = pd.dataframe({"date": dates, "fruit": fruits, "price": prices})
df.insert(2, "profit", 4, allow_duplicates=false)
print(df)
输出:
date fruit profit price
0 april-10 apple 4 3
1 april-11 papaya 4 1
2 april-12 banana 4 2
3 april-13 mango 4 4
在这里,名称为 profit
的列被插入到索引 2
,默认值为 4
。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串