Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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,希望这个问题有意义。我在网上找不到类似的东西 我有一组以下格式的数据: Name Field Value A Field1 Value1 A Field2 Value2 A Field3 Value3 B Field1 Value1 B Field2 Value2 ... 我想将其转换为数据帧,例如: Name Field1 Field2 Field3 A Value1 Value2 Value3 B Value1 Val

希望这个问题有意义。我在网上找不到类似的东西

我有一组以下格式的数据:

Name  Field  Value
A     Field1 Value1
A     Field2 Value2
A     Field3 Value3
B     Field1 Value1
B     Field2 Value2
...
我想将其转换为数据帧,例如:

Name  Field1  Field2  Field3
A     Value1  Value2  Value3
B     Value1  Value2  Value3
Name   Field1  Field2  Field3                        
A      Value1  Value2  Value3
B      Value1  Value2  Value3
C      Value1  Value2  Value3
如果我这样做:
df.pivot('Name','Field')
我会得到一个pivot表,其中的数据是我想要的“shape”,但作为pivot对象,我更喜欢有一个dataframe。在我看来,数据透视是用来处理数字的,我所做的只是将一列转换成变量,我相信有一种更简单的方法可以做到这一点

有些人要求提供数据:

In[224]: df = pd.DataFrame([['A','Field1', 'Value1'],['A', 'Field2', 'Value2'],['A', 'Field3', 'Value3'],['B','Field1', 'Value1'],['B', 'Field2', 'Value2'],['B', 'Field3', 'Value3'],['C','Field1', 'Value1'],['C', 'Field2', 'Value2'],['C', 'Field3', 'Value3']], columns=['Name', 'Field', 'Value'])
In[225]: df
Out[225]: 
  Name   Field   Value
0    A  Field1  Value1
1    A  Field2  Value2
2    A  Field3  Value3
3    B  Field1  Value1
4    B  Field2  Value2
5    B  Field3  Value3
6    C  Field1  Value1
7    C  Field2  Value2
8    C  Field3  Value3
In[226]: pv = df.pivot('Name', 'Field')
In[227]: pv
Out[227]: 
        Value                
Field  Field1  Field2  Field3
Name                         
A      Value1  Value2  Value3
B      Value1  Value2  Value3
C      Value1  Value2  Value3
我希望pv实际上是一个数据帧,例如:

Name  Field1  Field2  Field3
A     Value1  Value2  Value3
B     Value1  Value2  Value3
Name   Field1  Field2  Field3                        
A      Value1  Value2  Value3
B      Value1  Value2  Value3
C      Value1  Value2  Value3

一如既往,感谢大家的帮助

数据本身是您想要的格式,只是索引和列不是您想要的格式。因此,您只需编辑列并重置索引:

pv = df.pivot('Name', 'Field')
pv.columns = [c[1] for c in pv.columns]
pv.reset_index(inplace=True)