使用 pandas from_dict 转换为数据帧时,不要使用字典中的键作为索引
Do not use keys in dictionary as index when converting to dataframe using pandas from_dict
odict = OrderedDict([ ('dub', ['8084', 'command']),
('lhr',['8083','command']),
('ams',['8085','command']),])
df = pandas.DataFrame.from_dict(odict, orient='index')
print(df)
我有上面的 OrderedDict 和转换为数据帧的命令。我希望 dict 中的键用作列中的数据而不是用作索引。打印出来是这样的。
0 1
dub 8084 command
lhr 8083 command
ams 8085 command
但是我希望它使用我认为称为 RangeIndex 的方式打印出来。
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command
对 RangeIndex
使用 DataFrame.reset_index
,然后按 np.arange
:
创建默认列名称
df = pd.DataFrame.from_dict(odict, orient='index').reset_index()
df.columns = np.arange(len(df.columns))
print(df)
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command
另一个列表理解的解决方案:
df = pd.DataFrame([(k, *v) for k, v in odict.items()])
print(df)
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command
odict = OrderedDict([ ('dub', ['8084', 'command']),
('lhr',['8083','command']),
('ams',['8085','command']),])
df = pandas.DataFrame.from_dict(odict, orient='index')
print(df)
我有上面的 OrderedDict 和转换为数据帧的命令。我希望 dict 中的键用作列中的数据而不是用作索引。打印出来是这样的。
0 1
dub 8084 command
lhr 8083 command
ams 8085 command
但是我希望它使用我认为称为 RangeIndex 的方式打印出来。
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command
对 RangeIndex
使用 DataFrame.reset_index
,然后按 np.arange
:
df = pd.DataFrame.from_dict(odict, orient='index').reset_index()
df.columns = np.arange(len(df.columns))
print(df)
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command
另一个列表理解的解决方案:
df = pd.DataFrame([(k, *v) for k, v in odict.items()])
print(df)
0 1 2
0 dub 8084 command
1 lhr 8083 command
2 ams 8085 command