简体   繁体   English

从现有的两列python中创建唯一ID

[英]Create unique ID from the existing two columns, python

My question is: how to efficiently sign data unique id numbers from existing id columns? 我的问题是:如何从现有的id列有效地签署数据唯一ID号? For example: I have two columns [household_id], and [person_no]. 例如:我有两列[household_id]和[person_no]。 I try to make a new column, the query would be: household_id + '_' + person_no. 我尝试创建一个新列,查询将是:household_id +'_'+ person_no。

here is a sample: 这是一个示例:

hh_id       pno  
 682138    1   
 365348    1     
 365348    2

try to get: 想拿到:

unique_id
682138_1
365348_1
365348_2

and add this unique_id as a new column. 并将此unique_id添加为新列。 I am applying Python. 我正在应用Python。 My data is very large. 我的数据非常大。 Any efficient way to do it would be great. 任何有效的方法都会很棒。 Thanks! 谢谢!

You can use pandas . 你可以使用熊猫

Assuming your data is in a csv file, read in the data: 假设您的数据位于csv文件中,请读入数据:

import pandas as pd 

df = pd.read_csv('data.csv', delim_whitespace=True)

Create the new id column: 创建新的id列:

df['unique_id'] = df.hh_id.astype(str) + '_' + df.pno.astype(str)

Now df looks like this: 现在df看起来像这样:

    hh_id  pno unique_id
0  682138    1  682138_1
1  365348    1  365348_1
2  365348    2  365348_2

Write back to a csv file: 写回csv文件:

df.to_csv('out.csv', index=False)

The file content looks like this: 文件内容如下所示:

hh_id,pno,unique_id
682138,1,682138_1
365348,1,365348_1
365348,2,365348_2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python-如何从现有列中的唯一值和相应值创建数据框中的新列? - Python - how to create new columns in a dataframe from the unique values from an existing column with corresponding values? 根据两列之间的关系创建唯一的ID - Create unique id based on the relation between two columns Python:从现有列创建一个新列 - Python: create a new column from existing columns 使用 pandas/python 从 DataFrame 中的两个现有文本列创建一个新列 - Create a new column from two existing text columns in a DataFrame using pandas/python 从唯一 ID 创建具有第一个和最后一个日期的列 - Create columns with first and last date from a unique ID python 3 中多个列表中两列的唯一组合/乘积 - Unique combination/product of two columns from multiple lists in python 3 如何每次创建一个唯一的字母数字 id 并确保它不存在于我使用 python 的现有列表中? - How to create a unique alphanumeric id each time and ensure it doesn't exist in my existing list using python? 从 4 个现有列创建一个新列(python pandas) - create a new column from 4 existing columns (python pandas) 使用 python pandas 从现有列创建一个新的地图列 - Create a new map column from existing columns using python pandas Python Pandas:从现有列创建日期数据框 - Python pandas: create a dataframe of dates from existing columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM