Python 格式化字符串时替换行
我有这样一个熊猫数据框:Python 格式化字符串时替换行,python,pandas,dataframe,Python,Pandas,Dataframe,我有这样一个熊猫数据框: Date Miles Kilomètres Commentaires 0 07/04 17 27 string1 1 08/04 22 35 NaN 2 09/04 19 31 string2 3 10/04 20
Date Miles Kilomètres Commentaires
0 07/04 17 27 string1
1 08/04 22 35 NaN
2 09/04 19 31 string2
3 10/04 20 32 string2
4 11/04 7 11 Another random string
如果commentals
不是Nan
,我想连接列Date
和commentals
:
Date Miles Kilomètres Commentaires
0 07/04 17 27 07/04 - string1
1 08/04 22 35 NaN
2 09/04 19 31 09/04 - string2
3 10/04 20 32 10/04 - string2
4 11/04 7 11 11/04 - Another random string
以下代码段运行良好:
df.loc[(pd.notnull(df.Commentaires), 'Commentaires')] = df.Date + " - " + df.Commentaires
但它不是很像蟒蛇。我宁愿这样做:
df.loc[(pd.notnull(df.Commentaires), 'Commentaires')] = "{Date} - {Commentaires}".format(df)
但是我有一个键错误:“Date”
其他解决方案,其他问题:
df.loc[(pd.notnull(df.Commentaires), 'Commentaires')] = "{} - {}".format(df.Date, df.Commentaires)
print(df.head())
Date Miles Kilomètres Commentaires
0 07/04 17 27 0 07/04\n1 08/04\n2 09/04\n3 ...
1 08/04 22 35 NaN
2 09/04 19 31 0 07/04\n1 08/04\n2 09/04\n3 ...
3 10/04 20 32 0 07/04\n1 08/04\n2 09/04\n3 ...
4 11/04 7 11 0 07/04\n1 08/04\n2 09/04\n3 ...
我如何才能以最符合Python的方式获得我想要的结果?您可以删除布尔掩码:
df['Commentaires'] = df.Date + " - " + df.Commentaires
print (df)
Date Miles Kilometres Commentaires
0 07/04 17 27 07/04 - string1
1 08/04 22 35 NaN
2 09/04 19 31 09/04 - string2
3 10/04 20 32 10/04 - string2
4 11/04 7 11 11/04 - Another random string
通常情况下,当组合列时,zip非常强大。但是,对于要删除的na值,解决方案将更加复杂。类似于:
df['Commentaires'] = [' - '.join(i) if np.nan not in i else np.nan
for i in zip(df['Date'],df['Commentaires'])]
如何工作
df['commentals']=df.Date+“-”+df.commentals
?是的,为什么不工作df.Date+“-”+df.commentals
(将N/A转换为N/A)保持简单,愚蠢
:我没想到会这么容易。@Shan-x-没问题,它发生了;)