[英]Python: In a DataFrame, how do I loop through all strings of one column and check to see if they appear in another column and count them?
[英]Python: In a DataFrame, how do I find the year that strings from one column appear in another column?
我有一個數據框,想要遍歷c2列中的所有字符串,並打印該字符串及其出現在c2列中的年份,然后還打印出出現在c1列中的第一年 (如果它存在於c1中)。 然后在另一列中計算年份之間的差異。 c2中有NaN值。
df示例:
id year c1 c2
0 1999 luke skywalker han solo
1 2000 leia organa r2d2
2 2001 han solo finn
3 2002 r2d2 NaN
4 2004 finn c3po
5 2002 finn NaN
6 2005 c3po NaN
示例打印結果:
c2 year in c2 year in c1 delta
han solo 1999 2001 2
r2d2 2000 2002 2
finn 2001 2004 3
c3po 2004 2005 1
我正在將Jupyter Notebook與python和pandas一起使用。 謝謝!
您可以按照以下步驟進行操作:
df1 = df[df.c2.notnull()].copy()
s = df.groupby('c1')['year'].first()
df1['year in c1'] = df1.c2.map(s)
df1 = df1.rename(columns={'year':'year in c2'})
df1['delta'] = df1['year in c1'] - df1['year in c2']
print(df1[['c2','year in c2','year in c1', 'delta']])
輸出:
c2 year in c2 year in c1 delta
0 han solo 1999 2001 2
1 r2d2 2000 2002 2
2 finn 2001 2004 3
4 c3po 2004 2005 1
這是一種方法。
df['year_c1'] = df['c2'].map(df.groupby('c1')['year'].agg('first'))\
.fillna(0).astype(int)
df = df.rename(columns={'year': 'year_c2'})
df['delta'] = df['year_c1'] - df['year_c2']
df = df.loc[df['c2'].notnull(), ['id', 'year_c2', 'year_c1', 'delta']]
# id year_c2 year_c1 delta
# 0 0 1999 2001.0 2
# 1 1 2000 2002.0 2
# 2 2 2001 2004.0 3
# 4 4 2004 2005.0 1
說明
c1
映射到year
,按“ first”進行聚合。 c2
上計算year_c1
。 delta
為year_c2
和year_c1
之間的差。 c2
和order列中具有null
行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.