我需要列印資料框中的每一行。我使用 iterrow() 列印,但列印的行是元組。我想為每一行保留一個資料框
請參考以下代碼
def rowprint(df):
if len(df):
for row in iterrows():
print(row['col1'])
if __name__ == '__main__':
df= df.loc[df['col3']=='value']
rowprint(df)
錯誤:tuple indices must be integers or slices, not str
uj5u.com熱心網友回復:
iterrows回傳索引和行的系列。
您可以擴展為兩個引數:
def rowprint(df):
if len(df):
for index, row in iterrows():
print(row['col1'])
或者,當您對單個列進行子集化時,請在該列上進行迭代:
def rowprint(df):
if len(df) and 'col1' in df:
for value in df['col1']:
print(value)
uj5u.com熱心網友回復:
您忘記了索引:
def rowprint(df):
if len(df):
for index, row in df.iterrows():
print(row['col1'])
uj5u.com熱心網友回復:
因為您注意到 iterrows() 回傳一個元組,所以您可以做的是
for index, row in df.iterrows():
print(row)
這樣,您將元組的每個元素分配給 2 個變數,并且您不能使用“索引”變數。
Python 支持一次為多個變數賦值,例如當你有一個元組時。
a, b = (1, 2)
a, b, c, d = (1, 2, "Max", "")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454544.html
