M.N*_*lly 4 python concat dataframe pandas
我有三个数据帧:时间戳(带时间戳),dataSun(带有日出和日落的时间戳),dataData(带有不同的气候数据).Dataframe timestamp具有数据类型"int64".
timestamp.head()
timestamp
0 1521681600000
1 1521681900000
2 1521682200000
3 1521682500000
4 1521682800000
Dataframe dataSun也有数据类型"int64".
dataSun.head()
sunrise sunset
0 1521696105000 1521740761000
1 1521696105000 1521740761000
2 1521696105000 1521740761000
3 1521696105000 1521740761000
4 1521696105000 1521740761000
Run Code Online (Sandbox Code Playgroud)
具有气候数据的数据框具有数据dataData类型"float64".
dataData.head()
temperature pressure humidity
0 2.490000 1018.000000 99.0
1 2.408333 1017.833333 99.0
2 2.326667 1017.666667 99.0
3 2.245000 1017.500000 99.0
4 2.163333 1017.333333 99.0
5 2.081667 1017.166667 99.0
Run Code Online (Sandbox Code Playgroud)
我想将这三个数据帧连接在一起.
dataResult = pd.concat((timestamp, dataSun, dataData), axis = 1)
dataResult.head()
timestamp sunrise sunset temperature pressure
0 1521681600000 1.521696e+12 1.521741e+12 2.490000 1018.000000
1 1521681900000 1.521696e+12 1.521741e+12 2.408333 1017.833333
2 1521682200000 1.521696e+12 1.521741e+12 2.326667 1017.666667
3 1521682500000 1.521696e+12 1.521741e+12 2.245000 1017.500000
4 1521682800000 1.521696e+12 1.521741e+12 2.163333 1017.333333
5 1521683100000 1.521696e+12 1.521741e+12 2.081667 1017.166667
weatherMeasurements.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7188 entries, 0 to 7187
Data columns (total 6 columns):
timestamp 7188 non-null int64
sunrise 7176 non-null float64
sunset 7176 non-null float64
temperature 7176 non-null float64
pressure 7176 non-null float64
humidity 7176 non-null float64
dtypes: float64(5), int64(1)
Run Code Online (Sandbox Code Playgroud)
为什么要pd.concat更改值的数据类型DataSun?我尝试过不同的方法来连接数据帧.例如,我只串联timestamp并dataSun在一个数据帧,然后我级联导致数据框用dataData.但结果却是一样的.如何连接三个数据帧并保护数据类型?
因为这 -
timestamp 7188 non-null int64
sunrise 7176 non-null float64
...
Run Code Online (Sandbox Code Playgroud)
timestamp有7188个非空值,而sunrise以及之前有7176.不言而喻,有12个值不是非空的...意味着它们是NaN.
由于NaNs是dtype=float,所以该列中的每个其他值都会自动升级为浮点数,浮点数通常以科学计数法表示.
这就是原因,但这并不能真正解决您的问题.你现在的选择是
dropna fillna(现在您可以将这些行向下转换为int.)
另外,如果执行pd.concat有join='inner',NaN是不引入和dtypes被保留.
pd.concat((timestamp, dataSun, dataData), axis=1, join='inner')
timestamp sunrise sunset temperature pressure \
0 1521681600000 1521696105000 1521740761000 2.490000 1018.000000
1 1521681900000 1521696105000 1521740761000 2.408333 1017.833333
2 1521682200000 1521696105000 1521740761000 2.326667 1017.666667
3 1521682500000 1521696105000 1521740761000 2.245000 1017.500000
4 1521682800000 1521696105000 1521740761000 2.163333 1017.333333
humidity
0 99.0
1 99.0
2 99.0
3 99.0
4 99.0
Run Code Online (Sandbox Code Playgroud)使用选项3,对每个数据帧的索引执行内部联接.