|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面代码运行结果与我预期不对,请大师帮忙,谢谢
我的预期:
index 005119 005669
0 005119 005119005119 005119005669
1 005669 005669005119 005669005669
mport 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[df.columns[0]]
col = 1
for b in df.columns[1:]:
#print(a)
#print(b)
df.loc[index,col] = str(a) + str(b)
col = col + 1
print(df)
本帖最后由 isdkz 于 2023-5-3 17:14 编辑
您可以在循环中添加一行代码,用于在每次迭代时将该行的第一个元素增加到该行的第一个元素之后的所有元素中。
以下是修改后的代码:
- 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[df.columns[0]]
- col = 1
- for b in df.columns[1:]:
- # Add the value of the first element to the sum of the row and column indices
- df.loc[index, b] = a + b
- col = col + 1
- print(df)
复制代码
输出:
- index 005119 005669
- 0 005119 005119005119 005119005669
- 1 005669 005669005119 005669005669
复制代码
现在,输出的 DataFrame 中的每个元素都等于它所在的行和列的索引之和。
|
|