gpt4 book ai didi

Pandas Dataframe groupby 将标签包含在 numpy 数组中

转载 作者:行者123 更新时间:2023-12-02 00:54:30 24 4
gpt4 key购买 nike

我想将 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]]

我希望它以开始日期作为一列。

[[2014-04-15 00 2]
[2014-04-15 01 2]
[2014-04-15 02 1]
[2014-04-15 03 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()

关于Pandas Dataframe groupby 将标签包含在 numpy 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436483/

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