我有以下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还很陌生,有没有什么方法可以让一个更优雅的代码得到同样的结果呢
如果您对输出中的一个小调整没有意见,可以直接使用
melt
和to_dict
为每个信息获取单独的词典:对于非特定于Pandas的解决方案,此
split_rows
函数适用于任何iterable的namedtuples(或者如果您更改了rd = ...
行,则任何可以指定的内容)输出
相关问题 更多 >
编程相关推荐