python - 在熊猫数据框中正确左右对齐列
问题描述
我有一个以下字典,其中字典中的每个键都与一个数据框相关联。
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”选项卡下方对齐
解决方案
也许保存到 csv,然后在 excel 中打开,将表格复制到电子邮件中将是最快/最简单的。该方法通常会保留您选择的格式,具体取决于您的电子邮件客户端。
data.to_csv('newfilename.csv')
推荐阅读
- ansible - 在 Ansible Tower GUI 中设置凭据
- puppeteer - Puppeteer - 授权设备 (2FA)
- mysql - MYSQL 使用 WHERE、AND、OR 进行选择
- wordpress - 通过 CLI 在 WordPress 中更改主页
- python - 打开 nifti 文件时出现内存不足错误随机发生
- java - can i override singleTableEntityPersister for all my entities?
- javascript - 如何更改 JSPsych 中刺激呈现的权重?
- android - 当用户从 android 设置应用程序更改显示大小时,如何防止应用程序布局更改?
- angular - 如果使用搜索栏导航到 URI,则 Angular 身份验证防护失败
- c++ - 条件变量基本示例