[英]How to print the column name on Pandas DataFrame row?
I have this DataFrame: 我有这个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,31,''],'windspeed':[6,7,2,7,4,2,'']})
df
I am trying to find the headers for the missing values on index 6: 我试图找到索引6上缺少值的标头:
for x in df.loc[6]:
if x == '':
print(df.columns.values)
else: print(x)
I have tried searching and the closest I could get was what I have now. 我已经尝试过搜索,而我能得到的最接近的就是我现在拥有的。 Ultimately I'm trying insert these values into the dataframe: temperature = 34, windspeed = 8.
最终,我尝试将这些值插入数据帧:温度= 34,风速= 8。
But my first step was simply trying to build the loop/if statement that says if x=='' & [COLUMN_NAME] == 'temperature'... and that is where I got stuck. 但是我的第一步只是尝试构建loop / if语句,该语句表示x ==''&[COLUMN_NAME] =='temperature'...,这就是我遇到的问题。 I'm new to python, just trying to learn Pandas.
我是python的新手,只是想学习Pandas。 I need to only return the column I'm on, and not a list of all the columns.
我只需要返回我所在的列,而不是所有列的列表。
There are better ways to do this, but this works. 有更好的方法可以做到这一点,但这是可行的。
for col, val in df.loc[6].iteritems():
if not val: # this is the same as saying "if val == '':"
print(col)
else:
print(val)
Modified from your code: 从您的代码修改:
for i,x in enumerate(df.loc[6]):
if x == '':
print(df.columns[i])
else: print(x)
I would use list comprehension as follows: 我将使用列表推导,如下所示:
listOfNulls = [ind for ind in df.loc[6].index if df.loc[6][ind] == '']
and when I print the listOfNulls
, I get: 当我打印
listOfNulls
,我得到:
>>>> print(listOfNulls)
Out: ['temperature', 'windspeed']
The key here is it understand that df.loc[6] is a pandas Series
which has indices. 这里的关键是要理解df.loc [6]是具有索引的熊猫
Series
。 We are using the values of the Series
to get the indices. 我们正在使用
Series
的值来获取索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.