[英]Add new rows to data frame, where one column stays the same while other column changes values
sorry, if my title sounds a bit confusing.抱歉,如果我的标题听起来有点混乱。 What I'm basically trying to do is adding new rows in a data frame, where I duplicate the value of each unique value of one column, while another column's new values are changing.
我基本上想做的是在数据框中添加新行,我复制一列的每个唯一值的值,而另一列的新值正在改变。
This is what my data frame looks like:这是我的数据框的样子:
id ![]() |
year![]() |
---|---|
01 ![]() |
2022 ![]() |
02 ![]() |
2022 ![]() |
03 ![]() |
2022 ![]() |
... ![]() |
... ![]() |
99 ![]() |
2022 ![]() |
And I want it to look like this:我希望它看起来像这样:
id ![]() |
year![]() |
---|---|
01 ![]() |
2022 ![]() |
01 ![]() |
2023 ![]() |
01 ![]() |
2024 ![]() |
02 ![]() |
2022 ![]() |
02 ![]() |
2023 ![]() |
02 ![]() |
2024 ![]() |
03 ![]() |
2022 ![]() |
... ![]() |
... ![]() |
99 ![]() |
2024 ![]() |
Ie I want for every id to add the years 2023 and 2024 in the year column.即我希望每个 id 在年列中添加 2023 年和 2024 年。 I tried doing this with an apply function, but it always didn't work out, could you guys help me out in solving this?
我试过用apply函数做这个,但总是不行,你们能帮我解决这个问题吗?
years = [2022 + i for i in range(3)]
# or
years = [2022,2023, 2024]
pd.DataFrame({
'id': np.repeat((data:=df.id.to_numpy()), len(years)).reshape(-1,len(years)).flatten(),
'year': np.repeat(np.array(years), data.shape[0]).reshape(len(years), data.shape[0]).T.flatten()
})
一个快速的解决方案是制作当前数据框的两个副本,并将年份日期相应地更改为 2023 年和 2024 年。之后,使用pd.concat
将所有 3 个数据集连接在一起。
You can simply make a list comprehension and concat all dataframe years wirh increments of your desire.您可以简单地进行列表理解并根据您的需求增加所有数据帧年份。 For example:
例如:
pd.concat([df.assign(year=df.year+increment) for increment in range(0,3)]).sort_values(by='id').reset_index(drop=True)
This will increment your dataframe to three years as follows.这会将您的数据框增加到三年,如下所示。 You can play around with range for the desired number of extensions:
您可以使用范围来获得所需的扩展数量:
id ![]() |
year![]() |
---|---|
1 ![]() |
2022 ![]() |
1 ![]() |
2023 ![]() |
1 ![]() |
2024 ![]() |
2 ![]() |
2022 ![]() |
2 ![]() |
2023 ![]() |
2 ![]() |
2024 ![]() |
3 ![]() |
2022 ![]() |
3 ![]() |
2023 ![]() |
3 ![]() |
2024 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.