我有以下資料框:
A B
0 john doe
1 jacob smith
2 juli patel
3 jason bourne
4 alan turing
我想創建一個新列 C,它是列 A 和 B 的串聯以及從 1 開始的計數器。但是,如果 A B Counter 的總長度超過 11,那么我想將計數器重置回 1 .
因此,對于上述資料框,C 列將是:
A B C
0 john doe johndoe1
1 jacob smith jacobsmith2
2 juli patel julipatel3
3 jason bourne jasonbourne1
4 alan turing alanturing2
uj5u.com熱心網友回復:
import pandas as pd
data = {
"A": ["john", "jacob", "juli", "jason", "alan"],
"B": ["doe", "smith", "patel", "bourne", "turing"],
}
counter = 0
def update_trans(row):
global counter
length = len(row["A"] row["B"])
if length >= 11:
counter = 1
else:
counter = 1
return f"{row['A']}{row['B']}{str(counter)}"
if __name__ == "__main__":
df = pd.DataFrame(data)
df["C"] = df.apply(update_trans, axis=1)
print(df.head())
看看這是否有幫助...
由于這項任務看起來很基礎,因此利用應用功能可能沒問題。
uj5u.com熱心網友回復:
這是另一種方式:
s = df['A'] df['B']
s df.groupby((s.str.len()).ge(11).cumsum()).cumcount().add(1).astype(str)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491321.html
上一篇:用零替換列值
下一篇:根據向量選擇資料框值
