pandas

Snippets

エクセルに出力する

import pandas as pd
pd.io.formats.excel.ExcelFormatter.header_style = None

df = pd.DataFrame()
df['a'] = [0.9, 0.8, 0.7]
df['b'] = ['qqq', 'www', 'eee']
df['c'] = ['a' * 100, 's' * 100, 'd' * 100]

xlsx_writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter')
workbook  = xlsx_writer.book
cell_format = workbook.add_format(
    {'text_wrap': True, 'valign': 'top', 'font_size': 9})
header_format = workbook.add_format({'align': 'center'})
df.to_excel(xlsx_writer, sheet_name='hoge', index=False)
worksheet = xlsx_writer.sheets['hoge']
worksheet.set_column(0, 1, 10, cell_format)
worksheet.set_column(2, 2, 20, cell_format)
worksheet.set_row(0, None, header_format)
xlsx_writer.close()

雑然データにする

import numpy as np
import pandas as pd

df_s = pd.DataFrame()
df_s['a'] = [0.9, 0.8, 0.7]
df_s['b'] = ['qqq', 'www', 'eee']
df_s['c'] = ['aaa', 'sss', 'ddd']
df_s['d'] = [10, 20, 30]
print(df_s)

n = 3
target_cols = ['a', 'b', 'c']
cols_l = [f'{col}_{i + 1}' for i in range(n) for col in target_cols]
df_l = pd.DataFrame(columns=cols_l)
df_l.loc[0] = np.concatenate([df_s.loc[i, target_cols].values for i in range(n)])
print(df_l)
     a    b    c   d
0  0.9  qqq  aaa  10
1  0.8  www  sss  20
2  0.7  eee  ddd  30
   a_1  b_1  c_1  a_2  b_2  c_2  a_3  b_3  c_3
0  0.9  qqq  aaa  0.8  www  sss  0.7  eee  ddd