如何为数据框(整数)列编写 for-loop/if-statement
How to write a for-loop/if-statement for a dataframe (integer) column
我有一个数据框,其中有一列整数代表生日。每行都有 20xx 或 19xx,但有些行只有 xx 部分。
如果整数大于 22(从 0 开始),我想做的是在那些只有 2 个“元素”的数字前面加 19,or/and 在那些更小或更小的数字前面加 20等于 22.
这是我写的;
for x in DF.loc[DF["Year"] >= 2022]:
x + 1900
if:
x >= 22
else:
x + 2000
您也可以完全更改代码,我希望您能解释一下您的代码到底做了什么。
感谢所有花时间回答这个问题的人。
这基本上就是你所做的,if
在 for
中:
new_list_of_years = []
for year in DF.loc[DF["Year"]:
full_year = year+1900 if year >22 else year+2000
new_list_of_years.append(full_year)
DF['Year'] = pd.DataFrame(new_list_of_years)
编辑: 您也可以使用 for-if
列表理解来做到这一点:
DF['Year'] = [year+1900 if year > 22 else year+2000 for year in DF.loc[DF["Year"]]]
您可以使用 apply
方法在一行中完成。
示例:
df = pd.DataFrame({'date': [2002, 95, 1998, 3, 56, 1947]})
print(df)
date
0 2002
1 95
2 1998
3 3
4 56
5 1947
然后:
df = df.date.apply(lambda x: x+1900 if (x<100) & (x>22) else (x+2000 if (x<100)&(x<22) else x) )
print(df)
date
0 2002
1 1995
2 1998
3 2003
4 1956
5 1947
不用遍历行,而是使用 where
更改整列:
y = df["Year"] # just to save typing
df["Year"] = y.where(y > 99, (y + 1900).where(y > 22, y + 2000))
或indexing:
df["Year"][df["Year"].between(0, 21)] += 2000
df["Year"][df["Year"].between(22, 99)] += 1900
或loc
:
df.loc[df["Year"].between(0, 21), "Year"] += 2000
df.loc[df["Year"].between(22, 99), "Year"] += 1900
我有一个数据框,其中有一列整数代表生日。每行都有 20xx 或 19xx,但有些行只有 xx 部分。
如果整数大于 22(从 0 开始),我想做的是在那些只有 2 个“元素”的数字前面加 19,or/and 在那些更小或更小的数字前面加 20等于 22.
这是我写的;
for x in DF.loc[DF["Year"] >= 2022]:
x + 1900
if:
x >= 22
else:
x + 2000
您也可以完全更改代码,我希望您能解释一下您的代码到底做了什么。
感谢所有花时间回答这个问题的人。
这基本上就是你所做的,if
在 for
中:
new_list_of_years = []
for year in DF.loc[DF["Year"]:
full_year = year+1900 if year >22 else year+2000
new_list_of_years.append(full_year)
DF['Year'] = pd.DataFrame(new_list_of_years)
编辑: 您也可以使用 for-if
列表理解来做到这一点:
DF['Year'] = [year+1900 if year > 22 else year+2000 for year in DF.loc[DF["Year"]]]
您可以使用 apply
方法在一行中完成。
示例:
df = pd.DataFrame({'date': [2002, 95, 1998, 3, 56, 1947]})
print(df)
date
0 2002
1 95
2 1998
3 3
4 56
5 1947
然后:
df = df.date.apply(lambda x: x+1900 if (x<100) & (x>22) else (x+2000 if (x<100)&(x<22) else x) )
print(df)
date
0 2002
1 1995
2 1998
3 2003
4 1956
5 1947
不用遍历行,而是使用 where
更改整列:
y = df["Year"] # just to save typing
df["Year"] = y.where(y > 99, (y + 1900).where(y > 22, y + 2000))
或indexing:
df["Year"][df["Year"].between(0, 21)] += 2000
df["Year"][df["Year"].between(22, 99)] += 1900
或loc
:
df.loc[df["Year"].between(0, 21), "Year"] += 2000
df.loc[df["Year"].between(22, 99), "Year"] += 1900