Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x_Pandas - Fatal编程技术网

Python 使用双循环创建数据帧

Python 使用双循环创建数据帧,python,python-3.x,pandas,Python,Python 3.x,Pandas,我明白了: columns = ['a','b','c'] data = [1,2,3],[3,4],[4,5,5] df = pandas.DataFrame({i:pandas.Series(j) for i in columns for j in data}) print(df) 输出: a b c 0 4 4 4 1 5 5 5 2 5 5 5 a b c 0 1.0 3.0 4.0 1 2.0 4.0 5.0 2 3.0

我明白了:

columns = ['a','b','c']
data = [1,2,3],[3,4],[4,5,5]
df = pandas.DataFrame({i:pandas.Series(j) for i in columns for j in data})
print(df)
输出:

   a  b  c
0  4  4  4
1  5  5  5
2  5  5  5
    a    b    c
0  1.0  3.0  4.0
1  2.0  4.0  5.0
2  3.0  NaN  5.0
我需要:

   a  b  c
0  1  3  4
1  2  4  5
2  3     5
我真的不明白为什么这不起作用。我知道我正在以正确的方式访问
数据中的元素

有什么建议吗?

这应该可以做到:

import pandas as pd

data = [[1, 2, 3], [3, 4], [4, 5, 5]]
df = pd.DataFrame(data).transpose()
df.columns = columns
输出:

   a  b  c
0  4  4  4
1  5  5  5
2  5  5  5
    a    b    c
0  1.0  3.0  4.0
1  2.0  4.0  5.0
2  3.0  NaN  5.0

当您进入第二个循环时,您正在覆盖值。 您正在做的是:

import pandas


columns = ['a','b','c']
data = [1,2,3],[3,4],[4,5,5]

myDict = {}
for i in columns:
    for j in data:
        myDict[i]=j
print(pandas.DataFrame(myDict))
这就是数据被覆盖的原因。 你想做的很清楚:

myDict = {}
for i,key in enumerate(columns):
    myDict[key] = data[i]
然而,这将导致:

raise ValueError('arrays must all be same length')
ValueError: arrays must all be same length
它有一个描述良好的解决方案

pd.DataFrame([data],index=columns)。T