我已经做了一些搜索来回答这个问题,但我不知道该怎么做:
我有一个包含 185 行和 30 列的数据集。并非所有行都有值(value)。我想查找每列最后一个值的位置并获取该列的索引。我不确定如何执行此操作,因为当我使用下面的代码时,它会给我数据框的长度,而不仅仅是那一列:
len(data_exam['col'])
如有任何建议,我将不胜感激。
我还想确定,如果我想循环读取所有列,我的以下代码是否是一个不错的选择! :
list=[]
for col in data:
function which find the length of column
谢谢。
请您参考如下方法:
您可以使用 last_valid_index查找给定列中最后一个有效值的索引位置。还有它的双胞胎,first_valid_index。
# Set-up sample data.
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
df.iloc[2:, 0] = np.nan
df.iloc[4:, 1] = np.nan
>>> df
A B C
0 1.764052 0.400157 0.978738
1 2.240893 1.867558 -0.977278
2 NaN -0.151357 -0.103219
3 NaN 0.144044 1.454274
4 NaN NaN 0.443863
# Solution to find index of last valid values per column.
>>> df.apply(lambda series: series.last_valid_index())
A 1 # <== Index of last valid data in column A.
B 3 # <== Index of last valid data in column B.
C 4 # <== Index of last valid data in column C.
dtype: int64
