Python- excel添加自定义列标题
我正在使用CoinMarketCap REST API用于最新的加密货币类别。
代码将JSON响应打印到用于传输到Excel的数据框中(DF.TO_EXCEL)。我使用“ DF中的“ for column in in for column in in excel”中的宽度更大。
现在,我想知道如何在Excel表中添加服装列标题。
def Cryptocurrencies():
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/categories'
parameters = {
}
headers = {
'Accept': 'application/json',
'X-CMC_PRO_API_KEY': 'mypersonalapikey',
}
session = Session()
session.headers.update(headers)
data = session.get(url, params=parameters)
response = session.get(url, params=parameters)
f = (json.loads(response.text)['data'])
df = pd.DataFrame(f)
writer = pd.ExcelWriter("Workingpaper1D.xlsx",
engine='xlsxwriter',
datetime_format='mmm d yyyy hh:mm:ss',
date_format='mmmm dd yyyy')
df.to_excel(writer, sheet_name='Sheet1',
startrow=1, header=False, index=False, )
(max_row, max_col) = df.shape
worksheet = writer.sheets['Sheet1']
worksheet.autofilter(0, 0, max_row, max_col - 1)
for column in df:
column_length = max(df[column].astype(str).map(len).max(), len(column))
col_idx = df.columns.get_loc(column)
writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_length)
writer.save()
print(df)
return
I am using the Coinmarketcap REST Api for having the latest cryptocurrency categories.
The code prints the JSON response into a DataFrame which is used for the transfer to excel (df.to_excel). Im using the "for column in df" for a bigger width in excel.
Now I would like to know how I can add costum column headings into the excel sheet.
def Cryptocurrencies():
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/categories'
parameters = {
}
headers = {
'Accept': 'application/json',
'X-CMC_PRO_API_KEY': 'mypersonalapikey',
}
session = Session()
session.headers.update(headers)
data = session.get(url, params=parameters)
response = session.get(url, params=parameters)
f = (json.loads(response.text)['data'])
df = pd.DataFrame(f)
writer = pd.ExcelWriter("Workingpaper1D.xlsx",
engine='xlsxwriter',
datetime_format='mmm d yyyy hh:mm:ss',
date_format='mmmm dd yyyy')
df.to_excel(writer, sheet_name='Sheet1',
startrow=1, header=False, index=False, )
(max_row, max_col) = df.shape
worksheet = writer.sheets['Sheet1']
worksheet.autofilter(0, 0, max_row, max_col - 1)
for column in df:
column_length = max(df[column].astype(str).map(len).max(), len(column))
col_idx = df.columns.get_loc(column)
writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_length)
writer.save()
print(df)
return
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以设置这样的自定义标题:
另请参见 dataFrame标头格式。
You can set a custom header like this:
See also this section of the XlsxWriter docs on Formatting of the Dataframe headers.