【问题标题】:How can I assign first 10 values from one column, to first 10 rows of another column in pandas dataframe?如何将一列的前 10 个值分配给 pandas 数据框中另一列的前 10 行?
【发布时间】:2021-03-28 22:38:03
【问题描述】:

我有一个包含 2 列的数据框。我创建了一个新列并将所有值分配为“N”。

假设 Column1 = Year,Column2= week,现在 Column3(最初分配所有“N”)在最近 5 周内应等于“recent”,并且在此之前的所有周内都应等于“Pastweek”。我如何将 group by 与前 5 周条款一起使用? 我该怎么做?

Year Week C
2020 48 Recent
2020 47 Recent
2020 47 Recent
2020 46 Recent
2020 40 Pastwk
2019 52 PastWk

【问题讨论】:

标签: python pandas dataframe assign


【解决方案1】:

我为您的案例创建的示例数据集,我假设“C”列是新创建的列。

     A  B  C
0    1  a  N
1    2  b  N
2    3  c  N
3    4  d  N
4    5  a  N
5    6  b  N
6    7  c  N
7    8  d  N
8    9  a  N
9   10  b  N
10  11  c  N
11  12  d  N
12  13  a  N
13  14  b  N
14  15  c  N

您可以使用下面的代码将新列的前 10 个值更改为 A 列的前 10 个值。

for i in range(10):
    df.loc[df['C'].index == i, 'C'] = df['A'].iloc[i]

结果是:

     A  B   C
0    1  a   1
1    2  b   2
2    3  c   3
3    4  d   4
4    5  a   5
5    6  b   6
6    7  c   7
7    8  d   8
8    9  a   9
9   10  b  10
10  11  c   N
11  12  d   N
12  13  a   N
13  14  b   N
14  15  c   N

【讨论】:

  • 假设索引是随机的,因为另外两列是排序的,我们将如何访问 A 的前 5 行并将它们放入 C 中?
【解决方案2】:

对于您的情况,这应该有效:

df['name_of_col_1'][:10]= df['name_of_col_3'][:10]

【讨论】:

  • 谢谢。那行得通。但我发现了一个新的差异。假设 Colum1 = Year,Column2= week,现在 Column3 在最近 5 周内应该等于“recent”,并且在此之前的所有周内都应该等于“Pastweek”。如何将 group by 与前 5 周子句一起使用?
  • 这似乎是一个完全不同的问题,值得进一步研究。你有没有检查过,这样的案子是否已经开放?否则。请在新线程中提出该问题,以便其他人更容易找到它。
  • 这两个链接可能会对您有所帮助。我仍然建议添加一个新线程。 stackoverflow.com/questions/55222420/…stackoverflow.com/questions/48192376/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 2016-01-22
  • 2020-05-23
  • 1970-01-01
相关资源
最近更新 更多