【问题标题】:How to print the index numbers of rows and columns alongside the values?如何在值旁边打印行和列的索引号?
【发布时间】:2019-04-18 20:48:38
【问题描述】:

View Image 我正在尝试打印 excel 文件中数据的边缘。我得到了要打印的值。但由于循环数据帧,我无法打印行和列索引。

我尝试使用df.index 进行打印,但它给出的行范围如下: 5.0 RangeIndex(start=4, stop=30, step=1) 其中5 是边缘值,后者是索引。

    df = wb.iloc[rows, coln].fillna(0)
    dfa = df.to_numpy()
    for row in dfa:
        for value in row:
            if value!=0:
                print(value, df.index)
                break
This is the expexted result.

5 11 15.0

where 5 is the row number, 11 is the column number and 15.0 is the value on that cell.

我尝试使用 iterrows() 函数,如下所示循环遍历 df,然后我让它打印出单元格值旁边的行号。

df = wb.iloc[rows, coln].fillna(0)
    for index, row in df.iterrows():

但列号仍然没有进展。

【问题讨论】:

  • 你的二维数据是 wb 吗?
  • 不,数据是非结构化的。我将编辑并上传图片。
  • 那么您是在将 xml 读入数据框吗?
  • 不,它是一个 xlsx 文件。我已经上传了描述中的截图。
  • 哎呀,我的意思是输入 excel 而不是 xml,我的错。

标签: excel python-3.x pandas


【解决方案1】:

假设我的目标只是获取行、列和值(对于每个值), 我会将其转换为 numpy 数组并应用 ndenumerate() 如下:

import pandas as pd
import numpy as np

d = [[1,2],[3,4],[5,6]] #Assuming my data looks like d
df = pd.DataFrame(d)
na = np.array(df)

for index, value in np.ndenumerate(na):
  print(index, value)

(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
(2, 0) 5
(2, 1) 6

(或)

for index, value in np.ndenumerate(na):
  print(index[0], index[1], value)


0 0 1
0 1 2
1 0 3
1 1 4
2 0 5
2 1 6

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2023-03-12
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多