jur*_*kij 4 python pivot-table type-conversion dataframe pandas
我在将数据框转换为数据透视表时发现了熊猫的奇怪行为。
import pandas as pd
df = pd.DataFrame({'car_id': {0: 'Trabant', 1: 'Buick', 2: 'Dodge'}, 'car_order': {0: 2, 1: 1, 2: 14}, 'car_name': {0: 'Trabant', 1: 'Buick', 2: 'Dodge'}, 'car_rank': {0: 111111317.29, 1: 1111112324.0, 2: 1111112324.5}})
table = df.pivot_table(index=['car_id', 'car_name', 'car_order'], columns=[],values=['car_rank'], fill_value='',dropna=True)
print table
df1 = pd.DataFrame({'car_id': {0: 'Trabant', 1: 'Buick', 2: 'Dodge'}, 'car_order': {0: 2, 1: 1, 2: 14}, 'car_name': {0: 'Trabant', 1: 'Buick', 2: 'Dodge'}, 'car_rank': {0: 17.29, 1: 24.0, 2: 24.5}})
table1 = df1.pivot_table(index=['car_id', 'car_name', 'car_order'], columns=[],values=['car_rank'], fill_value='',dropna=True)
print table1
Run Code Online (Sandbox Code Playgroud)
结果输出:
Table
car_rank
car_id car_name car_order
Buick Buick 1 1111112324
Dodge Dodge 14 1111112324
Trabant Trabant 2 111111317
Table 1
car_rank
car_id car_name car_order
Buick Buick 1 24.00
Dodge Dodge 14 24.50
Trabant Trabant 2 17.29
Run Code Online (Sandbox Code Playgroud)
您知道为什么Table中的值转换为 int 而Table 1 中的值保持为 float 吗?
大熊猫 0.18.0,蟒蛇 2.7.9
这是我观察的结果pandas 0.18.0:
行pandas/tools/pivot.py定义源代码pivot_table():141-142:
if fill_value is not None:
table = table.fillna(value=fill_value, downcast='infer')
Run Code Online (Sandbox Code Playgroud)
这正是您的旋转 DF 发生的情况:
In [78]: df.fillna('', downcast='infer')
Out[78]:
car_id car_name car_order car_rank
0 Trabant Trabant 2 111111317
1 Buick Buick 1 1111112324
2 Dodge Dodge 14 1111112324
Run Code Online (Sandbox Code Playgroud)
类型:
In [48]: df.fillna('', downcast='infer').dtypes
Out[48]:
car_id object
car_name object
car_order int64
car_rank int64
dtype: object
Run Code Online (Sandbox Code Playgroud)
有趣的是 - 如果你使用pivot_table()得当(即旋转) - 它可以正常工作:
In [81]: df.pivot_table(index=['car_id', 'car_order'], columns=['car_name'], values=['car_rank'],dropna=True, fill_value='')
Out[81]:
car_rank
car_name Buick Dodge Trabant
car_id car_order
Buick 1 1111112324.00
Dodge 14 1111112324.50
Trabant 2 111111317.29
Run Code Online (Sandbox Code Playgroud)
PS我仍然不明白你为什么以那种奇怪的方式使用pivot_table——你要实现什么?
| 归档时间: |
|
| 查看次数: |
4598 次 |
| 最近记录: |