我有一个有两列的pandas数据框.我需要更改第一列的值而不影响第二列,只需更改第一列值即可返回整个数据框.我怎么能用熊猫申请呢?
我有一个像pandas DataFrame:
A B
'2010-01-01' 10 20
'2010-02-01' 20 30
'2010-03-01' 30 10
Run Code Online (Sandbox Code Playgroud)
我需要为每个列应用一些函数,并在此DataFrame中使用特殊名称创建新列.
A B A1 B1
'2010-01-01' 10 20 20 40
'2010-02-01' 20 30 40 60
'2010-03-01' 30 10 60 20
Run Code Online (Sandbox Code Playgroud)
所以我需要创建两个带有名称的列,A1并B2基于列A和B(如名称A1 = str(A) + str(1))乘以2.是否可以使用DataFrame.apply()或其他结构?
我正在查看Roman Pekar的这个答案以使用 apply。我最初完全复制了代码并且运行良好。然后我在从 csv 文件创建的 df3 上使用它,并得到一个 KeyError。我检查了我使用的列的数据类型是 int64,所以没关系。我没有空值。如果我能让这个工作正常,那么我会让这个功能变得更复杂。我怎样才能让它发挥作用?
def fxy(x, y):
return x * y
df3 = pd.read_csv(path + 'test_data.csv', usecols=[0,1,2])
print(df3.dtypes)
df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']))
Run Code Online (Sandbox Code Playgroud)
追溯
Traceback (most recent call last):
File "f:\...\my_file.py", line 54, in <module>
df3['Area'] = df3.apply(lambda x: fxy(x['Len'], x['Width']))
File "C:\...\frame.py", line 8833, in apply
return op.apply().__finalize__(self, method="apply")
File "C:\...\apply.py", line 727, in apply
return self.apply_standard()
File "C:\...\apply.py", line 851, in apply_standard
results, res_index = self.apply_series_generator()
File "C:\...\apply.py", line 867, …Run Code Online (Sandbox Code Playgroud) 我有一个带有列Longitude和的pandas数据框Latitude.我想X和Y他们相处.utm调用from_latlon中有一个函数可以执行此操作.它接收Latitude和Longitude并给出[X,Y].这是我做的:
def get_X(row):
return utm.from_latlon(row['Latitude'], row['Longitude'])[0]
def get_Y(row):
return utm.from_latlon(row['Latitude'], row['Longitude'])[1]
df['X'] = df.apply(get_X, axis=1)
df['Y'] = df.apply(get_Y, axis=1)
Run Code Online (Sandbox Code Playgroud)
我想定义一个函数get_XY并from_latlon只应用一次来节省时间.我看了一下这里,这里和这里,但我找不到用一个apply函数制作两列的方法.谢谢.