Python 3.x 如何格式化数据框中的列名?
如何格式化数据框中的列名?下面是一个具有长列名的数据帧,这会导致列宽过宽Python 3.x 如何格式化数据框中的列名?,python-3.x,pandas,Python 3.x,Pandas,如何格式化数据框中的列名?下面是一个具有长列名的数据帧,这会导致列宽过宽 import pandas as pd import numpy as np price = np.array(range(10,16)) dates = pd.date_range("2020-12-31", periods = 6, freq ="B") df = pd.DataFrame(price, index = dates, columns = ['Daily Pric
import pandas as pd
import numpy as np
price = np.array(range(10,16))
dates = pd.date_range("2020-12-31", periods = 6, freq ="B")
df = pd.DataFrame(price, index = dates, columns = ['Daily Price'])
df['Daily Simple Return'] = (df/df.shift(1)-1).fillna(0)
df['Cumulative Simple Return'] = np.cumprod(1 + df['Daily Simple Return']).round(4)
df
Daily Price Daily Simple Return Cumulative Simple Return
2020-12-31 10 0.000000 1.0
2021-01-01 11 0.100000 1.1
2021-01-04 12 0.090909 1.2
2021-01-05 13 0.083333 1.3
2021-01-06 14 0.076923 1.4
2021-01-07 15 0.071429 1.5
使用本文件中包含的信息
我试图用下面的代码行修改列名,但却得到了意想不到的不良后果。虽然列名按需要进行了修改,但最后一列中的索引名和值却以不希望的方式进行了修改
df.style.set_table_styles([dict(selector="th",props=[('max-width', '40px')])])
Daily Cumulative
Daily Simple Simple
Price Return Return
2020-12-31 00:00:00 10 0.000000 1.000000
2021-01-01 00:00:00 11 0.100000 1.100000
2021-01-04 00:00:00 12 0.090909 1.200000
2021-01-05 00:00:00 13 0.083333 1.300000
2021-01-06 00:00:00 14 0.076923 1.400000
2021-01-07 00:00:00 15 0.071429 1.500000
有鉴于此,我的问题是:
是否可以只修改列名,同时保留原始数据帧的所有其他属性