【问题标题】:Add uuid to a new column in a pandas DataFrame将 uuid 添加到 pandas DataFrame 中的新列
【发布时间】:2018-07-27 23:12:18
【问题描述】:

我希望在 pandas DataFrame 的单个新列中为每一行添加一个 uuid。这显然用相同的 uuid 填充列:

import uuid
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(4,3), columns=list('abc'),
                  index=['apple', 'banana', 'cherry', 'date'])
df['uuid'] = uuid.uuid4()
print(df)

               a         b         c                                  uuid
apple   0.687601 -1.332904 -0.166018  34115445-c4b8-4e64-bc96-e120abda1653
banana -2.252191 -0.844470  0.384140  34115445-c4b8-4e64-bc96-e120abda1653
cherry -0.470388  0.642342  0.692454  34115445-c4b8-4e64-bc96-e120abda1653
date   -0.943255  1.450051 -0.296499  34115445-c4b8-4e64-bc96-e120abda1653

我正在寻找的是 'uuid' 列的每一行中的新 uuid。我也尝试使用 .apply() 和 .map() 没有成功。

【问题讨论】:

    标签: python python-3.x pandas dataframe uuid


    【解决方案1】:

    这是一种方式:

    df['uuid'] = [uuid.uuid4() for _ in range(len(df.index))]
    

    【讨论】:

    • 你能解释一下为什么这还不够吗? df['uuid'] = [uuid.uuid4() for _ in df.index] 似乎有相同的结果..我错过了什么?
    • @m1nkeh,它应该可以工作。但是使用 Python 循环迭代 range 比迭代 NumPy 数组更有效。
    【解决方案2】:

    我不能在这里谈论计算效率,但我更喜欢这里的语法,因为它与我通常用来生成新行的其他 apply-lambda 修改一致:

    df['uuid'] = df.apply(lambda _: uuid.uuid4(), axis=1)
    

    你也可以选择一个随机列来移除轴要求(为什么axis=0是默认的,我永远不会明白):

    df['uuid'] = df['col'].apply(lambda _: uuid.uuid4())
    

    从技术上讲,这些方法的缺点是您传递了一个实际上并没有使用的变量 (_)。能够执行lambda: uuid.uuid4() 之类的功能会稍微好一点,但apply 不支持没有参数的lambas,这是合理的,因为它的用例相当有限。

    【讨论】:

      【解决方案3】:
      from uuid import uuid4
      df['uuid'] = df.index.to_series().map(lambda x: uuid4())
      

      【讨论】:

      • 请补充说明
      【解决方案4】:

      要创建新列,您必须有足够的值来填充该列。如果我们知道行数(通过计算数据帧的 len),我们可以创建一组值,然后可以将其应用于列。

      import uuid
      import pandas as pd
      import numpy as np
      
      df = pd.DataFrame(np.random.randn(4,3), columns=list('abc'),
                        index=['apple', 'banana', 'cherry', 'date'])
      
      
      # you can create a simple list of values using a list comprehension 
      #     based on the len (or number of rows) of the dataframe
      df['uuid'] = [uuid.uuid4() for x in range(len(df))]
      print(df)
      
      apple  -0.775699 -1.104219  1.144653  f98a9c76-99b7-4ba7-9c0a-9121cdf8ad7f
      banana -1.540495 -0.945760  0.649370  179819a0-3d0f-43f8-8645-da9229ef3fc3
      cherry -0.340872  2.445467 -1.071793  b48a9830-3a10-4ce0-bca0-0cc136f09732
      date   -1.286273  0.244233  0.626831  e7b7c65c-0adc-4ba6-88ab-2160e9858fc4
      

      【讨论】:

        猜你喜欢
        • 2014-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 2014-05-19
        • 2020-12-28
        • 2019-07-06
        相关资源
        最近更新 更多