如何使pandas将“not applicable”读取为null值

huangapple go评论71阅读模式
英文:

How to make pandas read "not applicable" as a null value

问题

基本上,我的数据框中的一列包含整数的纬度和经度,但某些条目包含“not applicable”。因此,该列的数据类型为对象。我希望pandas将“not applicable”解释为null,这样我就可以将该列视为整数系列。

到目前为止,我在网上还没有找到任何信息,但我记得曾在网上看到有关这个问题的一些内容。

英文:

Basically a column in my data frame has lat and long in integers but some entries have "not applicable". Due to this, the column has dtype of object. I want pandas to read the "not applicable" as null so i can treat the column like an integer series.

I haven't been able to find anything online so far but I recall having read something about this online.

答案1

得分: 1

如果你正在处理来自文件的数据,可以检查加载函数中的na_values参数(示例使用pd.read_csv()):

df = pd.read_csv('examplefile.csv', na_values='not applicable')

这将告诉pandas将每个包含'not applicable'的单元格视为NaN。

如果你的数据框是在程序内生成的,你可以使用pd.replace()来更改'not applicable'出现的位置的值:

这将将你告诉它的值更改为你告诉函数的另一个值:

df.replace('not applicable', np.nan, inplace=True)

inplace参数使数据框得到更新,而不是返回它。如果你不想使用它,你可以这样做:df = df.replace('not applicable', np.nan)

在这里,我使用了numpy的NaN作为替代值,但你可以告诉它替代为任何你想要的值。

要更改数据类型,你可以使用pd.astype()

英文:

If you're dealing with data from a file, you can check the na_values argument in the load functions (example with pd.read_csv())

df = pd.read_csv('examplefile.csv', na_values= 'not applicable')

This will tell pandas to treat every single cell that has 'not applicable' in it as a nan.

If your dataframe is something you've generated inside the program, you can change the values where 'not applicable' appears with pd.replace()

This will change the value you tell it to another value you tell the function:

df.replace('not applicable', np.nan, inplace=True)

The inplace argument makes it so the dataframe gets updated, instead of returning it. if you don't want to use it, you can do df = df.replace('not applicable', np.nan)

Here, I've used numpy's NaN as the replacement, but you can tell it to replace with any value you want.

For changing the data type, you can use pd.astype()

huangapple
  • 本文由 发表于 2023年6月27日 22:01:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定