连接dataframe中的列并生成新ID

2024-04-25 23:23:10 发布

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

我有一个数据帧

City  hits
A     10
B     1
C     22
D     122
E     1
F     165

我想用一个名为Hit\u ID的列创建一个数据帧,该列的行是

A_1
A_2
etc.
A_10
B_1
C_1
C_2 
etc.
D_124
D_125
E_1

我试过了 df['Hit_ID'] = df[['City','hits']].apply(lambda x:'_'.join(x.astype(str)),axis=1)但这只是连接列。如何修改apply函数以获得所需的op?你知道吗


Tags: 数据lambda函数idcitydfetcapply
2条回答

试试这个:

df['hits'] = df.hits.transform(lambda x: range(1, x))
s = df.apply(lambda x: pd.Series(x['hits']),axis=1).stack().reset_index(level=1, drop=True)
s.name = 'hits'
df = pd.concat([df.City, s], axis=1)
df['hit_id'] = df.City + '_' + df.hits.astype(str)
  • df.hits从整数列更改为列表列,范围从1到原始值。你知道吗
  • 使用@RomanPekar讨论的here技术将列表列扩展为一系列行。你知道吗
  • 将新列与原始df.City列连接起来。你知道吗
  • _将两列连接在一起。你知道吗

您需要:

#repeat index values by column hits
df = df.loc[df.index.repeat(df['hits'])].reset_index(drop=True)
#create counts
df['hits'] = df.groupby('City').cumcount() + 1
#concatenate columns
df['Hit_ID'] = df['City'] + '_' + df['hits'].astype(str)
print (df.head(20))
   City  hits Hit_ID
0     A     1    A_1
1     A     2    A_2
2     A     3    A_3
3     A     4    A_4
4     A     5    A_5
5     A     6    A_6
6     A     7    A_7
7     A     8    A_8
8     A     9    A_9
9     A    10   A_10
10    B     1    B_1
11    C     1    C_1
12    C     2    C_2
13    C     3    C_3
14    C     4    C_4
15    C     5    C_5
16    C     6    C_6
17    C     7    C_7
18    C     8    C_8
19    C     9    C_9

相关问题 更多 >