gpt4 book ai didi

python - Pandas :在字符串列中填充占位符

转载 作者:太空宇宙 更新时间:2023-11-04 02:20:37 24 4
gpt4 key购买 nike

我正在使用如下所示的 pandas DataFrame:

df = pd.DataFrame(
[['There are # people', '3', np.nan], ['# out of # people are there', 'Five', 'eight'],
['Only # are here', '2', np.nan], ['The rest is at home', np.nan, np.nan]])

导致:

    0                            1     2
0 There are # people 3 NaN
1 # out of # people are there Five eight
2 Only # are here 2 NaN
3 The rest is at home NaN NaN

我想用第 1 列和第 2 列中的不同字符串替换 # 占位符,导致:

0   There are 3 people
1 Five out of eight people are there
2 Only 2 are here
3 The rest is at home

我怎样才能做到这一点?

最佳答案

使用字符串格式

df=df.replace({'#':'%s',np.nan:'NaN'},regex=True)

l=[]

for x , y in df.iterrows():
if y[2]=='NaN' and y[1]=='NaN':
l.append(y[0])
elif y[2]=='NaN':
l.append(y[0] % (y[1]))
else:
l.append(y[0] % (y[1], y[2]))
l
Out[339]:
['There are 3 people',
'Five out of eight people are there',
'Only 2 are here',
'The rest is at home']

关于python - Pandas :在字符串列中填充占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51749235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com