[英]Pandas Dataframe, add new column with range of data for each row in Python using Pandas
I have a dataframe with a single column and want to create a new column called 'Hour' for hours 0-23 but for each row.我有一个带有单列的 dataframe,我想为 0-23 小时但为每一行创建一个名为“Hour”的新列。
Current:当前的:
AN_LOG_ID
00000001
00000002
00000003
Desired output: (0-23 for each hour of the day for each row)所需的 output:(每行每天每小时 0-23)
AN_LOG_ID HOUR
00000001 0
00000001 1
... ...
00000001 23
00000002 0
00000002 1
... ...
00000002 23
00000003 0
00000003 1
... ...
00000003 23
>>> df = df.assign(HOUR=[range(24)] * len(df)).explode("HOUR", ignore_index=True)
>>> df
AN_LOG_ID HOUR
0 00000001 0
1 00000001 1
2 00000001 2
3 00000001 3
4 00000001 4
.. ... ...
67 00000003 19
68 00000003 20
69 00000003 21
70 00000003 22
71 00000003 23
[72 rows x 2 columns]
Assign range(24)
to each row as "HOUR" first, and then explode that "HOUR" column to spread hours on its own rows.首先将
range(24)
分配给每一行作为“HOUR”,然后展开该“HOUR”列以在其自己的行上展开小时数。 (ignore_index=True makes the resultant index 0, 1, 2, ...) (ignore_index=True 使结果索引为 0, 1, 2, ...)
We can use Index.repeat
then use groupby.cumcount
to get your HOUR
column:我们可以使用
Index.repeat
然后使用groupby.cumcount
来获取您的HOUR
列:
df = df.loc[df.index.repeat(24)]
df = df.assign(HOUR=df.groupby(level=0).cumcount()).reset_index(drop=True)
N_LOG_ID HOUR
0 00000001 0
1 00000001 1
2 00000001 2
3 00000001 3
4 00000001 4
.. ... ...
67 00000003 19
68 00000003 20
69 00000003 21
70 00000003 22
71 00000003 23
Another possible solution, based on numpy
:另一种可能的解决方案,基于
numpy
:
pd.DataFrame(
np.concatenate(
(np.repeat(df.values, 24).reshape(-1,1),
np.tile(np.arange(24), len(df)).reshape(-1,1)), axis=1),
columns=['AN_LOG_ID', 'HOUR'])
Output: Output:
AN_LOG_ID HOUR
0 00000001 0
1 00000001 1
2 00000001 2
3 00000001 3
4 00000001 4
.. ... ...
67 00000003 19
68 00000003 20
69 00000003 21
70 00000003 22
71 00000003 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.