简体   繁体   English

如何使用带有 pandas 的 for 循环 append 列?

[英]How to append columns using for loop with pandas?

I have population data of a city divided into 10 zones.我有一个城市的人口数据,分为 10 个区域。 The rate of increase of population is given, I want to calculate the population of each zone for the next ten years and append population for every year in separate columns.给出了人口增长率,我想在单独的列中计算每个区域未来十年的人口和 append 每年的人口。 I am able to append one column but after that, not able to append the next column using the latest appended column.我能够 append 一个列,但在那之后,不能使用最新的附加列 append 下一列。 I am able to append column one by one, which is not a good way to do this我能够一一列append,这不是一个好方法

data['zone_pop'] = data['zone_pop'].apply(lambda zone_pop: population(zone_pop))

Please help me with this.请帮我解决一下这个。

Try to use concat function ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html ).尝试使用concat function ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.ZFC35FDC70D5FC69A539883A82EZC )

In the for loop, you should have something like this:在 for 循环中,你应该有这样的东西:

    new_data = pandas.DataFrame(population(data[label]), columns=[label_incr])
    data = pandas.concat([data, new_data], axis=1)

Where label and label_incr refer to str variables used to get current year data and new year calculation.其中labellabel_incr指的是用于获取当年数据和新年计算的 str 变量。

Edit (detail syntax)编辑(详细语法)

I guess you have already a dataframe data containing a single column 'population_zone' with 10 indexes (for each zone).我猜你已经有一个 dataframe data ,其中包含一个包含 10 个索引(每个区域)的单列“population_zone”。 And the rate of change r .和变化率r

The code above should work (at least, I tested on fake local data)上面的代码应该可以工作(至少,我在假本地数据上测试过)

current_label = 'population_zone'
for i in range(1, 11):
    new_label = 'population_zone_year' + str(i)
    new_data = pd.DataFrame((data[current_label] * (1+r/100.)**i).values, columns=[new_label])

    data = pd.concat([data, new_data], axis=1)
    current_label = new_label

If it doesn't work, I probably misunderstood how your data is stored .如果它不起作用,我可能误解了您的数据是如何存储的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM