Python 如何在DataFrame行上打印列名?

Python 如何在DataFrame行上打印列名?,python,pandas,dataframe,Python,Pandas,Dataframe,我有这个数据框: df = pd.DataFrame({'day':['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017','1/7/2017'], 'event':['Rain','Sunny','Snow','Snow','Rain','Sunny','Sunny'], 'temperature': [32, 35, 28,24,32

我有这个数据框:

 df = pd.DataFrame({'day':['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017','1/6/2017','1/7/2017'],
                     'event':['Rain','Sunny','Snow','Snow','Rain','Sunny','Sunny'],
                   'temperature': [32, 35, 28,24,32,31,''],'windspeed':[6,7,2,7,4,2,'']})
 df

我正在尝试查找索引6上缺失值的标题:

for x in df.loc[6]:
if x == '':
    print(df.columns.values)
else: print(x)

我尝试过搜索,我能找到的最接近的就是我现在拥有的。最后,我尝试将这些值插入数据框:温度= 34,风速=8


但我的第一步只是尝试构建循环/if语句,该语句表示if x=''&[COLUMN\u NAME]=='temperature'。。。这就是我被卡住的地方。我是python新手,只是想学习熊猫。我只需要返回我所在的列,而不需要返回所有列的列表。

有更好的方法,但这很有效

for col, val in df.loc[6].iteritems():
    if not val: # this is the same as saying "if val == '':"
        print(col)
    else:
        print(val)

有更好的方法可以做到这一点,但这是可行的

for col, val in df.loc[6].iteritems():
    if not val: # this is the same as saying "if val == '':"
        print(col)
    else:
        print(val)

根据您的代码修改:

for i,x in enumerate(df.loc[6]):
    if x == '':
        print(df.columns[i])
    else: print(x)

根据您的代码修改:

for i,x in enumerate(df.loc[6]):
    if x == '':
        print(df.columns[i])
    else: print(x)

我将使用以下列表理解:

listOfNulls = [ind  for ind in df.loc[6].index if df.loc[6][ind] == '']
当我打印
listOfNulls
时,我得到:

>>>> print(listOfNulls)
Out: ['temperature', 'windspeed']

这里的关键是要理解df.loc[6]是一个具有索引的系列。我们使用
系列的值来获取索引。

我将使用列表理解,如下所示:

listOfNulls = [ind  for ind in df.loc[6].index if df.loc[6][ind] == '']
当我打印
listOfNulls
时,我得到:

>>>> print(listOfNulls)
Out: ['temperature', 'windspeed']

这里的关键是要理解df.loc[6]是一个具有索引的系列。我们正在使用
系列的值
来获取索引。

我尝试使用iterrows()来获取索引,但没有成功。没有考虑使用iteritems()。很好!是的,我意识到有很多更好的方法来完成我需要做的事情,这更多的是学习不同的方法来分割数据帧我使用ItErrors()尝试过,但没有成功。没有考虑使用iteritems()。很好!是的,我意识到有很多更好的方法来完成我需要做的事情,这更多的是学习不同的方法来分割数据帧我希望我能选择两个答案。拥有这两个答案实际上有助于我看到实现这一目标的多种方式。非常感谢。我希望我能选择两个答案。拥有这两个答案实际上有助于我看到实现这一目标的多种方式。非常感谢。