【问题标题】:How to extract excel column data into python list using pandas from merged cell如何使用合并单元格中的熊猫将excel列数据提取到python列表中
【发布时间】:2020-12-02 23:55:42
【问题描述】:

我正在尝试使用 pandas 将“国家/地区”列数据提取到 python 列表中。在我以前的代码下面。还附上excel表格和输出。

代码:

from pandas import DataFrame
import pandas as pd
open_file = pd.read_excel('data.xlsx', sheet_name=0)
df = list(open_file['Country'])
print(df)

输出:

[nan, 'Great Britain', 'China ', 'Russia', 'United States', 'Korea', 'Japan', 'Germany']

进程以退出代码 0 结束

在输出中我可以看到“nan”,因为在工作表中,两个单元格合并为一个。如何避免这种情况?

enter image description here

【问题讨论】:

  • 您介意将此数据共享为 excel 文件,以便我或其他任何人尝试一下吗?
  • 请提供minimal reproducible example 并查看How to Ask 你有nan 因为列A1:A 没有数据。
  • 您还应该尝试将列名设置在一行中

标签: python pandas


【解决方案1】:

使用 header=1 然后您可以将其与未命名的 :0 或 1 或 2 一起使用以获取要列出的列值

import pandas as pd

df = pd.read_excel('data.xlsx', sheet_name=0, header=1)
print(df['Unnamed: 0'].to_list())

【讨论】:

    【解决方案2】:

    试试这个

    df = pd.read_excel('data.xlsx', header[0,1])
    df = df.rename(columns=lambda x: x if not 'Unnamed' in str(x) else '')
    

    现在标题是元组的形式。例如,要访问Country 或列Gold,您需要编写如下语句

    print(df[('Country', '')])
    print(df[('Media Tally', 'Gold')])
    

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2021-12-02
      • 2020-09-26
      • 2020-12-21
      • 2020-08-21
      • 2018-02-09
      • 1970-01-01
      • 2018-04-30
      • 2020-05-30
      相关资源
      最近更新 更多