Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算一系列浮点数中的出现次数_Python_Pandas_Counter_Series - Fatal编程技术网

Python 计算一系列浮点数中的出现次数

Python 计算一系列浮点数中的出现次数,python,pandas,counter,series,Python,Pandas,Counter,Series,我有一个数据帧: df.head() Index Value 0 1.0,1.0,1.0,1.0 1 1.0,1.0 2 1.0,1.0 3 3.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0 4 4 我想计算Val

我有一个数据帧:

df.head()

Index                          Value
0                    1.0,1.0,1.0,1.0
1                            1.0,1.0
2                            1.0,1.0
3    3.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0
4                                  4
我想计算
Value
列中出现的值:

Index                          Value   1    2    3    4
0                    1.0,1.0,1.0,1.0   4    0    0    0
1                            1.0,1.0   2    0    0    0
2                            1.0,1.0   2    0    0    0
3    3.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0   0    0    6    2
4                                  4   0    0    0    1
我以前用字符串值做过,但我用了
计数器
——我发现你不能用浮点数

df_counts = df['Value'].apply(lambda x: pd.Series(Counter(x.split(','))), 1).fillna(0).astype(int)

使用
映射
将浮点和最后一列映射为
整数

df_counts = (df['Value'].apply(lambda x: pd.Series(Counter(map(float, x.split(',')))), 1)
                        .fillna(0)
                        .astype(int)
                        .rename(columns=int))
print (df_counts)
   1  3  4
0  4  0  0
1  2  0  0
2  2  0  0
3  0  6  2
4  0  0  1
最后,如有必要,将所有缺少的类别添加到原始类别:

cols = np.arange(df_counts.columns.min(), df_counts.columns.max() + 1)
df = df.join(df_counts.reindex(columns=cols, fill_value=0))
print (df)
                                 Value  1  2  3  4
Index                                             
0                      1.0,1.0,1.0,1.0  4  0  0  0
1                              1.0,1.0  2  0  0  0
2                              1.0,1.0  2  0  0  0
3      3.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0  0  0  6  2
4                                    4  0  0  0  1

您的浮动是否总是以
.0
结尾?如果是这样,您可以将
.split
的结果转换为整数,如果需要,还可以进一步转换为字符串,那么计数应该可以正常工作。
df['Value'].apply(lambda x:pd.Series(Counter(map(float,x.split(','))),1)。fillna(0)。astype(int)
可以正常工作,然后。。。