我想将数据框转换为字符串。 How to turn a pandas dataframe row into a comma separated string这个主题很接近我想要的主题。此解决方案的唯一问题:我有一个带有字符串且带有分隔符的“国家/地区”列(例如,使用此解决方案,数据框正在转换为字符串,但是我有一个“美国”变成了“美国,州”) 所以目前我只有以下代码:
df = df.to_string(index=False).split('\n')
df = [','.join(ele.split()) for ele in df]
df = '\r\n'.join(df)
df = df.encode('utf8')
但对于这样的数据框:
data = [['United States', 10, 12], ['United Kingdom', 15, 25], ['France', 14, 18]]
df = pd.DataFrame(data, columns = ['Country', 'Number1', 'Number2'])
我会
b'Country,Number1,Number2\r\nUnited,States,10,12\r\n,United,Kingdom,15,25\r\nFrance,14,18'
代替:
b'Country,Number1,Number2\r\nUnited States,10,12\r\n,United Kingdom,15,25\r\nFrance,14,18'
目前我已经解决了许多问题:
df= df.replace('United,States', 'United States')
但这不是一个很好的解决方案,因为每当一个有空间的新国家来临时,我都必须更新脚本</ p>
(最终目标是在utf-8中将数据帧转换为字符串以允许计算其md5,而不使用df.to_csv()并计算所创建文件的md5,如果您有比此技巧更好的方法它也可以帮助我) 谢谢!
答案 0 :(得分:3)
data = [['United States', 10, 12], ['United Kingdom', 15, 25], ['France', 14, 18]]
df = pd.DataFrame(data, columns = ['Country', 'Number1', 'Number2'])
df = df.to_csv(header=None, index=False).strip('\n').split('\n')
df_string = '\r\n'.join(df) # <= this is the string that you can use with md5
df_bytes = df_string.encode('utf8') # <= this is bytes object to write the file
print(df_bytes)
使用df_string
用于 md5 和df_bytes
写入文件。
df_bytes
包含以下内容:
b'United States,10,12\r\nUnited Kingdom,15,25\r\nFrance,14,18'
答案 1 :(得分:1)
不发送到CSV的变体形式:
import pandas as pd
data = [['United States', 10, 12], ['United Kingdom', 15, 25], ['France', 14, 18]]
df = pd.DataFrame(data, columns = ['Country', 'Number1', 'Number2'])
df['Country']=df['Country'].str.replace(' ','_')
df = df.to_string(index=False).split('\n')
df = [','.join(ele.split()) for ele in df]
df = [element.replace('_',' ') for element in df]
df = '\r\n'.join(df)
df = df.encode('utf8')
df