python - Pandas DataFrame Groupby 获取唯一行条件并识别增加值直至组数

标签 python pandas

我有一个 DataFrame,其中列值的组合标识一个唯一地址(A、B、C)。我想识别所有此类行并为它们分配一个唯一标识符,我会根据地址递增该标识符。

例如

A B C D E
0 1 1 0 1
0 1 2 0 1
0 1 1 1 1
0 1 3 0 1
0 1 2 1 0
0 1 1 2 1

我想生成以下内容

A B C D E  ID
0 1 1 0 1  0
0 1 2 0 1  1
0 1 1 1 1  0
0 1 3 0 1  2
0 1 2 1 0  1
0 1 1 2 1  0

我尝试了以下方法:

id = 0
def set_id(df):
    global id
    df['ID'] = id
    id += 1


df.groupby(['A','B','C']).transform(set_id)

这将返回一个 NULL 数据框......这绝对不是这样做的方式......我是 Pandas 的新手。上面实际上应该使用 df[['A','B','C']].drop_duplicates() 来获取所有唯一值 谢谢。

最佳答案

我想这就是你需要的:

df2 = df[['A','B','C']].drop_duplicates() #get unique values of ABC
df2 = df2.reset_index(drop = True).reset_index()  #reset index to create a column named index
df2=df2.rename(columns = {'index':'ID'}) #rename index to ID
df = pd.merge(df,df2,on = ['A','B','C'],how = 'left') #append ID column with merge

关于python - Pandas DataFrame Groupby 获取唯一行条件并识别增加值直至组数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713931/

相关文章:

python - 让 Tkinter 等到按下按钮

python - pandas:通过将 DataFrame 行与另一个 DataFrame 的列进行比较来创建新列

python - 以任何方式保存 pandas styler 对象

python - 从散点图拟合数据

python - 使用 pd.read_excel() 时,有没有办法解决 python 上的 ssl 错误(DH key 太小)?

python - pandas - 根据列值合并几乎重复的行

Python 导入 MySQLdb,Apache 内部服务器错误

python - 如何重载除法并与Python 2.x中的__future__除法兼容

javascript - 为什么 Flask 会与 Reactjs 一起用于 Restful API?

python - 将数据帧值映射到另一个数据帧