简体   繁体   English

构造熊猫数据框:视为列还是行?

[英]Constructing Pandas Dataframe: Treating as columns or rows?

I find it hard to remember how Pandas decides to treat list as column or row at different times. 我发现很难记住熊猫是如何决定在不同时间将列表视为列或行的。

What is the general rule that is easy to remember? 容易记住的一般规则是什么?

Example: 例:

pd.DataFrame(data=[['x','y','z'],['a','b','c']])

xyz y
abc abc

pd.DataFrame(data={'A':['x','y','z'],'B':['a','b','c']})

xa a
yb b
zc 零碳

df = pd.DataFrame(data={'A':['x','y','z'],'B':['a','b','c']}) is best way of using pandas. df = pd.DataFrame(data={'A':['x','y','z'],'B':['a','b','c']})是最好的方法使用熊猫。 This means 'A' is the column header and reference, ['x', 'y', 'z'] are values of that column. 这意味着'A'是列标题和引用,['x','y','z']是该列的值。

You can even further filter rows etc. based on this like df[df['A']=='x'] to get only those rows which have value x in column 'A' 您甚至可以基于df[df['A']=='x']进一步过滤行等,以仅获取列“ A”中值为x的行

In second approach you can use DataFrame.from_dict with parameter orient : 在第二种方法中,您可以将DataFrame.from_dict与参数orient

a = pd.DataFrame.from_dict(data={'A':['x','y','z'],'B':['a','b','c']}, orient='index')
print (a)
   0  1  2
A  x  y  z
B  a  b  c

b= pd.DataFrame.from_dict(data={'A':['x','y','z'],'B':['a','b','c']}, orient='columns')
print (b)
   A  B
0  x  a
1  y  b
2  z  c

and first perfect explain EdChum in comment . 并且首先完美地解释了EdChum的评论

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

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