使用现有Dataframe中的数据在Pandas中的数据框中添加列

问题描述 投票:1回答:1

我有以下Dataframe,如下图所示:

我需要在现有的Dataframe中添加一个“Key”列,例如下图中的Dataframe:

有没有办法根据列Field和Seq创建一个列“Key”

python pandas dataframe
1个回答
1
投票

这是一个解决方案。

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

说明

  • 添加'key'列并将sep中的值替换为None,然后使用ffill()填充None值。
  • 仅在“字段”和“密钥”未对齐的情况下更新“密钥”列。
© www.soinside.com 2019 - 2024. All rights reserved.