简体   繁体   English

如何在数据帧的每一行中添加元素?

[英]How to add an element to every row in a data frame?

I have three types of columns in my dataframe: numeric, string and datetime. 我的数据框中有三种类型的列:数字,字符串和日期时间。

I need to add the element | 我需要添加元素| to the end of every value as a separator 到每个值的末尾作为分隔符

I have tried: 我努力了:

df['column'] = (df['column']+ '|')

but it does not work for the datetime columns and I have to add .astype(str) to the numeric columns which may result in formatting issues later. 但不适用于datetime列,因此我必须将.astype(str)添加到数字列中,这可能会在以后导致格式问题。

Any other suggestions? 还有其他建议吗?

you can use DataFrame.to_csv() with sep="|", if you want to create a csv. 如果要创建csv,则可以将DataFrame.to_csv()与sep =“ |”一起使用。

further documentation : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html 更多文档: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

Not too sure why you would want to do this but if you want to make a CSV file with | 不太清楚为什么要这样做,但是如果要使用| as the delimiter, you can set that in the df.to_csv('out.csv', sep='|') method. 作为分隔符,您可以在df.to_csv('out.csv', sep='|')方法中进行设置。 I think a cleaner way of doing this would be to use a lambda function: 我认为更干净的方法是使用lambda函数:

df['column'] = df['column'].apply(lambda x: f"{x}|")

You will always have to add .astype(str) though... 您将始终需要添加.astype(str) ……

在这种情况下,这可能对您有帮助:

df['column'] = df['column'].astype(str) + "|"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM