【问题标题】:How to add a items from a list to a dataframe column in Python Pandas?如何将列表中的项目添加到 Python Pandas 中的数据框列?
【发布时间】:2021-12-16 09:48:41
【问题描述】:

我的列表包含数字x =(1,2,3,4,5,6,7,8) 我还有一个包含 1000 多行的 DataFrame。 我需要的是将列表中的数字分配到一列/创建一个新列,以便第 1-8 行包含数字 1-8,但之后它会重新开始,所以第 9 行应该包含数字 1 和以此类推。

这似乎很容易,但不知怎的,我无法做到这一点。

【问题讨论】:

标签: python pandas list


【解决方案1】:

这里有两种可能的方式(这里的例子有 3 项要重复):

使用 numpy.tile

df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = np.tile(x, len(df)//len(x)+1)[:len(df)]

itertools

from itertools import cycle, islice

df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = list(islice(cycle(x), len(df

输入:

   col
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9

输出:

   col  newcol
0    0       1
1    1       2
2    2       3
3    3       1
4    4       2
5    5       3
6    6       1
7    7       2
8    8       3
9    9       1

【讨论】:

  • 坦克很多,效果很好!
【解决方案2】:
from math import ceil
df['new_column'] = (x*(ceil(len(df)/len(x))))[:len(df)] 

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 2020-07-14
    • 2018-03-28
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多