问题
我在panda中创建数据帧时遇到问题。我正在从现有数据帧df1创建一个新的空数据帧df2,其列如下所示:
import pandas as pd
import numpy as np
df2 = df1.DataFrame(columns=df1.columns)
现在,在循环中,我使用以下代码添加另一列,该列存储一个18位整数:
df2.loc[i, 'new column'] = 123123123123123123123123
然而,这将结果以指数形式存储在数据帧中,作为1.2331231231e+17。它截断最后两位数字。我希望将new column
中的值存储为18位整数。
我试了两次来解决这个问题。
方法1:在定义点进行修改
df2 = df1.DataFrame(columns=df1.columns)
df2['new column'] = 0
df2['new column'] = df2['new column'].astype(np.int64) # also tried .apply(np.int64)
方法2:分配点的修改
df2.loc[i, 'new column'] = np.int64(123123123123123123123123)
不幸的是,这两种解决方案对我都不起作用。
可复制代码以提高清晰度
df1 = pd.DataFrame(data={'A':[123123123123123123, 234234234234234234, 345345345345345345], 'B':[11,22,33]})
df1
输出:
A B
0 123123123123123123 11
1 234234234234234234 22
2 345345345345345345 33
for i in range(df1.shape[0]):
df1.loc[i, 'new column'] = 222222222222222222
df1
输出:
A B new column
0 123123123123123123 11 2.222222e+17
1 234234234234234234 22 2.222222e+17
2 345345345345345345 33 2.222222e+17
当我尝试将其转换回时,会得到一个不同的数字。
df1['new column'] = df1['new column'].astype(np.int64)
df1
输出:
A B new column
0 123123123123123123 11 222222222222222208
1 234234234234234234 22 222222222222222208
2 345345345345345345 33 222222222222222208
解决方案是在赋值之前将"new column"指定为对象,并在赋值完成后将其转换为长整数。我不确定这是否是最有效的方法。对更好的解决方案持开放态度。但它是有效的。
df1 = pd.DataFrame(data={'A':[123123123123123123, 234234234234234234, 345345345345345345], 'B':[11,22,33]})
df1['new column'] = df1['new column'].astype(object) # store as an object
for i in range(df1.shape[0]):
df1.loc[i, 'new column'] = 222222222222222222
df1['new column'] = df1['new column'].astype(np.int64) # convert it to long integer after assignment of the value
输出:
A B new column
0 123123123123123123 11 222222222222222222
1 234234234234234234 22 222222222222222222
2 345345345345345345 33 222222222222222222
df1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 3 non-null int64
1 B 3 non-null int64
2 new column 3 non-null int64
dtypes: int64(3)
memory usage: 200.0 bytes
尝试np.float
np.float64(123123123123123123123123)
# Output
1.2312312312312312e+23