我有一个Excel,我需要将其转换为特定格式以写入CSV文件。我面临的一个问题是我的单元格值带有换行符。
例如:
Hi, This is Me. This is a standard Description. This is what I do.
我想用字符串"\n“替换新行,如下所示。例如:
Hi, This is Me.\n This is a standard Description.\n This is what I do.
我不能这样做。
我已尝试将\n替换为\n这不起作用。但是,\n使用空字符串或任何其他有效字符都可以。
import pandas as pd
my_sheet = 'Sheet1' # name of the sheet in the excel file
file_name = 'bulkload_format.xlsx' # name of my excel file
df = pd.read_excel(file_name, sheet_name = my_sheet)
cols = [16] # i want data in column 16 alone, this has \n characters that needs replacing
df = df[df.columns[cols]]
df = df.replace('\n','\\n', regex=True) #this does not work
for index, row in df.iterrows():
print(index, row[0])
export_csv = df.to_csv('out.csv', index = None, header=True, encoding='utf-8') #it directly write new lines in the CSV
\n文本需要替换为\n字符串。
发布于 2019-10-11 15:48:45
与@Rajith Thennakoon的解决方案相比,使用pandas
的text功能的更快的解决方案是:
df['name'] = df['name'].str.replace('\n', '\\n')
# 1000 loops, best of 3: 663 µs per loop
与
df['temp'] = df['name'].apply(lambda x: x.split('\n'))
df['name'] = df['temp'].apply(lambda x: ' \\n '.join(x))
df.drop(columns=['temp'])
# 1000 loops, best of 3: 1.98 ms per loop
发布于 2019-10-10 22:11:01
这不是最有效的解决方案,希望它能起作用,让我们将列名作为text
,将dataframe作为df
df["temp"] = df["text"].apply(lambda x: x.split('\n'))
df["text"] = df["temp"].apply(lambda x: ' \\n '.join(x))
df.drop(["temp"])
发布于 2021-05-08 13:36:23
好吧,这绝对不是最好的解决方案,但非常简单。如果您的文本位于单元格、A1
、A2
和A3
中,则可以使用b1
中的单元格和以下公式生成文本:
=a1&"\n"&a2&"\n"&a3&"\n"
...
https://stackoverflow.com/questions/58324561
复制相似问题