import pandas as pd
tabel = [{'192.168.70.150': '30'},
{'192.168.72.15': '38'},
{'192.168.72.150': '29'}]
df = pd.DataFrame(tabel)
print df
输出结果为:
192.168.70.150 192.168.72.15 192.168.72.150
0 30 NaN NaN
1 NaN 38 NaN
2 NaN NaN 29
但我希望如此:
192.168.70.150 30
192.168.72.15 38
192.168.72.150 29
我需要在代码中更改什么?
答案 0 :(得分:1)
您需要stack
df.stack()
Out[349]:
0 192.168.70.150 30
1 192.168.72.15 38
2 192.168.72.150 29
dtype: object
或者你可以将你的dict列表展平为dict,然后使用pd.Serise
df = pd.Series({k: v for d in tabel for k, v in d.items()})
df
Out[353]:
192.168.70.150 30
192.168.72.15 38
192.168.72.150 29
dtype: object
答案 1 :(得分:1)
从字典创建df时,键将是列,值将是行。使用列表来实现目标。
>>> import pandas as pd
>>> tabel = [['192.168.70.150', '30'],
... ['192.168.72.15', '38'],
... ['192.168.72.150', '29']]
>>> df = pd.DataFrame(table, columns=['IP', 'Value'])
>>> df
IP Value
0 192.168.70.150 30
1 192.168.72.15 38
2 192.168.72.150 29
答案 2 :(得分:0)
如果可能重复ip
,最好在tuple
中创建list comprehension
:
tabel = [{'192.168.70.150': '30'},
{'192.168.72.15': '38'},
{'192.168.72.150': '29'},
{'192.168.72.150': '20'}]
L = [(a, b) for d in tabel for a, b in d.items()]
df = pd.DataFrame(L, columns=['a','b'])
print (df)
a b
0 192.168.70.150 30
1 192.168.72.15 38
2 192.168.72.150 29
3 192.168.72.150 20
答案 3 :(得分:0)
Eazy Peazy
pd.DataFrame([list(i.items())[0] for i in tabel])