Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列添加到数组_Python_Pandas - Fatal编程技术网

Python 将列添加到数组

Python 将列添加到数组,python,pandas,Python,Pandas,我有一个具有以下结构的df: date country value 20200215 Austria 123.32 20200215 Finland 321.21 20200216 Austria 123.32 20200216 Finland 321.21 我想要实现的是: date CountryValue 20200215 ['Austria':123.32,'Finland':321.21] 20200216 ['Austria':123.

我有一个具有以下结构的df:

date      country  value

20200215  Austria  123.32
20200215  Finland  321.21
20200216  Austria  123.32
20200216  Finland  321.21
我想要实现的是:


date     CountryValue

20200215  ['Austria':123.32,'Finland':321.21]
20200216  ['Austria':123.32,'Finland':321.21]

我无法找到解决方案,因此非常感谢您的帮助

如果需要,词典将
zip
dict
在lambda函数中按组使用:

f1 = lambda x: dict(zip(x['country'], x['value']))
df1 = df.groupby('date')['country','value'].apply(f1).reset_index(name='CountryValue')
print (df1)
       date                            CountryValue
0  20200215  {'Austria': 123.32, 'Finland': 321.21}
1  20200216  {'Austria': 123.32, 'Finland': 321.21}
如果需要列表,请在列表理解中使用展开列表:

f2 = lambda x: [z for y in x.values for z in y]
df2 = df.groupby('date')['country','value'].apply(f2).reset_index(name='CountryValue')
print (df2)

       date                        CountryValue
0  20200215  [Austria, 123.32, Finland, 321.21]
1  20200216  [Austria, 123.32, Finland, 321.21]

如果需要,词典在lambda函数中对每组使用
zip
dict

f1 = lambda x: dict(zip(x['country'], x['value']))
df1 = df.groupby('date')['country','value'].apply(f1).reset_index(name='CountryValue')
print (df1)
       date                            CountryValue
0  20200215  {'Austria': 123.32, 'Finland': 321.21}
1  20200216  {'Austria': 123.32, 'Finland': 321.21}
如果需要列表,请在列表理解中使用展开列表:

f2 = lambda x: [z for y in x.values for z in y]
df2 = df.groupby('date')['country','value'].apply(f2).reset_index(name='CountryValue')
print (df2)

       date                        CountryValue
0  20200215  [Austria, 123.32, Finland, 321.21]
1  20200216  [Austria, 123.32, Finland, 321.21]

我想实现的是:
,你能指定你期望的数据结构类型吗?
我想实现的是:
,你能指定你期望的数据结构类型吗?