我有一个 pandas 数据框,看起来像这样:
brand description former_price discounted_price
0 A icecream 1099.0 855.0
1 A cheese 469.0 375.0
2 B catfood 179.0 119.0
3 C NaN 699.0 399.0
4 NaN icecream 769.0 549.0
5 A icecream 769.0 669.0
Run Code Online (Sandbox Code Playgroud)
我想创建一个列,为每个品牌和描述组合分配唯一值。请注意,数据集中可能会缺少品牌或描述(由 NaN 值通知)。另请注意,如果品牌和描述相同(重复),我仍然希望该行的唯一值相同。
输出应如下所示:
product_key brand description former_price discounted_price
0 1 A icecream 1099.0 855.0
1 2 A cheese 469.0 375.0
2 3 B catfood 179.0 119.0
3 4 C NaN 699.0 399.0
4 5 NaN icecream 769.0 549.0
5 1 A icecream …Run Code Online (Sandbox Code Playgroud) 我有一个包含多个变量的数据框,我对如何对其进行子集化以使其仅包含第一个重复项很感兴趣。
>head(occurrence)
userId occurrence profile.birthday profile.gender postDate count
1 100469891698 6 47 Female 583 days 0
2 100469891698 6 47 Female 55 days 0
3 100469891698 6 47 Female 481 days 0
4 100469891698 6 47 Female 583 days 0
5 100469891698 6 47 Female 583 days 0
6 100469891698 6 47 Female 583 days 0
Run Code Online (Sandbox Code Playgroud)
在这里你可以看到数据框。'occurrence' 列计算同一个 userId 出现的次数。我尝试了以下代码来删除重复项:
occurrence <- occurrence[!duplicated(occurrence$userId),]
Run Code Online (Sandbox Code Playgroud)
但是,通过这种方式它可以删除“随机”重复项。我想保留 postDate 最旧的数据。例如,第一行应该是这样的:
userId occurrence profile.birthday profile.gender postDate count
1 100469891698 6 47 Female 583 days 0 …Run Code Online (Sandbox Code Playgroud) 我最近一直在使用 python,我发现了一个我似乎无法解决的问题。我正在使用 pandas 数据集,当我想使用 to_datetime 函数将变量的 dtype 从“object”更改为“datetime64”时,它不会将其更改为所需的“datetime64”dtype。
到目前为止我只尝试了 to_datetime 函数,但这似乎无法解决问题。我正在寻找一种解决方案来使 to_datetime 工作或任何其他可以将变量的数据类型从“object”更改为“datetime64”的代码
您可以在这里找到有关数据集的信息:
df.head()
Formatted Date Summary Precip Type Temperature (C) Apparent Temperature (C) Humidity Wind Speed (km/h) Wind Bearing (degrees) Visibility (km) Loud Cover Pressure (millibars) Daily Summary
0 2006-04-01 00:00:00.000 +0200 Partly Cloudy rain 9.472222 7.388889 0.89 14.1197 251.0 15.8263 0.0 1015.13 Partly cloudy throughout the day.
1 2006-04-01 01:00:00.000 +0200 Partly Cloudy rain 9.355556 7.227778 0.86 14.2646 259.0 15.8263 0.0 1015.63 Partly cloudy throughout the day. …Run Code Online (Sandbox Code Playgroud)