从字典创建pandas数据帧可以使用DataFrame()函数。在这个函数中,字典的键将成为数据帧的列名,字典的值将成为数据帧的行。
下面是创建pandas数据帧的代码示例:
import pandas as pd
data = {'col1': [[1, 2, 3], [4, 5, 6]],
'col2': [['a', 'b', 'c'], ['d', 'e', 'f']],
'col3': [['foo', 'bar', 'baz'], ['qux', 'quux', 'corge']]}
df = pd.DataFrame(data)
print(df)
输出结果如下:
col1 col2 col3
0 [1, 2, 3] [a, b, c] [foo, bar, baz]
1 [4, 5, 6] [d, e, f] [qux, quux, corge]
在这个示例中,字典data
的键col1
、col2
和col3
成为了数据帧df
的列名,而字典data
的对应值作为行被排列在各列下方。
在创建数据帧时,可以通过指定columns
参数来按特定顺序设置列名:
df = pd.DataFrame(data, columns=['col2', 'col3', 'col1'])
print(df)
输出结果如下:
col2 col3 col1
0 [a, b, c] [foo, bar, baz] [1, 2, 3]
1 [d, e, f] [qux, quux, corge] [4, 5, 6]
除了上述示例外,还可以通过指定index
参数来设置自定义的行索引,以及使用其他参数来进行数据处理和操作。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云