[英]How to slice strings in dataframe based on string length of column in Python?
我要解決的問題是:在一列上使用 Len() 並且每行的字符數需要應用於另一列。
我有一個 dataframe,總帳代碼的長度不同,我需要找到最低級別的詳細信息以防止重復計算。 我找到它的方法是使用當前行的字符數將當前行的數字與下一行的數字進行比較。 例如,11.0 和 111.0 是 1111-1123 的分組帳戶。 我只想要 111-1123 並排除組帳戶。
我可以使用 LEN function 獲取當前行的字符數,但我無法將其應用於整列。
我的 dataframe 看起來像這樣:
:df3['Next_Account'] = df3['Account'].shift(-1)
df3['Len_account'] = df3['Account'].str.len()-2
Account Amount Next_account Len_Account
0 11.0 1000.82 111.0 2
1 111.0 1000.42 1111.0 3
2 1111.0 791.51 1115.0 4
3 1115.0 1802.19 1116.0 4
4 1116.0 202.36 1117.0 4
5 1117.0 1507.33 1118.0 4
6 1118.0 0.03 1119.0 4
7 1119.0 0.00 1120.0 4
8 1120.0 0.00 1121.0 4
9 1121.0 24.28 1122.0 4
10 1122.0 376.87 1123.0 4
11 1123.0 0.25 12.0 4
14 12.0 80179.92 121.0 2
15 121.0 80179.92 12101.0 3
16 12101.0 0.00 12102.0 5
我嘗試通過為下一行添加一個新列,為當前行的字符長度添加一個新列來計算它。
df3['current_digits_next'] = df3['Next_Account'].str[:df3['Len_Account']]
df3
current_digits_next
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
10 NaN
11 NaN
14 NaN
15 NaN
16 NaN
我嘗試使用字符串 function 獲取 Next 帳戶的字符數,但由於某種原因這不起作用。
current_digits_next
0 11
1 111
2 1115
3 1116
4 1117
5 1118
6 1119
7 1120
8 1121
9 1122
10 1123
11 12.0
14 12
15 121
16 12102
首選output為:
current_digits_next 0 11 1 111 2 1115 3 1116 4 1117 5 1118 6 1119 7 1120 8 1121 9 1122 10 1123 11 12.0 14 12 15 121 16 12102
使用首選 output 我可以匹配數據並排除分組帳戶。 我究竟做錯了什么?
str
訪問器接受 int 而不是 Series 作為索引。 您可以嘗試在行上apply
df3['current_digits_next'] = df3.apply(lambda row: str(row['Next_Account'])[:row['Len_account']], axis=1)
Account Amount Next_Account Len_account current_digits_next
0 11.0 1000.82 111.0 2 11
1 111.0 1000.42 1111.0 3 111
2 1111.0 791.51 1115.0 4 1115
3 1115.0 1802.19 1116.0 4 1116
4 1116.0 202.36 1117.0 4 1117
5 1117.0 1507.33 1118.0 4 1118
6 1118.0 0.03 1119.0 4 1119
7 1119.0 0.00 1120.0 4 1120
8 1120.0 0.00 1121.0 4 1121
9 1121.0 24.28 1122.0 4 1122
10 1122.0 376.87 1123.0 4 1123
11 1123.0 0.25 12.0 4 12.0
12 12.0 80179.92 121.0 2 12
13 121.0 80179.92 12101.0 3 121
您可以將您的Account
字段轉換為字符串,然后使用apply
來檢查所需的條件
s1 = df['Account'].astype(int).astype(str)
s2 = df['Account'].astype(int).astype(str).shift(-1)
s3 = pd.concat([s1, s2], axis=1, ignore_index=True).loc[:len(s1), :].apply(lambda x: x[0] in x[1], axis=1)
df = pd.concat([df, s3], axis=1).fillna(False)
print(df)
Account Amount 0
0 11.0 1000.82 True
1 111.0 1000.42 True
2 1111.0 791.51 False
3 1115.0 1802.19 False
4 1116.0 202.36 False
5 1117.0 1507.33 False
6 1118.0 0.03 False
7 1119.0 0.00 False
8 1120.0 0.00 False
9 1121.0 24.28 False
10 1122.0 376.87 False
11 1123.0 0.25 False
14 12.0 80179.92 True
15 121.0 80179.92 True
16 12101.0 0.00 False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.