首页 > 解决方案 > 如何修改下面的 Python 代码以将字符附加到 Pandas 中字符串的开头?

问题描述

我正在做一项数据可视化任务,我需要在其中获取数据集并进行某些可视化。考虑以下关于数据集的内容:

所以我必须读取数据集,将带有“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  

疑点:

PS经度的转换产生了很多警告。如果有人能解释为什么我会收到这些警告以及如何防止它们,那就太好了?(再次,我是 Python 和 Pandas 的新手!)

数据集可以在这里找到

这是数据集的屏幕截图:
将数据放入数据框中后的数据截图

标签: pythonpython-3.xpandasdataframedata-processing

解决方案


我会在 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','')))

推荐阅读