熊猫数据框获取列名称和value_counts

时间:2018-10-13 21:46:55

标签: python pandas csv dataframe

如何将列中值为'f'或't'的所有列名称获取到数组中?

df['FTI'].value_counts()

代替此“ FTI”,我需要返回列的数组。有可能吗?

2 个答案:

答案 0 :(得分:2)

可复制的示例:

df = pd.DataFrame({'col1':[1,2,3], 'col2':['f', 'f', 'f'], 'col3': ['t','t','t'], 'col4':['d','d','d']})

    col1    col2    col3    col4
0   1       f       t       d
1   2       f       t       d
2   3       f       t       d

使用eqall

>>> s = (df.eq('t') | df.eq('f')).all()

col1    False
col2     True
col3     True
col4    False
dtype: bool

获取名称:

>>> s[s].index.values
array(['col2', 'col3'], dtype=object)

要获得职位:

>>> np.flatnonzero(s) + 1
array([2, 3])

答案 1 :(得分:0)

是的。有可能的。这是一种方法

您可以得到像这样的列。

cols=[]
for col in df.columns:
    if df[col].str.contains('f|t').any()==True:
        cols.append(col)

然后您可以将其用于频率

f= pd.Series()
for col in cols:
    f=pd.concat([f,df[col].value_counts()])