gpt4 book ai didi

python - 循环遍历列并调整值 pandas

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:43 24 4
gpt4 key购买 nike

我有一个大约 100,000 行和 1,000 列的 df,需要根据现有数据进行一些调整。我该如何最好地处理这个问题?大多数更改将遵循以下基本公式:

  1. 搜索一列(或两列或三列)以查看是否满足条件
  2. 如果满足,则更改该行中数十或数百列的值

这是我最好的尝试,我创建了一个列列表,并查看第一列是否包含值 1。在包含值 1 的地方,我只想添加一些数字。该部分有效,但仅适用于第一行,而不适用于该列中的所有 1。为了解决这个问题,我认为我需要创建一个循环,其中第二个 [i] 遍历所有行,但我不确定我是否错误地处理了整个问题。 FWIW,test_cols = 列列表,testing_2 是我的 df。

      def try_this(test_cols):
for i in range(len(test_cols)):
if i == 0 and testing_2[test_cols[i]][i] == 1:
testing_2[test_cols[i]][i]=testing_2[test_cols[i]][i]+78787
i+=1
return test_cols

编辑/示例:

       Year   Month    Mean_Temp 
City

Madrid 1999 Jan 7--this value should appear twice
Bilbao 1999 Jan 9--appear twice
Madrid 1999 Feb 9
Bilbao 1999 Feb 10
. . . .
. . . .
. . . .
Madrid 2000 Jan 6.8--this value should go away
Bilbao 2000 Jan 9.2--gone

所以我需要做类似的事情(使用你的答案):

def alter(row):
if row['Year'] == 2000 and row['Month'] == 'Jan':
row['Mean_Temp'] = row['Mean_Temp'] #from year 1999!
return row['Mean_Temp']
else:
return row['Mean_Temp']

最佳答案

实现此目的的一种方法是创建一个函数并应用它。假设如果“a”或“b”中的相应行是偶数,则要将“c”列增加 10 倍。

import pandas as pd

data = {'a':[1,2,3,4],'b':[3,6,8,12], 'c':[1,2,3,4]}
df = pd.DataFrame(data)

def alter(row):
if row['a']%2 == 0 or row['b']%2 == 0:
return row['b']*10
else:
return row['b']

df['c'] = df.apply(alter, axis=1)

会创建一个看起来像这样的 df,

   a   b    c
0 1 3 3
1 2 6 60
2 3 8 80
3 4 12 120

编辑添加:如果您想应用 df 其他部分的值,您可以将它们放入字典中,然后将其传递到您的 apply 函数中。

import pandas as pd

data = {'Cities':['Madrid', 'Balbao'] * 3, 'Year':[1999] * 4 + [2000] * 2,
'Month':['Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Jan'],
'Mean_Temp':[7, 9, 9, 10, 6.8, 9.2]}

df = pd.DataFrame(data)
df = df[['Cities', 'Year', 'Month', 'Mean_Temp']]

#create dicitonary with the values from 1999
edf = df[df.Year == 1999]
keys = zip(edf.Cities, edf.Month)
values = edf.Mean_Temp
dictionary = dict(zip(keys, values))


def alter(row, dictionary):
if row['Year'] == 2000 and row['Month'] == 'Jan':
return dictionary[(row.Cities, row.Month)]
else:
return row['Mean_Temp']

df['Mean_Temp'] = df.apply(alter, args = (dictionary,), axis=1)

这会给你一个看起来像这样的 df,

   Cities  Year Month  Mean_Temp
0 Madrid 1999 Jan 7
1 Balbao 1999 Jan 9
2 Madrid 1999 Feb 9
3 Balbao 1999 Feb 10
4 Madrid 2000 Jan 7
5 Balbao 2000 Jan 9

当然,您可以随意更改参数。希望这会有所帮助。

关于python - 循环遍历列并调整值 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com