python - 如何为 pandas 数据框的每一行打印索引值、列名和列数据?
问题描述
我有一个看起来像这样的数据框:
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 value
站内,column name
即对于数据帧的第一行,这将是:
位置 33 距离 675 站 0.223 公里以内
我努力了:
for index, column in df.iterrows():
print('Farm number ' + str(index) + ' is within 5km of ' + str(column))
但这每次都会打印所有索引值,我看不到下一步该去哪里。
我真的很感激一些指导。
解决方案
您可以将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
推荐阅读
- windows - msbuild 15 在解决方案目标之前是否支持?
- android - 在 Android NDK 18 上使用什么代替 STL_PORT
- dart - 如何在 Angular Dart 中实现网格布局?
- python - 通过成员值高效更新redis
- python - 了解循环的字符串和列表比较
- unix - TCSH 更改外壳突出显示颜色
- java - 在 onDestroy() 之后无法停止位置侦听器
- c# - LINQ 性能优化
- android - 如何定义 ANDROID_SDK_ROOT(Mac OS 上的 Xamarin.Forms)
- html - 如何在侧导航上方放置侧导航按钮