futui 发表于 2023-5-3 16:52:30

取第一列每行的值与第二列开始的列名的问题 ,请大师帮忙,谢谢

下面代码与我预期不对,请大师帮忙,谢谢
import pandas as pd

shtcode = ['005119','005669']
df = pd.DataFrame(0, index=shtcode, columns=shtcode)
df.reset_index(inplace=True)
for index, row in df.iterrows():
    a = row   
    for b in df.columns:
      print(a)
      print(b)

#print(df)

我的预期是:a是第一列的每行的值,b是第二列开始的列名
005119
005119
005119
005669

005669
005119
005669
005669

isdkz 发表于 2023-5-3 16:53:23

你需要将 `a = row` 改为 `a = row]`。因为在 `df.iterrows()` 循环中 `index` 表示 DataFrame 的行号,而 `row` 表示该行的数据,所以你需要使用 `df.columns` 表示第一列的列名。同时,`row` 会访问行中的元素,而你需要访问列中的元素。

以下是纠正后的代码:

import pandas as pd

shtcode = ['005119','005669']
df = pd.DataFrame(0, index=shtcode, columns=shtcode)
df.reset_index(inplace=True)
for index, row in df.iterrows():
    a = row]   
    for b in df.columns:
      print(a)
      print(b)

#print(df)
页: [1]
查看完整版本: 取第一列每行的值与第二列开始的列名的问题 ,请大师帮忙,谢谢