使用DataFrame中的列值按行填充字符串

2024-09-23 10:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有一个数据帧:

import pandas as pd

sales = [{'account': 'Jones LLC', 'nuts': 150, 'bolts': 200, 'totalval': 140, 'Cur': 'pesos'},
         {'account': 'Alpha Co',  'nuts': 200, 'bolts': 210, 'totalval': 215, 'Cur': 'euros'},
         {'account': 'Blue Inc',  'nuts': 50,  'bolts': 90,  'totalval': 95 , 'Cur': 'pounds'}]

mydf = pd.DataFrame(sales)

你想产生一个字符串来庆祝这个月的利润。例如:

"We made 140 pesos from Jones LLC. Wahoo!"

我第一次尝试解决这个问题是使用一个带有占位符的模板字符串,并用逐行的每月数字格式化它。请注意,这些每月的数字是整数,而不是字符串。你知道吗

celebstring = "We made amt Cur from Jones LLC. Woohoo!"

def createpr(inputdf):
    for index, row in inputdf.iterrows():
        filledstring = celebstring.replace("amt","{0}".format(str(row["totalval"]))).replace('Cur','{0}'.format(str(row['Cur'])))
        inputdf['fullstring'] = filledstring
    return inputdf

df2 = createpr(mydf)

但是,当您运行此代码时,所有行的“fullstring”字段只填充最后一行的值。数据框如下所示(注意,为了可读性,我删除了两列):

sales = [{'account': 'Jones LLC','totalval': 140, 'Cur': 'pesos', 'fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'},
         {'account': 'Alpha Co','totalval': 215, 'Cur': 'euros', 'fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'},
         {'account': 'Blue Inc','totalval': 95 , 'Cur': 'pounds','fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'}]

如何让函数根据每行中相应的值来替换这些值?你知道吗


Tags: 字符串accountrowwenutssalesjonescur
1条回答
网友
1楼 · 发布于 2024-09-23 10:24:12

更容易使用format_map

In [40]: mydf.apply('We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1)
Out[40]:
0    We made 140 pesos from Jones LLC. Woohoo!
1     We made 215 pesos from Alpha Co. Woohoo!
2      We made 95 pesos from Blue Inc. Woohoo!
dtype: object

分配回

In [46]: mydf.assign(fullstring=mydf.apply(
          'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1))
Out[46]:
      Cur    account  bolts  nuts  totalval  \
0   pesos  Jones LLC    200   150       140
1   euros   Alpha Co    210   200       215
2  pounds   Blue Inc     90    50        95

                                  fullstring
0  We made 140 pesos from Jones LLC. Woohoo!
1   We made 215 pesos from Alpha Co. Woohoo!
2    We made 95 pesos from Blue Inc. Woohoo!

对于dict,可以使用to_dict

In [48]: mydf.assign(fullstring=mydf.apply(
              'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1)
             ).to_dict(orient='r')
Out[48]:
[{'Cur': 'pesos',
  'account': 'Jones LLC',
  'bolts': 200,
  'nuts': 150,
  'totalval': 140,
  'fullstring': 'We made 140 pesos from Jones LLC. Woohoo!'},
 {'Cur': 'euros',
  'account': 'Alpha Co',
  'bolts': 210,
  'nuts': 200,
  'totalval': 215,
  'fullstring': 'We made 215 pesos from Alpha Co. Woohoo!'},
 {'Cur': 'pounds',
  'account': 'Blue Inc',
  'bolts': 90,
  'nuts': 50,
  'totalval': 95,
  'fullstring': 'We made 95 pesos from Blue Inc. Woohoo!'}]

相关问题 更多 >