Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.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 Pandas.melt函数:TypeError:只能将整数标量数组转换为标量索引_Python_Pandas_Dataframe - Fatal编程技术网

Python Pandas.melt函数:TypeError:只能将整数标量数组转换为标量索引

Python Pandas.melt函数:TypeError:只能将整数标量数组转换为标量索引,python,pandas,dataframe,Python,Pandas,Dataframe,我正在使用pd.melt函数将DF转换为以下格式: df= 转换为以下格式: 新的_df= 使用此代码: new\u df=pd.melt(df,id\u vars=['orders',var\u name=“samples”,value\u name=“Count”) 但我一直遇到这样的错误:TypeError:只有整数标量数组才能转换为标量索引。有人知道我做错了什么吗?我尝试过使用您的代码,但没有任何错误: import numpy as np # sample df o1 = [f'or

我正在使用pd.melt函数将DF转换为以下格式:

df=

转换为以下格式:

新的_df=

使用此代码:
new\u df=pd.melt(df,id\u vars=['orders',var\u name=“samples”,value\u name=“Count”)


但我一直遇到这样的错误:TypeError:只有整数标量数组才能转换为标量索引。有人知道我做错了什么吗?

我尝试过使用您的代码,但没有任何错误:

import numpy as np

# sample df
o1 = [f'order {x}' for x in range(1, 6)]
d = {f'sample {x}': np.random.random(5) for x in range(1, 6)}
df = pd.DataFrame({'orders': o1, ** d})

pd.melt(df,id_vars=['orders'], var_name="sample", value_name="Count")

     orders    sample     Count
0   order 1  sample 1  0.350265
1   order 2  sample 1  0.697328
2   order 3  sample 1  0.263138
3   order 4  sample 1  0.976091
4   order 5  sample 1  0.370498
5   order 1  sample 2  0.108410
6   order 2  sample 2  0.785301
7   order 3  sample 2  0.497472
8   order 4  sample 2  0.978428
9   order 5  sample 2  0.995097
10  order 1  sample 3  0.366750
11  order 2  sample 3  0.628643
12  order 3  sample 3  0.420587
13  order 4  sample 3  0.490384
14  order 5  sample 3  0.812225
15  order 1  sample 4  0.414280

实际上,我共享了这个示例,因为我的实际代码无法完全共享。如果计数中没有数据(即空白),会有任何问题吗?我正在试图理解为什么会出现此错误。是否要将计数列保留为空?如果没有这些数据,很难预测,但您的列的数据类型似乎导致了问题。请确保您的数据的格式与我在示例中给出的格式相同。如果我将某些计数值更新为空字符串“”,是否可能会导致问题?是的,可能是问题。请尝试以下方法:
df.set_index('orders').stack().reset_index().rename(列={'level_1':'sample',0:'count}