假设我有一个数据框架。我想取col1中的值(例如A
)并返回多个值,如A.1
,A.2
,A.3
等。
本列中的每个值对应于其他地方的数据组。我想运行一个自定义函数,返回这些值的列表,我想创建一个新的数据框,新行与原始行相同,除了在col1
中更改的值:
:
Col1, Col2, Col3
A, 55, type
如果A
对应一个列表,如AB
,AJ
,AI
,我想要一个新的数据帧:
Col1,Col2,Col3
AB, 55, type
AJ, 55, type,
AI, 55, type
假设col1
s之间的映射包含在字典中,例如
mapping = {'AB':'A', 'AJ':'A', 'AI':'A'}
然后你可以创建一个映射的新表,并将它连接到原来的表:
df = pd.DataFrame({'Col1':['A'], 'Col2':[55], 'Col3':['type']})
df_map = pd.DataFrame(mapping.items(), columns=['Col1_new', 'Col1'])
df_new = pd.merge(df, df_map)
Col1 Col2 Col3 Col1_new
0 A 55 type AB
1 A 55 type AJ
2 A 55 type AI
# define the two tables
a = pd.DataFrame({'Col1':['A'], 'Col2':[55], 'Col3':['type']})
b = pd.DataFrame({'Col1': ['AB', 'AJ', 'AI']})
# Create a column in your second table that matches `Col1` in your first table
# it appears you want that to be the first letter of `Col1` in table `b`:
b['key'] = b['Col1'].str[0]
# Join the two tables together on that key that matches across both
df = a.set_index('Col1').join(b.set_index('key'))
# Rearrange as you like:
df = df[['Col1', 'Col2', 'Col3']]
给出df
=:
Col1 Col2 Col3
A AB 55 type
A AJ 55 type
A AI 55 type
应该可以:
l = list('BJI')
df.iloc[[0]*len(l)].assign(Col1 = lambda x: x['Col1'].str.cat(l)).reset_index()