【问题标题】:Make index first row in group in pandas dataframe在熊猫数据框中创建索引第一行
【发布时间】:2020-09-26 22:51:30
【问题描述】:

我想知道是否可以根据索引创建每个组的第一行,即该索引的名称。假设我们有一个这样的df:

dic = {'index_col': ['a','a','a','b','b','b'],'col1': [1, 2, 3, 4, 5, 6]}
df = pd.DataFrame(dic).set_index('index_col')

是否可以将上面的数据框转换为类似于下面的数据框?这里发生的事情是索引已被重置,并且对于每个组,第一行是索引名称?

【问题讨论】:

  • 我想你要找的是groupby方法

标签: python pandas dataframe indexing expand


【解决方案1】:

结果是pandas.Series

df_list = []
for label , group in df.groupby('index_col'):
    df_list.append(pandas.concat([pandas.Series([label]), group['col1']]))

df_result = pandas.concat(df_list).reset_index(drop=True)

输出;

0    a
1    1
2    2
3    3
4    b
5    4
6    5
7    6
dtype: object

如果您需要数据框,请致电 df_result.to_frame()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 2016-01-13
    • 1970-01-01
    • 2022-09-24
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2022-07-10
    相关资源
    最近更新 更多