我正在尝试将value_count的输出分配给新的df。我的代码如下。
import pandas as pd
import glob
df = pd.concat((pd.read_csv(f, names=['date','bill_id','sponsor_id']) for f in glob.glob('/home/jayaramdas/anaconda3/df/s11?_s_b')))
column_list = ['date', 'bill_id']
df = df.set_index(column_list, drop = True)
df = df['sponsor_id'].value_counts()
df.columns=['sponsor', 'num_bills']
print (df)
未为指定'sponsor','num_bills'的列标题分配值计数。我从print.head获得以下输出
1036 426
791 408
1332 401
1828 388
136 335
Name: sponsor_id, dtype: int64
答案 0 :(得分:6)
您的列长度不匹配,您从csv读取3列,然后将索引设置为2,您计算了value_counts,它生成一个以列值为索引,value_counts为值的系列,您需要reset_index
,然后覆盖列名:
df = df.reset_index()
df.columns=['sponsor', 'num_bills']
示例:
In [276]:
df = pd.DataFrame({'col_name':['a','a','a','b','b']})
df
Out[276]:
col_name
0 a
1 a
2 a
3 b
4 b
In [277]:
df['col_name'].value_counts()
Out[277]:
a 3
b 2
Name: col_name, dtype: int64
In [278]:
type(df['col_name'].value_counts())
Out[278]:
pandas.core.series.Series
In [279]:
df = df['col_name'].value_counts().reset_index()
df.columns = ['col_name', 'count']
df
Out[279]:
col_name count
0 a 3
1 b 2
答案 1 :(得分:0)
将 value_counts() 附加到多列数据框:
df = pd.DataFrame({'C1':['A','B','A'],'C2':['A','B','A']})
vc_df = df.value_counts().to_frame('Count').reset_index()
display(df, vc_df)
C1 C2
0 A A
1 B B
2 A A
C1 C2 Count
0 A A 2
1 B B 1