Pandas 数据帧到键值对

标签 pandas

将以下 Pandas 数据帧转换为键值对的最佳方法是什么

前 :

datetime             name    qty     price
2017-11-01 10:20     apple    5       1
2017-11-01 11:20     pear     2       1.5
2017-11-01 13:20     banana   10      5

后 :
2017-11-01 10:20 name=apple qty=5 price=1
2017-11-01 11:20 name=pear  qty=2 price=1.5
2017-11-01 13:20 name=banana qty=10 price=5

请注意,我不希望在我的输出中使用 datetime 键。

最佳答案

看来你需要 to_dict :

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'}]

但如果不需要 key 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)]

编辑:

新品 DataFrame是用列名创建的,并添加了旧值。最后写 to_csv :
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

关于 Pandas 数据帧到键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185659/

相关文章:

python - Pandas DataFrame 根据列改变一个值,索引值比较

python - 如何使用批量API将日期格式的空值插入elasticsearch

python - 数据框 Pandas 中所有行的 Pearson 相关性

python - pandas 获取包含值的列的名称

pandas - 将函数应用于 Pandas 效率的唯一值

python - Pandas :插入缺失的行并在数据框中绘制多个系列

Python:将字符串(%,括号, ',')中的多种格式转换为数字

python - 使用其他数据帧替换数据帧中的值,并将字符串作为 Pandas 的键

python - 如何使用 pandas 和 numpy 一起处理 Series 和 Array?

python - 根据另一列中包含的字符串在新列中添加值