gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:03:29 24 4
gpt4 key购买 nike

我有以下数据框,如下图所示:

image

我需要在现有数据框中再添加一列“Key”,如下图所示:

image

有没有办法根据字段和序列列创建列“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

说明

  • 添加“key”列,并将 sep 中没有的值替换为 None,然后使用 ffill() 填充 值。
  • 仅在“字段”和“键”未对齐的情况下更新“键”列。

关于python - 使用现有数据框中的数据在 Pandas 的数据框中添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com