python - 获取数据框中的特定值

标签 python python-3.x pandas

我有一个 df,这些值是字典:

df:                               
                                      A
    2017-05-31    {'price': '7.25', 'weight': 0.0, 'time': 4.05am}
    2017-06-01    {'price': '7.22', 'weight': 0.0 'time': 4.08am}
    2017-06-02    {'price': '7.24', 'weight': 0.0, 'time': 5.08am}
    2017-06-05    {'price': '7.25', 'weight': 0.0, 'time': 6.07am}
    2017-06-06    {'price': '7.19', 'weight': 0.0, 'time':3.33am}
    2017-06-07    {'weight': 0.0, 'price': 7.12, 'time':1.09am}
    2017-06-09    {'weight': 0.0, 'price': 7.46, 'time':2.08am}

我想获取每行中键price的值。 所需的输出是

df:                               
                                  A
2017-05-31                       7.25
2017-06-01                       7.22
2017-06-02                       7.24
2017-06-05                       7.25
2017-06-06                       7.19
2017-06-07                       7.12
2017-06-09                       7.46

如果字典遵循相同的价格-权重-时间结构,我可以简单地应用这样的代码:

format = lambda x: list(x.values())[0]
print(df.applymap(format))

然而不幸的是事实并非如此。

我想也许对字典值进行排序,但我不知道如何在 df.

谁能帮我解决这个问题吗?

最佳答案

使用apply使用 lambda 来选择 key:

df['A'] = df['A'].apply(lambda x: x['price'])
print (df)
               A
2017-05-31  7.25
2017-06-01  7.22
2017-06-02  7.24
2017-06-05  7.25
2017-06-06  7.19
2017-06-07  7.12
2017-06-09  7.46.

对于所有值,请使用DataFrame构造函数:

df1 = pd.DataFrame(df['A'].values.tolist(), index=df.index)
print (df1)
           price    time  weight
2017-05-31  7.25  4.05am     0.0
2017-06-01  7.22  4.08am     0.0
2017-06-02  7.24  5.08am     0.0
2017-06-05  7.25  6.07am     0.0
2017-06-06  7.19  3.33am     0.0
2017-06-07  7.12  1.09am     0.0
2017-06-09  7.46  2.08am     0.0

关于python - 获取数据框中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44496612/

相关文章:

pandas - 在 Pandas 中聚合多列时如何重置索引

python - 如何在 PyGI GTK 中使用 GIO Actions 创建一个完整的菜单?

python - 如何使用 youtube data api 检查 Creativecommons 视频?我有以下代码,如果视频是知识共享,如何打印 true?

python-3.x - Python Pandas - 根据索引、列使用字典更新行

python - Discord.py 重写 Cogs : Load extensions from other archive

python - Pandas:将各种相似的子字符串映射到单一标准格式

python - 如何在 Pandas 中获得连续滚动平均值?

python - 将 np.where 应用于方括号过滤以进行 numpy 过滤

python - 如何处理输出文件的区分大小写排序?

python - 如何将数据框唯一值与列表进行比较?