【问题标题】:Store integers as integers and not as floats将整数存储为整数而不是浮点数
【发布时间】:2019-10-17 01:59:27
【问题描述】:

我执行以下操作:

import pandas as pd

df_texts = pd.read_csv('data_texts.csv', keep_default_na=True)

for index, row in df_texts.iterrows():   

    list_of_words = row['text'].split()

    df_texts.loc[index, '#_words'] = len(list_of_words)

    list_of_unique_words = set(list_of_words)  

    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words)

问题在于#_words#_unique_words 列中的数字即使是整数也被存储为浮点数。

只是为了澄清这两列并不预先存在于我阅读的 .csv (pd.read_csv) 中,但我在 for 循环中创建它们。

如何将它们直接存储为整数?

【问题讨论】:

  • @iamklaus 很酷,但我的问题仍然是:如何将它们直接存储为整数?
  • 在列中插入值后更改列数据类型或创建值列表并稍后插入。

标签: python python-3.x pandas type-conversion


【解决方案1】:

您可以将 int 函数应用于所需的列:

df= pd.DataFrame({
    'n':[1.12, 1.2345, 5.234]
})
df['n'] = df['n'].apply(lambda x: int(x))
df
    n
0   1
1   1
2   5

【讨论】:

  • 我认为我也可以使用pd.to_numeric()(这可能比您上面的解决方案更有效)但我仍在寻找(如果存在)更有效的东西。
【解决方案2】:

执行此操作并直接获取整数的更好方法是直接分配新列,并完全避免遍历数据框。

以一些虚拟数据为例:

import pandas as pd
texts = ['word1 word2 word3', 'word1 word2 word1', 'word3']

df_texts = pd.DataFrame(texts, columns = ['text'])
                text
0  word1 word2 word3
1  word1 word2 word1
2              word3

分别使用文本列计算所有行的长度,然后分配。

temp = df_texts['text'].str.split()
df_texts['#_words'] = [len(row) for row in temp] #iterates and creates a list of all lengths. assign to df
df_texts['#_unique_words'] = [len(set(row)) for row in temp]

print(df_texts)
#Output:
                text  #_words  #_unique_words
0  word1 word2 word3        3               3
1  word1 word2 word1        3               2
2              word3        1               1

【讨论】:

    【解决方案3】:

    如果通过为单行分配值来创建列,则所有其他行都会隐式初始化为NaN,这是一个浮点值。这会将整个列强制为float

    (如果您在设置所有值之前尝试使用df_texts['#_words'] = df_texts['#_words'].astype(int) 转换列,您也会注意到这一点。它将失败,因为NaN 无法转换为int。)

    因此,在设置所有值之前,该列不能成为整数列。如果在循环之前使用 df_texts['#_words'] = 0 初始化整个列,问题就会消失。

    编辑:另外,正如其他答案所指出的,这个分配可以在不使用循环的情况下完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2014-09-27
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多