【问题标题】:Pandas Dataframe groupby take lable included in numpy arrayPandas Dataframe groupby 将标签包含在 numpy 数组中
【发布时间】:2019-03-31 13:51:06
【问题描述】:

我想将 pandas 数据帧转换为带有 groupby 标签的 numpy 数组。 在 groupby 中,我必须使用正则表达式进行分组,因此带上它的标签很重要。

我的数据格式为:

start_date,is_member 

2014-04-15 00:01,1
2014-04-15 00:01,1
2014-04-15 01:01,1
2014-04-15 01:01,1
2014-04-15 02:02,1
2014-04-15 03:05,1

我试过了

df = pd.read_csv(filename, header=0)
df = df.groupby(df.start_date.str.extract("^(.*?)\:", expand=False))[['start_date']].count()[['start_date']]
print(df)

数据框的输出是

start_date               
2014-04-15 00           2
2014-04-15 01           2
2014-04-15 02           1
2014-04-15 03           1

我试过用

将它转换成 numpy 数组
numpy_array = df.values

numpy 数组的输出就是计数值

[[2]
 [2]
 [1]
 [1]]

我希望它以 startdate 作为列。

[[2014-04-15 00 2]
 [2014-04-15 01 2]
 [2014-04-15 02 1]
 [2014-04-15 03 1]]

【问题讨论】:

    标签: pandas numpy dataframe


    【解决方案1】:

    我相信您需要通过DataFrame.reset_index 将索引转换为列:

    #simplify code 
    df = df.groupby(df.start_date.str.extract("^(.*?)\:", expand=False))['start_date'].count()
    
    numpy_array = df.rename_axis('index').reset_index().values
    print (numpy_array)
    [['2014-04-15 00' 2]
     ['2014-04-15 01' 2]
     ['2014-04-15 02' 1]
     ['2014-04-15 03' 1]]
    

    for pandas 0.24+ 使用:

    numpy_array = df.rename_axis('index').reset_index().to_numpy()
    

    【讨论】:

    • 当我使用 .reset_index() 时出现错误,“无法插入 start_date,已存在”。如果你能帮忙的话。
    猜你喜欢
    • 2019-08-04
    • 2020-02-10
    • 2014-03-06
    • 1970-01-01
    • 2019-03-12
    • 2017-08-25
    • 2020-08-20
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多