【问题标题】:join aggregation with if condition on one column pandas在一列 pandas 上加入带有 if 条件的聚合
【发布时间】: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

标签: python pandas


【解决方案1】:
猜你喜欢
  • 2019-01-08
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2021-08-24
  • 2018-01-22
  • 2019-08-10
  • 1970-01-01
相关资源
最近更新 更多