简体   繁体   English

将元组转换为熊猫数据框

[英]converting tuple into pandas dataframe

Assume that we have the following tuple假设我们有以下元组

    S=({'country':[('India')],'state':[('Telangana')],'city':[('Hyderabad'),('Vizag')]}, {'date':[{'year': 2021, 'month':10}]})
    
    <class 'tuple'>
    

Can we convert this into a dataframe and get the date part into a variable我们可以将其转换为数据帧并将日期部分转换为变量吗

    df = key      value
         country  India
         state    Telangana
         city     Hyderabad
         city     Vizag
         
    Date = {'date':[{'year': 2021, 'month':10}]}

I have tried pd.DataFrame(json.loads(json.dumps(s))) but its not clean我试过 pd.DataFrame(json.loads(json.dumps(s))) 但它不干净

For the first part, you can try:对于第一部分,您可以尝试:

pd.Series(S[0]).explode()

Result:结果:

country    India    
state      Telangana
city       Hyderabad
city       Vizag    
dtype: object

If you need a dataframe, you can use:如果你需要一个数据框,你可以使用:

df = pd.DataFrame(pd.Series(S[0]).explode().reset_index().values, columns=['key', 'value'])

Result:结果:

print(df)

       key      value
0  country      India
1    state  Telangana
2     city  Hyderabad
3     city      Vizag

For the second part on Date , you can use:对于Date的第二部分,您可以使用:

Date = S[1]

Result:结果:

print(Date)

{'date': [{'year': 2021, 'month': 10}]}

For the Date part, you can try对于Date部分,您可以尝试

Date = S[1]
print(Date)
{'date': [{'year': 2021, 'month': 10}]}

As for the first part of your question, you may find the following code less than perfect, but it can easily be edited to match the desired output perfectly.至于问题的第一部分,您可能会发现以下代码不够完美,但可以轻松对其进行编辑以完美匹配所需的输出。

df = pd.DataFrame(
    {k:pd.Series(v) for k, v in dict(S[0]).items()}
).transpose()
print(df)
               0      1
country      India    NaN
state    Telangana    NaN
city     Hyderabad  Vizag

For more information, refer to this post有关更多信息,请参阅此帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM