看来你需要to_dict http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html:
d = df.drop('datetime', axis=1).to_dict(orient='records')
print (d)
[{'qty': 5, 'price': 1.0, 'name': 'apple'},
{'qty': 2, 'price': 1.5, 'name': 'pear'},
{'qty': 10, 'price': 5.0, 'name': 'banana'}]
但如果不需要钥匙datetime
:
d = df.set_index('datetime').to_dict(orient='index')
print (d)
{'2017-11-01 13:20': {'qty': 10, 'price': 5.0, 'name': 'banana'},
'2017-11-01 10:20': {'qty': 5, 'price': 1.0, 'name': 'apple'},
'2017-11-01 11:20': {'qty': 2, 'price': 1.5, 'name': 'pear'}}
如果顺序很重要:
tuples = [tup for tup in df.set_index('datetime').itertuples()]
print (tuples)
[Pandas(Index='2017-11-01 10:20', name='apple', qty=5, price=1.0),
Pandas(Index='2017-11-01 11:20', name='pear', qty=2, price=1.5),
Pandas(Index='2017-11-01 13:20', name='banana', qty=10, price=5.0)]
EDIT:
New DataFrame
使用列名称创建并添加旧值。最后写入to_csv http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html:
df = df.set_index('datetime').astype(str)
df1 = pd.DataFrame(np.tile(np.array(df.columns), len(df.index)).reshape(len(df.index), -1),
index=df.index,
columns=df.columns) + '='
df1 = df1.add(df)
print (df1)
name qty price
datetime
2017-11-01 10:20 name=apple qty=5 price=1.0
2017-11-01 11:20 name=pear qty=2 price=1.5
2017-11-01 13:20 name=banana qty=10 price=5.0
df1.to_csv('filename.csv', header=None)
2017-11-01 10:20,name=apple,qty=5,price=1.0
2017-11-01 11:20,name=pear,qty=2,price=1.5
2017-11-01 13:20,name=banana,qty=10,price=5.0