我有以下Dataframe,如下图所示:
我需要在现有的Dataframe中添加一个“Key”列,例如下图中的Dataframe:
有没有办法根据列Field和Seq创建一个列“Key”
这是一个解决方案。
import pandas as pd
df = pd.DataFrame({'Field': ['Indicator', 'A', 'B', 'Code', '1', '2', '3', 'Name', 'Address'],
'Count': [26785, 785, 26000, 12345, 45, 300, 12000, 12312, 1212],
'Seq': [1.0, 1.1, 1.1, 2.0, 2.1, 2.1, 2.1, 3.0, 4.0]})
sep = df.loc[df['Seq'].apply(lambda x: x == int(x)), 'Field'].tolist()
df['key'] = pd.Series(np.where(~df['Field'].isin(sep), None, df['Field'])).ffill()
df.loc[df['Field'] != df['key'], 'key'] += '+' + df['Field']
# Count Field Seq key
# 0 26785 Indicator 1.0 Indicator
# 1 785 A 1.1 Indicator+A
# 2 26000 B 1.1 Indicator+B
# 3 12345 Code 2.0 Code
# 4 45 1 2.1 Code+1
# 5 300 2 2.1 Code+2
# 6 12000 3 2.1 Code+3
# 7 12312 Name 3.0 Name
# 8 1212 Address 4.0 Address
说明
sep
中的值替换为None
,然后使用ffill()
填充None
值。