![](/img/trans.png)
[英]Python pandas Write dataframe to CSV in specific rows where column is equal to value
[英]Write and read csv files with Pandas where a specific column cell value could be a list of dicts
經過詳盡的搜索並嘗試使其工作...我在這里。
我需要的摘要:我需要創建和讀取csv文件,以便可以從文件中自由操作數據。 例如:
row1 = {"col1": "value1", "col2": 0.5, "col3": [{"key1": 0.2}, {"key2": 0.3}]
df = pandas.DataFrame(row1, columns=["col1", "col2", "col3"]
df.to_csv("test.csv")
我得到的文件如下所示:
col1 col2 col3
0 value1 0.5 [{'key1': 0.2}, {'key2': 0.3}]
之后,我可以使用以下命令讀取文件:
df = pandas.read_csv("test.csv")
問題出在諸如col3
情況下。 我愚蠢地以為,當我轉換數據幀時:
df = list(df.T.to_dict().values())
我可以通過以下方式訪問col3
:
for row in df:
wanted_data = row["col3"]
我以為我會得到一個包含兩個字典的列表。 我實際上得到的是一個字符串。
如何訪問key1
, key2
(密鑰不同)及其對應的值? 我已經嘗試過:
json.loads(wanted_data)
但是無論我做什么我都會得到這些錯誤:
Traceback (most recent call last): File "<pyshell#230>", line 1, in <module> now("tst_2.csv") File "D:\\test_DUAL_up_to_RoleMap_official_edition - Copy\\kb_test_manipulation.py", line 84, in now res = json.loads(new_supercl) File "C:\\Users\\NOTEBOOK2\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\json\\__init__.py", line 319, in loads return _default_decoder.decode(s) File "C:\\Users\\NOTEBOOK2\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\json\\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\\Users\\NOTEBOOK2\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\json\\decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
關於如何存儲和/或讀取數據以便可以正確訪問col3
任何想法?
問題是,當您保存初始DataFrame時,它已經將第3列存儲為字符串。 您的csv實際上看起來像這樣:
col1 col2 col3
0 value1 0.5 {'key1': 0.2}
1 value1 0.5 {'key2': 0.3}
# Note this column is string.
因此,當您閱讀它時, col3
給您一個str
對象,而不是您所期望的dict
。
如果沒有明確的理由將col3
存儲為字典的字符串表示形式,則僅存儲該值。 您應該更新row1['col3']
來反映這一點:
{'col1': 'value1', 'col2': 0.5, 'col3': [0.2, 0.3]}
假設col3
每個項目中只有一個帶有一個鍵的字典,則可以將其轉換為:
row1['col3'] = [[i for i in v.values()][0] for v in row1['col3']]
這樣,您的df
現在將只給您字典的值:
col1 col2 col3
0 value1 0.5 0.2
1 value1 0.5 0.3
之后,您的df.to_csv
和df.read_csv
應該沒問題。
我覺得有一個比我想念的解決方案更明顯的解決方案,所以任何pandas
專家都請加入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.