python - 用值代替熊猫数据框中的变量
问题描述
我有一个数据框如下:
df:
Name Age Type Result
Ra 35 adult $name is an $type of $age years
Ro 12 child $name behaves like $type as he is $age years old
<+100 rows>
结果列中的每个语句都是不同的。我需要做的就是用适当的值填充变量。
我知道多个选项,例如格式化字符串和字符串格式方法,但无法理解如何在上述数据框场景中实现它:
Option 1: f"Shepherd {name} is {age} years old."
Option 2: "Shepherd {} is {} years old.".format(name, age)
任何人都可以帮助使用吗?
解决方案
format_map采用字典来用实际值替换占位符。
在我们的例子中使用的占位符是列名。
DataFrame.applyaxis=1
使用数据框每一行的功能format_map
。
让你的 csv 像这样:
Name Age Type Result
Ra 35 adult {Name} is an {Type} of {Age} years
Ro 12 child {Name} behaves like {Type} as he is {Age} years old
代码:
df = pd.read_csv('data.csv', sep='\t')
df['Result'] = df.apply(lambda row: row['Result'].format_map(row), axis=1)
print(df)
输出
Name Age Type Result
0 Ra 35 adult Ra is an adult of 35 years
1 Ro 12 child Ro behaves like child as he is 12 years old
如果您无法更改数据,下面的代码也会产生相同的结果。
def str_substitute(row):
return row['Result']\
.replace('$name', row['Name'])\
.replace('$type', row['Type'])\
.replace('$age', str(row['Age']))
df['Result'] = df.apply(str_substitute, axis=1)
推荐阅读
- c - 当我只为它分配 1 个字节时,为什么 C 会正确输出一个整数?
- javascript - 如何使用react-js以动态形式将复选框值与文本输入绑定?
- php - 在单个 mysqli 查询中获得两个计数并执行计算
- jquery - 使用 jquery 显示自定义样式输入文件的文件名
- powershell - Powershell管道列表的第一行
- jwt - Identity Server 4 刷新令牌过期不起作用
- excel - 比较和突出第 18 列和第 20 列
- python - 如何找到两个numpy数组的多少列相互匹配?
- jquery - 将 keyup(Enter) 和 blur 事件组合在一起
- c# - 通过保持文本格式将所有文本从 RichTextBox1 克隆到 RichTextBox2