首页 > 解决方案 > 用值代替熊猫数据框中的变量

问题描述

我有一个数据框如下:

    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)

任何人都可以帮助使用吗?

标签: pythonpandasdataframe

解决方案


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)

推荐阅读