将第n行元素存储在列表熊猫数据框中

时间:2020-05-15 10:33:41

标签: python pandas

我是python的新手。能帮上忙吗? 我有一个数据框如下。 a,d,f和g是列名。数据框可以命名为df1

a   d   f   g
20  30  20  20
0   1   NaN NaN

我需要将df1的第二行放入没有NaN's的列表中。 理想情况如下。

x = [0,1]

2 个答案:

答案 0 :(得分:3)

使用df.iloc[1]选择第二行,然后使用.dropna删除nan值,最后使用.tolist方法将系列转换为python列表。

使用:

x = df.iloc[1].dropna().astype(int).tolist()  
# x = [0, 1]

答案 1 :(得分:0)

选中itertuples()

所以您会有类似ht的东西:

for row in df1.itertuples():
   row[0] #-> that's your index of row. You can do whatever you want with it, as well as with whole row which is a tuple now.

您还可以像这样使用ilocdropna()

row_2 = df1.iloc[1].dropna().to_list()