如何创建字符串索引而不是数据帧中的数字?

2024-10-05 10:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从dataframe列中的内容创建唯一的行标识符,以代替索引列

例如

import pandas as pd
from pprint import pprint

df = pd.DataFrame(columns=["ID", "Animal", "Weight", "Description"])
df["ID"] = ["Qw9457", "gft878"]
df["Animal"] = ["Mouse", "Lion"]
df["Weight"] = [20, 67]
df["Description"] = ["hsdg rie",  "gtre sjdhi"]
pprint(df)

Output:
       ID Animal  Weight Description
0  Qw9457  Mouse      20    hsdg rie
1  gft878   Lion      67  gtre sjdhi

我更喜欢使用其余列中的内容重命名索引列, 例如:

df.index = ["MQwrie", "Lgfgt"]

我想知道是否有很好的方法来编程生成 列内容的行标识符(即索引列)


Tags: importid内容df标识符descriptionpdpprint
1条回答
网友
1楼 · 发布于 2024-10-05 10:19:26

如果希望根据每列中的数据位生成索引,可以使用串行操作将其拼凑在一起,然后分配索引。下面,我们使用动物名字的第一个字母、体重和描述的第一个单词作为新索引

import pandas as pd

df = pd.DataFrame({'ID': ['Qw9457', 'gft878'],
                   'Animal': ['Mouse', 'Lion'],
                   'Weight': [20, 67],
                   'Description': ['hsdg rie', 'gtre sjdhi']})

# create new index from data in df, assign as index
ix = df.Animal.str[0] + df.Weight.astype(str) + df.Description.str.split().str.get(0)
df_new = df.set_index(ix)

df_new
# returns:
             ID Animal  Weight Description
M20hsdg  Qw9457  Mouse      20    hsdg rie
L67gtre  gft878   Lion      67  gtre sjdhi

编辑: 是的,如果添加当前行号(从零开始),则可以使用:

ix = (
    df.Animal.str[0] 
    + df.Weight.astype(str)
    + df.Description.str.split().str.get(0)
    + df.index.astype(str).str.zfill(3)
)

df_new = df.set_index(ix)
df_new
#returns:
                ID Animal  Weight Description
M20hsdg000  Qw9457  Mouse      20    hsdg rie
L67gtre001  gft878   Lion      67  gtre sjdhi

相关问题 更多 >

    热门问题