【发布时间】:2019-03-28 14:08:21
【问题描述】:
对 DataFrame 的分配不起作用,但 dtypes 已更改。
数据科学的新手,我想将target_frame 分配给empty_frame,但在再次分配之前它不起作用。而在分配过程中,empty_frame的dtypes从int32变为float64,最后设置为int64。
我尝试将我的模型简化为下面的代码,他们有同样的问题。
import pandas as pd
import numpy as np
dataset = [[[i for i in range(5)], ] for i in range(5)]
dataset = pd.DataFrame(dataset, columns=['test'])
empty_numpy = np.arange(25).reshape(5, 5)
empty_numpy.fill(np.nan)
# Solution 1: change the below code into 'empty_frame = pd.DataFrame(empty_numpy)' then everything will be fine
empty_frame = pd.DataFrame(empty_numpy, columns=[str(i) for i in range(5)])
series = dataset['test']
target_frame = pd.DataFrame(list(series))
# Solution 2: run `empty_frame[:] = target_frame` twice, work fine to me.
# ==================================================================
# First try.
empty_frame[:] = target_frame
print("="*40)
print(f"Data types of empty_frame: {empty_frame.dtypes}")
print("="*40)
print("Result of first try: ")
print(empty_frame)
print("="*40)
# Second try.
empty_frame[:] = target_frame
print(f"Data types of empty_frame: {empty_frame.dtypes}")
print("="*40)
print("Result of second try: ")
print(empty_frame)
print("="*40)
# ====================================================================
我希望上面代码的输出应该是:
========================================
Data types of empty_frame: 0 int64
1 int64
2 int64
3 int64
4 int64
dtype: object
========================================
Result of first try:
0 1 2 3 4
0 0 1 2 3 4
1 0 1 2 3 4
2 0 1 2 3 4
3 0 1 2 3 4
4 0 1 2 3 4
========================================
但我第一次尝试时它不起作用。
这个问题有两种解决方案,但我不知道为什么:
- 正如我在代码中显示的那样,一次运行两次尝试分配。
- 创建
empty_frame时删除列名。
我想弄清楚两件事:
- 为什么
empty_frame的数据类型发生了变化。 - 为什么我的代码中显示的解决方案可以解决这个分配问题。
谢谢。
【问题讨论】: