Above all,
Let's make initial column head.
import pandas as pd
#init
col_names = ['product', 'count']
word_pd = pd.DataFrame(columns = col_names)
There is no data yet.
So, let's add initial data
#add produce list
word_pd.loc[len(word_pd)] = ['apple', 4]
word_pd.loc[len(word_pd)] = ['orange', 7]
word_pd.loc[len(word_pd)] = ['beer', 10]
word_pd.loc[len(word_pd)] = ['cola', 7]
word_pd.loc[len(word_pd)] = ['beer', 8]
#check
print('origin data', word_pd)
>
origin data product count
0 apple 4
1 orange 7
2 beer 10
3 cola 7
4 beer 8
OK, then let's find specific product name and increase count.
#find product
list_pd = word_pd.loc[word_pd['product'] == 'apple']
list_f = list_pd.index.tolist()
#add count
if len(list_f)>0:
for index in list_f:
word_pd.iloc[index][1] = word_pd.iloc[index, word_pd.columns.get_loc('count')] +1
print('result')
print('data', word_pd)
>
result
data product count
0 apple 5
1 orange 7
2 beer 10
3 cola 7
4 beer 8
OK, at this time, let's find beer product and add count.
Note, there are 2 rows of beer product, so all beer product's count are increased.
#one more test
#find product
list_pd = word_pd.loc[word_pd['product'] == 'beer']
list_f = list_pd.index.tolist()
#add count
if len(list_f)>0:
for index in list_f:
word_pd.iloc[index][1] = word_pd.iloc[index, word_pd.columns.get_loc('count')] +1
print('result')
print('data', word_pd)
result
data product count
0 apple 5
1 orange 7
2 beer 11
3 cola 7
4 beer 9
This is whole source code.
import pandas as pd
#init
col_names = ['product', 'count']
word_pd = pd.DataFrame(columns = col_names)
#add produce list
word_pd.loc[len(word_pd)] = ['apple', 4]
word_pd.loc[len(word_pd)] = ['orange', 7]
word_pd.loc[len(word_pd)] = ['beer', 10]
word_pd.loc[len(word_pd)] = ['cola', 7]
word_pd.loc[len(word_pd)] = ['beer', 8]
#check
print('origin data', word_pd)
#find product
list_pd = word_pd.loc[word_pd['product'] == 'apple']
list_f = list_pd.index.tolist()
#add count
if len(list_f)>0:
for index in list_f:
word_pd.iloc[index][1] = word_pd.iloc[index, word_pd.columns.get_loc('count')] +1
print('result')
print('data', word_pd)
#one more test
#find product
list_pd = word_pd.loc[word_pd['product'] == 'beer']
list_f = list_pd.index.tolist()
#add count
if len(list_f)>0:
for index in list_f:
word_pd.iloc[index][1] = word_pd.iloc[index, word_pd.columns.get_loc('count')] +1
print('result')
print('data', word_pd)
Thank you.
No comments:
Post a Comment