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

时间:2018-09-07 09:26:50

标签: python pandas dataframe

假设您有一个数据框:

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)

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

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!'}]

如何获取根据每行中的对应值替换值的功能?

1 个答案:

答案 0 :(得分:3)

使用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!'}]