У меня есть такой фрейм данных для панд:
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
Я хочу объединить столбцы Date
и Commentaires
, если Commentaires
не Nan
:
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)
Но тогда у меня есть KeyError: '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 ...
Как я могу получитьрезультат, который я хочу самым питонским способом?