【问题标题】:Appending a csv with dictionary values using pandas python使用 pandas python 附加带有字典值的 csv
【发布时间】:2017-10-01 01:39:06
【问题描述】:

我的 python 脚本生成如下字典:

================================================ =================

TL&DR

我使用from_dict 方法使问题过于复杂,同时从字典创建数据框。感谢@Sword。

换句话说,pd.DataFrame.from_dict 仅在您想创建一个数据框时才需要,其中所有键在一个列中,所有值在另一列中。在所有其他情况下,它与接受的答案中提到的方法一样简单。

================================================ ===============

{u'19:00': 2, u'12:00': 1, u'06:00': 2, u'00:00': 0, u'23:00': 2, u'05:00': 2, u'11:00': 4, u'14:00': 2, u'04:00': 0, u'09:00': 7, u'03:00': 1, u'18:00': 6, u'01:00': 0, u'21:00': 5, u'15:00': 8, u'22:00': 1, u'08:00': 5, u'16:00': 8, u'02:00': 0, u'13:00': 8, u'20:00': 5, u'07:00': 11, u'17:00': 12, u'10:00': 8}

它还会产生一个变量,比如full_name(作为脚本的参数),其值为“John”。

每次我运行脚本时,它都会为我提供上述格式的字典和名称。

我想将其写入 csv 文件以供以后分析,格式如下:

FULLNAME | 00:00  |  01:00  |  02:00  | .....| 22:00  |  23:00  |
John     | 0      |  0      |  0      | .....| 1      |  2      |

我的代码如下:

import collections
import pandas as pd

# ........................
# Other part of code, which produces the dictionary by name "data_dict"
# ........................

#Sorting the dictionary (And adding it to a ordereddict) in order to skip matching dictionary keys with column headers
data_dict_sorted = collections.OrderedDict(sorted(data_dict.items()))

# For the first time to produce column headers, I used .items() and rest of the following lines follows it.
# df = pd.DataFrame.from_dict(data_dict_sorted.items())

#For the second time onwards, I just need to append the values, I am using .values()
df = pd.DataFrame.from_dict(data_dict_sorted.values())

df2 = df.T # transposing because from_dict creates all keys in one column, and corresponding values in the next column.
df2.columns = df2.iloc[0] 
df3 = df2[1:]
df3["FULLNAME"] = args.name #This is how we add a value, isn't it?
df3.to_csv('test.csv', mode = 'a', sep=str('\t'), encoding='utf-8', index=False)

我的代码正在生成以下 csv

00:00 | 01:00 | 02:00 | …….. | 22:00 | 23:00 | FULLNAME
0     | 0     | 0     | …….. | 1     | 2     | John
0     | 0     | 0     | …….. | 1     | 2     | FULLNAME
0     | 0     | 0     | …….. | 1     | 2     | FULLNAME

我的问题有两个:

  1. 为什么在第二次迭代中打印“FULLNAME”而不是“John”(就像在第二次运行脚本时一样)?我错过了什么?
  2. 有更好的方法吗?

【问题讨论】:

    标签: python csv pandas dictionary


    【解决方案1】:

    这个怎么样?

    df = pd.DataFrame(data_dict, index=[0])
    df['FullName'] = 'John'
    

    编辑:
    理解您执行操作的方式有点困难,但看起来问题出在 df.columns = df.iloc[0] 行上。我上面提到的代码不需要指定列名或转置操作。如果您在每次迭代时添加字典,请尝试:

    data_dict['FullName'] = 'John'
    df = df.append(pd.DataFrame(data_dict, index =[0]), ignore_index = True).reset_index()
    

    如果每一行可能有不同的名称,那么df['FullName'] = 'John' 将导致整个列等同于 John。因此,作为一个更好的步骤,在您的 dict 中创建一个名为“FullName”的键,并使用适当的名称作为其值,以避免为整个列分配统一的值,即

    data_dict['FullName'] = 'John'
    

    【讨论】:

    • index = [0] 有什么作用?
    • 每当您将字典传递给 pd.DataFrame 时,每个键的值都需要采用列表格式。但是在您的情况下,值是整数,只有在您提供有关索引的信息时才能传递标量。 index=[0] 仅表示行的索引为 0。对于多行,这应该是一个索引列表,可以是标签或数字。
    • 但我认为这并不能解决我在这里面临的问题。
    • 你是如何得到第 2 行和第 3 行的?假设您每次都向现有的 df 添加一个字典,我已经编辑了答案。
    • 就像在 cmets 中提到的那样,我首先运行df = pd.DataFrame.from_dict(data_dict_sorted.items()),它将列标题作为时隙(字典的键),然后是值。第二次运行脚本(这就是我所说的迭代),我将这一行替换为df = pd.DataFrame.from_dict(data_dict_sorted.values()),这样只会附加值,而不是键。唯一的问题是在“FULLNAME”列中,当第二次运行脚本时,我得到的值是“FULLNAME”而不是“John”。
    猜你喜欢
    • 2012-09-26
    • 2020-02-28
    • 2017-11-05
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多