Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.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 熊猫海螺不';当使用for循环创建一个DF时,不能按预期工作_Python_Pandas_Concat - Fatal编程技术网

Python 熊猫海螺不';当使用for循环创建一个DF时,不能按预期工作

Python 熊猫海螺不';当使用for循环创建一个DF时,不能按预期工作,python,pandas,concat,Python,Pandas,Concat,我试图连接两个Pandas数据帧,其中一个是使用for循环创建的。对于某些resason,pd.concat不会按行进行预期的连接 下面的代码说明了该问题: datasort = [143.477514,112.951071,869.627662,193.471612,140.428981,301.053040,190.684404,180.142223,127.569191,404.871493] sample_1 = pd.DataFrame(np.random.choice(dataso

我试图连接两个Pandas数据帧,其中一个是使用for循环创建的。对于某些resason,pd.concat不会按行进行预期的连接

下面的代码说明了该问题:

datasort = [143.477514,112.951071,869.627662,193.471612,140.428981,301.053040,190.684404,180.142223,127.569191,404.871493]

sample_1 = pd.DataFrame(np.random.choice(datasort,(8,10)))
samples_2 = pd.DataFrame()

for t in np.arange(10):

    samples_2[str(t)] = np.random.choice(datasort,2)

samples_3=pd.concat([samples_2,sample_1],ignore_index=True)
该代码生成了一个10x20的matix,其中包含大量的NaN,而不是我所期望的10x10


有人能指出我明显遗漏了什么吗?

问题是您将列强制转换为字符串,sa DataFrame无法对齐,因为不同的列名称:

for t in np.arange(10):
    #casting to string 
    samples_2[str(t)] = np.random.choice(datasort,2)

print (sample_1.columns)
RangeIndex(start=0, stop=10, step=1)
print (samples_2.columns)
Index(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='object')
解决方案:

for t in np.arange(10):
    samples_2[t] = np.random.choice(datasort,2)

哇,这很有道理,我从来没有考虑过。非常感谢你指出这一点。10分钟过后我会接受答案的