如何将Pandas数据框架转换为CSV字符串?

635 阅读2分钟

要将Pandas DataFrame转换成CSV字符串而不是CSV文件,只需使用 [pd.to_csv()](https://blog.finxter.com/pandas-dataframe-to_csv-method/)函数,不带任何文件名或路径参数。该函数返回一个CSV字符串,你可以在你的Python脚本中用于进一步处理。

这里有一个例子。

# Convert DataFrame to CSV
csv_string = df.to_csv()

# Print the CSV string
print(csv_string)
'''
,Name,Age,Income
0,Alice,23,99000
1,Bob,24,88000
2,Carl,19,21000
3,Dave,33,129000
'''

你可以通过传递index=False 参数来修改这个输出。

# Convert DataFrame to CSV (no index)
csv_string = df.to_csv(index=False)

# Print the CSV string
print(csv_string)
'''
Name,Age,Income
Alice,23,99000
Bob,24,88000
Carl,19,21000
Dave,33,129000
'''

现在,你可以做一些高级的字符串/文本处理,比如用',' 逗号代替'\t' 表格式字符作为CSV分界符。

# Replace commas with tabs and overwrite variable
csv_string = csv_string.replace(',', '\t')

# Print the modified CSV string
print(csv_string)
'''
Name	Age	Income
Alice	23	99000
Bob	24	88000
Carl	19	21000
Dave	33	129000
'''

这里使用 [string.replace()](https://blog.finxter.com/python-string-replace-2/)方法来创建一个 选项卡分隔的值(TSV) 而不是逗号分隔的值(CSV) 字符串。

次优选择1:转换为临时CSV

现在你知道了将pandas DataFrame转换为CSV字符串的最优方案,让我给你一个不太理想的方法:将字符串写入一个临时文件,然后马上读取这个文件以获得一个CSV字符串。

df.to_csv('dummy.csv')
csv_string = open('dummy.csv').read()

我知道,我知道...😒

次优选择2:使用df.to_string()方法

[df.to_string()](https://blog.finxter.com/pandas-dataframe-to_string-method/)方法创建一个可以分配给字符串变量的DataFrame的字符串表示。

# DataFrame to String
csv_string = df.to_string()
print(csv_string)
'''
    Name  Age  Income
0  Alice   23   99000
1    Bob   24   88000
2   Carl   19   21000
3   Dave   33  129000
'''

现在,你可以对字符串表示法做一些后处理,从DataFrame中获得一个CSV字符串。

import re
import pandas as pd


df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Carl', 'Dave'],
                   'Age': [23, 24, 19, 33],
                   'Income': [99000, 88000, 21000, 129000]})

print(df.to_string(index=False, justify='left'))
csv_string = df.to_string(index=False)
csv_string = re.sub('^\s+', '', csv_string, flags=re.MULTILINE)
csv_string = re.sub('[ ]+', ',', csv_string)

print(csv_string)
'''
Name,Age,Income
Alice,23,99000
Bob,24,88000
Carl,19,21000
Dave,33,129000
'''

我甚至不想在这里开始解释,因为整个方法都在尖叫。