【发布时间】:2023-01-18 23:10:25
【问题描述】:
我有一个看起来像这样的熊猫数据框:
| id | year | month | day | hour | timestamp | location_statindex |
|---|---|---|---|---|---|---|
| TP6045276120589011 | 2022 | 09 | 01 | 02 | 2022-09-01 02:01:23 | 1 |
| TP6031280073133032 | 2022 | 12 | 16 | 01 | 2022-12-16 01:48:42 | 1 |
大约有 300.000 行。
有类型
id object
year object
month object
day object
hour object
timestamp datetime64[ns]
location_statindex object
dtype: object
现在我创建一个新列,其中包含每一行的元素,例如:1\2022\09\01\02
使用此代码:df['folder_path'] = df[['location_statindex', 'year', 'month', 'day', 'hour']].agg('\\'.join, axis=1)
问题现在是否可以更改聚合,以便 location_statindex 的值是一个不同的字符串,具体取决于 if 条件。
像这样:
location = '2'
if location in ['1','2','3','4']:
location = f'Platz_optimiert_{location}'
elif location in ['5','6']:
location = f'KSPlatz_{location}'
else:
location = f'Platz_optimiert_TEF_{location}'
预期产出是同一数据框中的一个新列,其中包含来自相应行元素的连接字符串。例如,第一行的以下字符串。
'Platz_optimiert_1\2022\09\01\02'
我已经有一个解决方案,它使用 pandas 的 apply 函数和一个包含 if 块的自写函数。但是考虑到数据帧的大小,我想尝试减少必要的时间。聚合是否比应用更快?
【问题讨论】:
-
请提供结构正确的预期输出:
-
df.year.dtype不是int类型吗?agg应该抛出TypeError: sequence item 0: expected str instance, int found -
预期输出是同一数据框中的一个新列,其中包含来自相应行元素的连接字符串。例如,第一行的以下字符串。 'Platz_optimiert_1\2022\09\01\02'
-
列年、月、日、小时都是 str 的 dtype