将dict导入数据帧获取索引错误或列不正确

2024-09-30 22:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

格言样本:{'7/24/20':'redbank:280','7/23/20':'redbank:279','7/22/20':'redbank:277'} 我不能把它作为日期、城镇、计数输入熊猫

df = pd.DataFrame.from_dict(thelist, orient='index')
red_bank_covid_cnt = df[0].str.split(':', expand=True)
red_bank_covid_cnt.reindex(columns=['n']+red_bank_covid_cnt.columns[:-1].tolist())
red_bank_covid_cnt.info()
red_bank_covid_cnt.head()

output: 
Index: 118 entries, 7/24/20 to 3/21/20
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   0       118 non-null    object
 1   1       118 non-null    object
dtypes: object(2)
memory usage: 2.8+ KB
0   1
7/24/20 Red Bank    280
7/23/20 Red Bank    279
7/22/20 Red Bank    277
7/21/20 Red Bank    275
7/17/20 Red Bank    269

I am trying to make a line graph. 

Tags: columnstodfobjectrednullbank样本
1条回答
网友
1楼 · 发布于 2024-09-30 22:12:13

另一种方法是将字典修改为字典列表

In [36]: a
Out[36]:
{'7/24/20': 'Red Bank: 280',
 '7/23/20': 'Red Bank: 279',
 '7/22/20': 'Red Bank: 277'}

In [37]: modified_list = [{"Date":k,"Bank":v.split(":")[0],"Number":v.split(":")[1]} for k,v in a.items()]

In [38]: df = pd.DataFrame(modified_list)

In [40]: df["Date"] = pd.to_datetime(df["Date"])

In [41]: df
Out[41]:
        Date      Bank Number
0 2020-07-24  Red Bank    280
1 2020-07-23  Red Bank    279
2 2020-07-22  Red Bank    277

画线图

df["Number"] = df["Number"].astype(int)
df = df.set_index("Date")
df.plot.line(y="Number")

相关问题 更多 >