简体   繁体   English

如何将函数应用于数据框列

[英]How do you apply a function to a dataframe column

races = pd.read_csv("C:/Users/Sam/Documents/races.csv")
df_races = pd.DataFrame(races)
df_races = df_races[["raceId", "year", "name"]]
df_races = df_races.sort_values(by=['year'])
df_races = df_races[df_races['name'] == 'Australian Grand Prix']
# Australian Grand Prix 'Find Qualifying Data'
QLF = pd.read_csv("C:/Users/Sam/Documents/qualifying.csv")
df_QLF = pd.DataFrame(QLF)
df_QLF = df_QLF[["raceId", "position", "q1", "q2", "q3"]]
Race_Id_1 = df_races['raceId'].tolist()
# Filter Rows
df_QLF['Match'] = df_QLF["raceId"].isin(Race_Id_1)
def Find_Rid(row):
if row['Match'] == 'True':
    return row
df_QLF = df_QLF.apply(Find_Rid, axis=1)

print(df_QLF)

Once I run this all I get the following output, when actually all I want is when df_QLF['Match'] column == 'True' to keep these rows and discard all of the others一旦我运行这一切,我得到以下输出,实际上我想要的是当 df_QLF['Match'] column == 'True' 保留这些行并丢弃所有其他行

   0         None
   1         None
   2         None
   3         None
   ....      ....

I don't understand why.我不明白为什么。

df_QLF = df_QLF.loc[df_QLF['Match'] == True]

Following code worked for me.以下代码对我有用。 In python, True and False are specially reserved constants for bool class.在 python 中, TrueFalse是专门为 bool 类保留的常量。 Reference: 1) https://docs.python.org/2.3/whatsnew/section-bool.html 2) https://www.geeksforgeeks.org/bool-in-python/参考:1) https://docs.python.org/2.3/whatsnew/section-bool.html 2) https://www.geeksforgeeks.org/bool-in-python/

def Find_Rid(row):
    if row['Match'] == True:
         return row
df_QLF_true = df_QLF.apply(Find_Rid, axis=1)
print(df_QLF_true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用前几行的数据在 dataframe 列上应用 function? - How do you apply a function on a dataframe column using data from previous rows? 如何将函数应用于DataFrame中的几列之一? - How do you apply a function to one of several columns in a DataFrame? 如何将自定义函数应用于 pandas 数据框中的列并将输出存储在另一个数据框的列中? - How can you apply a custom function to a column in pandas dataframe and store the output in a column of another dataframe? 如何将此字符串长度函数应用于数据框中的列? - How do I apply this string length function to a column in my dataframe? 如何将自定义正则表达式 function 应用于 dataframe Python 中的列 - How do I apply a custom regex function to column in dataframe Python 将 function 应用于 dataframe 列 - apply function to dataframe column 将函数应用于Dask中的分组数据框:如何在函数中将分组的Dataframe指定为参数? - Apply function to grouped data frame in Dask: How do you specify the grouped Dataframe as argument in the function? 如何将我的函数应用于DataFrame列? - How to apply my function to DataFrame column? 如何通过数据框中的名称将功能应用于特定列 - How to apply a function to a certain column by name in a dataframe 如何在熊猫数据框的列上应用if函数 - How to apply an if between function on a column in pandas' DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM