gpt4 book ai didi

python - Pandas 数据帧 : Can you assign a label for the column names and/or the df values?

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:27 27 4
gpt4 key购买 nike

当您通过以下方式在 pandas 中定义数据框时

df = pd.DataFrame([['07-Dec-2015', 1,2],
['08-Dec-2015', 3,4],
['09-Dec-2015', 5,6]],
columns=['Date','FR','UK'])
df.set_index('Date')

Out[1]:
FR UK
Date
07-Dec-2015 1 2
08-Dec-2015 3 4
09-Dec-2015 5 6

有没有办法为列分配一个标签(假设为“国家/地区”),并为数据帧值分配另一个标签(假设为“点击”)。我想让它看起来像这样:

enter image description here

作为旁注:上面所附图片中的数据框已创建如下:

df = pd.DataFrame()
df['Date'] = ['07-Dec-2015','07-Dec-2015','08-Dec-2015','08-Dec-2015','09-Dec-2015','09-Dec-2015']
df['Country'] = ['UK','FR','UK','FR','UK','FR']
df['Hits'] = [2,1,4,3,6,5]
df = df.set_index(['Date','Country'])
df.unstack()
然而,这对于我的目的来说还不够好,因为在我的 python 应用程序中,数据帧构造函数传递了一个 numpy 数组,而索引 arg 传递了一个日期时间向量,因此从广义上讲,它看起来像: pd.DataFrame(numpy.ndarray, columns=columnNames, index=DatetimeIndex)

提前致谢

最佳答案

你可以:

df = pd.DataFrame(np.random.random((10, 2)), index=pd.DatetimeIndex(start=date(2015,1,1), periods=10, freq='D'))
df.index.name = 'Date'
df.columns = pd.MultiIndex.from_product([['Hits'], ['UK', 'FR']], names=['', 'Country'])

参见MultiIndex docs .

关于python - Pandas 数据帧 : Can you assign a label for the column names and/or the df values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com