我有一个下面的字典,其中字典中的每个键都与一个数据框相关联。
data['total_brands'] = pd.DataFrame({'total_brands': {0: 164}})
data['new_portfolios_added'] = pd.DataFrame({'new_portfolios_added': {0: 3}})
data['total_updated_portfolios'] = pd.DataFrame({'total_updated_portfolios': {0: 1}})
data['family_per_brand'] = pd.DataFrame({'brand_name': {0: 'Morningstar',
1: 'Vanguard',
2: 'WisdomTree',
3: 'State Street',
4: 'First Trust',
5: 'Franklin Templeton Investments',
6: 'Logicly',
7: 'Nuveen',
8: 'Scott Burns',
9: 'Paul Merriman',
10: 'Fidelity',
11: 'FlexShares',
12: 'Alpha Architect',
13: 'Rick Ferri',
14: 'Craig Israelsen',
15: 'Rajan Subramanian',
16: 'Goldman Sachs',
17: 'JPMorgan',
18: 'Xtrackers',
19: 'PIMCO',
20: 'John Hancock',
21: 'Hartford',
22: 'Invesco',
23: 'Schwab'},
'family_per_brand': {0: 7,
1: 6,
2: 5,
3: 5,
4: 4,
5: 4,
6: 3,
7: 3,
8: 2,
9: 2,
10: 2,
11: 1,
12: 1,
13: 1,
14: 1,
15: 1,
16: 0,
17: 0,
18: 0,
19: 0,
20: 0,
21: 0,
22: 0,
23: 0}})
现在,我想将我的所有数据以文本格式发送到电子邮件中,并且电子邮件正文中的数据框看起来很漂亮。我在堆栈溢出中进行了搜索,发现这些功能可以帮助解决我的情况:
blanks = r'^ *([a-zA-Z_0-9-]*) .*$'
blanks_comp = re.compile(blanks)
def find_index_in_line(line):
index = 0
spaces = False
for ch in line:
if ch == ' ':
spaces = True
elif spaces:
break
index += 1
return index
def pretty_to_string(df):
lines = df.to_string().split('\n')
header = lines[0]
m = blanks_comp.match(header)
indices = []
if m:
st_index = m.start(1)
indices.append(st_index)
non_header_lines = lines[1:len(lines)]
for line in non_header_lines:
index = find_index_in_line(line)
indices.append(index)
mn = np.min(indices)
newlines = []
for l in lines:
newlines.append(l[mn:len(l)])
return '\n'.join(newlines) if df.shape[0] > 1 else ':'.join(newlines)
然后我尝试了:
final = "\n".join(pretty_to_string(data[key]) for key in data.keys())
print(final)
为我提供了以下输出,从附件中可以看出,这些输出在视觉上并不吸引人。
理想情况下,我希望在total_brands下有164个,在new_portfolios_added下有3个,在total_updated_portfolios下有1个,所有这些都向右对齐 理想情况下,我希望数据框的“ brand_name”列在“ total_updated_portfolios”选项卡下方对齐
答案 0 :(得分:0)
也许保存到csv,然后在excel中打开,将表复制到电子邮件中将是最快/最简单的。该方法通常会保留您选择的格式,具体取决于您的电子邮件客户端。
data.to_csv('newfilename.csv')