我的数据框如下:
编辑:基于注释和一些缺点,我已经编辑了有问题的数据框。修改后的数据框如下:
ID Static_Text Params
1 Today, {0} is quite Sunny. Tomorrow, {1} 1-10-2020
may be little {2}
1 Today, {0} is quite Sunny. Tomorrow, {1} 2-10-2020
may be little {2}
1 Today, {0} is quite Sunny. Tomorrow, {1} Cloudy
may be little {2}
2 Let's have a coffee break near {0}, if I Balcony
don't get any SO reply by {1}
2 Let's have a coffee break near {0}, if I 30
don't get any SO reply by {1} mins
我想要实现的是:
ID Final Text
1 Today, 1-10-2020 is quite Sunny. Tomorrow, 2-10-2020
may be little Cloudy
2 Let's have a coffee break near Balcony, if I
don't get any SO reply by 30 mins
即所有参数都插入到文本中。
现在可能有两种方法可以做到这一点。
首先,如下转换数据框,
ID Static Text Params
1 Today, {0} is quite Sunny. [1-10-2020,2-10-2020, Cloudy]
Tomorrow, {1} may be little {2}
然后我写一个下面的函数:
def update_text(x):
x['Static Text'] = x['Static Text'.format(x['Params'][0],x['Params'][1],x['Params'][2])]
rev_text = x['Static Text']
return rev_text
df['Final Text'] = df.apply(lambda x : update_text(x),axis=1)
在上述方法中,我试图在单行中将params列值作为列表(如上所示)。我怎么能达到同样的目的?
编辑:如我们所见,对于ID==2
,我有2个参数。因此update_text(x)
函数将不起作用。
另一种方法可能是使用df['Static Text'].str.replace(r'...', 'Params',n=1)
。但是,我需要找到正确的regex
。
无论哪种方式,我都无法找到具体的解决方案。 有人可以帮忙吗?
答案 0 :(得分:0)
有运气吗?我认为update_text()
函数需要进行修改,以动态执行字符串中的参数。