python - 如何修改下面的 Python 代码以将字符附加到 Pandas 中字符串的开头?
问题描述
我正在做一项数据可视化任务,我需要在其中获取数据集并进行某些可视化。考虑以下关于数据集的内容:
- 列由经度表示(带有“E”或“W”的字符串列表分别表示东经或西经)
- 行由纬度表示(一列带有“N”或“S”的字符串分别表示北纬或南纬)
所以我必须读取数据集,将带有“N”的纬度转换为正浮点值,并将“S”作为负浮点值(整个数据在字符串中)。
同样,我必须将附有“E”的经度转换为正浮点值,并将附有“W”的经度转换为负浮点值。
由于我是 Python、Pandas、Numpy 的新手,因此我在实现相同目标方面遇到了很多困难。到目前为止,我已经能够将字符串格式的纬度和经度转换为浮点格式,并分别去掉“N”、“S”、“E”、“W”字符。但是,我无法弄清楚如何在浮点转换之前根据字符('N'、'S'、'E'、'W')使浮点值变为正值或负值。
以下是我到目前为止编写的代码:
import pandas as pd
df = pd.read_csv("Aug-2016-potential-temperature-180x188.txt", skiprows = range(7))
df.columns = ["longitude"]
df = df.longitude.str.split("\t", expand = True)
smaller = df.iloc[::10,:]
print(df.head(10), end = "\n")
print(smaller, end = "\n")
print(df.iloc[1][3], end = "\n")
print(smaller.iloc[2][175], end = "\n")
import numpy as np
import pandas as pd
data = pd.read_csv('~/documents/datasets/viz_a1/Aug-2016-potential-temperature-180x188.txt', skiprows=7)
data.columns = ['longitudes']
data = data['longitudes'].str.split('\t', expand=True)
df = data.iloc[::10,:]
df.head()
# replace 'E' with '' and 'W' with ''
df.loc[0] = df.loc[0].str.replace('E', '').str.replace('W', '')
# convert the longitude values to float values (THIS ONE WORKS)
df.loc[0] = df.loc[0][1:].astype(float)
# replace 'S' with '' and 'N' with ''
df.loc[:][0] = df.loc[:][0].str.replace('S', '').str.replace('N', '')
# convert latitude values into float values (THIS ONE DOES NOT WORK!!)
df.loc[:][0] = df.loc[:][0].astype(float)
# checking if the float values exist
print(df.loc[0][2], ' data-type ', type(df.loc[0][2])) # columns converted into float
print(df.loc[30][0], ' data-type ', type(df.loc[30][0])) # rows not converted into float
疑点:
- 如何根据符号将值转换为正负浮点值('S'、'W' 表示 -ve 浮点值,'E'、'N' 表示正浮点值)
- 我如何成功地将纬度转换为浮点值(我编写的代码没有将行转换为浮点数;也没有抛出任何错误!)
PS经度的转换产生了很多警告。如果有人能解释为什么我会收到这些警告以及如何防止它们,那就太好了?(再次,我是 Python 和 Pandas 的新手!)
数据集可以在这里找到
解决方案
我会在 read_csv 函数中添加更多参数来获得一个数据框,其中列是纵向字符串,索引是纬度。数据框中的数据现在是栅格数据
df = pd.read_csv(r'Aug-2016-potential-temperature-180x188.txt',
skiprows=8, delimiter='\t', index_col=0)
然后,我将使用以下代码将纵向字符串(数据帧的列)转换为浮点数:
column_series = pd.Series(df.columns)
df.columns = column_series.apply(lambda x: float(x.replace('E','')) if x.endswith('E') else -float(x.replace('W','')))
在我使用以下代码将纬度字符串(数据帧的索引)转换为浮点数后:
index_series = pd.Series(df.index)
df.index = index_series.apply(lambda x: float(x.replace('N','')) if x.endswith('N') else -float(x.replace('S','')))
推荐阅读
- amazon-web-services - How to auto create a Classic Link for AWS EB Instances to VPC
- windows - 如何在目录树中递归地用下划线替换所有文件和文件夹名称中的所有空格?
- php - 将 CSS 添加到数组的 foreach 循环中
- usb - 是否有任何用于 USB 调制解调器的 USSD 请求的 API
- python - 如何在 Cython 中将 C++ 向量转换为 numpy 向量,同时最小化 Python 解释器交互?
- opencl - OpenCL 可以从 .cl 源代码与预构建的二进制内核一起构建程序吗?
- python - returns max value of a columns for a date
- reactjs - 暂存环境中未显示基本 CSS 样式
- python - 从 Automator 接收变量作为字符串
- java - How to read same value from nodes with different keys in Firebase real-time database?