Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

pandas 如何新增列?

脚本:

import pandas

df = pandas.DataFrame([dict(
    id=1001,
    province='河南',
    city='郑州',
    amount=100,
), dict(
    id=1002,
    province='河南',
    city='安阳',
    amount=100,
), dict(
    id=1003,
    province='河北',
    city='保定',
    amount=100,
), dict(
    id=1004,
    province='河北',
    city='保定',
    amount=100,
)])

data = df.groupby(by=['province'])['amount'].sum(axis=0)
print(data)

输出:

province
河北    200
河南    200
Name: amount, dtype: int64

我希望增加一列,形成如下输出:

alias    province
省销售    河北        100
省销售    河南    200
Name: amount, dtype: int64

请问如何实现?

假设我要将列名称重新定义,并将形成扁平的数据,如何实现成为这种字典(我需要去循环 pandas 的统计结果,生成 sql 语句):

统计项      省份   城市     值
省市销售    河北   保定     200
省市销售    河南   郑州     100
省市销售    河南   安阳     100

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 在分组后得到一个 DataFrame 的结果

传入 as_index=False 参数, province 不会被设置为索引,得到的结果是 DataFrame

data = df.groupby(by=['province'], as_index=False)['amount'].sum()

image.png

  • 添加列
data['alias'] = '省销售'
  • 重命名
data = data.rename(columns={'alias':'统计项', 'province':'省份', 'amount':'值'})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...