本文介绍了将 pandas 数据帧转换为

问题描述

我知道之前有人问过这个问题,而我的最后一个问题被搁置了,所以现在我要详细说明.我有一个人口信息的 CSV 文件,我将它读给了熊猫,现在必须将它转换为

I know this question has been asked before and my last was put on hold, so now I'm specifying it detailed.I have a CSV file of population information, I read it to pandas and now have to transform it to <?

这是我的代码的阅读部分:
将熊猫导入为 pdpop = pd.read_csv(r'''directory\population.csv''', delimiter=";")

This is the reading part of my code:
import pandas as pdpop = pd.read_csv(r'''directory\population.csv''', delimiter=";")

尝试像之前在链接中提到的那样使用函数和循环:0 Alahärmä 2014 0 0.1 0.2 1 Alajärvi 2014 10171 5102 5069 2 Alastaro 2014 0 0 0 3 Alavieska 2014 2687 1400 1287 4 Alavus 2014 12103 6102 6001 5 Anjalankoski 2014 0 0 0

继续创建 python 脚本,我们首先使用以下行导入该文本文件:

Moving on to creating the python script, we first import that text file using the following line:

pop = pd.read_csv(r'directory\population.csv', delimiter=r"\s+", names=['cityname', 'year', 'total', 'male', 'females'])

这会将文本文件作为数据框引入,并为新数据框提供正确的列标题.

This brings in the text file as a dataframe and gives the new dataframe the correct column headers.

然后从您链接的问题中获取数据,我们将以下内容添加到我们的 Python 脚本中:

Then taking the data from the question you linked to, we add the following to our python script:

def func(row):
    

现在我们把它们放在一起,我们得到以下内容:

Now we put it all together and we get the below:

import pandas as pd
pop = pd.read_csv(r'directory\population.csv', delimiter=r"\s+", names=['cityname', 'year', 'total', 'male', ‘females'])

def func(row):
    

当我们运行上述文件时,我们得到以下输出:

When we run the above file we get the following output:

<item>
  <field name="cityname">Alahärmä</field>
  <field name="year">2014</field>
  <field name="total">0</field>
  <field name="male">0.1</field>
  <field name="females">0.2</field>
</item>
<item>
  <field name="cityname">Alajärvi</field>
  <field name="year">2014</field>
  <field name="total">10171</field>
  <field name="male">5102.0</field>
  <field name="females">5069.0</field>
</item>
<item>
  <field name="cityname">Alastaro</field>
  <field name="year">2014</field>
  <field name="total">0</field>
  <field name="male">0.0</field>
  <field name="females">0.0</field>
</item>
<item>
  <field name="cityname">Alavieska</field>
  <field name="year">2014</field>
  <field name="total">2687</field>
  <field name="male">1400.0</field>
  <field name="females">1287.0</field>
</item>
<item>
  <field name="cityname">Alavus</field>
  <field name="year">2014</field>
  <field name="total">12103</field>
  <field name="male">6102.0</field>
  <field name="females">6001.0</field>
</item>
<item>
  <field name="cityname">Anjalankoski</field>
  <field name="year">2014</field>
  <field name="total">0</field>
  <field name="male">0.0</field>
  <field name="females">0.0</field>
</item>

这篇关于将 pandas 数据帧转换为