按行和列增长的数据帧

2024-09-29 05:31:12 发布

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

我有以下dataframe(可以在行和信息列中增长):

City    Country   Info1  Info2
BCN      Spain    3      5.6   
Moscow   Russia   4      7   

我试着把这些信息分成以下几部分:

[
{Info1: 3,
 City: BCN,
 Country: Spain},

{Info2: 5.6,
 City: BCN,
 Country: Spain},

{Info1: 4,
 City: Moscow,
 Country: Russia},

{Info2: 7,
 City: Moscow,
 Country: Russia}
]

这样做有效:

import pandas as pd

dict = {'city':["BCN", "Moscow"], 
        'country': ["Spain", "Russia"], 
        'inf_1':[3, 5],
        'inf_2':[4,7]} 

#we make the dict a dataframe
df = pd.DataFrame(dict) 

# We make a list of the indicators
columns = list(df)[2:]
j=0
i=0


for rows in df.itertuples():
    for col in columns:
        print(" ")
        print("city: " + str(rows.city) )
        print("country: " + str(rows.country))
        print("ind_id: "+ str(columns[j]))
        print("value: "+ str(df[col][i]))
        print(" ")
        j=j+1
    j=0
    i=i+1

然而,这个结果在我看来并不美好。因为我对Pandas还很陌生,有没有什么方法可以让一个更优雅的代码得到同样的结果呢


Tags: columnscitydfcountrydictprintstrspain
2条回答

如果您对输出中的一个小调整没有意见,可以直接使用meltto_dict为每个信息获取单独的词典:

>>> df.melt(['City', 'Country']).to_dict('r')

[{'City': 'BCN', 'Country': 'Spain', 'value': 3.0, 'variable': 'Info1'},
 {'City': 'Moscow', 'Country': 'Russia', 'value': 4.0, 'variable': 'Info1'},
 {'City': 'BCN', 'Country': 'Spain', 'value': 5.6, 'variable': 'Info2'},
 {'City': 'Moscow', 'Country': 'Russia', 'value': 7.0, 'variable': 'Info2'}]

对于非特定于Pandas的解决方案,此split_rows函数适用于任何iterable的namedtuples(或者如果您更改了rd = ...行,则任何可以指定的内容)

import pandas as pd


def split_rows(namedtuple_iterable, cols):
    for row in namedtuple_iterable:
        rd = row._asdict()
        cs = [(col, rd.pop(col)) for col in cols]
        for key, value in cs:
            yield {**rd, key: value}


df = pd.DataFrame(
    {
        "city": ["BCN", "Moscow"],
        "country": ["Spain", "Russia"],
        "inf_1": [3, 5],
        "inf_2": [4, 7],
    }
)


for sr in split_rows(df.itertuples(), ("inf_1", "inf_2")):
    print(sr)

输出

{'Index': 0, 'city': 'BCN', 'country': 'Spain', 'inf_1': 3}
{'Index': 0, 'city': 'BCN', 'country': 'Spain', 'inf_2': 4}
{'Index': 1, 'city': 'Moscow', 'country': 'Russia', 'inf_1': 5}
{'Index': 1, 'city': 'Moscow', 'country': 'Russia', 'inf_2': 7}

相关问题 更多 >