簡體   English   中英

如何打印pandas dataframe每一行的索引值、列名和列數據?

[英]How to print index value, column name, and column data for each row of pandas dataframe?

我有一個看起來像這樣的 dataframe:

dict={'475':['NaN', 0.6, 'NaN', 'NaN', 'NaN', 'NaN'],
      '575':['NaN', 'NaN', 0.11, 'NaN', 'NaN', 'NaN'],
      '675':[0.223, 'NaN',  'NaN', 0.913, 'NaN', 'NaN'],
      '1775':['NaN', 'NaN', 'NaN', 'NaN', 3.46, 'NaN'], 
      '1875':['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 3.46] 
     } 

df=pd.DataFrame(dict,index=['33', '35', '36', '13', '41', '1222'])

在此處輸入圖像描述

我想為每一行打印一條語句:

位置index_value在站column namecolumn value內,即對於 dataframe 的第一行,這將是:

位置 33 距離 675 站 0.223 公里以內

我努力了:

for index, column in df.iterrows():
    print('Farm number ' + str(index) + ' is within 5km of ' + str(column))

但這每次都會打印所有索引值,我看不到接下來 go 的位置。

我真的很感激一些指導。

您可以將NaN字符串替換為NaN缺失值並通過DataFrame.stack重塑,因此缺失值被刪除,您可以使用MultiIndex Series循環:

for (i, c), v in df.replace('NaN',np.nan).stack().items():
    print(f"Location {i} is within {v}km of station {c}")

Location 33 is within 0.223km of station 675
Location 35 is within 0.6km of station 475
Location 36 is within 0.11km of station 575
Location 13 is within 0.913km of station 675
Location 41 is within 3.46km of station 1775
Location 1222 is within 3.46km of station 1875

您還可以創建DataFrame

df1 = df.replace('NaN',np.nan).stack().rename_axis(['i','c']).reset_index(name='v')
print (df1)
      i     c      v
0    33   675  0.223
1    35   475  0.600
2    36   575  0.110
3    13   675  0.913
4    41  1775  3.460
5  1222  1875  3.460

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM